lixnet 1.3.8 → 1.3.9

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/FOR_AGENTS.md ADDED
@@ -0,0 +1,591 @@
1
+ # Lixnet: usage guide for agents
2
+
3
+ This file is a **complete, standalone usage guide** intended for AI agents (and humans) consuming Lixnet from npm.
4
+
5
+ When Lixnet is installed, you typically see built `*.js` + `*.d.ts`, not the source `*.ts`. The goal here is that an agent can **read only this markdown** and immediately:
6
+
7
+ - implement a new RPC server + client
8
+ - add new endpoints safely
9
+ - wire Lixnet into Bun / Next.js / Workers
10
+ - use `request.cookies()` / `request.headers()` and `response.*` correctly
11
+ - use `LixnetPeer` over WebSockets (including callbacks + large payload chunking)
12
+
13
+ All examples are written for **TypeScript** and assume a Fetch-compatible runtime.
14
+
15
+ ## Goals (implicit contract)
16
+
17
+ - **Fetch-first**: everything is `Request`/`Response` compatible (Bun/Node/Next/Workers).
18
+ - **Type-first**: users bring their own `Events` type; Lixnet only derives `input`/`output` from function types.
19
+ - **Stable wire shapes**:
20
+ - HTTP request body: `{ event, input }`
21
+ - HTTP response body: `{ data }` or `{ error }`
22
+ - WS messages: event/callback/transmission shapes described below
23
+
24
+ ## What Lixnet is
25
+
26
+ Lixnet provides two related primitives:
27
+
28
+ - **HTTP RPC**: `LixnetServer` + `LixnetClient` for request/response RPC over HTTP (JSON).
29
+ - **WebSocket RPC**: `LixnetPeer` for event-based messaging over a `WebSocket`, with optional callbacks and an optional chunking layer for large payloads.
30
+
31
+ The package entrypoint exports these primitives and a small request/response helper layer.
32
+
33
+ ## Quickstart (HTTP RPC)
34
+
35
+ Install:
36
+
37
+ ```sh
38
+ bun add lixnet zod
39
+ ```
40
+
41
+ ### 1) Define your contract (`Events`)
42
+
43
+ Define an `Events` type where each key is an RPC name and each value is a **function type** describing input and output.
44
+
45
+ ```ts
46
+ export type Events = {
47
+ greet: (input: { name: string }) => Promise<string>;
48
+ add: (input: { a: number; b: number }) => number;
49
+ };
50
+ ```
51
+
52
+ ### 2) Create the RPC server (`LixnetServer`)
53
+
54
+ ```ts
55
+ import { z } from "zod";
56
+ import { LixnetServer } from "lixnet";
57
+ import type { Events } from "./events";
58
+
59
+ export const server = new LixnetServer<Events>({
60
+ debugLog: false,
61
+ defaultHeaders: {
62
+ // example defaults; you can remove these
63
+ "x-powered-by": "lixnet",
64
+ },
65
+ });
66
+
67
+ server.on([
68
+ {
69
+ event: "greet",
70
+ schema: z.object({ name: z.string().min(1) }),
71
+ handler: async ({ name, request, response }) => {
72
+ // Read inbound headers/cookies (Next-like APIs)
73
+ const ua = request.headers().get("user-agent");
74
+ if (ua) response.header("x-user-agent", ua);
75
+
76
+ // Stage cookies/headers/status
77
+ response.cookie("lastGreeting", name, { path: "/", maxAge: 60 });
78
+
79
+ return `Hello, ${name}!`;
80
+ },
81
+ },
82
+ {
83
+ event: "add",
84
+ schema: z.object({ a: z.number(), b: z.number() }),
85
+ handler: ({ a, b }) => a + b,
86
+ },
87
+ ]);
88
+ ```
89
+
90
+ ### 3) Wire the endpoint (Bun / Next.js / Workers)
91
+
92
+ #### Bun (`Bun.serve`)
93
+
94
+ ```ts
95
+ import { server } from "./rpc/server";
96
+
97
+ Bun.serve({
98
+ port: 3000,
99
+ async fetch(req) {
100
+ const url = new URL(req.url);
101
+ if (req.method === "POST" && url.pathname === "/rpc") {
102
+ return server.handle(req);
103
+ }
104
+ return new Response("Not found", { status: 404 });
105
+ },
106
+ });
107
+ ```
108
+
109
+ #### Next.js Route Handler (`app/api/rpc/route.ts`)
110
+
111
+ ```ts
112
+ import { server } from "@/rpc/server";
113
+
114
+ export async function POST(req: Request) {
115
+ return server.handle(req);
116
+ }
117
+ ```
118
+
119
+ #### Cloudflare Workers / standard Fetch handler
120
+
121
+ ```ts
122
+ import { server } from "./rpc/server";
123
+
124
+ export default {
125
+ async fetch(req: Request) {
126
+ const url = new URL(req.url);
127
+ if (req.method === "POST" && url.pathname === "/rpc") {
128
+ return server.handle(req);
129
+ }
130
+ return new Response("Not found", { status: 404 });
131
+ },
132
+ };
133
+ ```
134
+
135
+ ### 4) Create the client (`LixnetClient`)
136
+
137
+ ```ts
138
+ import { LixnetClient } from "lixnet";
139
+ import type { Events } from "./events";
140
+
141
+ const client = new LixnetClient<Events>({
142
+ rpcUrl: "http://localhost:3000/rpc",
143
+ });
144
+
145
+ const msg = await client.call("greet", { name: "World" });
146
+ const sum = await client.call("add", { a: 1, b: 2 });
147
+ ```
148
+
149
+ If you need cookies/auth, pass `RequestInit` (example):
150
+
151
+ ```ts
152
+ await client.call(
153
+ "greet",
154
+ { name: "World" },
155
+ { credentials: "include", headers: { Authorization: "Bearer ..." } },
156
+ );
157
+ ```
158
+
159
+ ## Agent playbook (how to “act”)
160
+
161
+ - **Add a new HTTP RPC**:
162
+ - Add a new key to your `Events` type.
163
+ - Register it via `server.on({ event: "...", schema?, handler })`.
164
+ - Call it with `client.call("...", input)`.
165
+ - **Validate inputs**: always provide `schema` for anything exposed publicly.
166
+ - **Set headers/cookies/status**: use `response.header(...)`, `response.cookie(...)`, `response.code(...)`.
167
+ - **Read request headers/cookies**: use `request.headers().get(...)` and `request.cookies().get(...)`.
168
+ - **Avoid breaking changes**:
169
+ - Do not change existing event names or input shapes without coordinating with the client.
170
+ - Keep the HTTP endpoint stable (`POST` JSON body `{ event, input }`).
171
+
172
+ ## Package surface (exports)
173
+
174
+ From the package entrypoint:
175
+
176
+ - **Classes**
177
+ - `LixnetServer`
178
+ - `LixnetClient`
179
+ - `LixnetPeer`
180
+ - `LixnetResponse`
181
+ - **Types**
182
+ - `LXN_ServerClient_EventType`
183
+ - `LXNServerHandler`
184
+ - `FunctionInput`
185
+ - `LXN_ServerClient_Request` (alias of `LixnetRequest`)
186
+ - `LixnetRequest`, `LixnetCookies`, `LixnetHeaders`
187
+
188
+ ## HTTP RPC: mental model
189
+
190
+ ### The “events” type
191
+
192
+ Both the server and client are generic over an `Events` object type (`LXN_ServerClient_EventType` is just `object`).
193
+
194
+ Each key is an event name and each value is a **function type** describing the RPC signature:
195
+
196
+ - Input type is `FunctionInput<Events[K]>` (the function’s first parameter type).
197
+ - Output type is `Awaited<ReturnType<Events[K]>>`.
198
+
199
+ This is how Lixnet achieves end-to-end typing without codegen: you define an `Events` type in your app and use it for both server and client.
200
+
201
+ ### Handler input shape (important)
202
+
203
+ Internally, the server calls the user’s handler with:
204
+
205
+ - **validated user input** (spread from `input`)
206
+ - plus injections:
207
+ - `request: LixnetRequest` (a proxied Request)
208
+ - `response: LixnetResponse` (the mutable accumulator)
209
+
210
+ This is encoded in `src/lib/server.ts` as:
211
+
212
+ - `FunctionInput<Events[TName]> & { request: LixnetRequest, response: LixnetResponse }`
213
+
214
+ If you ever change injection names/types, it’s a breaking change.
215
+
216
+ ### Handler examples (common patterns)
217
+
218
+ #### Returning data vs “void”
219
+
220
+ If your handler returns `undefined`/`null`, Lixnet will not set `.data(...)` automatically. If you want an explicit `data`, return it.
221
+
222
+ ```ts
223
+ server.on({
224
+ event: "noOp",
225
+ handler: async ({ response }) => {
226
+ response.code(204);
227
+ // return undefined; // no {data} payload
228
+ },
229
+ });
230
+ ```
231
+
232
+ #### Setting status codes
233
+
234
+ ```ts
235
+ server.on({
236
+ event: "createUser",
237
+ schema: z.object({ email: z.string().email() }),
238
+ handler: async ({ email, response }) => {
239
+ response.code(201);
240
+ return { id: "user_123", email };
241
+ },
242
+ });
243
+ ```
244
+
245
+ #### Cookies
246
+
247
+ ```ts
248
+ server.on({
249
+ event: "login",
250
+ schema: z.object({ token: z.string() }),
251
+ handler: async ({ token, request, response }) => {
252
+ const existing = request.cookies().get("session")?.value;
253
+ if (existing) response.deleteCookie("session", { path: "/" });
254
+ response.cookie("session", token, {
255
+ httpOnly: true,
256
+ path: "/",
257
+ sameSite: "lax",
258
+ });
259
+ return { ok: true as const };
260
+ },
261
+ });
262
+ ```
263
+
264
+ #### Headers (including append/delete)
265
+
266
+ ```ts
267
+ server.on({
268
+ event: "corsPing",
269
+ handler: async ({ response }) => {
270
+ response.header("access-control-allow-origin", "*");
271
+ response.header("access-control-allow-methods", "POST, OPTIONS");
272
+ return { ok: true as const };
273
+ },
274
+ });
275
+ ```
276
+
277
+ ### Request flow
278
+
279
+ `LixnetServer.handle(request: Request)`:
280
+
281
+ 1. Clones the incoming `Request` (`request.clone()`) because parsing consumes the body.
282
+ 2. Creates a `LixnetResponse` instance, which accumulates:
283
+ - `data` or `error`
284
+ - status code
285
+ - staged headers to set/delete
286
+ - staged cookies to set/delete
287
+ 3. Parses JSON body and validates it’s an object shaped like:
288
+ - `event` (required)
289
+ - `input` (required; can be any JSON)
290
+ 4. Looks up the registered event handler by `event` name.
291
+ 5. If a Zod schema was provided at registration time, parses `input` using `schema.parse(...)`.
292
+ 6. Wraps the cloned `Request` into a `LixnetRequest` proxy via `wrapLixnetRequest(...)`:
293
+ - `request.cookies()` gives a Next.js-like cookie API backed by the request snapshot plus staged response mutations.
294
+ - `request.headers()` gives a Next.js-like headers API backed by the request snapshot plus staged response mutations.
295
+ 7. Calls the handler with:
296
+ - validated input fields spread into the handler input object
297
+ - `request` (the wrapped request)
298
+ - `response` (the same `LixnetResponse` used to build the final Response)
299
+ 8. If the handler returns a non-`null`/non-`undefined` value, it is set as `data`.
300
+ 9. Returns `response.format()` which produces a real `Response`.
301
+
302
+ ### HTTP wire format (must stay stable)
303
+
304
+ Inbound:
305
+
306
+ ```json
307
+ { "event": "string", "input": {} }
308
+ ```
309
+
310
+ Outbound:
311
+
312
+ - Success:
313
+
314
+ ```json
315
+ { "data": {} }
316
+ ```
317
+
318
+ - Error:
319
+
320
+ ```json
321
+ { "error": "string" }
322
+ ```
323
+
324
+ ### Response formatting
325
+
326
+ Formatting is intentionally pluggable:
327
+
328
+ - `LixnetServer` accepts an optional `formatter` in its constructor.
329
+ - If not provided, it uses `getDefaultFormatter(defaultHeaders)` which:
330
+ - Ensures JSON content type.
331
+ - Applies staged header sets and deletes.
332
+ - Converts staged cookie operations into one or more `Set-Cookie` headers.
333
+ - Serializes response as:
334
+ - `{ error: string }` with status `responseCode || 500` when `.error(...)` was called.
335
+ - `{ data: any }` with status `responseCode || 200` otherwise.
336
+
337
+ Cookie values are validated to reject `;`, `=`, CR, or LF to reduce header injection risk.
338
+
339
+ ### Error behavior (important for compatibility)
340
+
341
+ `LixnetServer.handle(...)` currently uses a small set of string errors:
342
+
343
+ - `"Invalid JSON"`
344
+ - `"Invalid request body"`
345
+ - `"Event not found"`
346
+ - `"Input not found"`
347
+ - `"Invalid input"` (Zod schema failure)
348
+ - `"Handler error"` (thrown handler or unexpected errors)
349
+
350
+ If you change these strings, you may break downstream consumers that match on them. Prefer adding structured error codes later (new field) rather than changing the existing `error` string.
351
+
352
+ ### Observability caveat
353
+
354
+ At the moment, `debugLog` only logs “Invalid JSON” (see `src/lib/server.ts`). Handler errors are mapped to `"Handler error"` without logging the original exception. If you improve this, do it additively (e.g. optional logger hook) to avoid leaking sensitive details by default.
355
+
356
+ ### Default headers
357
+
358
+ `LixnetServer` accepts `defaultHeaders` which are included in every formatted response (unless deleted later by the handler).
359
+
360
+ ## HTTP Client: mental model
361
+
362
+ `LixnetClient` is a minimal fetch wrapper:
363
+
364
+ - Constructed with `{ rpcUrl }`.
365
+ - `call(event, input, options?)` sends:
366
+ - method `POST`
367
+ - JSON body `{ event, input }`
368
+ - header `Content-Type: application/json`
369
+ - spreads user-provided `RequestInit` `options` last (so callers can override headers/mode/etc.)
370
+ - Expects JSON response shaped like:
371
+ - `{ error: string }` OR `{ data: any }`
372
+ - Throws `Error(json.error)` when `error` exists, otherwise returns `data`.
373
+
374
+ Notes:
375
+
376
+ - There is no built-in retry, timeout, or streaming.
377
+ - If you add additional fields to the server response, keep `{ error }` / `{ data }` stable.
378
+
379
+ ### Client examples
380
+
381
+ #### Absolute vs relative `rpcUrl`
382
+
383
+ - In browsers, `"/rpc"` targets the current origin.
384
+ - In server-side scripts, prefer a full URL like `"http://localhost:3000/rpc"`.
385
+
386
+ ```ts
387
+ const browserClient = new LixnetClient<Events>({ rpcUrl: "/rpc" });
388
+ const nodeClient = new LixnetClient<Events>({
389
+ rpcUrl: "http://localhost:3000/rpc",
390
+ });
391
+ ```
392
+
393
+ #### Error handling
394
+
395
+ `client.call(...)` throws `Error(json.error)` when the server responds with `{ error }`.
396
+
397
+ ```ts
398
+ try {
399
+ await client.call("greet", { name: "" });
400
+ } catch (e) {
401
+ // e is Error("Invalid input") (when schema fails)
402
+ console.error(e);
403
+ }
404
+ ```
405
+
406
+ ## Request/Response helpers
407
+
408
+ ### `LixnetResponse`
409
+
410
+ `LixnetResponse` is a mutable accumulator used during request handling:
411
+
412
+ - `.data(...)` sets the payload.
413
+ - `.error(...)` sets an error string (and toggles formatted shape to `{ error }`).
414
+ - `.code(...)` sets the status code used by the formatter.
415
+ - `.header(...)`, `.deleteHeader(...)`, `.headers(...)` stage header operations.
416
+ - `.cookie(...)`, `.deleteCookie(...)` stage cookie operations.
417
+ - `.format()` produces a `Response` (by calling the configured formatter).
418
+
419
+ ### `LixnetRequest` / `wrapLixnetRequest`
420
+
421
+ `wrapLixnetRequest(...)` returns a `Proxy` over the `Request` which:
422
+
423
+ - Adds `cookies()` returning `LixnetCookies`.
424
+ - Adds `headers()` returning `LixnetHeaders`.
425
+
426
+ Both wrappers are “read from request snapshot, write into response staging”:
427
+
428
+ - Reading comes from a snapshot copy (so handler mutations do not alter the inbound request).
429
+ - Writing uses callbacks that call into `LixnetResponse` staging stores.
430
+
431
+ This emulates the ergonomic parts of Next.js’ server runtime without importing Next.js.
432
+
433
+ ## WebSocket peer: mental model
434
+
435
+ `LixnetPeer<ThisToThereEvents, ThereToThisEvents, SocketType>` provides:
436
+
437
+ - **Outgoing calls**: `peer.call(event, input, { callback? })`
438
+ - Sends `{ event, data, rf? }` over the socket (JSON string).
439
+ - If `callback` is provided, it stores it in `rb` keyed by a generated id (`rf`), and expects the remote to reply with `{ rb: <id>, data: <result> }`.
440
+ - **Incoming handlers**: `peer.on(event, handler)`
441
+ - Stores handler functions in `eventHandlers`.
442
+ - **Inbound dispatch**: `peer.handle({ data, socket })`
443
+ - Accepts incoming `data` (typically `event.data` from a WS message).
444
+ - Supports:
445
+ - Normal events: JSON string → `{ event, data, rf? }`
446
+ - Callback responses: `{ rb, data }`
447
+ - Chunked transmissions (see below)
448
+
449
+ ### WebSocket wire formats (must stay stable)
450
+
451
+ Normal outbound event (no callback):
452
+
453
+ ```json
454
+ { "event": "name", "data": {} }
455
+ ```
456
+
457
+ Normal outbound event (with callback id):
458
+
459
+ ```json
460
+ { "event": "name", "data": {}, "rf": "LX-..." }
461
+ ```
462
+
463
+ Callback response:
464
+
465
+ ```json
466
+ { "rb": "LX-...", "data": {} }
467
+ ```
468
+
469
+ ## WebSockets: complete example (`LixnetPeer`)
470
+
471
+ Define two contracts:
472
+
473
+ - `ThisToThereEvents`: what _this_ side can send
474
+ - `ThereToThisEvents`: what _this_ side can receive/handle
475
+
476
+ ### Server-side example (Bun WebSocket)
477
+
478
+ ```ts
479
+ import { LixnetPeer } from "lixnet";
480
+
481
+ type ServerToClient = {
482
+ notify: (input: { message: string }) => void;
483
+ };
484
+
485
+ type ClientToServer = {
486
+ ping: (input: { t: number }) => Promise<{ ok: true }>;
487
+ };
488
+
489
+ const peer = new LixnetPeer<ServerToClient, ClientToServer>();
490
+
491
+ peer.on("ping", async ({ t, socket }) => {
492
+ // socket is whatever you pass into peer.handle(...)
493
+ return { ok: true };
494
+ });
495
+
496
+ // Example wiring: you must set the socket and forward messages into peer.handle(...)
497
+ peer.setSocket(ws);
498
+ ws.addEventListener("message", (event) => {
499
+ peer.handle({ data: event.data, socket: ws });
500
+ });
501
+ ```
502
+
503
+ ### Client-side example (browser WebSocket)
504
+
505
+ ```ts
506
+ import { LixnetPeer } from "lixnet";
507
+
508
+ type ClientToServer = {
509
+ ping: (input: { t: number }) => Promise<{ ok: true }>;
510
+ };
511
+
512
+ type ServerToClient = {
513
+ notify: (input: { message: string }) => void;
514
+ };
515
+
516
+ const ws = new WebSocket("ws://localhost:3000/ws");
517
+ const peer = new LixnetPeer<ClientToServer, ServerToClient>();
518
+
519
+ peer.setSocket(ws);
520
+ ws.addEventListener("message", (event) => {
521
+ peer.handle({ data: event.data, socket: ws });
522
+ });
523
+
524
+ peer.on("notify", ({ message }) => {
525
+ console.log("notify:", message);
526
+ });
527
+
528
+ await peer.call(
529
+ "ping",
530
+ { t: Date.now() },
531
+ {
532
+ callback: (result) => {
533
+ console.log("pong:", result.ok);
534
+ },
535
+ },
536
+ );
537
+ ```
538
+
539
+ ### Chunking / large payload transmissions
540
+
541
+ If `transmissionLimit !== -1` and the outgoing JSON would exceed the limit, `call(...)` switches to a chunked protocol:
542
+
543
+ 1. Sender emits a “starter” message `{ tId, event, chunkCount, rf? }`.
544
+ 2. Receiver stores an entry in `transmissions[tId]` and replies `{ launch: true, tId }`.
545
+ 3. Sender then sends chunk messages as strings shaped like:
546
+ - `"${tId}.${chunkIndex}.${chunkPayload}"`
547
+ 4. Receiver collects chunks, assembles them in order, parses JSON, then dispatches to the registered handler.
548
+
549
+ There is a basic “abandoned transmission” / “slow transmission abuse” cleanup mechanism via `transmissionSecurityCheck`.
550
+
551
+ If you touch this protocol, keep it backwards compatible or bump major version (it’s wire-level behavior).
552
+
553
+ ### Chunking protocol details
554
+
555
+ - **Starter** (JSON string):
556
+ - `{ tId: "LX-...", event: "name", chunkCount: number, rf?: "LX-..." }`
557
+ - **Launch** (JSON string):
558
+ - `{ launch: true, tId: "LX-..." }`
559
+ - **Chunk** (raw string, not JSON):
560
+ - `"LX-....<dot><chunkIndex>.<chunkData>"`
561
+
562
+ Security/cleanup notes:
563
+
564
+ - Receiver schedules `transmissionSecurityCheck` after 30s on starter receipt.
565
+ - The check prunes:
566
+ - abandoned transmissions (no chunks or last chunk > 30s ago)
567
+ - very slow transmissions (estimated completion > 5 minutes)
568
+
569
+ ## How to extend safely
570
+
571
+ - **Adding new features**:
572
+ - Prefer additive changes (new fields) over changing existing shapes/strings.
573
+ - Keep `LixnetServer.handle(...)` accepting `{ event, input }` unchanged.
574
+ - Keep `LixnetClient.call(...)` returning `data` and throwing on `error`.
575
+ - **Changing cookie/header behavior**:
576
+ - Be careful: `wrapLixnetRequest` merges staged response headers/cookies into the read APIs; this is relied upon for “read your writes” inside a handler.
577
+ - Ensure header delete semantics remain case-insensitive (uses `toLowerCase()`).
578
+ - **Changing formatter**:
579
+ - Default formatter must remain usable in any Fetch-compatible runtime (Node/Next/Bun/Workers).
580
+ - Preserve multiple `Set-Cookie` support (uses `headers.append`).
581
+ - **Versioning**:
582
+ - Wire protocol changes (HTTP response shape, WS messages/chunking) should be treated as breaking.
583
+
584
+ ## Where to look first
585
+
586
+ - `src/lib/server.ts`: HTTP RPC, Zod validation, request/response injection.
587
+ - `src/lib/util/request.ts`: request wrappers (cookies/headers), and the `wrapLixnetRequest` proxy.
588
+ - `src/lib/util/response.ts`: response accumulator.
589
+ - `src/lib/util/getDefaultFormatter.ts`: default serialization, headers/cookies.
590
+ - `src/lib/client.ts`: HTTP client.
591
+ - `src/lib/peer.ts`: WebSocket peer + chunking protocol.
package/README.md CHANGED
@@ -0,0 +1,366 @@
1
+ <div align="center">
2
+ <h1>Lixnet</h1>
3
+ <h3>Lightweight, type-safe RPC over HTTP and WebSockets.<br />The tRPC and Next.js Server Actions, but for everyone.</h3>
4
+
5
+ <a href="https://github.com/Nitlix/Lixnet">
6
+ <img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/Nitlix/Lixnet?style=social">
7
+ </a>
8
+
9
+ <a href="https://www.npmjs.com/package/lixnet">
10
+ <img alt="npm version" src="https://img.shields.io/npm/v/lixnet.svg">
11
+ </a>
12
+ <a href="https://www.npmjs.com/package/lixnet">
13
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dm/lixnet.svg">
14
+ </a>
15
+ </div>
16
+
17
+ <br />
18
+
19
+ ## Intro
20
+
21
+ Lixnet is a tiny yet powerful TypeScript-first RPC library for teams who want a **small, explicit RPC layer** with excellent typing, without codegen or framework lock-in.
22
+
23
+ If you like the ergonomics of **tRPC** or **Next.js Server Actions**, but want something that:
24
+
25
+ - stays close to the **Fetch** platform (`Request`/`Response`)
26
+ - works in **Bun / Next.js / Workers**
27
+ - keeps the protocol simple and inspectable
28
+
29
+ Lixnet is a good fit.
30
+
31
+ It gives you:
32
+
33
+ - **HTTP RPC** via `fetch` (`LixnetServer` + `LixnetClient`)
34
+ - **WebSocket events + callbacks** (`LixnetPeer`)
35
+ - **Optional Zod validation** on the server
36
+ - **Next.js-like** `request.cookies()` / `request.headers()` ergonomics inside handlers (without pulling in Next)
37
+
38
+ It’s designed to be minimal: no codegen, no schema registry, no client bundler magic.
39
+
40
+ ## Table of contents
41
+
42
+ - [Quickstart (HTTP RPC)](#quickstart-http-rpc)
43
+ - [Framework adapters (server wiring)](#framework-adapters-server-wiring)
44
+ - [Server: `LixnetServer`](#server-lixnetserver)
45
+ - [Client: `LixnetClient`](#client-lixnetclient)
46
+ - [Handlers: `request` and `response`](#handlers-request-and-response)
47
+ - [WebSockets: `LixnetPeer`](#websockets-lixnetpeer)
48
+ - [API reference](#api-reference)
49
+ - [Contributor docs](#contributor-docs)
50
+ - [License](#license)
51
+
52
+ ## Quickstart (HTTP RPC)
53
+
54
+ Install:
55
+
56
+ ```sh
57
+ bun add lixnet zod
58
+ ```
59
+
60
+ Other package managers:
61
+
62
+ ```sh
63
+ pnpm add lixnet zod
64
+ npm i lixnet zod
65
+ ```
66
+
67
+ ### 1) Define an `Events` type
68
+
69
+ This is the contract shared by server and client.
70
+
71
+ ```ts
72
+ type Events = {
73
+ greet: (input: { name: string }) => Promise<string>;
74
+ };
75
+ ```
76
+
77
+ ### 2) Create the RPC server
78
+
79
+ Register handlers with optional Zod schemas, then expose an HTTP endpoint that forwards the incoming `Request` to `server.handle(...)`.
80
+
81
+ ```ts
82
+ import { z } from "zod";
83
+ import { LixnetServer } from "lixnet";
84
+
85
+ type Events = {
86
+ greet: (input: { name: string }) => Promise<string>;
87
+ };
88
+
89
+ export const server = new LixnetServer<Events>({
90
+ debugLog: false,
91
+ });
92
+
93
+ server.on({
94
+ event: "greet",
95
+ schema: z.object({ name: z.string() }),
96
+ handler: async ({ name, request, response }) => {
97
+ // Optional: read request cookies/headers (Next-like API)
98
+ const userAgent = request.headers().get("user-agent");
99
+ if (userAgent) response.header("x-user-agent", userAgent);
100
+
101
+ return `Hello, ${name}!`;
102
+ },
103
+ });
104
+ ```
105
+
106
+ ### 3) Wire the HTTP endpoint
107
+
108
+ Lixnet uses the Fetch standard `Request`/`Response`, so wiring is always “forward `Request` into `server.handle(...)`”.
109
+
110
+ ## Framework adapters (server wiring)
111
+
112
+ ### Bun
113
+
114
+ ```ts
115
+ import { server } from "./rpc/server";
116
+
117
+ Bun.serve({
118
+ port: 3000,
119
+ async fetch(req) {
120
+ const url = new URL(req.url);
121
+ if (req.method === "POST" && url.pathname === "/rpc") {
122
+ return server.handle(req);
123
+ }
124
+ return new Response("Not found", { status: 404 });
125
+ },
126
+ });
127
+ ```
128
+
129
+ ### Next.js Route Handler
130
+
131
+ ```ts
132
+ export async function POST(req: Request) {
133
+ return server.handle(req);
134
+ }
135
+ ```
136
+
137
+ ### Cloudflare Workers / standard Fetch handler
138
+
139
+ ```ts
140
+ export default {
141
+ async fetch(req: Request) {
142
+ const url = new URL(req.url);
143
+ if (req.method === "POST" && url.pathname === "/rpc") {
144
+ return server.handle(req);
145
+ }
146
+ return new Response("Not found", { status: 404 });
147
+ },
148
+ };
149
+ ```
150
+
151
+ ### 4) Create the RPC client
152
+
153
+ ```ts
154
+ import { LixnetClient } from "lixnet";
155
+
156
+ type Events = {
157
+ greet: (input: { name: string }) => Promise<string>;
158
+ };
159
+
160
+ const client = new LixnetClient<Events>({ rpcUrl: "/api/rpc" });
161
+
162
+ const message = await client.call("greet", { name: "World" });
163
+ ```
164
+
165
+ If you need auth/cookies, pass `fetch` options:
166
+
167
+ ```ts
168
+ await client.call(
169
+ "greet",
170
+ { name: "World" },
171
+ { credentials: "include", headers: { Authorization: "Bearer ..." } },
172
+ );
173
+ ```
174
+
175
+ ## Server: `LixnetServer`
176
+
177
+ ### Registering events
178
+
179
+ `server.on(...)` accepts either one registration object or an array.
180
+
181
+ - **`event`**: string key matching your `Events` type
182
+ - **`schema`** (optional): Zod schema to validate `input`
183
+ - **`handler`**: receives validated input plus `{ request, response }` injections
184
+
185
+ Example registering multiple events:
186
+
187
+ ```ts
188
+ server.on([
189
+ {
190
+ event: "greet",
191
+ schema: z.object({ name: z.string() }),
192
+ handler: async ({ name }) => `Hello, ${name}!`,
193
+ },
194
+ {
195
+ event: "health",
196
+ handler: async () => ({ ok: true as const }),
197
+ },
198
+ ]);
199
+ ```
200
+
201
+ ### Handling requests
202
+
203
+ `server.handle(request)` expects the request body to be JSON:
204
+
205
+ ```json
206
+ { "event": "someEvent", "input": { "...": "..." } }
207
+ ```
208
+
209
+ Responses are JSON and shaped as either:
210
+
211
+ ```json
212
+ { "data": "..." }
213
+ ```
214
+
215
+ or
216
+
217
+ ```json
218
+ { "error": "..." }
219
+ ```
220
+
221
+ ### Server configuration
222
+
223
+ `new LixnetServer({ ... })` supports:
224
+
225
+ - **`defaultHeaders`**: headers included on every response (unless deleted later)
226
+ - **`formatter`**: customize how `LixnetResponse` becomes a `Response`
227
+ - **`logger`** + **`debugLog`**: currently used for invalid JSON logging
228
+
229
+ Example:
230
+
231
+ ```ts
232
+ const server = new LixnetServer<Events>({
233
+ debugLog: true,
234
+ defaultHeaders: {
235
+ "access-control-allow-origin": "*",
236
+ },
237
+ });
238
+ ```
239
+
240
+ ## Client: `LixnetClient`
241
+
242
+ `client.call(event, input, options?)`:
243
+
244
+ - sends a `POST` with `{ event, input }`
245
+ - throws `Error(...)` when the response contains `{ error }`
246
+ - otherwise returns `{ data }`’s value
247
+
248
+ ### Client creation
249
+
250
+ ```ts
251
+ const client = new LixnetClient<Events>({
252
+ rpcUrl: "https://api.example.com/rpc",
253
+ });
254
+ ```
255
+
256
+ ## Handlers: `request` and `response`
257
+
258
+ Handler signature is:
259
+
260
+ - your validated input fields
261
+ - plus:
262
+ - `request`: a `Request` enhanced with `request.cookies()` and `request.headers()`
263
+ - `response`: a `LixnetResponse` you can use to stage headers/cookies/status
264
+
265
+ Common operations:
266
+
267
+ - **Set status**: `response.code(201)`
268
+ - **Set header**: `response.header("X-Foo", "bar")`
269
+ - **Delete header**: `response.deleteHeader("x-foo")`
270
+ - **Set cookie**: `response.cookie("session", "abc", { httpOnly: true, path: "/" })`
271
+ - **Delete cookie**: `response.deleteCookie("session", { path: "/" })`
272
+
273
+ `request.cookies()` / `request.headers()` also support “read your writes” inside the handler because they merge staged response mutations.
274
+
275
+ ## WebSockets: `LixnetPeer`
276
+
277
+ `LixnetPeer` is a typed event dispatcher for WebSockets with:
278
+
279
+ - **fire-and-forget events**
280
+ - **optional callbacks** (request/response style over WS)
281
+ - **optional chunking** for large payloads (see contributor docs for protocol details)
282
+
283
+ Minimal sketch:
284
+
285
+ ```ts
286
+ import { LixnetPeer } from "lixnet";
287
+
288
+ type ClientToServer = {
289
+ ping: (input: { t: number }) => Promise<{ ok: true }>;
290
+ };
291
+
292
+ type ServerToClient = {
293
+ notify: (input: { message: string }) => void;
294
+ };
295
+
296
+ const peer = new LixnetPeer<ServerToClient, ClientToServer>();
297
+
298
+ peer.on("ping", async ({ t, socket }) => {
299
+ return { ok: true };
300
+ });
301
+
302
+ // In your WS message handler:
303
+ // peer.handle({ data: event.data, socket: ws });
304
+ ```
305
+
306
+ ### WebSocket setup (typical pattern)
307
+
308
+ ```ts
309
+ const peer = new LixnetPeer<ServerToClient, ClientToServer>();
310
+ peer.setSocket(ws);
311
+
312
+ ws.addEventListener("message", (event) => {
313
+ peer.handle({ data: event.data, socket: ws });
314
+ });
315
+ ```
316
+
317
+ ### Callbacks (request/response over WS)
318
+
319
+ ```ts
320
+ await peer.call(
321
+ "ping",
322
+ { t: Date.now() },
323
+ {
324
+ callback: (result) => {
325
+ // result is typed as Awaited<ReturnType<ClientToServer["ping"]>>
326
+ console.log(result.ok);
327
+ },
328
+ },
329
+ );
330
+ ```
331
+
332
+ ### Large payloads (chunking)
333
+
334
+ If messages can exceed your runtime’s WS frame limits, enable chunking:
335
+
336
+ ```ts
337
+ peer.setTransmissionLimit(64_000); // bytes-ish (string length)
338
+ peer.setTransmissionChunksLimit(20); // currently stored, not enforced by sender
339
+ ```
340
+
341
+ ## API reference
342
+
343
+ ### Exports
344
+
345
+ From `src/exports.ts`:
346
+
347
+ - **`LixnetServer`**
348
+ - **`LixnetClient`**
349
+ - **`LixnetPeer`**
350
+ - **`LixnetResponse`**
351
+
352
+ Types:
353
+
354
+ - **`LXN_ServerClient_EventType`**
355
+ - **`LXNServerHandler`**
356
+ - **`FunctionInput`**
357
+ - **`LXN_ServerClient_Request`** (alias of `LixnetRequest`)
358
+ - **`LixnetRequest`**, **`LixnetCookies`**, **`LixnetHeaders`**
359
+
360
+ ## Contributor docs
361
+
362
+ - **Implementation + extension guide**: [`FOR_AGENTS.md`](FOR_AGENTS.md)
363
+
364
+ ## License
365
+
366
+ MIT
package/dist/exports.js CHANGED
@@ -1,3 +1,4 @@
1
+ // With <3 by https://nitlix.com
1
2
  import LixnetServer from "./lib/server";
2
3
  import LixnetClient from "./lib/client";
3
4
  import LixnetPeer from "./lib/peer";
@@ -2,6 +2,7 @@ export default function (defaultHeaders) {
2
2
  function formatter() {
3
3
  const headers = new Headers({
4
4
  "Content-Type": "application/json",
5
+ "X-Server": "Lixnet",
5
6
  ...defaultHeaders,
6
7
  });
7
8
  for (const [headerName, headerValue] of Object.entries(this.responseHeaders)) {
@@ -1,17 +1,12 @@
1
- export type CookieOptions = {
1
+ export type CookieBaseOptions = {
2
2
  domain?: string;
3
3
  path?: string;
4
- maxAge?: number;
5
4
  httpOnly?: boolean;
6
5
  secure?: boolean;
7
6
  sameSite?: 'lax' | 'strict' | 'none';
8
7
  };
9
- export type CookieDeleteOptions = {
10
- domain?: string;
11
- path?: string;
12
- httpOnly?: boolean;
13
- secure?: boolean;
14
- sameSite?: 'lax' | 'strict' | 'none';
8
+ export type CookieFullOptions = CookieBaseOptions & {
9
+ maxAge?: number;
15
10
  };
16
11
  export declare class LixnetResponse {
17
12
  responseData: any;
@@ -22,7 +17,7 @@ export declare class LixnetResponse {
22
17
  responseCookies: Record<string, {
23
18
  type: "value" | "delete";
24
19
  value?: string;
25
- options?: CookieOptions | CookieDeleteOptions;
20
+ options?: CookieFullOptions;
26
21
  }>;
27
22
  constructor({ formatter }: {
28
23
  formatter: (this: LixnetResponse) => Response;
@@ -33,8 +28,8 @@ export declare class LixnetResponse {
33
28
  error(error: string): void;
34
29
  code(code: number): void;
35
30
  headers(headers: Record<string, string>): void;
36
- cookie(cookieName: string, cookieValue: string, cookieOptions?: CookieOptions): void;
37
- deleteCookie(cookieName: string, options?: CookieDeleteOptions): void;
31
+ cookie(cookieName: string, cookieValue: string, cookieOptions?: CookieFullOptions): void;
32
+ deleteCookie(cookieName: string, options?: CookieBaseOptions): void;
38
33
  format: (this: LixnetResponse) => Response;
39
34
  setFormatter(formatter: (this: LixnetResponse) => Response): void;
40
35
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lixnet",
3
- "version": "1.3.8",
3
+ "version": "1.3.9",
4
4
  "author": "nitlix",
5
5
  "license": "MIT",
6
6
  "repository": {