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

@angular-libs/socket

v0.0.2

Published

A signal-first, lightweight WebSocket client library for Angular applications with offline outbox storage, channel/topic multiplexing, and auto-reconnect.

Readme

Socket

This project was generated using Angular CLI version 22.0.0.

Code scaffolding

Angular CLI includes powerful code scaffolding tools. To generate a new component, run:

ng generate component component-name

For a complete list of available schematics (such as components, directives, or pipes), run:

ng generate --help

Building

To build the library, run:

ng build @angular-libs/socket

This command will compile your project, and the build artifacts will be placed in the dist/ directory.

Publishing the Library

Once the project is built, you can publish your library by following these steps:

  1. Navigate to the dist directory:

    cd dist/angular-libs/socket
  2. Run the npm publish command to publish your library to the npm registry:

    npm publish

Running unit tests

To execute unit tests with the Karma test runner, use the following command:

ng test

Running end-to-end tests

For end-to-end (e2e) testing, run:

ng e2e

Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.

Additional Resources

For more information on using the Angular CLI, including detailed command references, visit the Angular CLI Overview and Command Reference page.

Signal-first WebSocket clients for Angular. The primary API returns one stable client object whose signals update as the URL, connection, and messages change.

Create a client

Call createWebSocket() from an Angular injection context, such as a component field initializer, constructor, provider factory, or service. Its connection is closed automatically with that context.

import { Component, computed, signal } from '@angular/core';
import { createWebSocket } from '@angular-libs/socket';

interface ChatCommand {
   text: string;
}

interface ChatEvent {
   sender: string;
   text: string;
}

@Component({ standalone: true, template: '' })
export class ChatComponent {
   private readonly room = signal('general');

   readonly socket = createWebSocket<ChatCommand, ChatEvent>(
      () => `wss://example.test/rooms/${this.room()}`,
      {
         bufferWhileOffline: true,
         reconnect: {
            maxAttempts: 10,
            initialDelayMs: 1_000,
            maxDelayMs: 15_000,
            backoffFactor: 2,
         },
         outbox: { maxSize: 500, overflow: 'reject-newest' },
      },
   );

   readonly connected = computed(() => this.socket.isConnected());
}

socket.status, socket.message, socket.error, socket.bufferedCount, and socket.nextReconnectDelay are Angular signals. Use socket.subscribe() when every received message must be consumed; message() intentionally contains only the most recent one.

Plugins & Auth Refresh

Intercept connection URLs or refresh auth tokens asynchronously right before connecting or reconnecting:

const socket = createWebSocket(() => url(), {
   detectNetworkStatus: true, // Instant reconnects on window 'online' events (default: true)
   plugins: [
      {
         async onBeforeConnect(currentUrl) {
            const token = await authService.getFreshToken();
            return `${currentUrl}?token=${token}`;
         }
      }
   ]
});

Outbox Storage & Topic Multiplexing

Persist offline buffered messages across browser restarts (IndexedDB, LocalStorage, OPFS):

const socket = createWebSocket(() => url(), {
   bufferWhileOffline: true,
   outbox: {
      maxSize: 100,
      storage: {
         async getItem() { return JSON.parse(localStorage.getItem('ws_outbox') || '[]'); },
         async setItem(items) { localStorage.setItem('ws_outbox', JSON.stringify(items)); },
         async clear() { localStorage.removeItem('ws_outbox'); }
      }
   }
});

Subscribe to specific channels or topics over a single connection using the multiplex plugin with optional network wire protocol framing:

import { createWebSocketMultiplexPlugin } from '@angular-libs/socket';

const multiplex = createWebSocketMultiplexPlugin({
   // Automatically send wire framing on topic subscribe/unsubscribe & reconnects
   onSubscribeTopic: (topic) => ({ action: 'subscribe', topic }),
   onUnsubscribeTopic: (topic) => ({ action: 'unsubscribe', topic })
});

const socket = createWebSocket(() => url(), { plugins: [multiplex] });

// Subscribe to a topic (triggers wire subscribe frame on 1st subscriber):
const unsubscribe = multiplex.subscribe('work-order:101', (message) => {
   console.log('Work order updated:', message);
});

// Send message targeting a specific topic (uses attached socket automatically):
multiplex.send('work-order:101', { action: 'UPDATE' });

// Access a Signal for a specific topic:
const trackingSignal = multiplex.topicSignal('work-order:101');

Call socket.close(code?, reason?) for a permanent local close, or socket.reconnect() to replace the active transport immediately. Reconnects invalidate old transport callbacks, preventing delayed events from a closed socket from changing the current connection state.

Protocol configuration

JSON serialization and deserialization are defaults. Supply a codec for another wire format. Application heartbeats are disabled by default because heartbeat formats are server-specific; configure both the payload and the receive filter.

const socket = createWebSocket<Command, Event>(() => url(), {
   serializer: (command) => JSON.stringify(command),
   deserializer: (event) => JSON.parse(event.data) as Event,
   heartbeat: {
      intervalMs: 30_000,
      payload: { type: 'ping' },
      isHeartbeat: (event) => event.data === JSON.stringify({ type: 'ping' }),
   },
});

error() returns a typed WebSocketError with a kind such as connection, send, deserialize, reconnect, or queue.

Testing

Provide a transport factory instead of replacing global browser state. The package includes a deterministic fake for this purpose.

import { createMockWebSocketFactory, createWebSocket } from '@angular-libs/socket';

const mock = createMockWebSocketFactory();
const socket = createWebSocket(() => 'ws://example.test', {
   webSocketFactory: mock.factory,
});

mock.openAll();
mock.receiveAll(JSON.stringify({ type: 'ready' }));

SSR and legacy API

When no native WebSocket and no webSocketFactory are available, the client stays disconnected and rejects sends. This makes SSR safe without creating an outbox that cannot be delivered.

websocketResource() remains available for existing callers. It keeps its resource-shaped return value and legacy 30-second heartbeat default, but new code should prefer createWebSocket() to avoid a second resource state machine and optional resource.value() access.

Build and test

ng build socket
ng test socket --watch=false