lixnet 1.5.1 → 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.
@@ -1,6 +1,7 @@
1
1
  import type { StandardSchemaV1 } from "./standardschema";
2
2
  import type { LixnetRequest } from "./util/request";
3
3
  import type { LixnetResponse } from "./util/response";
4
+ import type { LixnetSerializer } from "./serializer";
4
5
  export type DebugLogger = ({ error, message, cause, }: {
5
6
  error?: boolean;
6
7
  message: string;
@@ -17,6 +18,18 @@ export type FunctionOutput<T> = T extends (...args: any) => infer R ? Awaited<R>
17
18
  export type LXNCallArgs<TInput, TOptions> = {} extends TInput ? [input?: TInput, options?: TOptions] : [input: TInput, options?: TOptions];
18
19
  export type LXNServerHandler<Input, Output> = (input: Input) => Promise<Output> | Output;
19
20
  export type LXN_ServerClient_EventType = object;
21
+ /**
22
+ * The `fetch` a client sends requests with. Any `fetch`-compatible function works, e.g. a
23
+ * wrapper adding auth, or `(url, init) => server.handle(new Request(url, init))` for tests and SSR.
24
+ */
25
+ export type LixnetFetch = (url: string, init: RequestInit) => Promise<Response>;
26
+ export type LixnetClientOptions = {
27
+ rpcUrl: string;
28
+ /** Defaults to the global `fetch`, looked up on every call. */
29
+ fetch?: LixnetFetch;
30
+ /** Must be the server's serializer (e.g. `lixnetJSON`), or absent when the server has none. */
31
+ serializer?: LixnetSerializer;
32
+ };
20
33
  /** A schema whose parsed output must match the event's declared input type. */
21
34
  export type LXNEventSchema<Events, K extends keyof Events> = StandardSchemaV1<any, FunctionInput<Events[K]>>;
22
35
  /** One registration per event name, so arrays passed to `on()` are typed per element. */
@@ -25,9 +38,11 @@ export type LXNEventEntries<Events, TEntry extends {
25
38
  }> = TEntry[keyof Events & string][];
26
39
  /** The inbound request passed to handlers (Next.js–style `cookies()` / `headers()`). */
27
40
  export type { LixnetRequest as LXN_ServerClient_Request } from "./util/request";
28
- export type LixnetServerInjections = {
41
+ /** Injected into every handler next to its input. `ctx` holds what the route's middleware added. */
42
+ export type LixnetServerInjections<TCtx = {}> = {
29
43
  request: LixnetRequest;
30
44
  response: LixnetResponse;
45
+ ctx: TCtx;
31
46
  };
32
47
  /** The `stream` object injected into stream event handlers. */
33
48
  export type LXNStreamEmitter<TChunk> = {
@@ -36,3 +51,24 @@ export type LXNStreamEmitter<TChunk> = {
36
51
  /** Aborted when the client disconnects; `emit` becomes a no-op from then on. */
37
52
  signal: AbortSignal;
38
53
  };
54
+ export type LixnetStreamInjections<TCtx = {}> = LixnetServerInjections<TCtx> & {
55
+ stream: LXNStreamEmitter<unknown>;
56
+ };
57
+ /** Input keys a route can't use: the injections next to the input would overwrite them. */
58
+ export type LixnetReservedKey = keyof LixnetServerInjections;
59
+ /** Stream routes also reserve `stream`. */
60
+ export type LixnetStreamReservedKey = keyof LixnetStreamInjections;
61
+ /**
62
+ * Type-only check that a route's input (its schema's output or contract input) has no reserved key.
63
+ * `{}` when it's fine; otherwise `{ [TField]: "Lixnet: input key \"ctx\" is reserved" }`, which,
64
+ * intersected into the route, turns `TField` into a compile error naming the key.
65
+ */
66
+ export type LixnetReservedInputCheck<TInput, TReserved extends PropertyKey, TField extends PropertyKey> = 0 extends 1 & TInput ? {} : [Extract<KeysOf<TInput>, TReserved>] extends [never] ? {} : {
67
+ [P in TField]: `Lixnet: input key "${Extract<KeysOf<TInput>, TReserved> & string}" is reserved`;
68
+ };
69
+ /** Keys of every member of a union. */
70
+ type KeysOf<T> = T extends unknown ? keyof T : never;
71
+ /** {@link LixnetReservedInputCheck} for each schema of the `routes` constructor option. */
72
+ export type LixnetReservedSchemasCheck<TSchemas, TReserved extends PropertyKey> = {
73
+ [K in Extract<keyof TSchemas, string>]: TSchemas[K] extends StandardSchemaV1 ? LixnetReservedInputCheck<StandardSchemaV1.InferOutput<TSchemas[K]>, TReserved, "schema"> : {};
74
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A Proxy where every property is a function calling that event: `caller.greet(input, options)`
3
+ * is `call("greet", input, options)`. `then` (and symbols) read as undefined, so the caller isn't
4
+ * mistaken for a Promise when awaited or returned from an async function.
5
+ */
6
+ export default function createCaller<T>(call: (event: string, ...args: any[]) => unknown): T;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A Proxy where every property is a function calling that event: `caller.greet(input, options)`
3
+ * is `call("greet", input, options)`. `then` (and symbols) read as undefined, so the caller isn't
4
+ * mistaken for a Promise when awaited or returned from an async function.
5
+ */
6
+ export default function createCaller(call) {
7
+ const functions = new Map();
8
+ return new Proxy(Object.create(null), {
9
+ get(_, event) {
10
+ if (typeof event !== "string" || event === "then")
11
+ return undefined;
12
+ let fn = functions.get(event);
13
+ if (!fn) {
14
+ fn = (...args) => call(event, ...args);
15
+ functions.set(event, fn);
16
+ }
17
+ return fn;
18
+ },
19
+ });
20
+ }
@@ -1,11 +1,40 @@
1
1
  import type { LixnetResponse } from "./response";
2
- /** The `{ error, code, data?, detail? }` body for an errored response (also used for stream error frames). */
3
- export declare function errorBody(response: LixnetResponse): {
4
- detail?: string | undefined;
5
- data?: {} | null | undefined;
2
+ export type ErrorBody = {
6
3
  error: string | null;
7
4
  code: string;
5
+ data?: unknown;
6
+ detail?: string;
7
+ serializer?: string;
8
8
  };
9
+ /**
10
+ * The `{ data }` body of a successful response. With a serializer, `data` is always encoded
11
+ * (`undefined` included, so it round-trips); without one, no data is sent as `null`.
12
+ * Throws whatever the serializer throws.
13
+ */
14
+ export declare function dataBody(response: LixnetResponse): {
15
+ data: unknown;
16
+ serializer?: string;
17
+ };
18
+ /**
19
+ * The `{ error, code, data?, detail? }` body of an errored response. `data` is encoded with the
20
+ * serializer; if that fails, `data` is dropped and the error kept.
21
+ */
22
+ export declare function errorBody(response: LixnetResponse): ErrorBody;
23
+ /** `dataBody` as JSON text. Throws a 500 `LixnetError` "Could not serialize the response" on failure. */
24
+ export declare function dataJSON(response: LixnetResponse): string;
25
+ /** `errorBody` as JSON text. Never throws: `data` that JSON can't carry (e.g. BigInt, circular) is dropped. */
26
+ export declare function errorJSON(response: LixnetResponse): string;
27
+ /**
28
+ * One NDJSON stream frame, `{"stream":true,"data":…}\n` (plus `"serializer"` on the first frame).
29
+ * Throws like `dataJSON` if the chunk can't be encoded.
30
+ */
31
+ export declare function streamFrame(response: LixnetResponse, chunk: unknown): string;
32
+ /** The final NDJSON error frame (`errorJSON` plus a newline; echoes the serializer if it's the first frame). Never throws. */
33
+ export declare function errorFrame(response: LixnetResponse): string;
9
34
  /** Defaults, then staged header sets/deletes, then staged cookies as `Set-Cookie`. */
10
35
  export declare function buildResponseHeaders(response: LixnetResponse, defaultHeaders: Record<string, string>, contentType: string): Headers;
36
+ /**
37
+ * The default formatter. Throws a 500 `LixnetError` when the success body can't be encoded;
38
+ * the server turns that into an error response.
39
+ */
11
40
  export default function (defaultHeaders: Record<string, string>): (this: LixnetResponse) => Response;
@@ -1,12 +1,95 @@
1
- import { codeForStatus } from "../error";
2
- /** The `{ error, code, data?, detail? }` body for an errored response (also used for stream error frames). */
1
+ import { LixnetError, codeForStatus } from "../error";
2
+ /** The serializer name to echo, if this body/frame should carry it. */
3
+ function echo(response) {
4
+ return response.serializerEchoed ? undefined : response.serializer?.name;
5
+ }
6
+ function serializeFailure(cause) {
7
+ return new LixnetError("INTERNAL", "Could not serialize the response", { cause });
8
+ }
9
+ /**
10
+ * The `{ data }` body of a successful response. With a serializer, `data` is always encoded
11
+ * (`undefined` included, so it round-trips); without one, no data is sent as `null`.
12
+ * Throws whatever the serializer throws.
13
+ */
14
+ export function dataBody(response) {
15
+ const serializer = response.serializer;
16
+ if (!serializer)
17
+ return { data: response.responseData ?? null };
18
+ return { data: serializer.serialize(response.responseData), serializer: serializer.name };
19
+ }
20
+ /**
21
+ * The `{ error, code, data?, detail? }` body of an errored response. `data` is encoded with the
22
+ * serializer; if that fails, `data` is dropped and the error kept.
23
+ */
3
24
  export function errorBody(response) {
4
- return {
25
+ const body = {
5
26
  error: response.responseError,
6
27
  code: response.responseErrorCode ?? codeForStatus(response.responseCode || 500),
7
- ...(response.responseErrorData !== undefined ? { data: response.responseErrorData } : {}),
8
- ...(response.responseErrorDetail ? { detail: response.responseErrorDetail } : {}),
9
28
  };
29
+ let data = response.responseErrorData;
30
+ if (data !== undefined && response.serializer) {
31
+ try {
32
+ data = response.serializer.serialize(data);
33
+ }
34
+ catch {
35
+ data = undefined;
36
+ }
37
+ }
38
+ if (data !== undefined)
39
+ body.data = data;
40
+ if (response.responseErrorDetail)
41
+ body.detail = response.responseErrorDetail;
42
+ const name = echo(response);
43
+ if (name !== undefined)
44
+ body.serializer = name;
45
+ return body;
46
+ }
47
+ /** `dataBody` as JSON text. Throws a 500 `LixnetError` "Could not serialize the response" on failure. */
48
+ export function dataJSON(response) {
49
+ try {
50
+ return JSON.stringify(dataBody(response));
51
+ }
52
+ catch (cause) {
53
+ throw serializeFailure(cause);
54
+ }
55
+ }
56
+ /** `errorBody` as JSON text. Never throws: `data` that JSON can't carry (e.g. BigInt, circular) is dropped. */
57
+ export function errorJSON(response) {
58
+ const body = errorBody(response);
59
+ try {
60
+ return JSON.stringify(body);
61
+ }
62
+ catch {
63
+ delete body.data;
64
+ return JSON.stringify(body);
65
+ }
66
+ }
67
+ /**
68
+ * One NDJSON stream frame, `{"stream":true,"data":…}\n` (plus `"serializer"` on the first frame).
69
+ * Throws like `dataJSON` if the chunk can't be encoded.
70
+ */
71
+ export function streamFrame(response, chunk) {
72
+ const serializer = response.serializer;
73
+ let text;
74
+ try {
75
+ if (!serializer)
76
+ return JSON.stringify({ stream: true, data: chunk }) + "\n";
77
+ const data = serializer.serialize(chunk);
78
+ text = response.serializerEchoed
79
+ ? JSON.stringify({ stream: true, data })
80
+ : JSON.stringify({ stream: true, data, serializer: serializer.name });
81
+ }
82
+ catch (cause) {
83
+ throw serializeFailure(cause);
84
+ }
85
+ response.serializerEchoed = true;
86
+ return text + "\n";
87
+ }
88
+ /** The final NDJSON error frame (`errorJSON` plus a newline; echoes the serializer if it's the first frame). Never throws. */
89
+ export function errorFrame(response) {
90
+ const text = errorJSON(response) + "\n";
91
+ response.serializerEchoed = true;
92
+ return text;
10
93
  }
11
94
  /** Defaults, then staged header sets/deletes, then staged cookies as `Set-Cookie`. */
12
95
  export function buildResponseHeaders(response, defaultHeaders, contentType) {
@@ -61,22 +144,22 @@ export function buildResponseHeaders(response, defaultHeaders, contentType) {
61
144
  }
62
145
  return headers;
63
146
  }
147
+ /**
148
+ * The default formatter. Throws a 500 `LixnetError` when the success body can't be encoded;
149
+ * the server turns that into an error response.
150
+ */
64
151
  export default function (defaultHeaders) {
65
- function formatter() {
66
- const headers = buildResponseHeaders(this, defaultHeaders, "application/json");
152
+ return function formatter() {
67
153
  if (this.responseError) {
68
- return Response.json(errorBody(this), {
154
+ return new Response(errorJSON(this), {
69
155
  status: this.responseCode || 500,
70
- headers: headers,
156
+ headers: buildResponseHeaders(this, defaultHeaders, "application/json"),
71
157
  });
72
158
  }
73
- return Response.json({
74
- data: this.responseData,
75
- }, {
159
+ const body = dataJSON(this);
160
+ return new Response(body, {
76
161
  status: this.responseCode || 200,
77
- headers: headers,
162
+ headers: buildResponseHeaders(this, defaultHeaders, "application/json"),
78
163
  });
79
- }
80
- ;
81
- return formatter;
164
+ };
82
165
  }
@@ -68,9 +68,14 @@ export declare function wrapLixnetRequest(request: Request, response: {
68
68
  value?: string;
69
69
  options?: unknown;
70
70
  }>;
71
- }): LixnetRequest;
71
+ },
72
+ /**
73
+ * The request body, when the server already read it. Body methods (`json()`, `text()`,
74
+ * `body`, `clone()`, ...) are then served from it, so the request never needs cloning.
75
+ */
76
+ body?: string): LixnetRequest;
72
77
  /** Wraps `request` so its cookie/header writes are staged on `response`. */
73
- export declare function createLixnetRequest(request: Request, response: LixnetResponse): LixnetRequest;
78
+ export declare function createLixnetRequest(request: Request, response: LixnetResponse, body?: string): LixnetRequest;
74
79
  /** @deprecated Use {@link LixnetCookies}. */
75
80
  export type ReadonlyRequestCookies = LixnetCookies;
76
81
  /** @deprecated Use {@link LixnetHeaders}. */
@@ -125,7 +125,8 @@ export class LixnetHeaders {
125
125
  h;
126
126
  mut;
127
127
  constructor(headers, mut) {
128
- this.h = new Headers(headers);
128
+ // Not copied: incoming request headers are immutable, and writes go to the response.
129
+ this.h = headers;
129
130
  this.mut = mut;
130
131
  }
131
132
  get(name) {
@@ -206,9 +207,32 @@ export class LixnetHeaders {
206
207
  this.mut.deleteHeader(name);
207
208
  }
208
209
  }
210
+ /** `Request` body readers answered from the already-read body instead of the (consumed) stream. */
211
+ function bodyReaders(request, body) {
212
+ let bytes;
213
+ const getBytes = () => (bytes ??= new TextEncoder().encode(body));
214
+ let stream;
215
+ return {
216
+ text: async () => body,
217
+ json: async () => JSON.parse(body),
218
+ bytes: async () => getBytes().slice(),
219
+ arrayBuffer: async () => getBytes().slice().buffer,
220
+ blob: async () => new Blob([body], { type: request.headers.get("content-type") ?? "" }),
221
+ formData: () => new Response(body, { headers: request.headers }).formData(),
222
+ clone: () => new Request(request, { body }),
223
+ get body() {
224
+ return (stream ??= new Response(body).body);
225
+ },
226
+ bodyUsed: false,
227
+ };
228
+ }
209
229
  /** Used by the server only; not part of the public package API. */
210
- export function wrapLixnetRequest(request, response) {
211
- const snapshot = new Headers(request.headers);
230
+ export function wrapLixnetRequest(request, response,
231
+ /**
232
+ * The request body, when the server already read it. Body methods (`json()`, `text()`,
233
+ * `body`, `clone()`, ...) are then served from it, so the request never needs cloning.
234
+ */
235
+ body) {
212
236
  const cookieMut = {
213
237
  setCookie: (name, value, options) => response.cookie(name, value, options),
214
238
  deleteCookie: (name, options) => response.deleteCookie(name, options),
@@ -234,18 +258,20 @@ export function wrapLixnetRequest(request, response) {
234
258
  return out;
235
259
  },
236
260
  };
261
+ // Created on first use: most handlers never touch cookies or headers.
262
+ let cookies;
263
+ let headers;
264
+ const injected = {
265
+ cookies: () => (cookies ??= new LixnetCookies(request.headers.get("cookie"), cookieMut)),
266
+ headers: () => (headers ??= new LixnetHeaders(request.headers, headerMut)),
267
+ };
268
+ const readers = body === undefined ? undefined : bodyReaders(request, body);
237
269
  return new Proxy(request, {
238
270
  get(target, prop, receiver) {
239
- if (prop === "cookies") {
240
- return function cookies() {
241
- return new LixnetCookies(snapshot.get("cookie"), cookieMut);
242
- };
243
- }
244
- if (prop === "headers") {
245
- return function headers() {
246
- return new LixnetHeaders(snapshot, headerMut);
247
- };
248
- }
271
+ if (prop in injected)
272
+ return injected[prop];
273
+ if (readers && prop in readers)
274
+ return readers[prop];
249
275
  // `receiver` here is this Proxy itself, not `target`. Native accessor properties
250
276
  // (e.g. Workers' `Request.prototype.cf`) are branded getters that check `this` is
251
277
  // the real internal object — invoking them with the Proxy as receiver throws
@@ -255,14 +281,7 @@ export function wrapLixnetRequest(request, response) {
255
281
  });
256
282
  }
257
283
  /** Wraps `request` so its cookie/header writes are staged on `response`. */
258
- export function createLixnetRequest(request, response) {
259
- return wrapLixnetRequest(request, {
260
- header: response.header.bind(response),
261
- deleteHeader: response.deleteHeader.bind(response),
262
- cookie: response.cookie.bind(response),
263
- deleteCookie: response.deleteCookie.bind(response),
264
- responseHeaders: response.responseHeaders,
265
- responseHeaderDeletes: response.responseHeaderDeletes,
266
- responseCookies: response.responseCookies,
267
- });
284
+ export function createLixnetRequest(request, response, body) {
285
+ // LixnetResponse has every member wrapLixnetRequest needs; it's only ever called as a method.
286
+ return wrapLixnetRequest(request, response, body);
268
287
  }
@@ -1,3 +1,4 @@
1
+ import type { LixnetSerializer } from "../serializer";
1
2
  export type CookieBaseOptions = {
2
3
  domain?: string;
3
4
  path?: string;
@@ -9,13 +10,14 @@ export type CookieFullOptions = CookieBaseOptions & {
9
10
  maxAge?: number;
10
11
  };
11
12
  export declare class LixnetResponse {
13
+ /** Raw data as staged (not yet encoded); `undefined` until a handler returns or calls `data()`. */
12
14
  responseData: any;
13
15
  responseError: string | null;
14
16
  /** Extra error information, only sent when the server has `exposeErrors` enabled. */
15
17
  responseErrorDetail: string | null;
16
18
  /** Error code sent as `code`; derived from the status when not set. */
17
19
  responseErrorCode: string | null;
18
- /** JSON-serialisable data sent with the error as `data`. */
20
+ /** Data sent with the error as `data` (encoded with the serializer, if any, when the body is built). */
19
21
  responseErrorData: unknown;
20
22
  responseCode: number;
21
23
  responseHeaders: Record<string, string>;
@@ -25,8 +27,16 @@ export declare class LixnetResponse {
25
27
  value?: string;
26
28
  options?: CookieFullOptions;
27
29
  }>;
28
- constructor({ formatter }: {
30
+ /** The server's serializer: the body helpers in `getDefaultFormatter.ts` encode `data` with it. */
31
+ serializer?: LixnetSerializer;
32
+ /**
33
+ * Set once a stream frame has been written: only the first frame echoes the serializer's name.
34
+ * Flipped by `streamFrame`/`errorFrame` themselves; plain JSON bodies always echo it.
35
+ */
36
+ serializerEchoed: boolean;
37
+ constructor({ formatter, serializer, }: {
29
38
  formatter: (this: LixnetResponse) => Response;
39
+ serializer?: LixnetSerializer;
30
40
  });
31
41
  data(data: any): void;
32
42
  header(headerName: string, headerValue: string): void;
@@ -13,21 +13,29 @@ function assertCookie(cookieName, options) {
13
13
  }
14
14
  }
15
15
  export class LixnetResponse {
16
- responseData;
16
+ /** Raw data as staged (not yet encoded); `undefined` until a handler returns or calls `data()`. */
17
+ responseData = undefined;
17
18
  responseError = null;
18
19
  /** Extra error information, only sent when the server has `exposeErrors` enabled. */
19
20
  responseErrorDetail = null;
20
21
  /** Error code sent as `code`; derived from the status when not set. */
21
22
  responseErrorCode = null;
22
- /** JSON-serialisable data sent with the error as `data`. */
23
+ /** Data sent with the error as `data` (encoded with the serializer, if any, when the body is built). */
23
24
  responseErrorData = undefined;
24
25
  responseCode = 0;
25
26
  responseHeaders = {};
26
27
  responseHeaderDeletes = new Set();
27
28
  responseCookies = {};
28
- constructor({ formatter }) {
29
- this.responseData = null;
29
+ /** The server's serializer: the body helpers in `getDefaultFormatter.ts` encode `data` with it. */
30
+ serializer;
31
+ /**
32
+ * Set once a stream frame has been written: only the first frame echoes the serializer's name.
33
+ * Flipped by `streamFrame`/`errorFrame` themselves; plain JSON bodies always echo it.
34
+ */
35
+ serializerEchoed = false;
36
+ constructor({ formatter, serializer, }) {
30
37
  this.format = formatter;
38
+ this.serializer = serializer;
31
39
  }
32
40
  data(data) {
33
41
  this.responseData = data;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lixnet",
3
- "version": "1.5.1",
3
+ "version": "1.7.0",
4
4
  "author": "nitlix-hq",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -21,6 +21,12 @@
21
21
  "files": [
22
22
  "dist"
23
23
  ],
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "typecheck": "tsc --noEmit && tsc --noEmit --strict --skipLibCheck --module esnext --moduleResolution bundler --target esnext --verbatimModuleSyntax tests/*.ts tests/peer/*.ts tests/router/*.ts",
27
+ "test": "bun tests/run-all.ts",
28
+ "bench": "bun benchmarks/serializer.ts"
29
+ },
24
30
  "type": "module",
25
31
  "devDependencies": {
26
32
  "@types/bun": "latest",