@api.global/typedsocket
v8.6.0
Published
A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.
Maintainers
Readme
@api.global/typedsocket
Typed request/response communication over WebSockets with one peer-scoped transport for JSON RPC and ordered virtual-stream-v1 byte streams. TypedSocket 8 integrates TypedRequest 8, enforces an exact package-major handshake, and binds every server operation to the physical peer and routing surface selected during upgrade.
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.
Install
pnpm add @api.global/typedsocket @api.global/typedrequest @api.global/typedrequest-interfacesServer applications also need SmartServe:
pnpm add @push.rocks/smartserveTypedSocket 8 requires @api.global/typedrequest 8.0.3 or newer within major 8,
@api.global/typedrequest-interfaces 7.1 or newer within major 7, and
@push.rocks/smartserve 6.2.4 or newer within majors 6 and 7 (7.3.0 or newer to listen on a
Unix socket). These packages resolve
one TypedRequest 8 router graph and must not be mixed with earlier router or stream APIs.
Version 8 transport model
Each physical WebSocket peer has one always-on TypedSocket transport:
- text frames carry bidirectional TypedRequest envelopes;
- binary frames carry the same peer's
virtual-stream-v1streams; - SmartServe fixes the peer's
routingSurfaceandtransportOwnerduring upgrade; - the client and server must complete the exact TypedSocket package-major handshake before application requests or streams are admitted;
- the exact handshake also requires
typedrequest-cancellation-v1; mixed peers fail before application traffic; - client connection restoration runs after the handshake and before desired tags and the
connectedstate are published.
There are no optional native-byte or native-message capability modes in version 8. The v6 nativeBytes, native-byte-v1, native-message-v1, binary-message channel, and capability-mode APIs are not part of the v8 public surface. There is also no TypedSocket.fromSmartServe() attachment shortcut: server composition must happen before SmartServe is constructed.
Define shared contracts
TypedSocket uses ordinary TypedRequest interfaces. VirtualStreams use the transport-neutral TypedRequest 8 types:
import type {
ITypedRequest,
TVirtualStream,
implementsTR,
} from '@api.global/typedrequest-interfaces';
export interface IGreetRequest extends implementsTR<ITypedRequest, IGreetRequest> {
method: 'greet';
request: { name: string };
response: { message: string };
}
export interface IUploadRequest extends implementsTR<ITypedRequest, IUploadRequest> {
method: 'upload';
request: {
stream: TVirtualStream<'send'>;
};
response: {
storedBytes: number;
};
}
export interface IDownloadRequest extends implementsTR<ITypedRequest, IDownloadRequest> {
method: 'download';
request: { objectId: string };
response: {
// Direction is local to the requester. The server handler sees 'send'.
stream: TVirtualStream<'receive'>;
};
}
export interface IRestoreSessionRequest
extends implementsTR<ITypedRequest, IRestoreSessionRequest> {
method: 'restoreSession';
request: { token: string };
response: { restored: true };
}TypedHandler reverses stream directions at the handler boundary. An upload declared as requester-local send reaches the server handler as local receive; a download declared as requester-local receive is created by the handler as local send.
Server setup with SmartServe
Construction order is part of the transport contract:
- Create and populate the application
TypedRouter. - Call
TypedSocket.createServer(). - Obtain the generated transport routing surface with
getServerRoutingSurface(). - Construct SmartServe with that routing surface and the exact
webSocketTransportOwnerobject. - Call
attachSmartServe(). - Start SmartServe.
import { TypedSocket } from '@api.global/typedsocket';
import { TypedHandler, TypedRouter } from '@api.global/typedrequest';
import { SmartServe } from '@push.rocks/smartserve';
const applicationRouter = new TypedRouter();
applicationRouter.addTypedHandler(
new TypedHandler<IGreetRequest>('greet', async ({ name }) => ({
message: `Hello, ${name}!`,
})),
);
const typedSocket = TypedSocket.createServer(applicationRouter, {
onServerConnectionReady: (connection) => {
typedSocket.setServerTag(connection, 'application-client');
return undefined;
},
});
const smartServe = new SmartServe({
port: 3000,
websocket: {
typedRouter: typedSocket.getServerRoutingSurface(applicationRouter),
transportOwner: typedSocket.webSocketTransportOwner,
},
});
typedSocket.attachSmartServe(smartServe);
await smartServe.start();Do not pass applicationRouter directly to websocket.typedRouter. createServer() creates a distinct routing surface that composes the private TypedSocket protocol before the application router. SmartServe must bind that returned surface and the exact transport-owner identity to the peer.
onServerConnectionReady(connection) may synchronously assign protected tags or
other connection-local state after the exact handshake response has been
settled. It must return undefined; returning any other value, including a
Promise or custom thenable, or throwing closes the connection before readiness
is published.
Multiple isolated routing surfaces
One TypedSocket can compose multiple application routers without making them reachable from one another. Resolve the corresponding generated surface during upgrade:
const publicRouter = new TypedRouter();
const adminRouter = new TypedRouter();
const typedSocket = TypedSocket.createServer([publicRouter, adminRouter]);
const smartServe = new SmartServe({
port: 3000,
authorityValidation: 'strict',
websocket: {
resolveTypedRouter: (context) => {
if (context.url.hostname === 'api.example.com') {
return typedSocket.getServerRoutingSurface(publicRouter);
}
if (context.url.hostname === 'admin.example.com') {
return typedSocket.getServerRoutingSurface(adminRouter);
}
return undefined;
},
transportOwner: typedSocket.webSocketTransportOwner,
},
});
typedSocket.attachSmartServe(smartServe);
await smartServe.start();SmartServe rejects an upgrade when resolveTypedRouter() returns undefined. typedRouter and resolveTypedRouter are mutually exclusive, as are transportOwner and resolveTransportOwner.
Client setup
The client router handles server-initiated requests. createClient() resolves only after the package-major handshake, optional connection restoration, and desired-tag reconciliation succeed.
import { TypedHandler, TypedRouter } from '@api.global/typedrequest';
import { TypedSocket } from '@api.global/typedsocket';
const clientRouter = new TypedRouter();
clientRouter.addTypedHandler(
new TypedHandler<IGreetRequest>('greet', async ({ name }, tools) => {
tools?.abortSignal.throwIfAborted();
return { message: `Hello from the client, ${name}!` };
}),
);
const client = await TypedSocket.createClient(
clientRouter,
'https://api.example.com',
{
autoReconnect: true,
maxRetries: 20,
initialBackoffMs: 1_000,
maxBackoffMs: 30_000,
},
);
const response = await client
.createTypedRequest<IGreetRequest>('greet')
.fire({ name: 'Ada' });Use TypedSocket.useWindowLocationOriginUrl() for same-origin browser connections. Remote connections must use https: or wss:. Plain http: and ws: are restricted to loopback hosts. URLs containing credentials or fragments are rejected, and lifecycle logs redact paths and query strings.
Connecting over a Unix socket
A local controller can reach a TypedSocket server through a Unix domain socket instead of TCP. The server side needs no TypedSocket change: give SmartServe (7.3.0 or newer) a unixSocket listener, which owns the socket file and its permissions (mode 0600 by default).
const smartServe = new SmartServe({
unixSocket: { path: '/run/myservice/control.sock' },
websocket: {
typedRouter: server.getServerRoutingSurface(appRouter),
transportOwner: server.webSocketTransportOwner,
},
});
server.attachSmartServe(smartServe);
await smartServe.start();The client names the socket with unixSocketPath. The server URL still supplies the Host header and the request path. It must use http: or ws:, because TLS is not available over the socket, whose file permissions govern access, and like any plain http:/ws: URL it must name a loopback host.
const client = await TypedSocket.createClient(clientRouter, 'http://localhost', {
unixSocketPath: '/run/myservice/control.sock',
});The socket carries the same TypedSocket protocol as a TCP connection, and a reconnect opens a fresh connection to the same path. Deno 2.5.1 or newer (including deno compile binaries) uses its native WebSocket with a Unix-socket Deno.HttpClient, and older Deno releases reject unixSocketPath; Node.js uses the ws package, loaded only when unixSocketPath is set, and rejects a path containing :. Browsers and Bun reject unixSocketPath.
Restoring authenticated connection state
restoreConnection runs after the version handshake and before tags or readiness. Its request factory is deadline-bound and becomes invalid when the callback finishes:
declare const serverUrl: string;
declare const currentSessionToken: string;
const client = await TypedSocket.createClient(clientRouter, serverUrl, {
restoreConnection: async ({ createTypedRequest, abortSignal }) => {
if (abortSignal.aborted) return;
await createTypedRequest<IRestoreSessionRequest>('restoreSession').fire(
{ token: currentSessionToken },
);
},
});A TypedSocketHandshakeError is terminal for that client startup. A package-major mismatch, malformed handshake envelope, handshake timeout, or binary frame before handshake completion closes the connection instead of falling back to a reduced transport.
A refused restoration is terminal too, because retrying can only repeat the peer's verdict. Three rules decide a restoration that did not complete, in this order.
Whose refusal it is. A refusal is the hook's own only when the hook refused on its own account, which this package decides by provenance rather than by timing. A rejection it injected — a stopped client, a closed connection, a restore request it interrupted — is that interruption reported back to it, even when the hook catches it and rethrows something of its own, and an attempt whose restore request was still waiting for its answer when the interruption ran keeps the interruption. So a hook that ends its own client — aborting the client abortSignal or calling stop() — after its request was answered and then rejects still reports its own refusal, while a client stopped or aborted from outside reports that shutdown exactly as an ordinary shutdown does. A hook still working when the attempt ends reaches no refusal, and one it reaches afterwards never rewrites the finished attempt.
What ends the client, and what reconnects. Exactly three refusals end it, each a TypedSocketConnectionRestoreDeniedError: the hook's own refusal, which carries the error the hook threw as its standard cause, so the refusal's reason and data reach the consumer; the exhausted restoration deadline; and exhausted retained-callback capacity. The two bounds are this package's own and carry no cause. Everything else that fails a restoration is an ordinary connection failure the client reconnects from, including a transport failure, an interrupted restoration, and a connection that changed under the hook — the peer closing while the hook is finishing.
- On the first connection attempt,
createClient()rejects with the refusal and the client is already stopped. - On a reconnect, the client publishes one
restoreDenieddiagnostic carrying the refusal, the attempt,maxRetries, and the redacted endpoint, then settles ondisconnected. It never offers itself again.
What the consumer still owns. A refused client releases itself the way a failed createClient() does: no socket, no reconnect or deferral timer, and the listener it registered on the consumer's abortSignal removed, so stop() afterwards is the documented idempotent no-op. Subscriptions to statusSubject and diagnosticsSubject stay the consumer's to unsubscribe.
Throw TypedSocketRestoreDeferral instead when the refusal is temporary.
Deferring a refused registration
A server may refuse a peer for a stated period instead of permanently, for example while a protocol rollout is in progress. Throw TypedSocketRestoreDeferral from restoreConnection to close that attempt cleanly, wait, and offer the peer again:
import { TypedResponseError } from '@api.global/typedrequest';
import { TypedSocketRestoreDeferral } from '@api.global/typedsocket';
const client = await TypedSocket.createClient(clientRouter, serverUrl, {
restoreConnection: async ({ createTypedRequest }) => {
try {
await createTypedRequest<IOfferRegistration>('offerRegistration').fire(
{ nodeName: 'pallet-a' },
);
} catch (errorArg) {
if (
errorArg instanceof TypedResponseError
&& errorArg.errorData?.reason === 'protocol-incompatible'
) {
throw new TypedSocketRestoreDeferral(5 * 60 * 1000);
}
throw errorArg;
}
},
});retryAfterMsmust be a positive safe integer of at mostTYPEDSOCKET_MAX_RESTORE_DEFERRAL_MS(3,600,000). Non-finite, negative, zero, fractional, and larger values are refused byRangeErrorat construction, and thatRangeErrorreaches the client as an ordinary restore denial.- A deferral does not consume a reconnect retry:
retryCountand the exponential backoff both stay where they were, so a peer refused for days keeps its retries for real connection failures. A refusal consumes its scheduled retry and then ends the client. - A deferral is honoured only while reconnection is possible, so
autoReconnect: false, a stopped or aborted client, and exhausted retries surface the deferral to the caller instead. - The deferred attempt runs on its own timer, detached from the attempt that deferred it, so a long-refused client never nests reconnect chains. That timer is referenced, exactly like a pending reconnect delay: a pending deferral keeps the host process alive until it fires or the client stops, because a client-only process that exited during the window would never offer itself again.
stop()and the clientabortSignalcancel a pending deferral, so shutdown never waits for one. - When the first connection attempt is deferred,
createClient()resolves with a client in thereconnectingstate instead of rejecting: a refused peer stays up and keeps its workloads. UsestatusSubjectordiagnosticsSubjectto observe when it becomesconnected. - Every deferral publishes a
restoreDeferreddiagnostic carryingretryAfterMs, the unchangedattempt,maxRetries, and the redacted endpoint.
Explicit server targets
Client requests target their server implicitly because the client owns one current physical connection. Server-initiated requests always require an explicit ISmartServeConnectionWrapper:
const target = await typedSocket.findTargetConnectionByTag('account', {
accountId: 'account-123',
});
if (target) {
const response = await typedSocket
.createTypedRequest<IGreetRequest>('greet', target, {
timeoutMs: 15_000,
})
.fire({ name: 'server push' });
}Inside a server handler, bind follow-up work to the request's exact trusted peer:
applicationRouter.addTypedHandler(
new TypedHandler<IGreetRequest>('greet', async ({ name }, tools) => {
const target = typedSocket.getServerConnectionForRequest(tools);
typedSocket.setServerTag(target, 'authenticated', { subject: 'user-123' });
return { message: `Hello, ${name}!` };
}),
);findTargetConnection(), findAllTargetConnections(), and their tag variants return only live peers attached to this TypedSocket's generated routing surfaces. There is no implicit single-peer server fallback in v8.
VirtualStreams
TypedSocket 8 supplies TypedRequest 8's IVirtualStreamTransport for each handshake-ready physical peer. TypedRequest serializes only the JSON-compatible descriptor in the parent envelope; ordered Uint8Array chunks travel as bounded binary frames on that exact peer.
All stream facades expose protocol, direction, streamId, optional contentType and integrity, opened, completion, closed, and abort(). Senders add send(), writable, and close(). Receivers add receive(), readable, accept(), and reject(). Concurrent sender calls may fill the existing bounded admission window; authorization and frame transmission remain same-stream ordered, and each promise still resolves only after the receiver dequeues that exact logical chunk. close() waits for every admitted send before emitting FIN.
receive() returns one complete logical chunk at a time and undefined at graceful EOF. Dequeued bytes reach the application immediately while the corresponding bounded ACK write completes independently. ACK write failures still reject stream completion, and accept() waits for pending ACK writes before sending acceptance. The receiver must call accept() after draining EOF. completion resolves with the shared acceptance receipt; abnormal termination rejects it. Direct receive() and readable consumption are mutually exclusive.
Bounded application acceptance
Receivers can finish application processing, such as archive repacking and a durable metadata commit, before calling accept(). Both endpoints independently limit this phase to 30 seconds by default. A send creator can select acceptanceTimeoutMs on createRegistration() or the server createVirtualStream() facade. A receiver uses the locally configured receiverAcceptanceTimeoutMs on TypedSocket.createClient(), TypedSocket.createServer(), or VirtualStreamManager construction. That receiver policy applies to every stream received by that socket or manager, including receive creators. Receive creators cannot set the sender-only registration option.
const server = TypedSocket.createServer(applicationRouter, {
receiverAcceptanceTimeoutMs: 600_000,
});
const registration = client.virtualStreams.createRegistration({
creatorDirection: 'send',
acceptanceTimeoutMs: 600_000,
});Both options are snapshotted and validated as integer milliseconds from 1 through 3,600,000 (one hour). Neither option is serialized: the sender cannot extend the receiver's policy. The sender's fixed deadline starts after FIN transmission settles. The receiver's fixed deadline starts after validated FIN and drainage of all retained chunks and acknowledgements. Other traffic, clock changes, and authorization revalidation never renew these deadlines. The default runtime uses a monotonic clock; custom runtimes without monotonicNow() use a single fixed duration timer.
Opening, chunk delivery, unread payloads, FIN transmission, and ACCEPT transmission retain their existing transport deadlines and resource ceilings. The parent TypedRequest timeout is also unchanged. Applications whose processing outlives the parent request should return an admission response promptly, own the continuing processing operation, and call accept() only after the application commit completes. Observe completion rejection throughout processing, including after readable EOF: abort and join owned source/storage work before releasing its resources. closed alone does not mean acceptance or application commit. A timeout sends RESET (or closes a failed transport), rejects completion on both endpoints, and joins transport cleanup.
The descriptor, binary frames, and handshake remain virtual-stream-v1. Existing Socket 8 peers remain compatible and retain their own 30-second processing limit; a longer acceptance wait requires each receiving peer to configure its own policy in a version that supports it.
Client-created streams with manager registrations
Application-level client streams use the advanced manager registration API, then bind the registration to TypedRequest's public facade:
import { VirtualStream } from '@api.global/typedrequest';
const transport = client.virtualStreams.getClientTransport();
if (!transport) {
throw new Error('TypedSocket client transport is not connected');
}
const registration = client.virtualStreams.createRegistration({
creatorDirection: 'send',
contentType: 'application/octet-stream',
});
const stream = VirtualStream.fromRegistration({
transport,
registration,
});
const request = client.createTypedRequest<IUploadRequest>('upload');
const responsePromise = request.fire({ stream });
await stream.opened;
await stream.send(new Uint8Array([1, 2, 3]));
await stream.close();
const response = await responsePromise;Client registrations do not take a peer target: the manager binds them to the current handshake-ready client generation. Registration is synchronous and silent. Its descriptor capability expires if it is not consumed, and TypedRequest owns disposal after the facade is created. Do not hand-build descriptors or reuse them across connections.
The matching server handler receives a requester-local send stream as local receive:
applicationRouter.addTypedHandler(
new TypedHandler<IUploadRequest>('upload', async ({ stream }) => {
let storedBytes = 0;
while (true) {
const chunk = await stream.receive();
if (chunk === undefined) break;
storedBytes += chunk.byteLength;
}
await stream.accept();
return { storedBytes };
}),
);Server-created streams and the authorization facade
Server application code should create streams through TypedSocket.createVirtualStream(). This facade requires an exact attached target and a configured virtualStreamAuthorizationAdapter; it synchronously binds application authorization before publishing a descriptor.
interface IStreamAuthorization {
subject: string;
objectId: string;
revision: string;
}
declare function isStreamAuthorityCurrent(
authority: IStreamAuthorization,
operation: 'open' | 'chunk' | 'accept' | 'reject',
): Promise<boolean>;
const typedSocket = TypedSocket.createServer(applicationRouter, {
virtualStreamAuthorizationAdapter: {
bind: (authorization, context) => {
const authority = authorization as IStreamAuthorization;
if (!authority.subject || !authority.objectId || !authority.revision) {
throw new Error('Invalid stream authorization');
}
const target = context.target;
return {
revalidate: async ({ operation, connection, abortSignal }) => {
if (
abortSignal.aborted
|| connection.side !== 'server'
|| connection.peer !== target
) return false;
return await isStreamAuthorityCurrent(authority, operation);
},
};
},
},
});bind() must return synchronously and must provide revalidate(context). Revalidation runs with the exact connection binding, operation (open, chunk, accept, or reject), deadline, and abort signal. Return literal true only while the application authority remains current. Primitive boolean results settle their authorization slot synchronously. Promise results remain charged against the unchanged limits of four active revalidations per connection and 128 per server until the callback actually settles, including after caller-visible timeout or abort. A fifth per-connection or 129th server-wide asynchronous revalidation fails closed instead of raising those limits.
declare function loadBoundedObjectChunks(
objectId: string,
): AsyncIterable<Uint8Array>;
applicationRouter.addTypedHandler(
new TypedHandler<IDownloadRequest>('download', async ({ objectId }, tools) => {
const target = typedSocket.getServerConnectionForRequest(tools);
const stream = typedSocket.createVirtualStream({
target,
creatorDirection: 'send',
contentType: 'application/octet-stream',
authorization: {
subject: 'user-123',
objectId,
revision: 'revision-7',
} satisfies IStreamAuthorization,
});
const production = (async () => {
await stream.opened;
for await (const chunk of loadBoundedObjectChunks(objectId)) {
await stream.send(chunk);
}
await stream.close();
})();
void production.catch((error) => stream.abort(error).catch(() => undefined));
return { stream };
}),
);Finite streams may include { algorithm: 'sha256', byteLength, digest } integrity metadata. Open-ended streams omit integrity. Capabilities are opaque, single-use, peer-scoped, generation-scoped, and short-lived.
Connection tags
Client tag mutation is default-deny. Declare exact rules on the server:
const typedSocket = TypedSocket.createServer(applicationRouter, {
clientTagPolicy: {
authorizationTimeoutMs: 2_000,
rules: [{
name: 'workspace',
owner: 'client',
validateAndAuthorize: ({ payload, operation, abortSignal }) => {
if (abortSignal.aborted) return false;
if (operation === 'remove') return true;
return typeof payload === 'object'
&& payload !== null
&& typeof Reflect.get(payload, 'workspaceId') === 'string';
},
}],
},
});await client.setTag('workspace', { workspaceId: 'workspace-123' });
await client.removeTag('workspace');Use setServerTag() and removeServerTag() for authentication, roles, registration state, and other server-owned metadata. A server-owned name remains protected from client overwrite after removal. Desired client tags are reconciled after reconnect only after restoreConnection succeeds.
Do not use a universal allClients broadcast tag. Assign a dedicated application tag and target only clients that implement the corresponding server-initiated method.
Lifecycle, limits, and diagnostics
statusSubjectpublishesnew,connecting,connected,disconnected, andreconnectingtransitions.diagnosticsSubjectpublishes bounded structured events for invariant closes, peer rejection, reconnect scheduling, restore deferral, restore denial, reconnect exhaustion, and tag denial. Subscribers own unsubscription; the subject does not complete.- A refused connection restoration is terminal: the client stops reconnecting, publishes one
restoreDenieddiagnostic, releases itself, and ends ondisconnected. stop()disables client reconnect, cancels a pending restore deferral, rejects pending work, closes streams, and releases router registrations. Serverstop()detaches TypedSocket state and composition but does not stop SmartServe.- Request
timeoutMsandabortSignalare supported on both sides. Server requests are cancelled on target disconnect or server stop. - Timeout, caller abort, requester disconnect, target disconnect, client/server stop, and connection replacement abort the exact remote handler through
TypedTools.abortSignal. - Cancellation identity binds the physical peer, generated routing surface, connection generation, method, correlation ID, and fresh
requestInstanceId. The control method is__typedsocket_cancelRequestwith protocoltypedrequest-cancellation-v1and is never broadcast or forwarded to another peer. - Handshake and cancellation-control envelopes carry their own fresh top-level
requestInstanceId. A cancellation payload separately names the exact application request instance being cancelled. Malformed, oversized, or authority-mismatched identities fail closed. - A cancellation that wins routing before handler registration creates an
early-canceltombstone and delivers an already-aborted signal when that exact request registers. Completion replaces it with a terminal tombstone, so a late cancellation is ignored; reuse of the correlation ID is safe only with a fresh request instance ID. - Active handlers are capped at 64 per connection and 1,024 per TypedSocket. Disconnect, stop, and the five-minute handler lifetime abort and detach work, but global active accounting is released only when TypedRequest calls the registration's
complete()callback after the handler promise settles. Internal cancellation stats report that full unsettled count asactive, its detached subset asdetachedActive, and only live attached states asconnections. - Early/terminal cancellation tombstones are capped at 1,024 per connection and 16,384 per TypedSocket and expire after ten seconds. Per-connection overage closes that connection. On global pressure, largest-consumer selection includes the triggering connection and deterministically closes the oldest attached connection with the largest tombstone share. The triggering cancellation is admitted only when another consumer is reclaimed and the triggering connection remains open.
- Client
limitsmay lower package ceilings but cannot raise them. Untrusted network deployments should lower text-frame and queue ceilings to match the application protocol. - The stream transport bounds connections, active streams, logical chunk size, queued chunks and bytes, raw frames, outbound frames, revalidations, arrival accounting, tombstones, capability lifetime, outstanding protocol progress, and cleanup time. An open stream with no queued or retained work may remain idle indefinitely.
- Incoming binary frames are validated immediately, then dispatched in independent per-stream FIFO lanes. A slow application authorization callback on one stream cannot block data or control on another. RESET immediately cancels its own lane, including a held authority callback; it discards pending work instead of waiting behind it. The 64-frame / 2 MiB inbound budget includes active work; CHUNK traffic leaves eight admission slots for control and each stream may retain at most 40 incomplete frames before its own stream is reset. Malformed framing and the aggregate hard ceiling still close the connection.
- Server binary output pipelines up to eight native sends, with exact frame identity accounting until every native settlement arrives, including after detach. Logical chunks fill a sliding eight-fragment window; logical sequence, authorization, receiver dequeue ACKs, and FIN ordering stay intact. Both server and client reserve eight outbound entries for control and yield to data after at most four controls. This removes application-level cross-stream waits; a single WebSocket still has ordered transport delivery, including when carried over HTTP/3.
- Client binary output submits one frame immediately when idle, reserving a later continuation so repeated or reentrant sends cannot drain synchronously without a bound. Continuation turns send at most eight frames and 256 KiB. Control frames remain preferred, but queued data progresses after at most four controls. Requested follow-up turns use a cancellable immediate task when available, a shared MessageChannel task queue in browsers, and a zero-delay timer only when neither exists. A prospective 2 MiB
WebSocket.bufferedAmounthigh watermark pauses dequeue until the socket reaches the 1 MiB low watermark; the existing 30-second progress deadline still bounds blocked work. - The default runtime uses a monotonic clock to share client frame settlements across one connection deadline timer and move one lazy endpoint progress deadline instead of replacing its timer. Custom manager runtimes may provide
monotonicNow()for the same consolidation; otherwise duration timers preserve the exact timeout boundary. - Invalid framing, overflow, integrity failure, authority revocation, handshake failure, and timeout fail closed. Physical-peer identity and raw-frame settlement identity are never inferred from caller-controlled payloads.
Selected stream defaults are 32 KiB physical frames, 4 MiB logical chunks, 32 active streams per connection, a 10-second handshake and capability deadline, a 30-second deadline while protocol progress or retained chunks are outstanding, and a 5-second revalidation deadline. Root exports provide the principal package ceilings and timeout constants.
VirtualStream benchmark
Run the tracked Node loopback benchmark from the repository with:
pnpm run benchmark:virtualstreamThe default workload transfers 64 MiB in each direction as 64 KiB chunks over one connection and one outstanding send per stream. It reports throughput, sender latency, event-loop delay, memory deltas, and final transport accounting. Use --send-window=<1..8>, --streams=8 or --streams=32, --chunk-kib=<1..4096>, --total-mib=<value>, --integrity, and --delay-receive --receive-delay-ms=<value> to exercise pipelining, concurrency, chunk, integrity, and receiver-delay cases. The benchmark always enforces the unchanged stream and connection chunk/byte ceilings. --assert enforces the 100 MiB/s and 2 ms p95 targets only for the default 64 MiB, 64 KiB, one-stream, one-send-window acceptance workload.
Public API summary
TypedSocket
| API | Side | Purpose |
| --- | --- | --- |
| TypedSocket.createClient(router, url, options?) | client | Connects (over TCP, or a Unix socket with unixSocketPath), handshakes, restores connection state, and reconciles tags. |
| TypedSocket.createServer(routerOrRouters, options?) | server | Composes private protocol and application routers before SmartServe construction. |
| getServerRoutingSurface(applicationRouter?) | server | Returns the exact generated router SmartServe must bind during upgrade. |
| attachSmartServe(smartServe) | server | Attaches lifecycle, authority guards, and peer-scoped stream resolvers. |
| createTypedRequest(method, target?, options?) | both | Creates a TypedRequest; server calls require an explicit target. |
| createVirtualStream(options) | server | Creates an exact authorized stream facade for one attached peer. |
| getServerConnectionForRequest(tools) | server | Resolves the exact trusted physical peer for an incoming request. |
| setTag() / removeTag() | client | Mutates an explicitly allowed client-owned tag. |
| setServerTag() / removeServerTag() | server | Maintains protected server-owned peer metadata. |
| findTargetConnection*() / findAllTargetConnections*() | server | Finds live attached targets by predicate or tag. |
| getStatus() | both | Returns the current connection status. |
| stop() | both | Releases all TypedSocket-owned lifecycle state. |
virtualStreams
VirtualStreamManager is the peer-scoped transport manager. Client applications may use getClientTransport() and createRegistration() for explicit creator registrations. getStats() exposes bounded transport accounting. Server registration is not exposed on the manager; server applications must use the authorization-enforcing TypedSocket.createVirtualStream() facade.
Migration to version 8
- Replace TypedRequest 7 and SmartServe 5 with TypedRequest 8.0.3 or newer and SmartServe 6.2.4 or newer within majors 6 and 7 so the transport resolves one TypedRouter major.
- Treat wire major 8 as intentionally incompatible with TypedSocket 7. The exact handshake requires package major 8,
typedrequest-cancellation-v1, and a fresh request instance ID; there is no compatibility fallback. - TypedSocket 7 application APIs remain otherwise unchanged.
- When migrating directly from version 6, remove
nativeByteCapabilityMode,nativeMessageCapabilityMode,nativeBytes, message-channel APIs, and native-specific authorization adapters. - Replace native stream DTOs with
TVirtualStream<'send' | 'receive'>from@api.global/typedrequest-interfaces. - Replace
fromSmartServe()with the requiredcreateServer()→ SmartServe construction →attachSmartServe()order. - Pass
getServerRoutingSurface(applicationRouter)to SmartServe, not the application router itself. - Always pass an explicit server target to
createTypedRequest(). - Configure
virtualStreamAuthorizationAdapterand usecreateVirtualStream()for server-created streams. - Treat a package-major handshake failure as terminal; there is no JSON-only or capability-disabled fallback.
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.md 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.
