@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/typedrequestconcepts
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
TypedSocket composes its private protocol handlers into the application router before that router is given to SmartServe:
import { TypedSocket } from '@api.global/typedsocket';
import * as typedrequest from '@api.global/typedrequest';
import { SmartServe } from '@push.rocks/smartserve';
// 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}! 👋`,
};
})
);
const server = TypedSocket.createServer(typedRouter);
const smartServe = new SmartServe({
port: 3000,
websocket: {
typedRouter,
},
});
server.attachSmartServe(smartServe);
await smartServe.start();
Integration with SmartServe
For SmartServe-based applications, compose the protocol router synchronously, attach the transport, and then start listening:
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}!` };
})
);
const typedSocket = TypedSocket.createServer(typedRouter);
// Create SmartServe with the composed application router
const smartServe = new SmartServe({
port: 3000,
websocket: {
typedRouter,
onConnectionOpen: (peer) => {
// Tag connections for later filtering
peer.tags.add('client');
}
}
});
typedSocket.attachSmartServe(smartServe);
await smartServe.start();
// Push notifications to tagged clients
const clients = await typedSocket.findAllTargetConnectionsByTag('client');
for (const client of clients) {
const request = typedSocket.createTypedRequest<IGreetingRequest>('greet', client);
await request.fire({ name: '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.
Multiple isolated application routers can share one transport without becoming reachable from each other:
const typedSocket = TypedSocket.createServer([publicRouter, adminRouter]);
const smartServe = new SmartServe({
port: 3000,
authorityValidation: 'strict',
websocket: {
resolveTypedRouter: (context) => {
if (context.url.hostname === 'example.com') return publicRouter;
if (context.url.hostname === 'admin.example.com') return adminRouter;
return undefined;
},
},
});
typedSocket.attachSmartServe(smartServe);
await smartServe.start();
TypedSocket adds a private, one-way fallback router containing its protocol
handlers to every application router. Duplicate protocol method names are
rejected during composition and on later router mutations; stop() releases
the owned fallback edges. fromSmartServe() remains available as a
compatibility shortcut that delegates to createServer() and
attachSmartServe().
Connection lookup and implicit single-peer targeting span every peer on the
attached SmartServe transport, regardless of the surface router that accepted
the peer. Multi-surface servers should tag or filter peers by surface and pass
an explicit target to createTypedRequest().
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'
);
Abortable Startup
Pass an AbortSignal when startup or reconnect attempts must be cancellable. Aborting stops the in-flight WebSocket and prevents queued reconnect attempts from continuing.
const abortController = new AbortController();
const clientPromise = TypedSocket.createClient(
clientRouter,
'http://localhost:3000',
{
abortSignal: abortController.signal,
initialBackoffMs: 1000,
maxRetries: 10,
}
);
// Later, if the connection attempt should no longer continue:
abortController.abort();
try {
const client = await clientPromise;
} catch (error) {
// Startup was aborted before a stable connection was established.
}
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);
Request Deadlines and Cancellation
TypedSocket forwards both configured request cancellation and per-fire() deadlines to its client
and SmartServe server transports. The first timeout or abort to occur cancels the transport work and
cleans the pending request state.
const requestAbort = new AbortController();
const request = client.createTypedRequest<IGreetingRequest>(
'greet',
undefined,
{
timeoutMs: 10_000,
abortSignal: requestAbort.signal,
}
);
const responsePromise = request.fire(
{ name: 'World' },
{ timeoutMs: 3_000 }
);
// A lifecycle owner can independently cancel before either timeout:
// requestAbort.abort();
const response = await responsePromise;
Connection Tagging
Tag connections for organized, targeted communication:
// Client side: add a tag
interface IUserTag extends typedrequestInterfaces.ITag {
name: 'userRole';
payload: 'admin' | 'user' | 'guest';
}
await client.setTag<IUserTag>('userRole', 'admin');
// On reconnect, stored tags are restored before statusSubject emits
// "connected". A failed restoration keeps the client unready and is retried
// through the normal reconnect policy.
// Removed tags are not restored after reconnect, even if this rejects because
// the server is unavailable while the removal request is attempted.
await client.removeTag('userRole');
// 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<IGreetingRequest>('greet', conn);
await request.fire({ name: 'admin' });
}
// Find a single connection
const firstAdmin = await server.findTargetConnectionByTag<IUserTag>('userRole', 'admin');
Event Handling
Subscribe to connection status events:
client.statusSubject.subscribe((status) => {
console.log('Connection status:', status);
});
server.statusSubject.subscribe((status) => {
console.log('Server connection event:', status);
});
Cleanup
Properly close connections when done:
// Client
await client.stop();
// Server integration
await typedSocket.stop();
await smartServe.stop();
API Reference
TypedSocket
Static Methods
| Method | Description |
|---|---|
createClient(router, serverUrl, options?) |
Creates a WebSocket client that connects to the specified server URL. Options include autoReconnect, maxRetries, initialBackoffMs, maxBackoffMs, and abortSignal. |
createServer(routerOrRouters) |
Synchronously composes TypedSocket protocol handling into one or more isolated application routers. |
fromSmartServe(smartServe, routerOrRouters) |
Compatibility shortcut that creates and attaches a server-side TypedSocket. |
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. |
statusSubject |
RxJS Subject for connection status events. |
Instance Methods
| Method | Description |
|---|---|
attachSmartServe(smartServe) |
Attaches one SmartServe transport to a composed server-side TypedSocket before listening. |
createTypedRequest(method, targetConnection?, options?) |
Creates a typed request. Options include the transport timeoutMs and abortSignal; per-call fire() deadlines are also forwarded to the transport. |
setTag(name, payload) |
Sets a tag on the client connection (client-side only). |
removeTag(name) |
Immediately removes a tag from local reconnect state, then removes it from the server connection; rejects if the server removal fails. |
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() |
On clients, closes the WebSocket and rejects pending requests. On servers, cancels pending requests, cleans their interests, unsubscribes from SmartServe, and releases protocol-router composition without stopping SmartServe itself. |
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 hello@task.vc.
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.