npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@daniel_hammerle/sanesockets

v1.0.0

Published

SaneSockets is a simple and efficient WebSocket wrapper for JavaScript and TypeScript that provides a more intuitive, pull-based API. It simplifies the handling of WebSocket communication by allowing developers to focus on message processing without getti

Downloads

73

Readme

SaneSocket npm version license

SaneSockets

SaneSockets is a simple and efficient WebSocket wrapper for JavaScript and TypeScript that provides a more intuitive, pull-based API. It simplifies the handling of WebSocket communication by allowing developers to focus on message processing without getting bogged down in callback hell.

Why SaneSockets?

In a world where real-time communication is crucial, managing WebSocket connections can often lead to complex code. SaneSocket aims to streamline this process by offering an easy-to-use interface that reduces boilerplate code while enhancing readability and maintainability.

Features

  • Pull-based Message Handling: Easily read messages using async iterators or promise-based methods.
  • Built-in JSON Support: Send and receive JSON data effortlessly.
  • Runtime Type Checking: Validate incoming data with libraries like Zod for robust applications.
  • Cross-Platform Support: Works seamlessly in both browser and Node.js environments.
  • Easy to Use: A clean API that reduces boilerplate code and improves developer experience.

Installation

To install SaneSockets, you can use npm or yarn:

npm install sanesockets

Usage

Basic Example

Here's how to create a simple WebSocket connection and send/receive messages:

import { SaneSocket } from "sanesockets";

async function example() {
    const socket = await SaneSocket.start("wss://echo.websocket.org/");
    
    // Send a text message
    socket.writeText("Hello, World!");

    // Read the echoed message
    const response = await socket.readText();
    console.log(response); // Outputs: Hello, World!

    socket.close();
}

example();

Working with Json

Sending and receiving JSON data is straightforward:

import { SaneSocket } from "sanesockets";

async function jsonExample() {
    const socket = await SaneSocket.start("wss://echo.websocket.org/");
    
    const data = { name: "Tom", age: 18 };
    
    // Send JSON data
    socket.writeJson(data);

    // Read the JSON response
    const response = await socket.readJson();
    console.log(response); // Outputs: { name: "Tom", age: 18 }

    socket.close();
}

jsonExample();

Type validation with Zod

You can integrate runtime type checking with libraries like Zod:

import { SaneSocket } from "sanesockets";
import { z } from "zod";

const schema = z.object({
    name: z.string(),
    age: z.number()
});

async function typeValidationExample() {
    const socket = await SaneSocket.start("wss://echo.websocket.org/");
    
    const data = { name: "Tom", age: 18 };
    socket.writeJson(data);

    // Validate the incoming data
    const validatedData = await socket.readChecked(schema);
    console.log(validatedData); // Outputs: { name: "Tom", age: 18 }

    socket.close();
}

typeValidationExample();

Async Iterators

You can use async iterators to handle incoming messages in a loop:

import { SaneSocket } from "sanesockets";
import { z } from "zod";

const PacketSchema = z.object({
    name: z.string(),
    age: z.number()
});

async function loopExample() {
    const socket = await SaneSocket.start("wss://your.websocket.server");

    // Iterate over incoming validated packets
    for await (const packet of socket.iterChecked(PacketSchema)) {
        console.log(packet);
    }

    socket.close();
}

loopExample();

API

SaneSocket

  • static start(url: string | URL, protocols?: string | string[]): Promise<SaneSocket>: Initiates a WebSocket connection.
  • writeText(value: string): void: Sends a text message.
  • writeJson(value: any): void: Sends a JSON object.
  • readText(): Promise<string>: Reads a text message.
  • readJson(): Promise<any>: Reads and parses a JSON message.
  • readChecked<E>(parser: Parser<E>): Promise<E>: Reads and validates a JSON message against a parser.
  • close(code?: number, reason?: string): void: Closes the WebSocket connection.

Async Iterators

  • iterMessage(): AsyncGenerator<Message>: Asynchronously iterates over incoming messages.
  • iterJson(): AsyncGenerator<any>: Asynchronously iterates over incoming JSON messages.
  • iterChecked<E>(parser: Parser<E>): AsyncGenerator<E>: Asynchronously iterates over incoming validated JSON messages.