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

@api.global/typedsocket

v4.1.0

Published

A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.

Downloads

627

Readme

@api.global/typedsocket

A TypeScript library for creating typed WebSocket connections with bi-directional communication support. Extends @api.global/typedrequest to bring type-safe request/response patterns to WebSocket connections.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Features

  • 🔒 Full Type Safety - Leverages TypeScript for compile-time checking of all request/response payloads
  • 🔄 Bi-directional Communication - Both server and client can initiate requests
  • 🔌 Auto-reconnect - Client automatically reconnects on connection loss
  • 🏷️ Connection Tagging - Tag and filter connections for targeted messaging
  • 🌐 Browser Compatible - Works in both Node.js and browser environments
  • 🚀 SmartServe Integration - Native support for SmartServe's WebSocket handling

Install

npm install @api.global/typedsocket

Or with pnpm:

pnpm add @api.global/typedsocket

Usage

Prerequisites

  • TypeScript project setup
  • Basic understanding of async/await patterns
  • Familiarity with @api.global/typedrequest concepts

Define Your Request Interface

First, define the typed request interface that both client and server will use:

import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';

interface IGreetingRequest extends typedrequestInterfaces.implementsTR<
  typedrequestInterfaces.ITypedRequest,
  IGreetingRequest
> {
  method: 'greet';
  request: {
    name: string;
  };
  response: {
    message: string;
  };
}

Server Setup

Create a WebSocket server that handles typed requests:

import { TypedSocket } from '@api.global/typedsocket';
import * as typedrequest from '@api.global/typedrequest';

// Create the router and add handlers
const typedRouter = new typedrequest.TypedRouter();

typedRouter.addTypedHandler<IGreetingRequest>(
  new typedrequest.TypedHandler('greet', async (requestData) => {
    return {
      message: `Hello, ${requestData.name}! 👋`,
    };
  })
);

// Start the TypedSocket server (defaults to port 3000)
const server = await TypedSocket.createServer(typedRouter);

Integration with SmartServe

For SmartServe-based applications, use fromSmartServe() for native integration:

import { TypedSocket } from '@api.global/typedsocket';
import { SmartServe } from '@push.rocks/smartserve';
import * as typedrequest from '@api.global/typedrequest';

const typedRouter = new typedrequest.TypedRouter();

// Add handlers for client-to-server requests
typedRouter.addTypedHandler<IGreetingRequest>(
  new typedrequest.TypedHandler('greet', async (requestData) => {
    return { message: `Hello, ${requestData.name}!` };
  })
);

// Create SmartServe with typedRouter in websocket options
const smartServe = new SmartServe({
  port: 3000,
  websocket: {
    typedRouter,
    onConnectionOpen: (peer) => {
      // Tag connections for later filtering
      peer.tags.add('client');
    }
  }
});

await smartServe.start();

// Create TypedSocket bound to SmartServe
const typedSocket = TypedSocket.fromSmartServe(smartServe, typedRouter);

// Push notifications to tagged clients
const clients = await typedSocket.findAllTargetConnectionsByTag('client');
for (const client of clients) {
  const request = typedSocket.createTypedRequest<INotifyRequest>('notify', client);
  await request.fire({ message: 'Hello from server!' });
}

Note: When using SmartServe, the WebSocket transport is managed by SmartServe. TypedSocket acts as a convenience layer for finding connections and sending server-initiated requests.

Client Setup

Connect to the WebSocket server from a client:

import { TypedSocket } from '@api.global/typedsocket';
import * as typedrequest from '@api.global/typedrequest';

// Create a router for handling server-initiated requests (if needed)
const clientRouter = new typedrequest.TypedRouter();

// Connect to the server
const client = await TypedSocket.createClient(
  clientRouter,
  'http://localhost:3000'
);

Using Window Location (Browser)

In browser environments, you can automatically use the current page's origin:

const client = await TypedSocket.createClient(
  clientRouter,
  TypedSocket.useWindowLocationOriginUrl()
);

Sending Requests

Client to Server

const request = client.createTypedRequest<IGreetingRequest>('greet');
const response = await request.fire({
  name: 'World',
});

console.log(response.message); // "Hello, World! 👋"

Server to Client

The server can also initiate requests to connected clients:

// When only one client is connected, it's automatically selected
const request = server.createTypedRequest<IGreetingRequest>('greet');
const response = await request.fire({
  name: 'Client',
});

// For multiple clients, specify the target connection
const connection = await server.findTargetConnection(async (conn) => {
  // Your filter logic here
  return true;
});
const targetedRequest = server.createTypedRequest<IGreetingRequest>('greet', connection);

Connection Tagging

Tag connections for organized, targeted communication:

// Client side: add a tag
interface IUserTag extends typedrequestInterfaces.ITag {
  name: 'userRole';
  payload: 'admin' | 'user' | 'guest';
}

client.addTag<IUserTag>('userRole', 'admin');
// Server side: find connections by tag
const adminConnections = await server.findAllTargetConnectionsByTag<IUserTag>(
  'userRole',
  'admin'
);

// Send to all admins
for (const conn of adminConnections) {
  const request = server.createTypedRequest<INotificationRequest>('notify', conn);
  await request.fire({ message: 'Admin notification' });
}

// Find a single connection
const firstAdmin = await server.findTargetConnectionByTag<IUserTag>('userRole', 'admin');

Event Handling

Subscribe to connection status events:

client.eventSubject.subscribe((status) => {
  console.log('Connection status:', status);
});

server.eventSubject.subscribe((status) => {
  console.log('Server connection event:', status);
});

Cleanup

Properly close connections when done:

// Client
await client.stop();

// Server
await server.stop();

API Reference

TypedSocket

Static Methods

| Method | Description | |--------|-------------| | createServer(router) | Creates a WebSocket server (defaults to port 3000). | | createClient(router, serverUrl, alias?) | Creates a WebSocket client that connects to the specified server URL. | | fromSmartServe(smartServe, router) | Creates a TypedSocket bound to an existing SmartServe instance. | | useWindowLocationOriginUrl() | Returns the current window location origin (browser only). |

Instance Properties

| Property | Description | |----------|-------------| | side | Whether this instance is a 'server' or 'client'. | | typedrouter | The TypedRouter instance handling requests. | | eventSubject | RxJS Subject for connection status events. |

Instance Methods

| Method | Description | |--------|-------------| | createTypedRequest(method, targetConnection?) | Creates a typed request for the specified method. | | addTag(name, payload) | Adds a tag to the client connection (client-side only). | | findAllTargetConnections(filterFn) | Finds all connections matching the filter (server-side only). | | findTargetConnection(filterFn) | Finds the first connection matching the filter (server-side only). | | findAllTargetConnectionsByTag(key, payload?) | Finds all connections with the specified tag. | | findTargetConnectionByTag(key, payload?) | Finds the first connection with the specified tag. | | stop() | Closes the WebSocket connection. |

License and Legal Information

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the LICENSE file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at [email protected].

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.