lixnet 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,10 @@
1
1
  <div align="center">
2
- <h1>Lixnet</h1>
2
+ <h1>
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="./assets/wordmark-v2-white.svg?v=4">
5
+ <img alt="Lixnet" src="./assets/wordmark-v2-black.svg?v=4" width="293">
6
+ </picture>
7
+ </h1>
3
8
  <h3>Lightweight, type-safe RPC over HTTP and WebSockets.<br />The tRPC and Next.js Server Actions, but for everyone.</h3>
4
9
 
5
10
  <a href="https://github.com/Nitlix/Lixnet">
@@ -45,6 +50,8 @@ It’s designed to be minimal: no codegen, no schema registry, no client bundler
45
50
  - [Server: `LixnetServer`](#server-lixnetserver)
46
51
  - [Errors](#errors-lixneterror)
47
52
  - [CORS](#cors)
53
+ - [Middleware](#middleware)
54
+ - [Serialization](#serialization)
48
55
  - [Client: `LixnetClient`](#client-lixnetclient)
49
56
  - [Handlers: `request` and `response`](#handlers-request-and-response)
50
57
  - [WebSockets: `LixnetPeer`](#websockets-lixnetpeer)
@@ -279,12 +286,32 @@ or
279
286
  { "error": "...", "code": "UNAUTHORIZED", "data": {} }
280
287
  ```
281
288
 
289
+ With a `serializer`, both shapes also carry `"serializer": "<name>"` and `data` is in that serializer's format (see [Serialization](#serialization)).
290
+
282
291
  ### Server configuration
283
292
 
284
293
  `new LixnetServer({ ... })` supports:
285
294
 
286
295
  - **`defaultHeaders`**: headers included on every response (unless deleted later)
287
- - **`formatter`**: customize how `LixnetResponse` becomes a `Response`
296
+ - **`formatter`**: customize how `LixnetResponse` becomes a `Response`. It sees raw values: `this.responseData` (`undefined` when nothing was staged) and `this.responseErrorData` are not encoded yet. Build bodies with `lixnetDataBody(this)` / `lixnetErrorBody(this)`: they apply the server's `serializer` and add the `serializer` echo that clients check. `lixnetResponseHeaders(this, defaultHeaders, contentType)` gives the default headers plus staged headers and cookies.
297
+
298
+ ```ts
299
+ import { LixnetServer, LixnetResponse, lixnetDataBody, lixnetErrorBody, lixnetResponseHeaders } from "lixnet";
300
+
301
+ const defaultHeaders = { "x-powered-by": "lixnet" };
302
+
303
+ new LixnetServer({
304
+ defaultHeaders,
305
+ formatter(this: LixnetResponse) {
306
+ const headers = lixnetResponseHeaders(this, defaultHeaders, "application/json");
307
+ headers.set("x-formatted", "yes");
308
+ if (this.responseError) {
309
+ return Response.json(lixnetErrorBody(this), { status: this.responseCode || 500, headers });
310
+ }
311
+ return Response.json(lixnetDataBody(this), { status: this.responseCode || 200, headers });
312
+ },
313
+ });
314
+ ```
288
315
  - **`logger`** + **`debugLog`**: currently used for invalid JSON logging
289
316
 
290
317
  Example:
@@ -335,7 +362,12 @@ Built-in errors (both servers, same messages as before plus a `code`):
335
362
  | `"Event not found"` (unknown `event`) | `NOT_FOUND` | 404 |
336
363
  | `"Invalid input"` (schema failure) | `INVALID_INPUT` | 400 |
337
364
  | `"Origin not allowed"` (with `cors`) | `FORBIDDEN` | 403 |
338
- | `"Handler error"` (handler threw a non-`LixnetError`) | `INTERNAL` | 500 |
365
+ | `"Invalid input encoding"` (`serializer` couldn't decode `input`) | `BAD_REQUEST` | 400 |
366
+ | `"This server uses the …"` / `"This server has no serializer, …"` | `BAD_REQUEST` | 400 |
367
+ | `"Handler error"` (handler or middleware threw a non-`LixnetError`) | `INTERNAL` | 500 |
368
+ | `"Could not serialize the response"` (output JSON/the serializer can't encode, e.g. circular) | `INTERNAL` | 500 |
369
+
370
+ `server.handle(...)` always resolves to a `Response`. Error `data` that can't be encoded is dropped and the error kept.
339
371
 
340
372
  `INVALID_INPUT` always includes the validation issues, so forms can show errors per field:
341
373
 
@@ -379,6 +411,97 @@ export default {
379
411
  - Every response, errors included, gets `Access-Control-Allow-Origin` (the caller's origin, plus `Vary: Origin`) and `Access-Control-Allow-Credentials` when enabled.
380
412
  - Requests whose `Origin` isn't allowed get `403 { "error": "Origin not allowed" }` without running the handler. Requests without an `Origin` header (server-to-server, SSR) are not CORS and pass through.
381
413
 
414
+ ## Middleware
415
+
416
+ Optional. Middleware runs before a handler and can reject the call, add typed fields to the handler's `ctx`, set headers or cookies, or answer without running the handler. It works on `LixnetServer` and `LixnetStreamServer`.
417
+
418
+ ```ts
419
+ import { LixnetError, LixnetServer, lixnetMiddleware, type LixnetMiddlewareOptions } from "lixnet";
420
+
421
+ const auth = lixnetMiddleware(async ({ request, next }) => {
422
+ const user = await getUser(request.cookies().get("session")?.value);
423
+ if (!user) throw new LixnetError("UNAUTHORIZED", "Sign in first");
424
+ return next({ user }); // merged into ctx for everything after this
425
+ });
426
+
427
+ // Reads what `auth` added, so it annotates the ctx it needs.
428
+ const admin = lixnetMiddleware(async ({ ctx, next }: LixnetMiddlewareOptions<{ user: User }>) => {
429
+ if (!ctx.user.isAdmin) throw new LixnetError("FORBIDDEN", "Admins only");
430
+ return next();
431
+ });
432
+
433
+ const timing = lixnetMiddleware(async ({ event, response, next }) => {
434
+ const start = Date.now();
435
+ try {
436
+ return await next(); // the rest of the chain: later middleware, validation, handler
437
+ } finally {
438
+ response.header("Server-Timing", `${event};dur=${Date.now() - start}`);
439
+ }
440
+ });
441
+
442
+ export const server = new LixnetServer({ use: [timing] }) // every route
443
+ .route("health", { handler: () => "ok" })
444
+ .use(auth) // routes added after this line
445
+ .route("me", { handler: ({ ctx }) => ctx.user }) // ctx.user is typed
446
+ .route("ban", {
447
+ schema: z.object({ id: z.string() }),
448
+ use: [admin], // this route only, after the server's
449
+ handler: ({ id }) => banUser(id),
450
+ });
451
+ ```
452
+
453
+ - **Where it applies:** the `use` constructor option covers every route. `.use(...)` covers only routes registered after it, so `health` above stays public. A route's own `use` (in `.route`, `on` or a `routes` entry) runs after the server's.
454
+ - **Order:** constructor `use` → `.use(...)` calls → the route's `use` → schema validation → handler. Middleware gets `{ request, response, event, input, ctx, next }`.
455
+ - **Middleware runs before validation.** `input` is deserialized but **not validated**: treat it as untrusted (transforms and coercions haven't run yet). An unauthenticated caller gets your `401`, not validation issues that reveal the input shape. A schema failure makes `next()` reject with an `INVALID_INPUT` `LixnetError`, so logging or error-mapping middleware can catch it.
456
+ - **Contract:** return `next()`'s result, throw (a `LixnetError` keeps its code and status), or return `{ output }` to answer without validation or the handler (for example from a cache). Call `next()` at most once and only while the middleware is running: after it returned or threw, `next()` rejects and the handler never runs. Calling `next()` twice or returning anything else answers `500 "Handler error"`. A `next()` you forget to await can't crash the process, but its error is lost, so always `return next()` or `return await next()`.
457
+ - **Typing:** keep the `.use(...)` result by chaining or reassigning it, because it returns a server whose `ctx` type includes what was added. With an `Events` contract, write `new LixnetServer<Events>().use(auth)` and the `on(...)` handlers see `ctx.user`.
458
+ - **Compile-time ctx checks:** what each middleware reads from `ctx` is checked everywhere (`use` option, `.use(...)`, a route's `use`, `routes` entries, `on`), in order. `use: [auth, admin]` and `.use(auth, admin)` compile; `[admin, auth]`, or `admin` with no `auth` before it, is an error on `admin`. Two limits: inline middleware (`use: [async ({ ctx, next }) => ...]`) gets `ctx: any` and isn't checked, so define it with `lixnetMiddleware` and `LixnetMiddlewareOptions<Ctx>`; and a list kept in a plain array variable is checked against the server's ctx only (write it inline or `as const` to get the in-order check).
459
+ - **Streams:** on `LixnetStreamServer`, middleware wraps the whole stream; see "HTTP streaming" in [FOR_AGENTS.md](FOR_AGENTS.md).
460
+ - **Limitation:** in the `routes` option, a schema-less handler's parameter stays `any`. Add a schema, annotate the parameter (`LixnetServerInjections<{ user: User }>`), or use `.route(...)`.
461
+
462
+ Handlers always receive `ctx` (`{}` without middleware), next to `request` and `response`. Those names (and `stream` on stream routes) are **reserved**: a schema output or `Events` input with a `ctx`, `request`, `response` (or `stream`) key is a compile error, `Lixnet: input key "ctx" is reserved`. Rename the field, or `.transform()` it away (only the schema's output counts).
463
+
464
+ ## Serialization
465
+
466
+ Optional. By default inputs and outputs are plain JSON, so a `Date` arrives as a string and `Map`, `Set` and `BigInt` don't survive. Give both sides a `serializer` to keep them:
467
+
468
+ ```ts
469
+ import { LixnetClient, LixnetServer, lixnetJSON } from "lixnet";
470
+
471
+ const server = new LixnetServer({ serializer: lixnetJSON }).route("shift", {
472
+ schema: z.object({ when: z.date() }), // the schema sees a real Date
473
+ handler: ({ when }) => ({ next: new Date(when.getTime() + 86_400_000), tags: new Set(["a"]) }),
474
+ });
475
+
476
+ const client = new LixnetClient<typeof server>({ rpcUrl: "/rpc", serializer: lixnetJSON });
477
+ const { next, tags } = await client.caller.shift({ when: new Date() }); // Date, Set
478
+ ```
479
+
480
+ - **`lixnetJSON`** keeps `Date` (also invalid dates), `Map`, `Set`, `BigInt`, `undefined`, `NaN`/`±Infinity`/`-0`, `RegExp`, `URL`, `Error` (`name` and `message` only, never the stack; arrives as an `Error` with that `name`), `ArrayBuffer`, `DataView` and every typed array (`Uint8Array`, `Int32Array`, `Float64Array`, `BigInt64Array`, ...; a `Buffer` arrives as a `Uint8Array`). Plain JSON passes through unchanged.
481
+ - **What it doesn't keep:** holes in sparse arrays arrive as `null` (like JSON), an object referenced twice arrives as two copies (circular values throw), class instances are sent the way `JSON.stringify` sends them (`toJSON(key)` included), and extremely deep values (around 10k levels) can overflow the stack.
482
+ - **Decoding is strict:** a malformed tagged value is a `400 BAD_REQUEST "Invalid input encoding"` on the server and a `BAD_RESPONSE` `LixnetError` on the client.
483
+ - **Don't mutate what `lixnetJSON.serialize` returns:** for speed it returns its input itself when it's plain JSON, and shares untouched parts otherwise. `lixnetJSON.deserialize` never mutates its input.
484
+ - **Any library works.** A serializer is `{ name, serialize, deserialize }`. For superjson: `{ name: "superjson", serialize: (v) => superjson.serialize(v), deserialize: (v) => superjson.deserialize(v as any) }`. Custom serializers always get `deserialize` called (the "skip decoding" shortcut below is `lixnetJSON`-only).
485
+ - **What it covers:** the input, the output (`response.data(...)` too), error `data` (`response.error(..., { data })` too), stream chunks (`LixnetStreamServer`/`LixnetStreamClient`) and WebSocket calls (`new LixnetPeer({ serializer })`, which both peers need).
486
+ - **Always give routes a schema when a serializer is on.** A schema-less route accepts whatever the caller encodes, so its handler can receive a `Map`, `RegExp` or `BigInt` where it expects a string.
487
+
488
+ ### Mismatches fail loudly
489
+
490
+ The client sends its serializer's `name` in the request body, and a server with a serializer echoes `"serializer": "<name>"` in every JSON body and the first stream frame. Both sides check:
491
+
492
+ - A server with a serializer rejects requests naming another one, or none, with `400 BAD_REQUEST` (`This server uses the "lixnet-json" serializer; give the client the same \`serializer\``). A server without one rejects requests that name one. `"serializer": null` counts as none.
493
+ - A client with a serializer throws a `BAD_RESPONSE` `LixnetError` when a success body or the first stream frame doesn't echo the same name (`Server at <url> did not confirm the "lixnet-json" serializer — is it an older Lixnet or configured without \`serializer\`?`), or when data can't be decoded. Error responses are still thrown as themselves; their `data` is only decoded when the echo matched.
494
+
495
+ | client ↓ / server → | ≤ 1.6.0 | no serializer | serializer |
496
+ | --- | --- | --- | --- |
497
+ | ≤ 1.6.0 | ok | ok (same bytes) | `400 BAD_REQUEST` |
498
+ | no serializer | ok | ok | `400 BAD_REQUEST` |
499
+ | serializer | `BAD_RESPONSE` (the call still ran) | `400 BAD_REQUEST` | ok (same `name`; else `400`) |
500
+
501
+ Turn a serializer on in the server and its clients together. Plain clients (curl, other languages) can't call a server that has a serializer. `LixnetPeer` has **no** negotiation: a peer with another (or no) serializer gets tagged objects without an error, so configure both peers the same.
502
+
503
+ **Performance:** a plain 4.3 KB payload costs about 18% more with `lixnetJSON` than without a serializer on an in-process round trip (12.5 vs 10.5 µs on bun). Plain JSON is detected without allocating and sent as-is, and decoding is skipped when the body has no `"$t"` key. Payloads full of `Date`s or `Map`s cost more. Reproduce with `cd benchmarks && bun serializer.ts`.
504
+
382
505
  ## Client: `LixnetClient`
383
506
 
384
507
  `client.call(event, input, options?)`:
@@ -558,9 +681,16 @@ From `src/exports.ts`:
558
681
  - **`LixnetPeer`**, **`LixnetPeerEvents`**
559
682
  - **`LixnetStreamServer`**, **`LixnetStreamClient`**
560
683
  - **`LixnetResponse`**
684
+ - **`LixnetError`**, **`LIXNET_ERROR_STATUS`**
685
+ - **`lixnetMiddleware`** (types a standalone middleware)
686
+ - **`lixnetJSON`** (built-in serializer)
561
687
 
562
688
  Types:
563
689
 
690
+ - **`LixnetMiddleware`**, **`LixnetMiddlewareOptions`**, **`LixnetMiddlewareResult`**, **`LixnetMiddlewareContext`**, **`LixnetNext`**
691
+ - **`LixnetSerializer`**
692
+ - **`LixnetServerInjections<Ctx>`**, **`LixnetStreamInjections<Ctx>`**
693
+
564
694
  - **`LXN_ServerClient_EventType`**
565
695
  - **`LXNServerHandler`**
566
696
  - **`FunctionInput`**
@@ -570,6 +700,8 @@ Types:
570
700
  ## Contributor docs
571
701
 
572
702
  - **Implementation + extension guide**: [`FOR_AGENTS.md`](FOR_AGENTS.md)
703
+ - **Changelog**: [`CHANGELOG.md`](CHANGELOG.md)
704
+ - **Checks**: `bun run typecheck` (source and tests) and `bun run test` (every test file, each in its own process). CI runs both on every push and pull request, and a release tag publishes to npm only after they pass. `bun run bench` runs the serializer benchmark; it isn't part of CI because timings vary between runs.
573
705
 
574
706
  ## License
575
707
 
package/dist/exports.d.ts CHANGED
@@ -6,9 +6,15 @@ import LixnetStreamServer from "./lib/streamserver";
6
6
  import LixnetStreamClient from "./lib/streamclient";
7
7
  import { LixnetResponse } from "./lib/util/response";
8
8
  import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
9
- export { LixnetServer, LixnetClient, LixnetPeer, LixnetPeerEvents, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
9
+ import { lixnetMiddleware } from "./lib/middleware";
10
+ import { lixnetJSON } from "./lib/serializer";
11
+ import { dataBody as lixnetDataBody, errorBody as lixnetErrorBody, buildResponseHeaders as lixnetResponseHeaders } from "./lib/util/getDefaultFormatter";
12
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetPeerEvents, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, lixnetMiddleware, lixnetJSON, lixnetDataBody, lixnetErrorBody, lixnetResponseHeaders, };
13
+ export type { LixnetMiddleware, LixnetMiddlewareOptions, LixnetMiddlewareResult, LixnetMiddlewareContext, LixnetNext, } from "./lib/middleware";
14
+ export type { LixnetSerializer } from "./lib/serializer";
15
+ export type { ErrorBody as LixnetErrorBody } from "./lib/util/getDefaultFormatter";
10
16
  export type { LixnetErrorCode, LixnetIssue } from "./lib/error";
11
- export type { LixnetRoute, LixnetRoutes, LixnetRouteDefinitions, LixnetRoutesFromDefinitions, LixnetRouteDefinitionInput, LixnetRoutesOption, InferLixnetEvents, } from "./lib/router";
17
+ export type { LixnetRoute, LixnetRoutes, LixnetRouteDefinitions, LixnetRoutesFromDefinitions, LixnetRouteDefinitionInput, LixnetRoutesOption, LixnetRouteUses, InferLixnetEvents, } from "./lib/router";
12
18
  export type { LixnetCookies, LixnetHeaders, LixnetRequest, ReadonlyHeaders, ReadonlyRequestCookies, RequestCookie, } from "./lib/util/request";
13
19
  export type { LXN_ServerClient_EventType, LXNServerHandler, FunctionInput, LXN_ServerClient_Request, LixnetServerInjections, LXNStreamEmitter, LXNCallArgs, LixnetFetch, LixnetClientOptions, LixnetStreamInjections, } from "./lib/types";
14
20
  export type { LixnetPeerInjections } from "./lib/peerevents";
package/dist/exports.js CHANGED
@@ -7,4 +7,7 @@ import LixnetStreamServer from "./lib/streamserver";
7
7
  import LixnetStreamClient from "./lib/streamclient";
8
8
  import { LixnetResponse } from "./lib/util/response";
9
9
  import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
10
- export { LixnetServer, LixnetClient, LixnetPeer, LixnetPeerEvents, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
10
+ import { lixnetMiddleware } from "./lib/middleware";
11
+ import { lixnetJSON } from "./lib/serializer";
12
+ import { dataBody as lixnetDataBody, errorBody as lixnetErrorBody, buildResponseHeaders as lixnetResponseHeaders, } from "./lib/util/getDefaultFormatter";
13
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetPeerEvents, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, lixnetMiddleware, lixnetJSON, lixnetDataBody, lixnetErrorBody, lixnetResponseHeaders, };
@@ -1,5 +1,8 @@
1
1
  import type { FunctionInput, FunctionOutput, LXNCallArgs, LXN_ServerClient_EventType, LixnetClientOptions } from "./types";
2
+ import type { LixnetSerializer } from "./serializer";
2
3
  import type { InferLixnetEvents } from "./router";
4
+ /** The `{ event, input, serializer? }` request body, shared with `LixnetStreamClient`. */
5
+ export declare function requestBody(event: string, input: unknown, serializer?: LixnetSerializer): string;
3
6
  type ExtractRPCResponse<T> = T extends (...args: any) => infer R ? Awaited<R> : never;
4
7
  /** One function per event: `caller.greet({ name })` is `client.call("greet", { name })`. */
5
8
  export type LixnetCaller<Events> = {
@@ -9,13 +12,20 @@ export type LixnetCaller<Events> = {
9
12
  export default class LixnetClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
10
13
  private rpcUrl;
11
14
  private fetcher?;
15
+ private serializer?;
12
16
  /**
13
17
  * Every event as a typed function: `await client.caller.greet({ name: "World" })`.
14
18
  * Destructuring works too (`const { greet } = client.caller`). An event named `then` can only
15
19
  * be called through `call(...)`.
16
20
  */
17
21
  readonly caller: LixnetCaller<Events>;
18
- constructor({ rpcUrl, fetch }: LixnetClientOptions);
22
+ constructor({ rpcUrl, fetch, serializer }: LixnetClientOptions);
19
23
  call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, RequestInit>): Promise<ExtractRPCResponse<Events[K]>>;
20
24
  }
25
+ /**
26
+ * The serializer to decode a value parsed from `text` with. lixnetJSON offers a faster one for
27
+ * fresh `JSON.parse` output (decodes in place, or not at all when `text` has no tagged value);
28
+ * any other serializer is used as-is. Shared with `LixnetStreamClient`.
29
+ */
30
+ export declare function received<S extends LixnetSerializer | undefined>(serializer: S, text: string): S;
21
31
  export {};
@@ -1,19 +1,29 @@
1
1
  import withJsonContentType from "./util/withJsonContentType";
2
2
  import createCaller from "./util/createCaller";
3
- import { LixnetError, codeForStatus, errorFromBody } from "./error";
3
+ import { LixnetError, codeForStatus, decodeResponse, errorFromBody, serializerMismatch } from "./error";
4
+ /** The `{ event, input, serializer? }` request body, shared with `LixnetStreamClient`. */
5
+ export function requestBody(event, input, serializer) {
6
+ // An omitted input is sent as `{}` so the server's schema sees an object.
7
+ const value = input === undefined ? {} : input;
8
+ if (!serializer)
9
+ return JSON.stringify({ event, input: value });
10
+ return JSON.stringify({ event, input: serializer.serialize(value), serializer: serializer.name });
11
+ }
4
12
  /** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
5
13
  export default class LixnetClient {
6
14
  rpcUrl;
7
15
  fetcher;
16
+ serializer;
8
17
  /**
9
18
  * Every event as a typed function: `await client.caller.greet({ name: "World" })`.
10
19
  * Destructuring works too (`const { greet } = client.caller`). An event named `then` can only
11
20
  * be called through `call(...)`.
12
21
  */
13
22
  caller;
14
- constructor({ rpcUrl, fetch }) {
23
+ constructor({ rpcUrl, fetch, serializer }) {
15
24
  this.rpcUrl = rpcUrl;
16
25
  this.fetcher = fetch;
26
+ this.serializer = serializer;
17
27
  this.caller = createCaller((event, ...args) => this.call(event, ...args));
18
28
  }
19
29
  async call(event, ...[input, options = {}]) {
@@ -23,16 +33,38 @@ export default class LixnetClient {
23
33
  ...options,
24
34
  method: "POST",
25
35
  headers: withJsonContentType(options.headers),
26
- body: JSON.stringify({ event, input: input === undefined ? {} : input }),
36
+ body: requestBody(event, input, this.serializer),
27
37
  });
28
- const json = await response.json().catch(() => null);
38
+ // As text first: lixnetJSON can skip decoding when the text has no tagged value.
39
+ const text = await response.text().catch(() => "");
40
+ let json = null;
41
+ try {
42
+ json = JSON.parse(text);
43
+ }
44
+ catch { }
29
45
  // Not a Lixnet response, e.g. a proxy's HTML error page.
30
46
  if (json === null || typeof json !== "object") {
31
47
  throw new LixnetError(response.ok ? "BAD_RESPONSE" : codeForStatus(response.status), `Unexpected response from ${this.rpcUrl} (status ${response.status})`, { status: response.status });
32
48
  }
49
+ // A server with a serializer echoes its name; anything else means the two disagree on encoding.
50
+ const serializer = this.serializer;
51
+ const confirmed = json.serializer === serializer?.name;
33
52
  if (typeof json.error === "string") {
34
- throw errorFromBody(json, response.status);
53
+ // Without a confirmed serializer the error is still worth throwing, but its data stays raw.
54
+ throw errorFromBody(json, response.status, confirmed ? received(serializer, text) : undefined, this.rpcUrl);
35
55
  }
36
- return json.data;
56
+ if (!confirmed)
57
+ throw serializerMismatch(this.rpcUrl, serializer?.name, json.serializer, response.status);
58
+ if (!serializer)
59
+ return json.data;
60
+ return decodeResponse(received(serializer, text), json.data, this.rpcUrl, response.status);
37
61
  }
38
62
  }
63
+ /**
64
+ * The serializer to decode a value parsed from `text` with. lixnetJSON offers a faster one for
65
+ * fresh `JSON.parse` output (decodes in place, or not at all when `text` has no tagged value);
66
+ * any other serializer is used as-is. Shared with `LixnetStreamClient`.
67
+ */
68
+ export function received(serializer, text) {
69
+ return (serializer?.deserialize?.["~received"]?.(text) ?? serializer);
70
+ }
@@ -1,4 +1,5 @@
1
1
  import type { StandardSchemaV1 } from "./standardschema";
2
+ import type { LixnetSerializer } from "./serializer";
2
3
  /** Built-in error codes and their default HTTP statuses. Any other string is also a valid code. */
3
4
  export declare const LIXNET_ERROR_STATUS: {
4
5
  readonly BAD_REQUEST: 400;
@@ -20,7 +21,22 @@ export type LixnetIssue = {
20
21
  export declare function toIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>): LixnetIssue[];
21
22
  /** Picks a code for a status that came without one (e.g. `response.code(403)` + `response.error(...)`). */
22
23
  export declare function codeForStatus(status: number): LixnetErrorCode;
23
- /** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
24
+ /**
25
+ * Decodes `value` with the serializer; any failure becomes a `BAD_RESPONSE` `LixnetError` whose
26
+ * `cause` is the decode error. Shared by both clients and `errorFromBody`.
27
+ */
28
+ export declare function decodeResponse(serializer: LixnetSerializer, value: unknown,
29
+ /** The server's URL, for the message. */
30
+ from: string, status?: number, what?: string): unknown;
31
+ /**
32
+ * The `BAD_RESPONSE` thrown when a response's `serializer` echo isn't the client's serializer name
33
+ * (`expected`, `undefined` for a client without one).
34
+ */
35
+ export declare function serializerMismatch(from: string, expected: string | undefined, got: unknown, status?: number): LixnetError;
36
+ /**
37
+ * Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. Returns a
38
+ * `BAD_RESPONSE` error instead if `data` can't be decoded.
39
+ */
24
40
  export declare function errorFromBody(body: {
25
41
  error: string;
26
42
  code?: string;
@@ -28,7 +44,11 @@ export declare function errorFromBody(body: {
28
44
  detail?: string;
29
45
  },
30
46
  /** Omitted for stream error frames (sent after a 200): derived from the code instead. */
31
- status?: number): LixnetError;
47
+ status?: number,
48
+ /** Decodes `data`; pass it only when the server confirmed the same serializer, else `data` stays raw. */
49
+ serializer?: LixnetSerializer,
50
+ /** The server's URL, for messages. */
51
+ from?: string): LixnetError;
32
52
  /**
33
53
  * An error with a machine-readable `code`, an HTTP `status` and optional JSON `data`.
34
54
  *
package/dist/lib/error.js CHANGED
@@ -29,15 +29,54 @@ export function codeForStatus(status) {
29
29
  }
30
30
  return status >= 500 ? "INTERNAL" : "BAD_REQUEST";
31
31
  }
32
- /** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
32
+ /**
33
+ * Decodes `value` with the serializer; any failure becomes a `BAD_RESPONSE` `LixnetError` whose
34
+ * `cause` is the decode error. Shared by both clients and `errorFromBody`.
35
+ */
36
+ export function decodeResponse(serializer, value,
37
+ /** The server's URL, for the message. */
38
+ from, status, what = "the response") {
39
+ try {
40
+ return serializer.deserialize(value);
41
+ }
42
+ catch (cause) {
43
+ throw new LixnetError("BAD_RESPONSE", `Could not deserialize ${what} from ${from}`, { status, cause });
44
+ }
45
+ }
46
+ /**
47
+ * The `BAD_RESPONSE` thrown when a response's `serializer` echo isn't the client's serializer name
48
+ * (`expected`, `undefined` for a client without one).
49
+ */
50
+ export function serializerMismatch(from, expected, got, status) {
51
+ const message = got === undefined
52
+ ? `Server at ${from} did not confirm the "${expected}" serializer — is it an older Lixnet or configured without \`serializer\`?`
53
+ : expected === undefined
54
+ ? `Server at ${from} uses the ${JSON.stringify(got)} serializer; give the client the same \`serializer\``
55
+ : `Server at ${from} uses the ${JSON.stringify(got)} serializer, but the client uses "${expected}"`;
56
+ return new LixnetError("BAD_RESPONSE", message, { status });
57
+ }
58
+ /**
59
+ * Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. Returns a
60
+ * `BAD_RESPONSE` error instead if `data` can't be decoded.
61
+ */
33
62
  export function errorFromBody(body,
34
63
  /** Omitted for stream error frames (sent after a 200): derived from the code instead. */
35
- status) {
36
- return new LixnetError(body.code ?? codeForStatus(status ?? 500), body.error, {
37
- status,
38
- data: body.data,
39
- cause: body.detail,
40
- });
64
+ status,
65
+ /** Decodes `data`; pass it only when the server confirmed the same serializer, else `data` stays raw. */
66
+ serializer,
67
+ /** The server's URL, for messages. */
68
+ from = "the server") {
69
+ const code = body.code ?? codeForStatus(status ?? 500);
70
+ let data = body.data;
71
+ if (serializer && data !== undefined) {
72
+ try {
73
+ data = decodeResponse(serializer, data, from, status, `the data of the "${code}" error (${body.error})`);
74
+ }
75
+ catch (error) {
76
+ return error;
77
+ }
78
+ }
79
+ return new LixnetError(code, body.error, { status, data, cause: body.detail });
41
80
  }
42
81
  /**
43
82
  * An error with a machine-readable `code`, an HTTP `status` and optional JSON `data`.
@@ -0,0 +1,88 @@
1
+ import type { LixnetRequest } from "./util/request";
2
+ import type { LixnetResponse } from "./util/response";
3
+ /**
4
+ * What `next()` resolves to: the handler's (or the next middleware's) `output`. Return it from the
5
+ * middleware. `~ctx` is type-only: it carries the context this middleware added.
6
+ */
7
+ export type LixnetMiddlewareResult<TAdd = {}> = {
8
+ output: unknown;
9
+ readonly "~ctx"?: TAdd;
10
+ };
11
+ /** Runs the rest of the chain. Fields passed in are merged into `ctx` for everything after it. */
12
+ export type LixnetNext = <TAdd extends object = {}>(add?: TAdd) => Promise<LixnetMiddlewareResult<TAdd>>;
13
+ export type LixnetMiddlewareOptions<TCtx = any> = {
14
+ request: LixnetRequest;
15
+ response: LixnetResponse;
16
+ /** The event being called. */
17
+ event: string;
18
+ /**
19
+ * The input, deserialized but **not yet validated**: the route's schema runs after all
20
+ * middleware, right before the handler. Treat it as untrusted.
21
+ */
22
+ input: unknown;
23
+ /** Context added by the middleware that ran before this one. */
24
+ ctx: TCtx;
25
+ next: LixnetNext;
26
+ };
27
+ /**
28
+ * Runs before a handler. Call `next()` (optionally with fields to add to `ctx`) and return its
29
+ * result, throw (e.g. a `LixnetError`) to reject the call, or return `{ output }` to answer
30
+ * without running the handler.
31
+ */
32
+ export type LixnetMiddleware<TAdd extends object = {}, TCtx = any> = (options: LixnetMiddlewareOptions<TCtx>) => LixnetMiddlewareResult<TAdd> | Promise<LixnetMiddlewareResult<TAdd>>;
33
+ type ContextAddedBy<M> = M extends (options: any) => infer R ? Awaited<R> extends LixnetMiddlewareResult<infer TAdd> ? TAdd : {} : {};
34
+ type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
35
+ /**
36
+ * The `ctx` a list of middleware gives the handler: everything each one adds. The bare
37
+ * `LixnetMiddleware[]` constraint (an omitted, uninferred `use`) adds nothing.
38
+ */
39
+ export type LixnetMiddlewareContext<TUse> = readonly LixnetMiddleware<any, any>[] extends TUse ? {} : TUse extends readonly (infer M)[] ? [M] extends [never] ? {} : UnionToIntersection<ContextAddedBy<M>> : {};
40
+ /** The `ctx` a middleware reads: its options' `ctx` type (`any` when it doesn't annotate one). */
41
+ type ContextRequiredBy<M> = M extends (options: infer O) => any ? O extends {
42
+ ctx: infer TCtx;
43
+ } ? TCtx : any : any;
44
+ /**
45
+ * Checks a `use` list against the `ctx` available before it, in order: each middleware may read
46
+ * `TCtx` plus what the ones before it add. A valid list maps to itself; a middleware whose `ctx`
47
+ * isn't provided maps to `LixnetMiddleware<any, …ctx it would get>`, so the compile error points at
48
+ * it and names the missing fields. Non-tuple arrays are checked against `TCtx` only.
49
+ */
50
+ export type LixnetCheckMiddleware<TUse, TCtx> = TUse extends readonly [infer M, ...infer Rest] ? readonly [
51
+ TCtx extends ContextRequiredBy<M> ? M : LixnetMiddleware<any, TCtx>,
52
+ ...LixnetCheckMiddleware<Rest, TCtx & ContextAddedBy<M>>
53
+ ] : readonly LixnetMiddleware<any, TCtx>[];
54
+ /**
55
+ * Intersected into a route (or options) object whose `use` is `TUse`: `{}` when the list passes
56
+ * {@link LixnetCheckMiddleware}, otherwise `{ use: <checked list> }`, so the error lands on the
57
+ * offending middleware while `TUse` (and the handler's `ctx`) is still inferred from `use` alone.
58
+ */
59
+ export type LixnetUseCheck<TUse, TCtx> = TUse extends readonly unknown[] ? TUse extends LixnetCheckMiddleware<TUse, TCtx> ? {} : {
60
+ use?: LixnetCheckMiddleware<TUse, TCtx>;
61
+ } : {};
62
+ /** {@link LixnetUseCheck} for each entry of the `routes` constructor option (`TUses`: each entry's `use`). */
63
+ export type LixnetRouteUsesCheck<TUses, TCtx> = {
64
+ [K in Extract<keyof TUses, string>]: LixnetUseCheck<TUses[K], TCtx>;
65
+ };
66
+ /**
67
+ * Types a middleware defined on its own, so the context it adds is inferred:
68
+ *
69
+ * ```ts
70
+ * const auth = lixnetMiddleware(async ({ request, next }) => {
71
+ * const user = await getUser(request.cookies().get("session")?.value);
72
+ * if (!user) throw new LixnetError("UNAUTHORIZED");
73
+ * return next({ user });
74
+ * });
75
+ * ```
76
+ *
77
+ * To read context added by an earlier middleware, annotate the options:
78
+ * `async ({ ctx, next }: LixnetMiddlewareOptions<{ user: User }>) => ...`.
79
+ */
80
+ export declare function lixnetMiddleware<TAdd extends object = {}, TCtx = any>(middleware: LixnetMiddleware<TAdd, TCtx>): LixnetMiddleware<TAdd, TCtx>;
81
+ /** Runs `stack` in order, then `handler` with the merged context. Resolves to the final output. */
82
+ export declare function runMiddleware(stack: readonly LixnetMiddleware<any, any>[], base: {
83
+ request: LixnetRequest;
84
+ response: LixnetResponse;
85
+ event: string;
86
+ input: unknown;
87
+ }, handler: (ctx: object) => unknown): Promise<unknown>;
88
+ export {};
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Types a middleware defined on its own, so the context it adds is inferred:
3
+ *
4
+ * ```ts
5
+ * const auth = lixnetMiddleware(async ({ request, next }) => {
6
+ * const user = await getUser(request.cookies().get("session")?.value);
7
+ * if (!user) throw new LixnetError("UNAUTHORIZED");
8
+ * return next({ user });
9
+ * });
10
+ * ```
11
+ *
12
+ * To read context added by an earlier middleware, annotate the options:
13
+ * `async ({ ctx, next }: LixnetMiddlewareOptions<{ user: User }>) => ...`.
14
+ */
15
+ export function lixnetMiddleware(middleware) {
16
+ return middleware;
17
+ }
18
+ const noop = () => { };
19
+ /** `next()` lifecycle per middleware. */
20
+ const IDLE = 0;
21
+ const CALLED = 1;
22
+ const RETURNED = 2;
23
+ /** Runs `stack` in order, then `handler` with the merged context. Resolves to the final output. */
24
+ export async function runMiddleware(stack, base, handler) {
25
+ const run = async (index, ctx) => {
26
+ if (index === stack.length)
27
+ return { output: await handler(ctx) };
28
+ let state = IDLE;
29
+ let result;
30
+ try {
31
+ result = await stack[index]({
32
+ ...base,
33
+ ctx,
34
+ next: (add) => {
35
+ let promise;
36
+ if (state === IDLE) {
37
+ state = CALLED;
38
+ promise = run(index + 1, add ? { ...ctx, ...add } : ctx);
39
+ }
40
+ else {
41
+ const misuse = state === CALLED ? "more than once" : "after the middleware returned";
42
+ promise = Promise.reject(new Error(`Lixnet middleware called next() ${misuse} (event "${base.event}")`));
43
+ }
44
+ // An un-awaited next() must never become an unhandled rejection; awaiting still rejects.
45
+ promise.catch(noop);
46
+ return promise;
47
+ },
48
+ });
49
+ }
50
+ finally {
51
+ // Thrown or returned: the response is decided, so the rest of the chain must not run.
52
+ state = RETURNED;
53
+ }
54
+ if (result === null || typeof result !== "object" || !("output" in result)) {
55
+ throw new Error(`Lixnet middleware must return the result of next() or { output } (event "${base.event}")`);
56
+ }
57
+ return result;
58
+ };
59
+ return (await run(0, {})).output;
60
+ }
@@ -2,6 +2,7 @@ import type { InferLixnetEvents } from "./router";
2
2
  import type { LXNCallArgs } from "./types";
3
3
  import type LixnetPeerEvents from "./peerevents";
4
4
  import { LixnetError } from "./error";
5
+ import type { LixnetSerializer } from "./serializer";
5
6
  export type PeerEventInput<T> = T extends (input: infer TInput) => any ? TInput : never;
6
7
  type PeerEventOutput<T> = T extends (...args: any) => infer R ? Awaited<R> : never;
7
8
  export type LixnetPeerCallOptions<TOutput> = {
@@ -28,9 +29,17 @@ export default class LixnetPeer<ThisToThereEvents extends object, ThereToThisEve
28
29
  transmissionLimit: number;
29
30
  transmissionChunksLimit: number;
30
31
  setTransmissionChunksLimit(limit: number): void;
31
- constructor({ events }?: {
32
+ private serializer?;
33
+ /**
34
+ * `serializer` (e.g. `lixnetJSON`) encodes call inputs and callback results, for types JSON
35
+ * can't carry. Both peers must use the same one.
36
+ */
37
+ constructor({ events, serializer, }?: {
32
38
  events?: LixnetPeerEvents<any, any, any>;
39
+ serializer?: LixnetSerializer;
33
40
  });
41
+ private encode;
42
+ private decode;
34
43
  call: Caller<InferLixnetEvents<ThisToThereEvents>>;
35
44
  private getChunkLimits;
36
45
  /** Handlers by event name, from `events` and `on(...)`. */