# @api.global/typedsocket

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

Latest version **8.2.0** (published 2026-09-14) · MIT license · 0 weekly downloads

## Install

```sh
npm install @api.global/typedsocket
pnpm add @api.global/typedsocket
yarn add @api.global/typedsocket
bun add @api.global/typedsocket
```

## Health

**Score 55/100 (C)** — status: active.

Positive: no vulnerabilities; recently updated; high maintenance score.

Warnings: low downloads; no types; no esm support.

## Facts

| | |
|---|---|
| Version | 8.2.0 |
| Published | 2026-09-14 |
| First published | 2023-08-06 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Task Venture Capital GmbH |
| Maintainers | lossless |
| Keywords | WebSocket, Type Safety, Real-time Communication, Client-Server Architecture, TypeScript, Networking |

## Links

- npm: https://www.npmjs.com/package/@api.global/typedsocket
- npm.io page: https://npm.io/package/@api.global/typedsocket

## Alternatives

- [@opentelemetry/exporter-zipkin](https://npm.io/package/@opentelemetry/exporter-zipkin.md) — 14.8M weekly downloads
- [pusher-js](https://npm.io/package/pusher-js.md) — 2.0M weekly downloads
- [browserify](https://npm.io/package/browserify.md) — 1.7M weekly downloads
- [sqs-consumer](https://npm.io/package/sqs-consumer.md) — 1.7M weekly downloads
- [@sanity/eventsource](https://npm.io/package/@sanity/eventsource.md) — 930.8K weekly downloads

## Recent versions

- 8.2.0 (latest) — 2026-09-14
- 8.1.0 — 2026-09-09
- 8.0.3 — 2026-08-30
- 8.0.2 — 2026-08-29
- 8.0.1 — 2026-08-23
- 8.0.0 — 2026-08-15
- 7.1.0 — 2026-08-05
- 7.0.0 — 2026-08-05
- 6.3.0 — 2026-08-04
- 6.2.0 — 2026-08-04
- 6.1.0 — 2026-08-03
- 6.0.0 — 2026-08-02
- 5.1.2 — 2026-07-31
- 5.1.1 — 2026-07-30
- 5.1.0 — 2026-07-29
- … 18 more at https://npm.io/package/@api.global/typedsocket/versions

## 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/](https://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/](https://code.foss.global/) account to submit Pull Requests directly.

## Install

```bash
pnpm add @api.global/typedsocket @api.global/typedrequest @api.global/typedrequest-interfaces
```

Server applications also need SmartServe:

```bash
pnpm add @push.rocks/smartserve
```

TypedSocket 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 major 6. 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-v1` streams;
- SmartServe fixes the peer's `routingSurface` and `transportOwner` during 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 `connected` state 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:

```typescript
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 6

Construction order is part of the transport contract:

1. Create and populate the application `TypedRouter`.
2. Call `TypedSocket.createServer()`.
3. Obtain the generated transport routing surface with `getServerRoutingSurface()`.
4. Construct SmartServe with that routing surface and the exact `webSocketTransportOwner` object.
5. Call `attachSmartServe()`.
6. Start SmartServe.

```typescript
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:

```typescript
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.

```typescript
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.

### 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:

```typescript
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.

## 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`:

```typescript
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:

```typescript
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. 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.

```typescript
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:

```typescript
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`:

```typescript
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.

```typescript
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.

```typescript
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:

```typescript
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';
      },
    }],
  },
});
```

```typescript
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

- `statusSubject` publishes `new`, `connecting`, `connected`, `disconnected`, and `reconnecting` transitions.
- `diagnosticsSubject` publishes bounded structured events for invariant closes, peer rejection, reconnect scheduling or exhaustion, and tag denial. Subscribers own unsubscription; the subject does not complete.
- `stop()` disables client reconnect, rejects pending work, closes streams, and releases router registrations. Server `stop()` detaches TypedSocket state and composition but does not stop SmartServe.
- Request `timeoutMs` and `abortSignal` are 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_cancelRequest` with protocol `typedrequest-cancellation-v1` and 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-cancel` tombstone 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 as `active`, its detached subset as `detachedActive`, and only live attached states as `connections`.
- 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 `limits` may 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 runs in turns of 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.bufferedAmount` high 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:

```bash
pnpm run benchmark:virtualstream
```

The 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, 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.1 or newer 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 required `createServer()` → SmartServe construction → `attachSmartServe()` order.
- Pass `getServerRoutingSurface(applicationRouter)` to SmartServe, not the application router itself.
- Always pass an explicit server target to `createTypedRequest()`.
- Configure `virtualStreamAuthorizationAdapter` and use `createVirtualStream()` 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](./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<br>
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.

---
_Source: https://npm.io/package/@api.global/typedsocket · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
