lixnet 1.3.14 → 1.5.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
@@ -32,7 +32,7 @@ It gives you:
32
32
 
33
33
  - **HTTP RPC** via `fetch` (`LixnetServer` + `LixnetClient`)
34
34
  - **WebSocket events + callbacks** (`LixnetPeer`)
35
- - **Optional Zod validation** on the server
35
+ - **Zero dependencies**, with optional validation through any [Standard Schema](https://standardschema.dev) library (zod, valibot, arktype, ...)
36
36
  - **Next.js-like** `request.cookies()` / `request.headers()` ergonomics inside handlers (without pulling in Next)
37
37
 
38
38
  It’s designed to be minimal: no codegen, no schema registry, no client bundler magic.
@@ -41,7 +41,10 @@ It’s designed to be minimal: no codegen, no schema registry, no client bundler
41
41
 
42
42
  - [Quickstart (HTTP RPC)](#quickstart-http-rpc)
43
43
  - [Framework adapters (server wiring)](#framework-adapters-server-wiring)
44
+ - [Inferred contract (`server.route`)](#inferred-contract-serverroute)
44
45
  - [Server: `LixnetServer`](#server-lixnetserver)
46
+ - [Errors](#errors-lixneterror)
47
+ - [CORS](#cors)
45
48
  - [Client: `LixnetClient`](#client-lixnetclient)
46
49
  - [Handlers: `request` and `response`](#handlers-request-and-response)
47
50
  - [WebSockets: `LixnetPeer`](#websockets-lixnetpeer)
@@ -54,7 +57,7 @@ It’s designed to be minimal: no codegen, no schema registry, no client bundler
54
57
  Install:
55
58
 
56
59
  ```sh
57
- bun add lixnet zod
60
+ bun add lixnet zod # zod is optional: any Standard Schema library (zod, valibot, arktype) works
58
61
  ```
59
62
 
60
63
  Other package managers:
@@ -76,7 +79,7 @@ type Events = {
76
79
 
77
80
  ### 2) Create the RPC server
78
81
 
79
- Register handlers with optional Zod schemas, then expose an HTTP endpoint that forwards the incoming `Request` to `server.handle(...)`.
82
+ Register handlers with optional schemas (any Standard Schema library), then expose an HTTP endpoint that forwards the incoming `Request` to `server.handle(...)`.
80
83
 
81
84
  ```ts
82
85
  import { z } from "zod";
@@ -172,6 +175,49 @@ await client.call(
172
175
  );
173
176
  ```
174
177
 
178
+ ## Inferred contract (`server.route`)
179
+
180
+ Instead of writing an `Events` type by hand, chain `.route(...)` on the server and let the client infer everything from `typeof server`. Experimental: `Events` + `on()` keeps working and both can be used side by side.
181
+
182
+ ```ts
183
+ // cloudflare/ioServer.ts (worker only)
184
+ import { z } from "zod";
185
+ import { LixnetServer } from "lixnet";
186
+ import live from "./(functions)/live";
187
+
188
+ export default function createRpcServer(options: { defaultHeaders?: Record<string, string> } = {}) {
189
+ return new LixnetServer(options)
190
+ .route("helloThere", {
191
+ schema: z.object({ name: z.string() }),
192
+ handler: ({ name }) => ({ message: `Hello ${name}` }),
193
+ })
194
+ // no schema: input is the handler's parameter type minus request/response
195
+ .route("live", { handler: live });
196
+ }
197
+
198
+ export type RpcServer = ReturnType<typeof createRpcServer>;
199
+ ```
200
+
201
+ ```ts
202
+ // cloudflare/io.ts (browser)
203
+ import type { RpcServer } from "./ioServer"; // type-only: erased at build time
204
+ import { LixnetClient } from "lixnet";
205
+
206
+ export const rpcClient = new LixnetClient<RpcServer>({ rpcUrl: "/rpc" });
207
+
208
+ await rpcClient.call("helloThere", { name: "World" }); // { message: string }
209
+ await rpcClient.call("live"); // input omitted: live takes no client input
210
+ ```
211
+
212
+ - With a schema, the handler receives the schema's output and the client sends the schema's input (so `z.string().transform(Number)` means the client sends a string).
213
+ - Without a schema, annotate the handler's parameter; `request`/`response` are removed from the client input. Anything else in that parameter (e.g. an optional `db`) becomes client input, so keep server-only values out of handler params.
214
+
215
+ Keeping server code out of the client:
216
+
217
+ - Always `import type` the server type. Enable `verbatimModuleSyntax` (or the `consistent-type-imports` lint rule) so an accidental value import fails instead of bundling the worker (sharp, wasm, ...) into the browser.
218
+ - The bundle is safe either way, but type-checking still follows the import into the server files. Keep `ioServer.ts` thin (it imports handlers only) and give handlers explicit return types, so the client's tsconfig doesn't have to resolve worker-only types.
219
+ - If the client tsconfig still can't resolve worker types, emit declarations from the worker project (`tsc --emitDeclarationOnly`) and `import type` from the generated `.d.ts`.
220
+
175
221
  ## Server: `LixnetServer`
176
222
 
177
223
  ### Registering events
@@ -179,7 +225,7 @@ await client.call(
179
225
  `server.on(...)` accepts either one registration object or an array.
180
226
 
181
227
  - **`event`**: string key matching your `Events` type
182
- - **`schema`** (optional): Zod schema to validate `input`
228
+ - **`schema`** (optional): a Standard Schema (zod, valibot, arktype, ...) to validate `input`
183
229
  - **`handler`**: receives validated input plus `{ request, response }` injections
184
230
 
185
231
  Example registering multiple events:
@@ -215,7 +261,7 @@ Responses are JSON and shaped as either:
215
261
  or
216
262
 
217
263
  ```json
218
- { "error": "..." }
264
+ { "error": "...", "code": "UNAUTHORIZED", "data": {} }
219
265
  ```
220
266
 
221
267
  ### Server configuration
@@ -237,12 +283,93 @@ const server = new LixnetServer<Events>({
237
283
  });
238
284
  ```
239
285
 
286
+ ## Errors (`LixnetError`)
287
+
288
+ Throw a `LixnetError` from a handler to send a specific error; the client throws it back with the same `code`, `status` and `data`:
289
+
290
+ ```ts
291
+ import { LixnetError } from "lixnet";
292
+
293
+ // server
294
+ throw new LixnetError("UNAUTHORIZED", "Session expired");
295
+ throw new LixnetError("TOO_MANY_REQUESTS", "Slow down", { data: { retryAfter: 30 } });
296
+ throw new LixnetError("PLAN_LIMIT", "Upgrade your plan", { status: 402 }); // custom code
297
+
298
+ // client
299
+ try {
300
+ await client.call("me");
301
+ } catch (e) {
302
+ if (LixnetError.is(e) && e.code === "UNAUTHORIZED") redirect("/login");
303
+ }
304
+ ```
305
+
306
+ - Built-in codes and their default statuses (`LIXNET_ERROR_STATUS`): `BAD_REQUEST` 400, `INVALID_INPUT` 400, `UNAUTHORIZED` 401, `FORBIDDEN` 403, `NOT_FOUND` 404, `CONFLICT` 409, `TOO_MANY_REQUESTS` 429, `INTERNAL` 500. Any other string works as a code (default status 400).
307
+ - `LixnetError.is(e)` is preferred over `instanceof`: it also works when two copies of Lixnet end up in one bundle.
308
+ - Every client error is a `LixnetError` (it extends `Error`, so `e.message` is unchanged), including non-Lixnet responses such as a proxy's HTML 502.
309
+ - For errors the caller is expected to handle as part of the result, returning a typed union (`{ ok: false, ... }`) is still the better fit; `LixnetError` is for cross-cutting cases (auth, permissions, rate limits, validation).
310
+ - `response.code(403); response.error("Forbidden")` still works; the code is derived from the status (`FORBIDDEN`), or pass one: `response.error("Forbidden", { code: "NO_ACCESS" })`.
311
+
312
+ Built-in errors (both servers, same messages as before plus a `code`):
313
+
314
+ | `error` | `code` | Status |
315
+ | --- | --- | --- |
316
+ | `"Invalid JSON"` | `BAD_REQUEST` | 400 |
317
+ | `"Invalid request body"` | `BAD_REQUEST` | 400 |
318
+ | `"Event not found"` (missing `event`) | `BAD_REQUEST` | 400 |
319
+ | `"Input not found"` | `BAD_REQUEST` | 400 |
320
+ | `"Event not found"` (unknown `event`) | `NOT_FOUND` | 404 |
321
+ | `"Invalid input"` (schema failure) | `INVALID_INPUT` | 400 |
322
+ | `"Origin not allowed"` (with `cors`) | `FORBIDDEN` | 403 |
323
+ | `"Handler error"` (handler threw a non-`LixnetError`) | `INTERNAL` | 500 |
324
+
325
+ `INVALID_INPUT` always includes the validation issues, so forms can show errors per field:
326
+
327
+ ```json
328
+ {
329
+ "error": "Invalid input",
330
+ "code": "INVALID_INPUT",
331
+ "data": { "issues": [{ "path": ["email"], "message": "Invalid email address" }] }
332
+ }
333
+ ```
334
+
335
+ Error responses always go through the formatter, so `defaultHeaders` and CORS headers are included. Keep the `error` strings stable; match on `code` in new code.
336
+
337
+ ## CORS
338
+
339
+ When the RPC server is on another origin than the app (e.g. a Worker on `api.example.com`), pass `cors` instead of hand-writing CORS headers and an `OPTIONS` branch. Works on `LixnetServer` and `LixnetStreamServer`.
340
+
341
+ ```ts
342
+ const server = new LixnetServer({
343
+ cors: {
344
+ origin: ["https://example.com", "http://localhost:3000"], // or "*", or (origin) => boolean
345
+ credentials: true, // cookies; not allowed with origin "*"
346
+ // maxAge: 7200, // preflight cache in seconds (default 7200, Chrome's cap)
347
+ // allowHeaders: ["Content-Type", "Authorization"], // default: whatever the browser asks for
348
+ // exposeHeaders: ["X-Request-Id"],
349
+ },
350
+ });
351
+
352
+ export default {
353
+ async fetch(request: Request) {
354
+ const url = new URL(request.url);
355
+ if (url.pathname === "/rpc" && (request.method === "POST" || request.method === "OPTIONS")) {
356
+ return server.handle(request);
357
+ }
358
+ return new Response("Not found", { status: 404 });
359
+ },
360
+ };
361
+ ```
362
+
363
+ - `OPTIONS` preflights get `204` with `Access-Control-Max-Age` (default 7200), so the browser preflights at most once per 2 hours per origin instead of before every call.
364
+ - Every response, errors included, gets `Access-Control-Allow-Origin` (the caller's origin, plus `Vary: Origin`) and `Access-Control-Allow-Credentials` when enabled.
365
+ - 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.
366
+
240
367
  ## Client: `LixnetClient`
241
368
 
242
369
  `client.call(event, input, options?)`:
243
370
 
244
371
  - sends a `POST` with `{ event, input }`
245
- - throws `Error(...)` when the response contains `{ error }`
372
+ - throws a `LixnetError` (with `code`, `status`, `data`) when the response contains `{ error }`; see "Errors" below
246
373
  - otherwise returns `{ data }`’s value
247
374
 
248
375
  ### Client creation
package/dist/exports.d.ts CHANGED
@@ -4,7 +4,13 @@ import LixnetPeer from "./lib/peer";
4
4
  import LixnetStreamServer from "./lib/streamserver";
5
5
  import LixnetStreamClient from "./lib/streamclient";
6
6
  import { LixnetResponse } from "./lib/util/response";
7
- export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse };
7
+ import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
8
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
9
+ export type { LixnetErrorCode, LixnetIssue } from "./lib/error";
10
+ export type { LixnetRoute, LixnetRoutes, InferLixnetEvents } from "./lib/router";
8
11
  export type { LixnetCookies, LixnetHeaders, LixnetRequest, ReadonlyHeaders, ReadonlyRequestCookies, RequestCookie, } from "./lib/util/request";
9
- export type { LXN_ServerClient_EventType, LXNServerHandler, FunctionInput, LXN_ServerClient_Request, LixnetServerInjections, LXNStreamEmitter, } from "./lib/types";
12
+ export type { LXN_ServerClient_EventType, LXNServerHandler, FunctionInput, LXN_ServerClient_Request, LixnetServerInjections, LXNStreamEmitter, LXNCallArgs, } from "./lib/types";
10
13
  export type { LXNStreamCallOptions } from "./lib/streamclient";
14
+ export type { LixnetServerBaseOptions } from "./lib/serverbase";
15
+ export type { LixnetCorsOptions } from "./lib/util/cors";
16
+ export type { StandardSchemaV1 } from "./lib/standardschema";
package/dist/exports.js CHANGED
@@ -5,4 +5,5 @@ import LixnetPeer from "./lib/peer";
5
5
  import LixnetStreamServer from "./lib/streamserver";
6
6
  import LixnetStreamClient from "./lib/streamclient";
7
7
  import { LixnetResponse } from "./lib/util/response";
8
- export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse };
8
+ import { LixnetError, LIXNET_ERROR_STATUS } from "./lib/error";
9
+ export { LixnetServer, LixnetClient, LixnetPeer, LixnetStreamServer, LixnetStreamClient, LixnetResponse, LixnetError, LIXNET_ERROR_STATUS, };
@@ -1,10 +1,12 @@
1
- import type { FunctionInput, LXN_ServerClient_EventType } from "./types";
1
+ import type { FunctionInput, LXNCallArgs, LXN_ServerClient_EventType } from "./types";
2
+ import type { InferLixnetEvents } from "./router";
2
3
  type ExtractRPCResponse<T> = T extends (...args: any) => infer R ? Awaited<R> : never;
3
- export default class LixnetClient<Events extends LXN_ServerClient_EventType> {
4
+ /** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
5
+ export default class LixnetClient<Contract extends LXN_ServerClient_EventType, Events extends LXN_ServerClient_EventType = InferLixnetEvents<Contract>> {
4
6
  private rpcUrl;
5
7
  constructor({ rpcUrl }: {
6
8
  rpcUrl: string;
7
9
  });
8
- call<K extends keyof Events>(event: K, input: FunctionInput<Events[K]>, options?: RequestInit): Promise<ExtractRPCResponse<Events[K]>>;
10
+ call<K extends keyof Events>(event: K, ...[input, options]: LXNCallArgs<FunctionInput<Events[K]>, RequestInit>): Promise<ExtractRPCResponse<Events[K]>>;
9
11
  }
10
12
  export {};
@@ -1,20 +1,25 @@
1
+ import withJsonContentType from "./util/withJsonContentType";
2
+ import { LixnetError, codeForStatus, errorFromBody } from "./error";
3
+ /** `Contract` is either an events contract or `typeof server` for a server built with `.route(...)`. */
1
4
  export default class LixnetClient {
2
5
  rpcUrl;
3
6
  constructor({ rpcUrl }) {
4
7
  this.rpcUrl = rpcUrl;
5
8
  }
6
- async call(event, input, options = {}) {
9
+ async call(event, ...[input, options = {}]) {
7
10
  const response = await fetch(this.rpcUrl, {
8
- method: "POST",
9
- headers: {
10
- "Content-Type": "application/json",
11
- },
12
- body: JSON.stringify({ event, input }),
13
11
  ...options,
12
+ method: "POST",
13
+ headers: withJsonContentType(options.headers),
14
+ body: JSON.stringify({ event, input: input === undefined ? {} : input }),
14
15
  });
15
- const json = await response.json();
16
- if (json.error) {
17
- throw new Error(json.error);
16
+ const json = await response.json().catch(() => null);
17
+ // Not a Lixnet response, e.g. a proxy's HTML error page.
18
+ if (json === null || typeof json !== "object") {
19
+ throw new LixnetError(response.ok ? "BAD_RESPONSE" : codeForStatus(response.status), `Unexpected response from ${this.rpcUrl} (status ${response.status})`, { status: response.status });
20
+ }
21
+ if (typeof json.error === "string") {
22
+ throw errorFromBody(json, response.status);
18
23
  }
19
24
  return json.data;
20
25
  }
@@ -0,0 +1,46 @@
1
+ /** Built-in error codes and their default HTTP statuses. Any other string is also a valid code. */
2
+ export declare const LIXNET_ERROR_STATUS: {
3
+ readonly BAD_REQUEST: 400;
4
+ readonly INVALID_INPUT: 400;
5
+ readonly UNAUTHORIZED: 401;
6
+ readonly FORBIDDEN: 403;
7
+ readonly NOT_FOUND: 404;
8
+ readonly CONFLICT: 409;
9
+ readonly TOO_MANY_REQUESTS: 429;
10
+ readonly INTERNAL: 500;
11
+ };
12
+ export type LixnetErrorCode = keyof typeof LIXNET_ERROR_STATUS | (string & {});
13
+ /** One validation problem, sent as `data.issues` with `INVALID_INPUT`. */
14
+ export type LixnetIssue = {
15
+ path: (string | number)[];
16
+ message: string;
17
+ };
18
+ /** Picks a code for a status that came without one (e.g. `response.code(403)` + `response.error(...)`). */
19
+ export declare function codeForStatus(status: number): LixnetErrorCode;
20
+ /** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
21
+ export declare function errorFromBody(body: {
22
+ error: string;
23
+ code?: string;
24
+ data?: unknown;
25
+ detail?: string;
26
+ },
27
+ /** Omitted for stream error frames (sent after a 200): derived from the code instead. */
28
+ status?: number): LixnetError;
29
+ /**
30
+ * An error with a machine-readable `code`, an HTTP `status` and optional JSON `data`.
31
+ *
32
+ * Throw it from a handler to send it to the client as-is; `LixnetClient` throws it back on the
33
+ * client, so `catch (e) { if (LixnetError.is(e) && e.code === "UNAUTHORIZED") ... }` works.
34
+ */
35
+ export declare class LixnetError<TData = unknown> extends Error {
36
+ readonly code: LixnetErrorCode;
37
+ readonly status: number;
38
+ readonly data: TData | undefined;
39
+ constructor(code: LixnetErrorCode, message?: string, options?: {
40
+ status?: number;
41
+ data?: TData;
42
+ cause?: unknown;
43
+ });
44
+ /** Like `instanceof`, but also works across duplicate copies of Lixnet in one bundle. */
45
+ static is(error: unknown): error is LixnetError;
46
+ }
@@ -0,0 +1,57 @@
1
+ /** Built-in error codes and their default HTTP statuses. Any other string is also a valid code. */
2
+ export const LIXNET_ERROR_STATUS = {
3
+ BAD_REQUEST: 400,
4
+ INVALID_INPUT: 400,
5
+ UNAUTHORIZED: 401,
6
+ FORBIDDEN: 403,
7
+ NOT_FOUND: 404,
8
+ CONFLICT: 409,
9
+ TOO_MANY_REQUESTS: 429,
10
+ INTERNAL: 500,
11
+ };
12
+ const LIXNET_ERROR_BRAND = Symbol.for("lixnet.error");
13
+ /** Picks a code for a status that came without one (e.g. `response.code(403)` + `response.error(...)`). */
14
+ export function codeForStatus(status) {
15
+ // INVALID_INPUT is skipped so a bare 400 maps to the generic BAD_REQUEST.
16
+ for (const [code, codeStatus] of Object.entries(LIXNET_ERROR_STATUS)) {
17
+ if (codeStatus === status && code !== "INVALID_INPUT")
18
+ return code;
19
+ }
20
+ return status >= 500 ? "INTERNAL" : "BAD_REQUEST";
21
+ }
22
+ /** Rebuilds the error a server sent (`{ error, code?, data?, detail? }`) on the client. */
23
+ export function errorFromBody(body,
24
+ /** Omitted for stream error frames (sent after a 200): derived from the code instead. */
25
+ status) {
26
+ return new LixnetError(body.code ?? codeForStatus(status ?? 500), body.error, {
27
+ status,
28
+ data: body.data,
29
+ cause: body.detail,
30
+ });
31
+ }
32
+ /**
33
+ * An error with a machine-readable `code`, an HTTP `status` and optional JSON `data`.
34
+ *
35
+ * Throw it from a handler to send it to the client as-is; `LixnetClient` throws it back on the
36
+ * client, so `catch (e) { if (LixnetError.is(e) && e.code === "UNAUTHORIZED") ... }` works.
37
+ */
38
+ export class LixnetError extends Error {
39
+ code;
40
+ status;
41
+ data;
42
+ constructor(code, message = code, options = {}) {
43
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
44
+ this.name = "LixnetError";
45
+ this.code = code;
46
+ this.status =
47
+ options.status ??
48
+ LIXNET_ERROR_STATUS[code] ??
49
+ 400;
50
+ this.data = options.data;
51
+ Object.defineProperty(this, LIXNET_ERROR_BRAND, { value: true });
52
+ }
53
+ /** Like `instanceof`, but also works across duplicate copies of Lixnet in one bundle. */
54
+ static is(error) {
55
+ return typeof error === "object" && error !== null && LIXNET_ERROR_BRAND in error;
56
+ }
57
+ }
package/dist/lib/peer.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { LIXNET_ID_PREFIX } from "./vars";
1
2
  function createLixnetId() {
2
- return "LXN-" + Math.random().toString(36).substring(2, 15);
3
+ return LIXNET_ID_PREFIX + Math.random().toString(36).substring(2, 15);
3
4
  }
4
5
  export default class LixnetPeer {
5
6
  socket = null;
@@ -37,6 +38,11 @@ export default class LixnetPeer {
37
38
  tId,
38
39
  dataLength: dataString.length,
39
40
  });
41
+ if (limits.length > this.transmissionChunksLimit) {
42
+ if (rf)
43
+ delete this.rb[rf];
44
+ throw new Error(`LIXNET - Payload needs ${limits.length} chunks, limit is ${this.transmissionChunksLimit}`);
45
+ }
40
46
  // Send transmission id and rf
41
47
  const sendData = {
42
48
  tId,
@@ -138,7 +144,9 @@ export default class LixnetPeer {
138
144
  }, 10000);
139
145
  }
140
146
  handle({ data, socket }) {
141
- if (data.startsWith("LX-")) {
147
+ if (typeof data !== "string")
148
+ return;
149
+ if (data.startsWith(LIXNET_ID_PREFIX)) {
142
150
  // Transmission chunk
143
151
  const splits = data.split(".");
144
152
  const tId = splits[0];
@@ -148,6 +156,11 @@ export default class LixnetPeer {
148
156
  // No transmission found
149
157
  return;
150
158
  }
159
+ if (!Number.isInteger(chunkIndex) ||
160
+ chunkIndex < 0 ||
161
+ chunkIndex >= this.transmissions[tId].chunkCount) {
162
+ return;
163
+ }
151
164
  this.transmissions[tId].chunks[chunkIndex] = chunk;
152
165
  this.transmissions[tId].chunkTimes[chunkIndex] = Date.now();
153
166
  if (this.transmissions[tId].chunkCount ==
@@ -197,6 +210,13 @@ export default class LixnetPeer {
197
210
  // Normal event, not a transmission chunk
198
211
  if (data.tId) {
199
212
  // Starting transmission, allow the client to start sending chunks
213
+ if (typeof data.tId !== "string" ||
214
+ !data.tId.startsWith(LIXNET_ID_PREFIX) ||
215
+ !Number.isInteger(data.chunkCount) ||
216
+ data.chunkCount < 1 ||
217
+ data.chunkCount > this.transmissionChunksLimit) {
218
+ return;
219
+ }
200
220
  this.transmissions[data.tId] = {
201
221
  chunks: {},
202
222
  chunkTimes: {},
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Type-level description of a route added with `LixnetServer.route(...)`: the input the
3
+ * client sends and the output it receives.
4
+ */
5
+ export type LixnetRoute<TInput, TOutput> = {
6
+ input: TInput;
7
+ output: TOutput;
8
+ };
9
+ export type LixnetRoutes = Record<string, LixnetRoute<any, any>>;
10
+ /**
11
+ * Converts `typeof server` (built with `.route(...)`) into the `Events` shape clients use
12
+ * (`name: (input) => output`). Anything else is passed through, so clients accept either.
13
+ */
14
+ export type InferLixnetEvents<T> = T extends {
15
+ readonly "~routes": infer TRoutes extends LixnetRoutes;
16
+ } ? {
17
+ [K in keyof TRoutes]: (input: TRoutes[K]["input"]) => TRoutes[K]["output"];
18
+ } : T;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,27 +1,43 @@
1
- import { z } from "zod";
2
- import type { DebugLogger, FunctionInput, FunctionOutput, LXNServerHandler, LXN_ServerClient_EventType } from "./types";
1
+ import LixnetServerBase, { type LixnetServerBaseOptions } from "./serverbase";
2
+ import type { FunctionInput, FunctionOutput, LXNEventEntries, LXNEventSchema, LXNServerHandler, LXN_ServerClient_EventType } from "./types";
3
3
  import { LixnetResponse } from "./util/response";
4
- import { LixnetRequest } from "./util/request";
4
+ import { type LixnetRequest } from "./util/request";
5
+ import type { StandardSchemaV1 } from "./standardschema";
6
+ import type { LixnetRoute, LixnetRoutes } from "./router";
7
+ import type { LixnetServerInjections } from "./types";
5
8
  type LXNServerEventInput<Events extends LXN_ServerClient_EventType, TName extends keyof Events> = {
6
9
  event: TName;
7
10
  handler: LXNServerHandler<FunctionInput<Events[TName]> & {
8
11
  request: LixnetRequest;
9
12
  response: LixnetResponse;
10
13
  }, FunctionOutput<Events[TName]>>;
11
- schema?: z.ZodSchema<any>;
14
+ schema?: LXNEventSchema<Events, TName>;
12
15
  };
13
- export default class LixnetServer<Events extends LXN_ServerClient_EventType> {
14
- private events;
15
- private logger;
16
- private debugLog;
16
+ export default class LixnetServer<Events extends LXN_ServerClient_EventType = LXN_ServerClient_EventType, Routes extends LixnetRoutes = {}> extends LixnetServerBase<LXNServerEventInput<Events, keyof Events>> {
17
+ /** Type-only: the routes added with `.route(...)`, read by `InferLixnetEvents`. */
18
+ readonly "~routes": Routes;
17
19
  private formatter;
18
- constructor({ debugLog, logger, formatter, defaultHeaders, }: {
19
- debugLog?: boolean;
20
- logger?: DebugLogger;
20
+ constructor({ formatter, ...options }?: LixnetServerBaseOptions & {
21
21
  formatter?: (this: LixnetResponse) => Response;
22
- defaultHeaders?: Record<string, string>;
23
22
  });
24
- on<K extends keyof Events & string>(input: LXNServerEventInput<Events, K> | LXNServerEventInput<Events, K>[]): void;
23
+ /**
24
+ * Adds an event whose types are inferred, so no `Events` contract is needed. Chain calls and
25
+ * give the client `typeof server` through an `import type`.
26
+ *
27
+ * With a schema, the handler gets the schema's output and the client sends its input.
28
+ */
29
+ route<K extends string, TSchema extends StandardSchemaV1, TOutput>(event: K, route: {
30
+ schema: TSchema;
31
+ handler: (input: StandardSchemaV1.InferOutput<TSchema> & LixnetServerInjections) => TOutput;
32
+ }): LixnetServer<Events, Routes & Record<K, LixnetRoute<StandardSchemaV1.InferInput<TSchema>, Awaited<TOutput>>>>;
33
+ /** Without a schema, the input is the handler's parameter type minus `request`/`response`. */
34
+ route<K extends string, TParams, TOutput>(event: K, route: {
35
+ schema?: undefined;
36
+ handler: (input: TParams) => TOutput;
37
+ }): LixnetServer<Events, Routes & Record<K, LixnetRoute<Omit<TParams, keyof LixnetServerInjections>, Awaited<TOutput>>>>;
38
+ on<K extends keyof Events & string>(input: LXNServerEventInput<Events, K> | LXNEventEntries<Events, {
39
+ [P in keyof Events & string]: LXNServerEventInput<Events, P>;
40
+ }>): void;
25
41
  handle(request: Request): Promise<Response>;
26
42
  }
27
43
  export {};
@@ -1,101 +1,44 @@
1
- import { z } from "zod";
2
- import LixnetLog from "./util/log";
1
+ import LixnetServerBase from "./serverbase";
3
2
  import { LixnetResponse } from "./util/response";
4
- import { wrapLixnetRequest } from "./util/request";
3
+ import { createLixnetRequest } from "./util/request";
5
4
  import getDefaultFormatter from "./util/getDefaultFormatter";
6
- export default class LixnetServer {
7
- events = {};
8
- logger = LixnetLog;
9
- debugLog = false;
5
+ export default class LixnetServer extends LixnetServerBase {
10
6
  formatter;
11
- constructor({ debugLog = false, logger, formatter, defaultHeaders = {}, }) {
12
- this.debugLog = debugLog;
13
- logger ? (this.logger = logger) : "";
14
- this.formatter = formatter ?? getDefaultFormatter(defaultHeaders);
7
+ constructor({ formatter, ...options } = {}) {
8
+ super(options);
9
+ this.formatter = formatter ?? getDefaultFormatter(this.defaultHeaders);
10
+ }
11
+ route(event, route) {
12
+ this.register({ ...route, event });
13
+ return this;
15
14
  }
16
15
  on(input) {
17
- if (Array.isArray(input)) {
18
- input.forEach((event) => {
19
- this.events[event.event] = event;
20
- });
21
- }
22
- else {
23
- this.events[input.event] = input;
24
- }
16
+ this.register(input);
25
17
  }
26
18
  async handle(request) {
27
19
  const requestClone = request.clone();
28
20
  const response = new LixnetResponse({ formatter: this.formatter });
29
- let jsonData;
30
- try {
31
- jsonData = (await request.json());
32
- }
33
- catch (error) {
34
- this.debugLog
35
- ? this.logger({
36
- error: true,
37
- message: "Invalid JSON",
38
- })
39
- : "";
40
- response.error("Invalid JSON");
41
- return response.format();
42
- }
43
- if (jsonData === null ||
44
- typeof jsonData !== "object" ||
45
- Array.isArray(jsonData)) {
46
- response.error("Invalid request body");
47
- return response.format();
48
- }
49
- if (!jsonData.event) {
50
- response.error("Event not found");
51
- return response.format();
52
- }
53
- if (!("input" in jsonData)) {
54
- response.error("Input not found");
55
- return response.format();
56
- }
57
- const event = this.events[jsonData.event];
58
- if (!event) {
59
- response.error("Event not found");
60
- return response.format();
21
+ const corsResponse = this.handleCors(request, response);
22
+ if (corsResponse)
23
+ return corsResponse;
24
+ const parsed = await this.parse(request);
25
+ if (!parsed.ok) {
26
+ return this.fail(response, parsed);
61
27
  }
62
28
  try {
63
- const validatedInput = event.schema
64
- ? event.schema.parse(jsonData.input)
65
- : jsonData.input;
66
- try {
67
- const newRequest = wrapLixnetRequest(requestClone, {
68
- header: response.header.bind(response),
69
- deleteHeader: response.deleteHeader.bind(response),
70
- cookie: response.cookie.bind(response),
71
- deleteCookie: response.deleteCookie.bind(response),
72
- responseHeaders: response.responseHeaders,
73
- responseHeaderDeletes: response.responseHeaderDeletes,
74
- responseCookies: response.responseCookies,
75
- });
76
- const data = await event.handler({
77
- ...validatedInput,
78
- request: newRequest,
79
- response: response,
80
- });
81
- //check data isnt void/null/undefined
82
- if (!(data === undefined || data === null)) {
83
- response.data(data);
84
- }
85
- return response.format();
86
- }
87
- catch (error) {
88
- response.error("Handler error");
89
- return response.format();
29
+ const data = await parsed.entry.handler({
30
+ ...parsed.input,
31
+ request: createLixnetRequest(requestClone, response),
32
+ response: response,
33
+ });
34
+ //check data isnt void/null/undefined
35
+ if (!(data === undefined || data === null)) {
36
+ response.data(data);
90
37
  }
38
+ return response.format();
91
39
  }
92
40
  catch (error) {
93
- if (error instanceof z.ZodError) {
94
- response.error("Invalid input");
95
- return response.format();
96
- }
97
- response.error("Handler error");
98
- return response.format();
41
+ return this.fail(response, this.failureFromThrown(error, parsed.entry.event));
99
42
  }
100
43
  }
101
44
  }