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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@alternet/wss-mux-client

v0.6.2

Published

Browser TypeScript client for wss-mux WebSocket multiplexer

Readme

@alternet/wss-mux-client

Browser TypeScript client for the wss-mux WebSocket multiplexer.

  • Zero runtime dependencies.
  • Browser-first (uses globalThis.WebSocket; injectable for other hosts).
  • Automatic reconnect with exponential backoff.
  • Token refresh via a caller-provided getToken callback on initial connect and on close-code 4401 (expired_token).
  • Subscribe and publish over a single WebSocket connection.
  • Typed errors for the documented wss-mux error codes and close codes.

Install

npm install @alternet/wss-mux-client

Quickstart

import { WssMuxClient } from "@alternet/wss-mux-client";

const client = new WssMuxClient({
  // Whatever path your wss-mux deployment serves the WebSocket on; the
  // handshake response from your auth endpoint is the canonical source.
  wssUrl: "wss://realtime.example.com/stream",
  getToken: async () => kcAuth.token,            // your token source
  onError: (err) => console.warn(err.code, err.message),
});

const sid = await client.subscribe("notification_banner", "*", (event) => {
  console.log(event.payload);
});

// Publish over the same connection.
await client.publish("chat_messages", "room-42", {
  from: "alice",
  text: "hello",
});

// later...
await client.unsubscribe(sid);
await client.close();

The getToken callback is called on the initial connect and whenever the server closes the connection with code 4401. Other reconnects reuse the cached token.

getToken contract (in detail)

The SDK invokes getToken() in exactly two situations:

  1. Initial connection. Once, before sending the first auth frame.
  2. Reconnect after a close-code 4401. When the server closes with 4401 (expired_token / unauthenticated), the SDK re-invokes getToken() before re-auth'ing, sends the freshly returned value on the new connection, and replays subscriptions.

The fresh value reaches the wire — the SDK does not cache the previous token across a 4401-driven reconnect. (Other reconnects, e.g. a transient 1006 disconnect, do reuse the cached token to avoid hammering the token issuer on flapping connections.)

This is the safety net the SDK provides for token rotation: the consumer keeps the latest token reachable from inside the callback — typically a React ref, an atom, a signal, or whatever your framework's "read the current value" primitive is — and getToken returns whatever is current at refresh time. The SDK calls it for you when it matters; you don't have to re-mount the client.

Pre-emptive token refresh (refreshing before the server says 4401) is out of scope — it's an app-layer concern. The 4401-driven path above is the safety net for when that pre-emptive refresh missed.

API

new WssMuxClient(options)

| Option | Type | Default | Description | |---|---|---|---| | wssUrl | string | required | Full WebSocket URL: wss://host[:port]/path. | | getToken | () => string \| Promise<string> | required | Returns the auth token. | | WebSocket | typeof WebSocket | globalThis.WebSocket | Constructor override for non-browser hosts. | | reconnect.maxAttempts | number | Infinity | Cap on reconnect attempts. | | reconnect.initialBackoffMs | number | 1000 | Initial backoff. | | reconnect.maxBackoffMs | number | 30000 | Max backoff. | | reconnect.backoffMultiplier | number | 2 | Backoff multiplier per attempt. | | onError | (err: ProtocolError) => void | — | Called when the server sends an error frame. | | onStateChange | (state: ConnectionState) => void | — | Called on connection state transitions. | | publishSettleMs | number | 250 | How long publish() waits for a possible error frame before resolving. |

client.subscribe(stream, [key], callback) → Promise<SubscriptionId>

Binds a subscription. The callback is invoked for every matching event. Omit key to receive all events on the stream.

client.unsubscribe(id) → Promise<void>

Removes a subscription. Idempotent.

client.publish(stream, [key], payload) → Promise<void>

Emits an event on stream. Same downstream dispatch path as the server's HTTP POST /events — same per-subscription delivery, same coalescing, same peer fanout. The connection's principals must intersect the stream's publish audience on the server; otherwise the call rejects with a ProtocolError whose code is unauthorized_publish.

Ack-by-absence: the server does not send a success frame. The returned promise resolves once the settle window (publishSettleMs, default 250 ms) elapses without an error frame matching the publish's id. If an error frame arrives within the window the promise rejects with the matching ProtocolError. If the connection drops while pending, it rejects with ConnectionClosedError.

client.close() → Promise<void>

Graceful shutdown. After calling close(), no further subscribe() calls are accepted.

client.connectionState

Current state: "idle" | "connecting" | "authenticating" | "ready" | "reconnecting" | "closing" | "closed".

Error handling

ProtocolError wraps server-sent error frames. The code field is one of the documented wss-mux error codes (unauthorized_subscribe, unauthorized_publish, publish_payload_too_large, unknown_stream, duplicate_subscription_id, rate_limited, overflow, etc.). For per-subscription fatal codes the SDK automatically removes the subscription from its local map; for publish errors the awaited publish() promise rejects (and onError still fires for parity).

ConnectionClosedError is surfaced when the server closes with code 4400 (bad_frame), which indicates a protocol bug — the SDK does not reconnect in that case.

Development

npm install
npm run typecheck
npm run build
npm test          # unit tests via node:test
npm run test:e2e  # against a real wss-mux instance; see tests/e2e.test.mjs
                  # — the repo-level harness at `tests/e2e/run.sh` boots a
                  # wss-mux binary and exports the env vars this suite reads.

License

MIT OR Apache-2.0.