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.
@@ -0,0 +1,385 @@
1
+ const TAG = "$t";
2
+ const SKIP = Symbol("skip");
3
+ /** Thrown by the fast encode past `MAX_DEPTH`: the value is encoded again, tracking cycles. */
4
+ const DEEP = Symbol("deep");
5
+ const MAX_DEPTH = 500;
6
+ const OBJECT = Object.prototype;
7
+ const ARRAY = Array.prototype;
8
+ /**
9
+ * Binary views, tagged by kind (their `Symbol.toStringTag`, so a Node/Bun `Buffer` is sent as a
10
+ * `Uint8Array`). The payload is the view's own bytes in base64, in the platform's byte order
11
+ * (little-endian on every runtime Lixnet targets).
12
+ */
13
+ const VIEWS = new Map(Object.entries({
14
+ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array,
15
+ Float32Array, Float64Array, BigInt64Array, BigUint64Array, DataView,
16
+ // Feature-detected: not every runtime has it yet.
17
+ ...(globalThis.Float16Array && { Float16Array: globalThis.Float16Array }),
18
+ }));
19
+ const NUMBERS = new Map([["NaN", NaN], ["Infinity", Infinity], ["-Infinity", -Infinity], ["-0", -0]]);
20
+ // Padded base64 (length checked separately). A simple class run: no backtracking stack on large payloads.
21
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
22
+ const INTEGER = /^-?\d+$/;
23
+ function toBase64(bytes) {
24
+ let binary = "";
25
+ for (let i = 0; i < bytes.length; i += 0x8000) {
26
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
27
+ }
28
+ return btoa(binary);
29
+ }
30
+ function fromBase64(base64) {
31
+ if (typeof base64 !== "string" || base64.length % 4 || !BASE64.test(base64))
32
+ fail("invalid base64");
33
+ const binary = atob(base64);
34
+ const bytes = new Uint8Array(binary.length);
35
+ for (let i = 0; i < binary.length; i++)
36
+ bytes[i] = binary.charCodeAt(i);
37
+ return bytes;
38
+ }
39
+ function fail(message) {
40
+ throw new TypeError(`lixnetJSON: ${message}`);
41
+ }
42
+ const isArray = (v, length) => Array.isArray(v) && (length === undefined || v.length === length);
43
+ const isString = (v) => typeof v === "string";
44
+ /** Plain assignment of `__proto__` would set the prototype instead of a key. */
45
+ function setKey(target, key, value) {
46
+ if (key === "__proto__") {
47
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
48
+ }
49
+ else {
50
+ target[key] = value;
51
+ }
52
+ }
53
+ /** Array, Map and Set members can't be dropped, so functions/symbols become `null` like in JSON arrays. */
54
+ function member(value, parents, depth, key) {
55
+ const encoded = encode(value, parents, depth, key, true);
56
+ return encoded === SKIP ? null : encoded;
57
+ }
58
+ /** Tagged form of a built-in type JSON can't carry, or `undefined` for anything else. */
59
+ function special(object) {
60
+ if (object instanceof Date) {
61
+ return { [TAG]: "Date", v: Number.isNaN(object.getTime()) ? null : object.toISOString() };
62
+ }
63
+ if (object instanceof RegExp)
64
+ return { [TAG]: "RegExp", v: [object.source, object.flags] };
65
+ if (typeof URL !== "undefined" && object instanceof URL)
66
+ return { [TAG]: "URL", v: object.href };
67
+ // Name and message only: the stack and cause stay on the side that threw.
68
+ if (object instanceof Error)
69
+ return { [TAG]: "Error", v: [String(object.name), String(object.message)] };
70
+ if (object instanceof ArrayBuffer)
71
+ return { [TAG]: "ArrayBuffer", v: toBase64(new Uint8Array(object)) };
72
+ if (ArrayBuffer.isView(object) && VIEWS.has(object[Symbol.toStringTag])) {
73
+ // Only the view's own bytes, never the rest of a shared buffer.
74
+ const bytes = new Uint8Array(object.buffer, object.byteOffset, object.byteLength);
75
+ return { [TAG]: object[Symbol.toStringTag], v: toBase64(bytes) };
76
+ }
77
+ return undefined;
78
+ }
79
+ /**
80
+ * Copy-on-write: returns `value` itself when `JSON.stringify` already writes it the way lixnetJSON
81
+ * would, so plain JSON costs one read-only walk. An array or object is copied only once one of its
82
+ * members changes (and then only from the first such member on), so untouched subtrees are shared.
83
+ *
84
+ * `key` is what `toJSON(key)` receives, as with `JSON.stringify`. `json` is false for a value that
85
+ * `toJSON` just returned: like `JSON.stringify`, that value's own `toJSON` isn't called again (so
86
+ * if it has one, it's copied into a plain object for `JSON.stringify` not to call it either).
87
+ *
88
+ * `parents` is null on the fast pass, which only counts depth; past `MAX_DEPTH` it throws `DEEP`
89
+ * and `serialize` encodes again with a parents set, which tells a cycle from a deep value.
90
+ * Recursive, so extremely deep values (~10k+ levels) can overflow the stack, as `JSON.stringify` can.
91
+ */
92
+ function encode(value, parents, depth, key, json) {
93
+ switch (typeof value) {
94
+ case "string":
95
+ case "boolean":
96
+ return value;
97
+ case "number":
98
+ if (Number.isFinite(value) && !Object.is(value, -0))
99
+ return value;
100
+ return { [TAG]: "number", v: Object.is(value, -0) ? "-0" : String(value) };
101
+ case "bigint":
102
+ return { [TAG]: "bigint", v: value.toString() };
103
+ case "undefined":
104
+ return { [TAG]: "undefined" };
105
+ case "function":
106
+ case "symbol":
107
+ // Dropped, like JSON.stringify does.
108
+ return SKIP;
109
+ }
110
+ if (value === null)
111
+ return null;
112
+ const object = value;
113
+ if (parents === null) {
114
+ if (depth > MAX_DEPTH)
115
+ throw DEEP;
116
+ }
117
+ else if (parents.has(object)) {
118
+ fail("cannot serialize a circular structure");
119
+ }
120
+ // Plain objects and arrays (the common case) can't be any of the special types.
121
+ const proto = Object.getPrototypeOf(object);
122
+ const plain = proto === OBJECT || proto === ARRAY;
123
+ if (!plain) {
124
+ const tagged = special(object);
125
+ if (tagged !== undefined)
126
+ return tagged;
127
+ }
128
+ const hasToJSON = typeof object.toJSON === "function";
129
+ if (json && hasToJSON)
130
+ return encode(object.toJSON(String(key)), parents, depth, key, false);
131
+ // Only plain objects and arrays without a toJSON can be handed to JSON.stringify as they are:
132
+ // it would call that toJSON, unbox `new Number(1)`, print `JSON.rawJSON` text... So anything
133
+ // else is copied, like before.
134
+ const copy = hasToJSON || !plain;
135
+ parents?.add(object);
136
+ depth++;
137
+ let result;
138
+ if (Array.isArray(object)) {
139
+ const length = object.length;
140
+ let out = copy ? new Array(length) : undefined;
141
+ for (let i = 0; i < length; i++) {
142
+ const item = object[i];
143
+ // Holes in sparse arrays become `null`, as with JSON (not `undefined`).
144
+ const encoded = item === undefined && !(i in object) ? null : member(item, parents, depth, i);
145
+ if (out === undefined) {
146
+ if (encoded === item)
147
+ continue;
148
+ out = new Array(length);
149
+ for (let j = 0; j < i; j++)
150
+ out[j] = object[j];
151
+ }
152
+ out[i] = encoded;
153
+ }
154
+ result = out ?? object;
155
+ }
156
+ else if (!plain && object instanceof Map) {
157
+ // Map and Set members get "" as their toJSON key.
158
+ result = { [TAG]: "Map", v: Array.from(object, ([k, item]) => [member(k, parents, depth, ""), member(item, parents, depth, "")]) };
159
+ }
160
+ else if (!plain && object instanceof Set) {
161
+ result = { [TAG]: "Set", v: Array.from(object, (item) => member(item, parents, depth, "")) };
162
+ }
163
+ else {
164
+ const keys = Object.keys(object);
165
+ let out = copy ? {} : undefined;
166
+ for (let i = 0; i < keys.length; i++) {
167
+ const k = keys[i];
168
+ const item = object[k];
169
+ const encoded = encode(item, parents, depth, k, true);
170
+ if (out === undefined) {
171
+ if (encoded === item)
172
+ continue;
173
+ out = {};
174
+ for (let j = 0; j < i; j++)
175
+ setKey(out, keys[j], object[keys[j]]);
176
+ }
177
+ if (encoded !== SKIP)
178
+ setKey(out, k, encoded);
179
+ }
180
+ // A plain object that has a `$t` key of its own is wrapped so it isn't read as a tagged value.
181
+ result = Object.hasOwn(object, TAG) ? { [TAG]: "object", v: out ?? object } : out ?? object;
182
+ }
183
+ parents?.delete(object);
184
+ return result;
185
+ }
186
+ function decodeObject(object, owned) {
187
+ if (object === null || typeof object !== "object" || Array.isArray(object))
188
+ fail("object tag needs an object");
189
+ const source = object;
190
+ const keys = Object.keys(source);
191
+ if (owned) {
192
+ // In place: only members that decode to something else are written back.
193
+ for (let i = 0; i < keys.length; i++) {
194
+ const item = source[keys[i]];
195
+ if (item === null || typeof item !== "object")
196
+ continue;
197
+ const decoded = decode(item, true);
198
+ if (decoded !== item)
199
+ setKey(source, keys[i], decoded);
200
+ }
201
+ return source;
202
+ }
203
+ const out = {};
204
+ for (let i = 0; i < keys.length; i++)
205
+ setKey(out, keys[i], decode(source[keys[i]], false));
206
+ return out;
207
+ }
208
+ /**
209
+ * Strict: every tag checks its payload and throws a TypeError on anything the encoder can't produce.
210
+ * `owned` (Lixnet's own call sites, on fresh `JSON.parse` output) decodes arrays and plain objects
211
+ * in place; otherwise they're copied and the input is left untouched.
212
+ */
213
+ function decode(value, owned) {
214
+ if (value === null || typeof value !== "object")
215
+ return value;
216
+ if (Array.isArray(value)) {
217
+ if (!owned)
218
+ return value.map((item) => decode(item, false));
219
+ for (let i = 0; i < value.length; i++) {
220
+ const item = value[i];
221
+ if (item === null || typeof item !== "object")
222
+ continue;
223
+ const decoded = decode(item, true);
224
+ if (decoded !== item)
225
+ value[i] = decoded;
226
+ }
227
+ return value;
228
+ }
229
+ const object = value;
230
+ const tag = object[TAG];
231
+ if (tag === undefined)
232
+ return decodeObject(object, owned);
233
+ const v = object.v;
234
+ switch (tag) {
235
+ case "number":
236
+ if (!NUMBERS.has(v))
237
+ fail("invalid number");
238
+ return NUMBERS.get(v);
239
+ case "bigint":
240
+ if (!isString(v) || !INTEGER.test(v))
241
+ fail("invalid bigint");
242
+ return BigInt(v);
243
+ case "undefined":
244
+ return undefined;
245
+ case "Date": {
246
+ if (v !== null && !isString(v))
247
+ fail("invalid Date");
248
+ const date = new Date(v === null ? NaN : v);
249
+ if (v !== null && Number.isNaN(date.getTime()))
250
+ fail("invalid Date");
251
+ return date;
252
+ }
253
+ case "RegExp":
254
+ if (!isArray(v, 2) || !isString(v[0]) || !isString(v[1]))
255
+ fail("invalid RegExp");
256
+ try {
257
+ return new RegExp(v[0], v[1]);
258
+ }
259
+ catch {
260
+ fail("invalid RegExp");
261
+ }
262
+ case "URL":
263
+ if (!isString(v))
264
+ fail("invalid URL");
265
+ try {
266
+ return new URL(v);
267
+ }
268
+ catch {
269
+ fail("invalid URL");
270
+ }
271
+ case "Error": {
272
+ if (!isArray(v, 2) || !isString(v[0]) || !isString(v[1]))
273
+ fail("invalid Error");
274
+ const error = new Error(v[1]);
275
+ error.name = v[0];
276
+ return error;
277
+ }
278
+ case "ArrayBuffer":
279
+ return fromBase64(v).buffer;
280
+ case "Map":
281
+ if (!isArray(v) || !v.every((entry) => isArray(entry, 2)))
282
+ fail("invalid Map");
283
+ return new Map(v.map(([key, item]) => [decode(key, owned), decode(item, owned)]));
284
+ case "Set":
285
+ if (!isArray(v))
286
+ fail("invalid Set");
287
+ return new Set(v.map((item) => decode(item, owned)));
288
+ case "object":
289
+ return decodeObject(v, owned);
290
+ }
291
+ const View = isString(tag) ? VIEWS.get(tag) : undefined;
292
+ if (!View)
293
+ fail(`unknown tag ${JSON.stringify(tag)}`);
294
+ const bytes = fromBase64(v);
295
+ const size = View.BYTES_PER_ELEMENT ?? 1;
296
+ if (bytes.length % size)
297
+ fail(`invalid ${tag} length`);
298
+ return View === Uint8Array ? bytes : new View(bytes.buffer, 0, bytes.length / size);
299
+ }
300
+ /** Whether a primitive needs a tag: anything but strings, booleans and finite numbers other than -0. */
301
+ function taggedPrimitive(v) {
302
+ // Number.isFinite/Object.is, not arithmetic tricks: those made Bun's JIT unstable here (2-4x).
303
+ return typeof v === "number" ? !Number.isFinite(v) || Object.is(v, -0) : typeof v !== "string" && typeof v !== "boolean";
304
+ }
305
+ /**
306
+ * The fast check `serialize` runs first: allocates nothing and stops at the first thing
307
+ * `JSON.stringify` wouldn't write the way lixnetJSON does. Conservative: anything other than a
308
+ * plain object or array (`Object.prototype` / `Array.prototype`), any `toJSON` key, an own `$t`
309
+ * key, a tagged primitive or a very deep (or circular) value answers true, and `encode` decides.
310
+ * This walk is the whole cost of plain JSON, so it's tuned for Bun/JSC (see the comments).
311
+ */
312
+ function needsEncoding(value, depth) {
313
+ if (depth > MAX_DEPTH)
314
+ return true;
315
+ const proto = Object.getPrototypeOf(value);
316
+ if (proto === ARRAY) {
317
+ if (value.toJSON !== undefined)
318
+ return true;
319
+ for (let i = 0; i < value.length; i++) {
320
+ const item = value[i];
321
+ if (typeof item === "object" ? item !== null && needsEncoding(item, depth + 1) : taggedPrimitive(item))
322
+ return true;
323
+ }
324
+ return false;
325
+ }
326
+ if (proto !== OBJECT || value.toJSON !== undefined || Object.hasOwn(value, TAG))
327
+ return true;
328
+ // for-in is ~2x faster than Object.keys here. It would also visit enumerable keys someone added
329
+ // to Object.prototype, which can only make the answer more conservative.
330
+ for (const key in value) {
331
+ const item = value[key];
332
+ if (typeof item === "object" ? item !== null && needsEncoding(item, depth + 1) : taggedPrimitive(item))
333
+ return true;
334
+ }
335
+ return false;
336
+ }
337
+ function serialize(value) {
338
+ // Plain JSON (the common case) is returned as it is.
339
+ if (typeof value === "object" ? value === null || !needsEncoding(value, 0) : !taggedPrimitive(value))
340
+ return value;
341
+ let encoded;
342
+ try {
343
+ encoded = encode(value, null, 0, "", true);
344
+ }
345
+ catch (error) {
346
+ if (error !== DEEP)
347
+ throw error;
348
+ // Deep or circular: again, with cycle tracking.
349
+ encoded = encode(value, new Set(), 0, "", true);
350
+ }
351
+ return encoded === SKIP ? { [TAG]: "undefined" } : encoded;
352
+ }
353
+ const NAME = "lixnet-json";
354
+ const ownedDecoder = { name: NAME, serialize, deserialize: (value) => decode(value, true) };
355
+ const passThrough = { name: NAME, serialize, deserialize: (value) => value };
356
+ /** Public: copies, so a caller's own object is never modified. */
357
+ const deserialize = Object.assign((value) => decode(value, false), {
358
+ // Lixnet only uses this on fresh `JSON.parse` output it owns, so it decodes in place, and skips
359
+ // decoding when the text has no `"$t"` at all (then there's no tagged value to decode). A key
360
+ // written with an escape (`"\u0024t"`) gets past the text check, but then simply stays a plain
361
+ // object: it can't turn into another type, so that's acceptable.
362
+ "~received": (text) => (hasTagKey(text) ? ownedDecoder : passThrough),
363
+ });
364
+ /**
365
+ * Whether `text` contains `"$t"`. Searches for `$t` and checks the quotes around it: much faster
366
+ * than `includes('"$t"')`, whose first character, `"`, is everywhere in JSON.
367
+ */
368
+ function hasTagKey(text) {
369
+ for (let i = text.indexOf(TAG); i !== -1; i = text.indexOf(TAG, i + 2)) {
370
+ if (text.charCodeAt(i - 1) === 34 && text.charCodeAt(i + 2) === 34)
371
+ return true;
372
+ }
373
+ return false;
374
+ }
375
+ /**
376
+ * The built-in serializer. Plain JSON passes through unchanged; on top of it, it keeps `Date`,
377
+ * `Map`, `Set`, `BigInt`, `undefined`, `NaN` / `±Infinity` / `-0`, `RegExp`, `URL`, `Error`
378
+ * (name and message only), `ArrayBuffer`, `DataView` and every typed array (`Buffer` arrives as a
379
+ * `Uint8Array`). Decoding is strict: a malformed tagged value throws a `TypeError`. Other class
380
+ * instances are sent like `JSON.stringify` sends them (`toJSON()`, else their own enumerable fields).
381
+ *
382
+ * `serialize` shares what needs no encoding with its input (plain JSON comes back as the same
383
+ * object), so don't mutate its result. `deserialize` always returns new arrays and objects.
384
+ */
385
+ export const lixnetJSON = { name: NAME, serialize, deserialize };
@@ -1,55 +1,62 @@
1
1
  import LixnetServerBase, { type LixnetServerBaseOptions } from "./serverbase";
2
- import type { FunctionInput, FunctionOutput, LXNEventEntries, LXNEventSchema, LXNServerHandler, LXN_ServerClient_EventType } from "./types";
2
+ import type { FunctionInput, FunctionOutput, LXNEventEntries, LXNEventSchema, LXNServerHandler, LXN_ServerClient_EventType, LixnetReservedInputCheck, LixnetReservedSchemasCheck, LixnetReservedKey } from "./types";
3
3
  import { LixnetResponse } from "./util/response";
4
- import { type LixnetRequest } from "./util/request";
5
4
  import type { StandardSchemaV1 } from "./standardschema";
6
- import type { LixnetRoute, LixnetRouteDefinitions, LixnetRoutes, LixnetRoutesFromDefinitions } from "./router";
5
+ import type { LixnetRouteDefinitions, LixnetRoute, LixnetRoutes, LixnetRoutesFromDefinitions, LixnetRoutesOption, LixnetRouteUses } from "./router";
7
6
  import type { LixnetServerInjections } from "./types";
8
- type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extends keyof Events> = {
7
+ import type { LixnetCheckMiddleware, LixnetMiddleware, LixnetMiddlewareContext, LixnetRouteUsesCheck, LixnetUseCheck } from "./middleware";
8
+ type Middleware = readonly LixnetMiddleware<any, any>[];
9
+ type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extends keyof Events, TCtx = {}, TUse extends Middleware = Middleware> = {
9
10
  event: TName;
10
- handler: LXNServerHandler<FunctionInput<Events[TName]> & {
11
- request: LixnetRequest;
12
- response: LixnetResponse;
13
- }, FunctionOutput<Events[TName]>>;
11
+ /** Middleware for this event only, run after the server's. */
12
+ use?: TUse;
13
+ handler: LXNServerHandler<FunctionInput<Events[TName]> & LixnetServerInjections<TCtx>, FunctionOutput<Events[TName]>>;
14
14
  schema?: LXNEventSchema<Events, TName>;
15
15
  };
16
- /**
17
- * Routes with inferred types, as `{ name: { schema?, handler } }`: the same as calling
18
- * `.route(name, ...)` for each. `events` is an alias of `routes`; pass one or the other.
19
- */
20
- type LixnetServerRoutesOption<TRouteDefinitions> = {
21
- routes?: TRouteDefinitions;
22
- events?: never;
23
- } | {
24
- events?: TRouteDefinitions;
25
- routes?: never;
26
- };
27
16
  export default class LixnetServer<Events extends LXN_ServerClient_EventType = LXN_ServerClient_EventType, Routes extends LixnetRoutes = {}, TSchemas extends Record<string, unknown> = {}, TDefs extends Record<string, {
28
17
  handler: (input: any) => unknown;
29
- }> = {}> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events>> {
18
+ }> = {}, const TUse extends Middleware = [], TUses = {}> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events, any>> {
30
19
  /** Type-only: routes from the `routes` option and `.route(...)`, read by `InferLixnetEvents`. */
31
20
  readonly "~routes": Routes & LixnetRoutesFromDefinitions<TDefs>;
32
21
  private formatter;
33
22
  constructor({ formatter, routes, events, ...options }?: LixnetServerBaseOptions & {
34
23
  formatter?: (this: LixnetResponse) => Response;
35
- } & LixnetServerRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas>>);
24
+ /** Middleware for every route. Each may read what the ones before it add to `ctx`. */
25
+ use?: TUse;
26
+ } & LixnetUseCheck<TUse, {}> & LixnetRoutesOption<TDefs & LixnetRouteDefinitions<TSchemas, LixnetServerInjections, LixnetMiddlewareContext<TUse>, TUses> & LixnetRouteUses<TUses> & LixnetRouteUsesCheck<TUses, LixnetMiddlewareContext<TUse>> & LixnetReservedSchemasCheck<TSchemas, LixnetReservedKey>>);
27
+ /**
28
+ * Adds middleware for the routes registered after this call (not earlier ones). Each can add
29
+ * fields to `ctx`: `server.use(auth).route("me", { handler: ({ ctx }) => ctx.user })`.
30
+ *
31
+ * Reassign or chain the result to keep the added `ctx` types.
32
+ */
33
+ use<const M extends Middleware>(...middleware: M & LixnetCheckMiddleware<M, LixnetMiddlewareContext<TUse>>): LixnetServer<Events, Routes, TSchemas, TDefs, [...TUse, ...M], TUses>;
34
+ /** Without a schema or input of its own: the handler gets only the injections (typed `ctx` included). */
35
+ route<K extends string, TOutput, const U extends Middleware>(event: K, route: {
36
+ schema?: undefined;
37
+ use?: U;
38
+ handler: (input: LixnetServerInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TOutput;
39
+ } & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>>): LixnetServer<Events, Routes & Record<K, LixnetRoute<{}, Awaited<TOutput>>>, TSchemas, TDefs, TUse, TUses>;
40
+ /** Without a schema, the input is the handler's parameter type minus `request`/`response`/`ctx`. */
41
+ route<K extends string, TParams, TOutput, const U extends Middleware>(event: K, route: {
42
+ schema?: undefined;
43
+ use?: U;
44
+ handler: (input: TParams & LixnetServerInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TOutput;
45
+ } & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>>): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>, TSchemas, TDefs, TUse, TUses>;
36
46
  /**
37
47
  * Adds an event whose types are inferred, so no `Events` contract is needed. Chain calls and
38
48
  * give the client `typeof server` through an `import type`.
39
49
  *
40
50
  * With a schema, the handler gets the schema's output and the client sends its input.
41
51
  */
42
- route<K extends string, TSchema extends StandardSchemaV1, TOutput>(event: K, route: {
52
+ route<K extends string, TSchema extends StandardSchemaV1, TOutput, const U extends Middleware>(event: K, route: {
43
53
  schema: TSchema;
44
- handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections) => TOutput;
45
- }): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>, TSchemas, TDefs>;
46
- /** Without a schema, the input is the handler's parameter type minus `request`/`response`. */
47
- route<K extends string, TParams, TOutput>(event: K, route: {
48
- schema?: undefined;
49
- handler: (input: TParams) => TOutput;
50
- }): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>, TSchemas, TDefs>;
51
- on<K extends keyof Events & string>(input: LXNServerEventInput<Events, K> | LXNEventEntries<Events, {
52
- [P in keyof Events & string]: LXNServerEventInput<Events, P>;
54
+ /** Middleware for this route only, run after the server's. */
55
+ use?: U;
56
+ handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections<LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>>) => TOutput;
57
+ } & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<StandardSchemaV1.InferOutput<TSchema>, LixnetReservedKey, "schema">): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>, TSchemas, TDefs, TUse, TUses>;
58
+ on<K extends keyof Events & string, const U extends Middleware>(input: LXNServerEventInput<Events, K, LixnetMiddlewareContext<TUse> & LixnetMiddlewareContext<U>, U> & LixnetUseCheck<U, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<FunctionInput<Events[K]>, LixnetReservedKey, "handler"> | LXNEventEntries<Events, {
59
+ [P in keyof Events & string]: LXNServerEventInput<Events, P, LixnetMiddlewareContext<TUse>> & LixnetReservedInputCheck<FunctionInput<Events[P]>, LixnetReservedKey, "handler">;
53
60
  }>): void;
54
61
  handle(request: Request): Promise<Response>;
55
62
  }
@@ -11,6 +11,16 @@ export default class LixnetServer extends LixnetServerBase {
11
11
  this.register({ ...route, event });
12
12
  }
13
13
  }
14
+ /**
15
+ * Adds middleware for the routes registered after this call (not earlier ones). Each can add
16
+ * fields to `ctx`: `server.use(auth).route("me", { handler: ({ ctx }) => ctx.user })`.
17
+ *
18
+ * Reassign or chain the result to keep the added `ctx` types.
19
+ */
20
+ use(...middleware) {
21
+ this.addMiddleware(middleware);
22
+ return this;
23
+ }
14
24
  route(event, route) {
15
25
  this.register({ ...route, event });
16
26
  return this;
@@ -19,8 +29,7 @@ export default class LixnetServer extends LixnetServerBase {
19
29
  this.register(input);
20
30
  }
21
31
  async handle(request) {
22
- const requestClone = request.clone();
23
- const response = new LixnetResponse({ formatter: this.formatter });
32
+ const response = new LixnetResponse({ formatter: this.formatter, serializer: this.serializer });
24
33
  const corsResponse = this.handleCors(request, response);
25
34
  if (corsResponse)
26
35
  return corsResponse;
@@ -29,15 +38,15 @@ export default class LixnetServer extends LixnetServerBase {
29
38
  return this.fail(response, parsed);
30
39
  }
31
40
  try {
32
- const data = await parsed.entry.handler({
33
- ...parsed.input,
34
- request: createLixnetRequest(requestClone, response),
41
+ const output = await this.invoke(parsed.entry, parsed.input, {
42
+ request: createLixnetRequest(request, response, parsed.body),
35
43
  response: response,
36
44
  });
37
- //check data isnt void/null/undefined
38
- if (!(data === undefined || data === null)) {
39
- response.data(data);
45
+ // A null/undefined return keeps data staged with `response.data()`. Raw: encoded when formatted.
46
+ if (output != null || response.responseData === undefined) {
47
+ response.data(output);
40
48
  }
49
+ // Throws a 500 LixnetError "Could not serialize the response" if the output can't be encoded.
41
50
  return response.format();
42
51
  }
43
52
  catch (error) {
@@ -1,6 +1,9 @@
1
1
  import type { StandardSchemaV1 } from "./standardschema";
2
2
  import type { DebugLogger } from "./types";
3
3
  import type { LixnetResponse } from "./util/response";
4
+ import type { LixnetRequest } from "./util/request";
5
+ import { type LixnetMiddleware } from "./middleware";
6
+ import type { LixnetSerializer } from "./serializer";
4
7
  import { type LixnetErrorCode } from "./error";
5
8
  import { type LixnetCorsOptions } from "./util/cors";
6
9
  export type LixnetServerBaseOptions = {
@@ -18,10 +21,27 @@ export type LixnetServerBaseOptions = {
18
21
  * headers to every response, and rejects requests from origins that aren't allowed.
19
22
  */
20
23
  cors?: LixnetCorsOptions;
24
+ /**
25
+ * Middleware run before every route, in order (routes added with `.use(...)` later get those too).
26
+ * Each can add fields to the handler's `ctx`.
27
+ */
28
+ use?: readonly LixnetMiddleware<any, any>[];
29
+ /**
30
+ * Serializer for inputs, outputs and error `data`, for types JSON can't carry (e.g. `lixnetJSON`).
31
+ * The client must use the same one: requests with another (or none) are rejected.
32
+ */
33
+ serializer?: LixnetSerializer;
21
34
  };
22
35
  type EventEntry = {
23
36
  event: PropertyKey;
24
37
  schema?: StandardSchemaV1;
38
+ handler: (input: any) => unknown;
39
+ /** The route's own middleware, run after the server's. */
40
+ use?: readonly LixnetMiddleware<any, any>[];
41
+ };
42
+ /** An entry as stored: with the full middleware chain resolved when it was registered. */
43
+ type StoredEntry<TEntry> = TEntry & {
44
+ middleware: readonly LixnetMiddleware<any, any>[];
25
45
  };
26
46
  /** A failed request, before it's written to the response. */
27
47
  type Failure = {
@@ -33,23 +53,43 @@ type Failure = {
33
53
  cause?: unknown;
34
54
  event?: string;
35
55
  };
56
+ /**
57
+ * `input` is deserialized but not validated: validation runs in `invoke`, after middleware.
58
+ * `body` is the raw request body, kept so handlers can re-read it without `request.clone()`.
59
+ */
36
60
  type ParsedRpcRequest<TEntry> = {
37
61
  ok: true;
38
- entry: TEntry;
62
+ entry: StoredEntry<TEntry>;
39
63
  input: any;
64
+ body: string;
40
65
  } | ({
41
66
  ok: false;
42
67
  } & Failure);
68
+ type Injections = {
69
+ request: LixnetRequest;
70
+ response: LixnetResponse;
71
+ } & Record<string, unknown>;
43
72
  /** Shared request parsing and error handling for `LixnetServer` and `LixnetStreamServer`. */
44
73
  export default abstract class LixnetServerBase<TEntry extends EventEntry> {
45
- protected events: Record<string, TEntry>;
74
+ protected events: Record<string, StoredEntry<TEntry>>;
75
+ protected middleware: LixnetMiddleware<any, any>[];
76
+ protected serializer?: LixnetSerializer;
46
77
  protected logger: DebugLogger;
47
78
  protected debugLog: boolean;
48
79
  protected exposeErrors: boolean;
49
80
  protected defaultHeaders: Record<string, string>;
50
81
  protected cors?: LixnetCorsOptions;
51
- protected constructor({ debugLog, exposeErrors, logger, defaultHeaders, cors, }: LixnetServerBaseOptions);
82
+ protected constructor({ debugLog, exposeErrors, logger, defaultHeaders, cors, use, serializer, }: LixnetServerBaseOptions);
83
+ /** Each entry keeps the server middleware registered so far, so `.use(...)` only affects later routes. */
52
84
  protected register(input: TEntry | TEntry[]): void;
85
+ protected addMiddleware(middleware: readonly LixnetMiddleware<any, any>[]): void;
86
+ /**
87
+ * Runs the entry's middleware, then validates the input against its schema, then runs its
88
+ * handler with `ctx` and the injections. Resolves (or returns, when sync) the output.
89
+ * Middleware sees the deserialized input; the handler gets the schema's output. A validation
90
+ * failure is thrown as an `INVALID_INPUT` `LixnetError` inside the chain, so middleware can catch it.
91
+ */
92
+ protected invoke(entry: StoredEntry<TEntry>, input: any, injections: Injections): Promise<unknown> | unknown;
53
93
  protected parse(request: Request): Promise<ParsedRpcRequest<TEntry>>;
54
94
  /**
55
95
  * With `cors` set: answers preflights and rejects disallowed origins (returns the Response),
@@ -60,6 +100,7 @@ export default abstract class LixnetServerBase<TEntry extends EventEntry> {
60
100
  protected failureFromThrown(error: unknown, event: string): Failure;
61
101
  /** Logs the failure (with `debugLog`) and stages it on the response with its status. */
62
102
  protected stageFailure(response: LixnetResponse, { error, status, code, data, cause, event }: Failure): void;
103
+ /** Stages the failure and formats it. Never throws: if formatting fails, a bare 500 is sent. */
63
104
  protected fail(response: LixnetResponse, failure: Failure): Response;
64
105
  }
65
106
  export {};