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

@statewalker/webrun-streams-signaling

v0.5.2

Published

Generic P2P signaling/connection-setup (PeerManager, QrSignaling, RoomManager) yielding ByteChannels

Readme

@statewalker/webrun-streams-signaling

What it is

Connection-setup helpers for peer-to-peer links. Each one runs a handshake and hands back an established ByteChannel (send / recv / closed / close, declared by this package). PeerManager runs WebRTC offer/answer/ICE over a signaling transport you supply; QrSignaling pairs two devices without a server by exchanging compact QR strings; RoomManager joins a LiveKit-style room and opens a channel per participant. What runs on the channel afterwards — typically webrun-rpc's port stack, through messageTargetOverByteChannel — is up to you.

Why it exists

Every peer-to-peer transport needs the same preliminary step: find the peer, exchange session descriptions and ICE candidates, and wait for a data channel to open. That step is separate from moving bytes. This package does only that step and stops at a ByteChannel, so any byte protocol can run on the result. It contains no signaling server (STUN/TURN/rendezvous); these are clients. Vendor code stays out of the import graph: native WebRTC is reached through an injectable factory and LiveKit through a structural RoomLike interface and a roomFactory, so the package can be tested with in-memory mocks and livekit-client is only needed if you use RoomManager.

How to use

pnpm add @statewalker/webrun-streams-signaling
# only for RoomManager:
pnpm add livekit-client

livekit-client (^2.18.3) is an optional peer dependency; the package never imports it, you pass () => new Room(). One entry point, ., ESM only. It targets browsers: it uses RTCPeerConnection (unless you inject rtc), crypto.getRandomValues, btoa / atob. In Node, pass an rtc factory from a WebRTC implementation.

Exports

| Export | Purpose | | --- | --- | | new PeerManager(signaling, options?) | WebRTC connections keyed by peer id over a SignalingTransport. connect(peerId): Promise<ByteChannel>, onConnection((peerId, ch) => void): () => void, close(). | | PeerManagerOptions | WebRtcConnectionOptions plus onError?: (error, peerId) => void, called when a connection fails with no caller to tell (a signal it rejects, an inbound channel that never opens). | | new QrSignaling(options?) | Serverless pairing. offer(): Promise<{ qr, accept(answerQr): Promise<ByteChannel> }>, answer(offerQr): Promise<{ qr, channel }>, getSessionId(). | | QrSignalingOptions | { sessionId?: string; connection?: WebRtcConnectionOptions }. | | new RoomManager(options: RoomManagerOptions) | Room membership. join(room), participants(): AsyncIterable<string>, channelTo(peerId, options?): Promise<ByteChannel> (a byteChannelFromRoom channel), leave(). | | new PeerConnection(role, options?) | One WebRTC connection's lifecycle, which PeerManager and QrSignaling build on. connect(), handleSignal(msg), open(): Promise<ByteChannel>, waitForIceGathering(), getLocalDescription(), getCollectedCandidates(), getState(), getRole(), hasRemoteDescription(), getDataChannel(), on / off, close(). | | byteChannelFromDataChannel(dc) | Wrap an RTCDataChannel as a ByteChannel, with the data channel's bufferedAmount and a whenDrained() that waits for bufferedamountlow. | | byteChannelFromRoom(room, peerId, options?) | A ByteChannel to one participant of a RoomLike, on its own data topic (options.topic, default DEFAULT_ROOM_TOPIC). It closes when the room disconnects, the participant leaves, the peer's channel closes, a reliable publish fails, or a send exceeds options.maxFrameBytes (default DEFAULT_ROOM_MAX_FRAME_BYTES), so whatever runs on it learns the other end is gone. Packets and goodbye follow webrun-streams-livekit's conventions. | | ByteChannelFromRoomOptions | { topic?: string; maxFrameBytes?: number }. | | DEFAULT_ROOM_TOPIC, DEFAULT_ROOM_MAX_FRAME_BYTES | "webrun/port-stack" and 64_000, the same defaults as webrun-streams-livekit. | | messageTargetOverByteChannel(channel, options?) | A ByteChannel as { target, signal, maxMessageSize } for webrun-rpc's overPipe: a MessageTarget of bytes, a signal aborted when the channel closes, and the payload ceiling (DEFAULT_MAX_MESSAGE_SIZE, 16 KiB − 256, what every browser pair delivers over a data channel; pass maxMessageSize: 12 * 1024 for a byteChannelFromRoom channel). target also has the channel's bufferedAmount and whenDrained(), so overPipe with frameSize paces its frames by the transport. It must be the channel's only reader. | | DRAIN_LOW_WATER | 256 * 1024. The channels' whenDrained() resolves once bufferedAmount is at most this. | | ByteChannel | The channel type: send, recv, closed, close, and optional bufferedAmount / whenDrained(). It used to come from @statewalker/webrun-streams; it is declared here since emulateMux was removed. | | generateSessionId(), createCompressedSignal(...), parseCompressedSignal(signal), encodeSignal(signal), decodeSignal(text) | The pure QR payload functions. |

Types and constants: SignalingTransport (localId, send(to, msg), onMessage(handler): () => void), SignalingMessage (offer / answer / candidate / ready), SessionDescription, IceCandidate, PeerRole, ConnectionState, PeerConnectionEvents (stateChange, signal, open, close, error), WebRtcConnectionOptions, RtcPeerConnectionFactory, DEFAULT_ICE_SERVERS (two Google STUN servers), CompressedSignal, RoomLike, RoomParticipantLike, RoomLocalParticipantLike, RoomManagerOptions (url, getToken(room), roomFactory), ROOM_EVENT (the four LiveKit event names used), ParticipantInfo (exported, not used by any API here).

WebRtcConnectionOptions:

| option | default | meaning | | --- | --- | --- | | iceServers | DEFAULT_ICE_SERVERS | ICE servers. | | connectionTimeout | 30000 ms | How long open() waits for the data channel (for QrSignaling's initiator, from accept). | | iceGatheringTimeout | 5000 ms | How long QrSignaling waits for ICE gathering before using what it has. | | channelLabel | "webrun-data" | Data channel label. | | ordered | true | Ordered delivery. | | maxRetransmits | unset | Retransmit limit for unreliable mode. | | rtc | new RTCPeerConnection(config) | Factory for the peer connection. |

Examples

PeerManager: dial a peer over your signaling channel, then multiplex

The SignalingTransport below is an in-memory bus, so both peers run in one page; in an application it wraps your WebSocket or other rendezvous channel.

import { msgpackCodec } from "@statewalker/webrun-msgpack";
import { connect, overPipe, serve } from "@statewalker/webrun-rpc";
import {
  messageTargetOverByteChannel,
  PeerManager,
  type SignalingMessage,
  type SignalingTransport,
} from "@statewalker/webrun-streams-signaling";

function signalingBus() {
  const handlers = new Map<string, (from: string, msg: SignalingMessage) => void>();
  return (localId: string): SignalingTransport => ({
    localId,
    send: (to, msg) => queueMicrotask(() => handlers.get(to)?.(localId, msg)),
    onMessage(handler) {
      handlers.set(localId, handler);
      return () => handlers.delete(localId);
    },
  });
}

const bus = signalingBus();
const a = new PeerManager(bus("A"));
const b = new PeerManager(bus("B"));

b.onConnection((peerId, channel) => {
  const { target, signal, maxMessageSize } = messageTargetOverByteChannel(channel);
  void serve(
    { mux: overPipe(target, { codec: msgpackCodec, side: "responder", signal, maxMessageSize }) },
    async function* echo(input) {
      for await (const chunk of input) yield chunk;
    },
  );
});

const pipe = messageTargetOverByteChannel(await a.connect("B"));
const { call, close } = await connect({
  mux: overPipe(pipe.target, {
    codec: msgpackCodec,
    side: "initiator",
    signal: pipe.signal,
    maxMessageSize: pipe.maxMessageSize,
  }),
});
for await (const chunk of call([new TextEncoder().encode("ping")])) {
  console.log(new TextDecoder().decode(chunk)); // "ping"
}
await close();

a.close();
b.close();

QrSignaling: pair two devices without a server

import { QrSignaling } from "@statewalker/webrun-streams-signaling";

// Device A
const deviceA = new QrSignaling();
const { qr: offerQr, accept } = await deviceA.offer(); // show offerQr as a QR code

// Device B, after scanning offerQr
const deviceB = new QrSignaling();
const { qr: answerQr, channel: channelB } = await deviceB.answer(offerQr); // show answerQr

// Device A, after scanning answerQr
const channelA = await accept(answerQr);

This flow does not currently complete against a real WebRTC stack; see What answer() waits for.

RoomManager: one channel per participant

import { Room } from "livekit-client";
import { RoomManager } from "@statewalker/webrun-streams-signaling";

const rooms = new RoomManager({
  url: "wss://livekit.example.com",
  getToken: (room) => fetch(`/token?room=${room}`).then((r) => r.text()),
  roomFactory: () => new Room(),
});

await rooms.join("room1");
for await (const peerId of rooms.participants()) {
  const channel = await rooms.channelTo(peerId);
  channel.send(new Uint8Array([5, 5]));
}
// participants() does not end until leave() is called

Internals

  SignalingTransport / QR strings / LiveKit room      (you provide)
                │  offer, answer, ICE candidates
                ▼
  PeerConnection ── RTCPeerConnection (or your `rtc` factory)
                │  data channel opens
                ▼
  ByteChannel  ── send / recv / closed / close
                │
                ▼
  the port stack (messageTargetOverByteChannel) or any byte protocol   (you run)

How PeerManager routes signals

Each peer id maps to one PeerConnection. connect(peerId) creates an initiator, creates the data channel and offer, and resolves when the channel opens. An inbound offer from an unknown peer creates a responder; onConnection handlers are called when its channel opens. Answers and candidates from unknown peers are ignored. Candidates that arrive before the remote description is set are queued and applied after it. When ICE gathering completes, a { type: "ready" } signal is sent; receivers ignore it. A connection is closed and forgotten when its data channel closes, when its state becomes failed or closed, when its channel does not open, or when it rejects a signal; the peer's next offer then starts a new responder. A connection makes one offer, so a new offer from a peer means it started over (for example it reloaded before ICE reported a failure here): if this side answered that peer before, or dialed it and already applied its answer, the old connection is closed and the offer starts a new responder at once. An offer to a connection that is still waiting for its answer is glare: both dials fail (reported through onError on this side) and must be retried. connect(peerId) replaces any existing connection to that peer.

What answer() waits for

QrSignaling sends everything in one payload: it waits for ICE gathering (up to iceGatheringTimeout), then packs the SDP and all gathered candidates. offer() returns the offer QR and an accept that applies the answer. answer(), however, awaits the responder's data channel before it returns the answer QR. With a real WebRTC stack that channel opens only after the initiator has applied the answer, which needs the answer QR. So answer() rejects with Connection timeout after <connectionTimeout>ms instead of returning, and the flow in the example above does not complete. The test suite uses a mock RTCPeerConnection that opens the channel as soon as both descriptions are set on one side, so it does not exercise this ordering.

offer() does not wait for its channel: accept does, so connectionTimeout counts from accept, not from the offer, and the people scanning the codes can take as long as they need. If applying the answer fails, accept closes the connection and rejects.

How QR payloads stay small

createCompressedSignal keeps only the SDP lines needed to connect (v=, o=, s=, t=, m=, c=, a=group:, a=ice-ufrag:, a=ice-pwd:, a=fingerprint:, a=setup:, a=mid:, a=sctp-port:, a=max-message-size:) and packs each candidate into a |-separated string, dropping the attributes after typ. A candidate that carries raddr, rport or tcptype (a srflx, relay or TCP candidate) is kept raw instead, prefixed R:, with only those attributes, and so is a candidate that does not parse. A null sdpMLineIndex travels as an empty field, so 0 stays 0. encodeSignal is URL-safe base64 of the JSON, without padding. parseCompressedSignal throws Unsupported protocol version: <v> for any version other than 1, and a malformed packed candidate throws Invalid compressed candidate: <text>.

How the channels behave

  • Both channels buffer inbound bytes from the moment they are created, so data that arrives before your for await starts is not lost.
  • byteChannelFromDataChannel sets binaryType = "arraybuffer" and copies every inbound payload. A non-byte message (a string) ends the channel, as does a send that throws (a closed channel, or Chrome's full 16 MiB send queue): either way the stream above lost a message. closed resolves on the data channel's close event or on close(); a send after that is ignored. It sets bufferedAmountLowThreshold to DRAIN_LOW_WATER; whenDrained() resolves on bufferedamountlow or when the channel ends.
  • messageTargetOverByteChannel's whenDrained() is the channel's, and resolves at once over a channel without one or once the pipe has ended.
  • byteChannelFromRoom publishes with reliable: true to destinationIdentities: [peerId] on its topic, and accepts dataReceived events from that participant on that topic only; packets with no participant, from anyone else, or on another topic are ignored, so several channels to one participant can share a room on different topics. It ends when the room disconnects, the participant leaves, a reliable publish fails, a send exceeds maxFrameBytes (that send throws RangeError), or the peer's goodbye arrives. When it ends on this side (close(), an oversized send, a failed publish) it publishes an empty goodbye on <topic>/close, the same convention as webrun-streams-livekit's CLOSE_TOPIC, so the peer's channel ends although the room stays connected. The topic, goodbye and frame ceiling match messageTargetOverLiveKit's defaults, so the port stack over this channel talks to one over that adapter. bufferedAmount counts bytes whose publish has not settled; whenDrained() resolves once that is at most DRAIN_LOW_WATER.

What RoomManager tracks

participants() yields the identities already in the room when join returns, then each one that joins, and ends at leave(). Departures are not reported. Only the most recently created participants() iterator receives new joiners. channelTo() before join() throws channelTo() before join().

Failure modes

  • PeerConnection.open() rejects with Connection timeout after <n>ms, with the data channel's error, or with Connection failed when the connection state becomes failed.
  • connect() on a responder throws connect() should only be called by initiator; an offer to an initiator throws Received offer but not in responder role; an answer to a responder throws Received answer but not in initiator role.
  • PeerManager: a failed connect() rejects and forgets the connection. A failure with no caller (an offer during glare, malformed SDP or candidates, an inbound channel that never opens) closes and forgets the connection and goes to onError; without onError it is dropped. Either way onConnection is not called for it.
  • PeerConnection.open() also rejects with Connection closed before the data channel opened when the connection is closed first.

Dependencies

One runtime dependency, @statewalker/webrun-streams at runtime, for newMessagePipe: the pipe module every transport adapter shares (listeners, delivery, life, the byte check, the frame ceiling, drain, close), so a pipe rule is fixed once for all of them (#151). The target is a MessageTarget by shape and carries its own closeSignal and maxMessageSize, so overPipe(target, { codec, side }) needs nothing else. ByteChannel is declared here, and messageTargetOverByteChannel takes an optional maxFrameBytes. @statewalker/webrun-rpc, -msgpack and -streams-conformance are dev dependencies of the tests: tests/conformance.test.ts runs the conformance suite over messageTargetOverByteChannel and the port stack, on byteChannelFromDataChannel and on byteChannelFromRoom (in-process stand-ins for the data channel and the room). livekit-client is an optional peer, used only through the RoomLike shape you inject. A neutrality test (tests/neutrality.test.ts) keeps the source from importing anything else.

License

MIT