@fairfox/polly 0.22.0 → 0.24.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.
Files changed (36) hide show
  1. package/README.md +55 -1
  2. package/dist/src/elysia/index.js +5 -3
  3. package/dist/src/elysia/index.js.map +3 -3
  4. package/dist/src/elysia/peer-repo-plugin.d.ts +1 -1
  5. package/dist/src/mesh-node.d.ts +89 -0
  6. package/dist/src/mesh-node.js +594 -0
  7. package/dist/src/mesh-node.js.map +14 -0
  8. package/dist/src/mesh.d.ts +10 -0
  9. package/dist/src/mesh.js +926 -24
  10. package/dist/src/mesh.js.map +17 -9
  11. package/dist/src/peer.d.ts +1 -0
  12. package/dist/src/peer.js +108 -85
  13. package/dist/src/peer.js.map +11 -10
  14. package/dist/src/shared/lib/blob-cache.d.ts +58 -0
  15. package/dist/src/shared/lib/blob-store-impl.d.ts +33 -0
  16. package/dist/src/shared/lib/blob-store.d.ts +87 -0
  17. package/dist/src/shared/lib/blob-transfer.d.ts +58 -0
  18. package/dist/src/shared/lib/crdt-specialised.d.ts +1 -1
  19. package/dist/src/shared/lib/crdt-state.d.ts +1 -1
  20. package/dist/src/shared/lib/keyring-storage.d.ts +57 -0
  21. package/dist/src/shared/lib/mesh-client.d.ts +91 -0
  22. package/dist/src/shared/lib/mesh-network-adapter.d.ts +1 -1
  23. package/dist/src/shared/lib/mesh-signaling-client.d.ts +6 -0
  24. package/dist/src/shared/lib/mesh-state.d.ts +1 -1
  25. package/dist/src/shared/lib/mesh-webrtc-adapter.d.ts +20 -1
  26. package/dist/src/shared/lib/peer-relay-adapter.d.ts +1 -1
  27. package/dist/src/shared/lib/peer-repo-server.d.ts +1 -1
  28. package/dist/src/shared/lib/peer-state.d.ts +1 -1
  29. package/dist/src/shared/lib/wasm-init.d.ts +17 -0
  30. package/dist/tools/quality/src/cli.js +98 -47
  31. package/dist/tools/quality/src/cli.js.map +4 -4
  32. package/dist/tools/quality/src/index.d.ts +25 -0
  33. package/dist/tools/quality/src/index.js +196 -0
  34. package/dist/tools/quality/src/index.js.map +10 -0
  35. package/dist/tools/quality/src/no-as-casting.d.ts +44 -0
  36. package/package.json +22 -2
package/README.md CHANGED
@@ -125,6 +125,53 @@ First-time key exchange between devices uses a pairing token displayed as a QR c
125
125
 
126
126
  The three tiers coexist in one application — public settings in `$sharedState`, collaborative documents in `$peerState`, private notes in `$meshState`. See [docs/STATE.md](docs/STATE.md) for the full decision tree and [docs/RFC-041-choosing.md](docs/RFC-041-choosing.md) for the design rationale.
127
127
 
128
+ ### Node and Bun are first-class mesh peers
129
+
130
+ Archival cron, LLM proxies, admin CLIs, headless bridges — every always-on participant gets the same state primitives as the browser, without monkey-patching globals or writing bespoke transport wiring. Polly ships a factory that accepts injectable transport and storage:
131
+
132
+ ```typescript
133
+ import { createMeshClient, $meshState } from "@fairfox/polly/mesh";
134
+ import { bootstrapCliKeyring, fileKeyringStorage } from "@fairfox/polly/mesh/node";
135
+ import { RTCPeerConnection } from "werift"; // or '@roamhq/wrtc'
136
+
137
+ const storage = fileKeyringStorage("~/.fairfox/keyring.json");
138
+ const keyring = await bootstrapCliKeyring({ storage }); // first run prompts for a pairing token
139
+
140
+ const client = await createMeshClient({
141
+ signaling: { url: "wss://example.com/polly/signaling", peerId: "cli-a1b2" },
142
+ rtc: { RTCPeerConnection },
143
+ keyring,
144
+ });
145
+
146
+ const doc = $meshState("agenda", { items: [] });
147
+ await doc.loaded;
148
+ await client.close();
149
+ ```
150
+
151
+ `createMeshClient` is runtime-agnostic — in a browser the `rtc` option is optional because `globalThis.RTCPeerConnection` exists. The `@fairfox/polly/mesh/node` subpath adds filesystem-backed keyring storage, atomic writes with `0600` permissions, and the stdin bootstrap flow. Neither `werift` nor `@roamhq/wrtc` is bundled; both are declared as optional peer dependencies. Pick the one that fits your deployment — `werift` installs cleanly anywhere (pure TypeScript, no native deps), `@roamhq/wrtc` is faster but needs prebuilt binaries for your platform.
152
+
153
+ ### Blob storage for large files
154
+
155
+ CRDT documents shouldn't carry binary payloads — the op history grows with every sync. Polly ships a content-addressed blob store that transfers files peer-to-peer over the same WebRTC channels as `$meshState`, with no server storage. Documents hold lightweight `BlobRef` values; the bytes live in a local IndexedDB cache and move between peers in 64 KiB chunks.
156
+
157
+ ```typescript
158
+ import { createBlobStore, createBlobRef } from "@fairfox/polly/mesh";
159
+
160
+ const blobs = createBlobStore(webrtcAdapter, { encrypt: { key: docKey } });
161
+
162
+ // Sender
163
+ const bytes = new Uint8Array(await file.arrayBuffer());
164
+ const ref = await createBlobRef({ bytes, filename: file.name, mimeType: file.type });
165
+ await blobs.put(ref, bytes); // caches locally, announces to peers
166
+ doc.value = { ...doc.value, attachment: ref };
167
+
168
+ // Receiver (on any connected peer)
169
+ const received = await blobs.get(ref.hash); // fetches from peers, verifies hash
170
+ const url = await blobs.url(ref.hash); // object URL for <img src>
171
+ ```
172
+
173
+ SHA-256 content addressing deduplicates across peers and documents. Encryption is optional — when configured, the sender encrypts once (XSalsa20-Poly1305) and chunks the ciphertext; the receiver reassembles, decrypts, and verifies the plaintext hash against the `BlobRef`. See [docs/RFC-042-blob-sync.md](docs/RFC-042-blob-sync.md) for the design.
174
+
128
175
  ## Verification that plugs in
129
176
 
130
177
  A popup and a background script both write to the same state. A content script reads it mid-update. Tests miss these bugs because they depend on timing.
@@ -243,13 +290,20 @@ polly format Format your code
243
290
  polly test Run tests
244
291
  polly verify Run formal verification
245
292
  polly visualize Generate architecture diagrams (Structurizr DSL)
293
+ polly quality Run conformance checks (no-as-casting)
246
294
  ```
247
295
 
248
296
  ## Quality tooling
249
297
 
250
298
  Polly ships conformance checks and a browser test harness that consuming applications can adopt directly.
251
299
 
252
- **No-as-casting check.** Bans TypeScript `as` type assertions codebase-wide (only `as const` and the explicit escape hatch `as unknown as` are allowed). Violations include pattern-specific fix advice. Import it programmatically:
300
+ **No-as-casting check.** Bans TypeScript `as` type assertions codebase-wide (only `as const` and the explicit escape hatch `as unknown as` are allowed). Violations include pattern-specific fix advice. Run as a CLI:
301
+
302
+ ```bash
303
+ polly quality [--root <dir>] [--exclude-packages <names>] [--exclude-files <names>]
304
+ ```
305
+
306
+ Or import it programmatically for integration into custom check scripts:
253
307
 
254
308
  ```typescript
255
309
  import { checkNoAsCasting } from "@fairfox/polly/quality";
@@ -48,7 +48,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
48
48
  import { Elysia } from "elysia";
49
49
 
50
50
  // src/shared/lib/peer-repo-server.ts
51
- import { Repo } from "@automerge/automerge-repo";
51
+ import { Repo } from "@automerge/automerge-repo/slim";
52
52
  import { WebSocketServerAdapter } from "@automerge/automerge-repo-network-websocket";
53
53
  import { NodeFSStorageAdapter } from "@automerge/automerge-repo-storage-nodefs";
54
54
  import * as ws from "ws";
@@ -78,7 +78,9 @@ async function createPeerRepoServer(options) {
78
78
  client.terminate();
79
79
  } catch {}
80
80
  }
81
- repo.shutdown();
81
+ try {
82
+ await repo.shutdown();
83
+ } catch {}
82
84
  try {
83
85
  wss.close();
84
86
  } catch {}
@@ -394,4 +396,4 @@ export {
394
396
  peerRepo
395
397
  };
396
398
 
397
- //# debugId=0BDEE51AC0A70CC764756E2164756E21
399
+ //# debugId=8580681D01EEB1A864756E2164756E21
@@ -3,13 +3,13 @@
3
3
  "sources": ["../src/elysia/peer-repo-plugin.ts", "../src/shared/lib/peer-repo-server.ts", "../src/elysia/plugin.ts", "../src/core/clock.ts", "../src/utils/function-serialization.ts", "../src/elysia/signaling-server-plugin.ts"],
4
4
  "sourcesContent": [
5
5
  "// @ts-nocheck - Optional peer dependencies (elysia, @automerge/automerge-repo*)\n/**\n * peerRepo — Elysia plugin that runs a Polly peer-relay server alongside an\n * Elysia application and exposes the server's Repo on the Elysia context.\n *\n * The Phase 1 plan originally framed the relay server as an Elysia plugin\n * that registers a WebSocket route on Elysia's native socket layer. That\n * design does not work directly: Automerge's WebSocketServerAdapter requires\n * an `isomorphic-ws` WebSocketServer instance, and Elysia's WebSocket layer\n * is built on Bun's native WebSocket API, which is a different shape. The\n * realistic Phase 1 cut is therefore a *lifecycle* plugin: it runs\n * createPeerRepoServer on its own port during Elysia startup, decorates the\n * Elysia context so route handlers can reach the resulting Repo, and tears\n * the server down during Elysia shutdown. Authenticated WebSocket upgrades\n * via Elysia's hook system are a Phase 1.1 follow-up that requires either\n * a custom Bun-native NetworkAdapter or an upgrade-time auth bridge.\n *\n * @example\n * ```ts\n * import { Elysia } from \"elysia\";\n * import { peerRepo } from \"@fairfox/polly/elysia\";\n *\n * const app = new Elysia()\n * .use(peerRepo({ port: 3030, storagePath: \"./data/polly-peer\" }))\n * .get(\"/stats\", ({ pollyPeerRepo }) => {\n * return { peers: pollyPeerRepo.peers.length };\n * })\n * .listen(8080);\n * ```\n */\n\nimport { Elysia } from \"elysia\";\nimport {\n type CreatePeerRepoServerOptions,\n createPeerRepoServer,\n type PeerRepoServer,\n} from \"../shared/lib/peer-repo-server\";\n\nexport interface PeerRepoPluginOptions extends CreatePeerRepoServerOptions {\n /** Optional path for a health endpoint that returns peer count and storage\n * id. Set to false to skip the health route entirely. Defaults to\n * \"/polly/peer/health\". */\n healthPath?: string | false;\n}\n\n/**\n * Elysia plugin that boots a Polly peer-relay server alongside the host app\n * and decorates the context with `pollyPeerRepo` (the Repo) and\n * `pollyPeerServer` (the full {@link PeerRepoServer} for advanced use).\n *\n * The plugin starts the relay server during Elysia's onStart lifecycle and\n * shuts it down during onStop, so route handlers and cron jobs can use the\n * decorated Repo throughout the request lifetime without managing the\n * underlying transport themselves.\n */\nexport function peerRepo(options: PeerRepoPluginOptions) {\n // The plugin holds a single PeerRepoServer for the lifetime of the Elysia\n // app. It is created during onStart so the listening socket is bound and\n // ready before any request handler can reach it.\n let server: PeerRepoServer | undefined;\n\n const healthPath =\n options.healthPath === false ? null : (options.healthPath ?? \"/polly/peer/health\");\n\n let app = new Elysia({ name: \"polly-peer-repo\" })\n .decorate(\"pollyPeerRepo\", null as unknown as PeerRepoServer[\"repo\"] | null)\n .decorate(\"pollyPeerServer\", null as unknown as PeerRepoServer | null)\n .onStart(async () => {\n server = await createPeerRepoServer(options);\n // Decorate after construction so handlers see the live Repo. Elysia's\n // decorate is mutable in-place when called on the running instance.\n app.decorate(\"pollyPeerRepo\", server.repo);\n app.decorate(\"pollyPeerServer\", server);\n })\n .onStop(async () => {\n if (server) {\n await server.close();\n server = undefined;\n }\n });\n\n if (healthPath) {\n app = app.get(healthPath, () => {\n if (!server) {\n return { status: \"starting\", peers: 0 };\n }\n return {\n status: \"running\",\n peers: server.repo.peers.length,\n port: options.port,\n };\n });\n }\n\n return app;\n}\n",
6
- "/**\n * peer-repo-server — Phase 1 server-side factory for the Polly peer-relay\n * transport. Constructs an Automerge-Repo `Repo` wired to a WebSocket server\n * and a NodeFS storage backend, ready to relay sync messages between\n * connected $peerState clients.\n *\n * The \"always-on peer\" role for $peerState lives here. The server holds a\n * full Automerge replica of every document, participates in the sync protocol\n * as an ordinary peer, and persists state to disk so the next process restart\n * picks up where the previous one left off. Server-side cron, HTTP handlers,\n * and other compute can open document handles on the returned Repo and mutate\n * them; mutations propagate to connected clients through the same sync\n * protocol that handles client-to-client traffic.\n *\n * The plan originally called this an \"Elysia plugin,\" but Automerge's\n * `WebSocketServerAdapter` requires an `isomorphic-ws` `WebSocketServer`\n * instance — not Elysia's native WebSocket — so the cleanest first cut is a\n * standalone factory that runs its own `ws` server. Elysia integration for\n * authenticated upgrades is a Phase 1.1 follow-up that wraps this factory.\n *\n * @example\n * ```ts\n * import { createPeerRepoServer } from \"@fairfox/polly\";\n *\n * const server = await createPeerRepoServer({\n * port: 3030,\n * storagePath: \"./data/polly-peer\",\n * });\n *\n * // Open a document handle on the server's Repo for cron or compute work.\n * const handle = server.repo.create({ counter: 0 });\n *\n * // On shutdown:\n * await server.close();\n * ```\n */\n\nimport { Repo } from \"@automerge/automerge-repo\";\nimport { WebSocketServerAdapter } from \"@automerge/automerge-repo-network-websocket\";\nimport { NodeFSStorageAdapter } from \"@automerge/automerge-repo-storage-nodefs\";\nimport * as ws from \"ws\";\n\n// `@types/ws` uses CJS `export = WebSocket` with WebSocketServer hanging off\n// the namespace. Under the project's bundler module resolution, the namespace\n// import gives us access to both the constructor and the type.\ntype WebSocketServer = ws.WebSocketServer;\n\nexport interface CreatePeerRepoServerOptions {\n /** Port to listen on. The factory creates its own `WebSocketServer` and\n * binds to this port. */\n port: number;\n /** Filesystem directory for the NodeFS storage adapter. The directory is\n * created on demand. Defaults to `./automerge-repo-data` (Automerge's own\n * default). */\n storagePath?: string;\n /** Hostname interface to bind to. Defaults to all interfaces. */\n host?: string;\n /** Override the `WebSocketServer` instance entirely. When provided, `port`\n * and `host` are ignored and the caller is responsible for the lifecycle.\n * Useful for tests that want to bind to a random port. */\n webSocketServer?: WebSocketServer;\n}\n\nexport interface PeerRepoServer {\n /** A configured Repo participating as the always-on peer. Server-side\n * cron and HTTP handlers can open document handles on this directly. */\n repo: Repo;\n /** The underlying WebSocket server. Exposed for advanced use such as\n * health checks or graceful shutdown coordination. */\n webSocketServer: WebSocketServer;\n /** The Automerge network adapter wrapping the WebSocket server. */\n adapter: WebSocketServerAdapter;\n /** The NodeFS storage adapter writing to {@link CreatePeerRepoServerOptions.storagePath}. */\n storage: NodeFSStorageAdapter;\n /** Tear down the server: disconnect peers, flush storage, close the\n * underlying WebSocket server. Returns a promise that resolves once the\n * tear-down is complete. */\n close: () => Promise<void>;\n}\n\n/**\n * Construct a Polly peer-relay server. Returns a Repo that participates as\n * the always-on peer, the underlying WebSocket server and storage adapter\n * for advanced use, and a close function for orderly shutdown.\n *\n * Applications typically call this once at startup, hold the returned\n * `repo` reference for cron and compute work, and wire the close function\n * into their process shutdown signal handlers.\n */\nexport async function createPeerRepoServer(\n options: CreatePeerRepoServerOptions\n): Promise<PeerRepoServer> {\n // Construct the WebSocket server first and wait until it is actually\n // listening before wiring up the Repo. Using the constructor callback\n // avoids the race where the 'listening' event fires before our listener\n // is attached (the callback form is reliable across Node and Bun).\n const wss = await (options.webSocketServer\n ? Promise.resolve(options.webSocketServer)\n : new Promise<WebSocketServer>((resolve, reject) => {\n const created: WebSocketServer = new ws.WebSocketServer(\n {\n port: options.port,\n ...(options.host !== undefined && { host: options.host }),\n },\n () => resolve(created)\n );\n created.once(\"error\", reject);\n }));\n\n // The cast bridges a @types/ws identity quirk: Automerge's adapter type\n // expects WebSocketServer with options.WebSocket typed via isomorphic-ws's\n // CJS-style namespace, and our direct `ws` import resolves through a\n // different path with the same runtime shape but a structurally distinct\n // TypeScript type. The runtime is identical, the cast names that fact.\n const adapter = new WebSocketServerAdapter(\n wss as unknown as ConstructorParameters<typeof WebSocketServerAdapter>[0]\n );\n const storage = new NodeFSStorageAdapter(options.storagePath);\n\n const repo = new Repo({\n network: [adapter],\n storage,\n });\n\n // Force the storage subsystem to finish initialising before returning. The\n // Repo constructor is synchronous, but its NetworkSubsystem holds back the\n // peer-metadata JOIN until storageSubsystem.id() resolves. If a client\n // connects before that resolution lands, the handshake stalls indefinitely.\n // Awaiting storageId() drains the relevant microtask chain and guarantees\n // the server is ready to accept peers when this factory returns.\n await repo.storageId();\n\n return {\n repo,\n webSocketServer: wss,\n adapter,\n storage,\n close: async () => {\n // Forcibly terminate any still-open client sockets before closing the\n // server, otherwise wss.close() can hang waiting for orderly drain when\n // a peer disappeared without a clean disconnect. We then fire the\n // server close without awaiting its callback — the underlying socket\n // is released immediately by terminate(), and waiting for the close\n // callback can hang under Bun even after every client is gone.\n for (const client of wss.clients) {\n try {\n client.terminate();\n } catch {\n // best effort\n }\n }\n void repo.shutdown();\n try {\n wss.close();\n } catch {\n // best effort\n }\n },\n };\n}\n",
6
+ "/**\n * peer-repo-server — Phase 1 server-side factory for the Polly peer-relay\n * transport. Constructs an Automerge-Repo `Repo` wired to a WebSocket server\n * and a NodeFS storage backend, ready to relay sync messages between\n * connected $peerState clients.\n *\n * The \"always-on peer\" role for $peerState lives here. The server holds a\n * full Automerge replica of every document, participates in the sync protocol\n * as an ordinary peer, and persists state to disk so the next process restart\n * picks up where the previous one left off. Server-side cron, HTTP handlers,\n * and other compute can open document handles on the returned Repo and mutate\n * them; mutations propagate to connected clients through the same sync\n * protocol that handles client-to-client traffic.\n *\n * The plan originally called this an \"Elysia plugin,\" but Automerge's\n * `WebSocketServerAdapter` requires an `isomorphic-ws` `WebSocketServer`\n * instance — not Elysia's native WebSocket — so the cleanest first cut is a\n * standalone factory that runs its own `ws` server. Elysia integration for\n * authenticated upgrades is a Phase 1.1 follow-up that wraps this factory.\n *\n * @example\n * ```ts\n * import { createPeerRepoServer } from \"@fairfox/polly\";\n *\n * const server = await createPeerRepoServer({\n * port: 3030,\n * storagePath: \"./data/polly-peer\",\n * });\n *\n * // Open a document handle on the server's Repo for cron or compute work.\n * const handle = server.repo.create({ counter: 0 });\n *\n * // On shutdown:\n * await server.close();\n * ```\n */\n\nimport { Repo } from \"@automerge/automerge-repo/slim\";\nimport { WebSocketServerAdapter } from \"@automerge/automerge-repo-network-websocket\";\nimport { NodeFSStorageAdapter } from \"@automerge/automerge-repo-storage-nodefs\";\nimport * as ws from \"ws\";\n\n// `@types/ws` uses CJS `export = WebSocket` with WebSocketServer hanging off\n// the namespace. Under the project's bundler module resolution, the namespace\n// import gives us access to both the constructor and the type.\ntype WebSocketServer = ws.WebSocketServer;\n\nexport interface CreatePeerRepoServerOptions {\n /** Port to listen on. The factory creates its own `WebSocketServer` and\n * binds to this port. */\n port: number;\n /** Filesystem directory for the NodeFS storage adapter. The directory is\n * created on demand. Defaults to `./automerge-repo-data` (Automerge's own\n * default). */\n storagePath?: string;\n /** Hostname interface to bind to. Defaults to all interfaces. */\n host?: string;\n /** Override the `WebSocketServer` instance entirely. When provided, `port`\n * and `host` are ignored and the caller is responsible for the lifecycle.\n * Useful for tests that want to bind to a random port. */\n webSocketServer?: WebSocketServer;\n}\n\nexport interface PeerRepoServer {\n /** A configured Repo participating as the always-on peer. Server-side\n * cron and HTTP handlers can open document handles on this directly. */\n repo: Repo;\n /** The underlying WebSocket server. Exposed for advanced use such as\n * health checks or graceful shutdown coordination. */\n webSocketServer: WebSocketServer;\n /** The Automerge network adapter wrapping the WebSocket server. */\n adapter: WebSocketServerAdapter;\n /** The NodeFS storage adapter writing to {@link CreatePeerRepoServerOptions.storagePath}. */\n storage: NodeFSStorageAdapter;\n /** Tear down the server: disconnect peers, flush storage, close the\n * underlying WebSocket server. Returns a promise that resolves once the\n * tear-down is complete. */\n close: () => Promise<void>;\n}\n\n/**\n * Construct a Polly peer-relay server. Returns a Repo that participates as\n * the always-on peer, the underlying WebSocket server and storage adapter\n * for advanced use, and a close function for orderly shutdown.\n *\n * Applications typically call this once at startup, hold the returned\n * `repo` reference for cron and compute work, and wire the close function\n * into their process shutdown signal handlers.\n */\nexport async function createPeerRepoServer(\n options: CreatePeerRepoServerOptions\n): Promise<PeerRepoServer> {\n // Construct the WebSocket server first and wait until it is actually\n // listening before wiring up the Repo. Using the constructor callback\n // avoids the race where the 'listening' event fires before our listener\n // is attached (the callback form is reliable across Node and Bun).\n const wss = await (options.webSocketServer\n ? Promise.resolve(options.webSocketServer)\n : new Promise<WebSocketServer>((resolve, reject) => {\n const created: WebSocketServer = new ws.WebSocketServer(\n {\n port: options.port,\n ...(options.host !== undefined && { host: options.host }),\n },\n () => resolve(created)\n );\n created.once(\"error\", reject);\n }));\n\n // The cast bridges a @types/ws identity quirk: Automerge's adapter type\n // expects WebSocketServer with options.WebSocket typed via isomorphic-ws's\n // CJS-style namespace, and our direct `ws` import resolves through a\n // different path with the same runtime shape but a structurally distinct\n // TypeScript type. The runtime is identical, the cast names that fact.\n const adapter = new WebSocketServerAdapter(\n wss as unknown as ConstructorParameters<typeof WebSocketServerAdapter>[0]\n );\n const storage = new NodeFSStorageAdapter(options.storagePath);\n\n const repo = new Repo({\n network: [adapter],\n storage,\n });\n\n // Force the storage subsystem to finish initialising before returning. The\n // Repo constructor is synchronous, but its NetworkSubsystem holds back the\n // peer-metadata JOIN until storageSubsystem.id() resolves. If a client\n // connects before that resolution lands, the handshake stalls indefinitely.\n // Awaiting storageId() drains the relevant microtask chain and guarantees\n // the server is ready to accept peers when this factory returns.\n await repo.storageId();\n\n return {\n repo,\n webSocketServer: wss,\n adapter,\n storage,\n close: async () => {\n // Forcibly terminate any still-open client sockets before closing the\n // server, otherwise wss.close() can hang waiting for orderly drain when\n // a peer disappeared without a clean disconnect. We then fire the\n // server close without awaiting its callback — the underlying socket\n // is released immediately by terminate(), and waiting for the close\n // callback can hang under Bun even after every client is gone.\n for (const client of wss.clients) {\n try {\n client.terminate();\n } catch {\n // best effort\n }\n }\n try {\n await repo.shutdown();\n } catch {\n // best effort — automerge-repo's xstate DocHandle machine can\n // throw \"Cycle detected\" during teardown when sync messages are\n // still in flight.\n }\n try {\n wss.close();\n } catch {\n // best effort\n }\n },\n };\n}\n",
7
7
  "// @ts-nocheck - Optional peer dependencies (elysia, @elysiajs/eden)\nimport type { Signal } from \"@preact/signals-core\";\nimport { Elysia } from \"elysia\";\nimport { createLamportClock } from \"../core/clock\";\nimport { serializeFunction } from \"../utils/function-serialization\";\nimport type { PollyConfig, PollyResponseMetadata } from \"./types\";\n\n/**\n * Broadcast message sent to connected clients\n */\ninterface BroadcastMessage {\n type: \"effect\";\n path: string;\n method: string;\n result: unknown;\n clock: { tick: number; contextId: string };\n}\n\n/**\n * Minimal WebSocket interface for broadcasting\n */\ninterface MinimalWebSocket {\n readyState: number;\n send(data: string): void;\n}\n\n/**\n * Route pattern matcher\n * Supports:\n * - Exact match: 'POST /todos'\n * - Param match: 'GET /todos/:id'\n * - Wildcard: '/todos/*'\n */\nfunction matchRoute(pattern: string, method: string, path: string): boolean {\n // Split pattern into method + path or just path\n const hasMethod = pattern.includes(\" \");\n const patternMethod = hasMethod ? pattern.split(\" \")[0] : null;\n const patternPath = hasMethod ? pattern.split(\" \")[1] : pattern;\n\n // Check method\n if (patternMethod && patternMethod !== method) {\n return false;\n }\n\n // Check path\n const patternSegments = patternPath.split(\"/\").filter(Boolean);\n const pathSegments = path.split(\"/\").filter(Boolean);\n\n if (patternSegments.length !== pathSegments.length && !patternPath.includes(\"*\")) {\n return false;\n }\n\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSeg = patternSegments[i];\n const pathSeg = pathSegments[i];\n\n if (patternSeg === \"*\") return true;\n if (patternSeg.startsWith(\":\")) continue; // Param match\n if (patternSeg !== pathSeg) return false;\n }\n\n return true;\n}\n\n/**\n * Find matching config for a route\n */\nfunction findMatchingConfig<T>(\n configs: Record<string, T> | undefined,\n method: string,\n path: string\n): T | undefined {\n if (!configs) return undefined;\n\n for (const [pattern, config] of Object.entries(configs)) {\n if (matchRoute(pattern, method, path)) {\n return config;\n }\n }\n\n return undefined;\n}\n\n/**\n * WebSocket broadcast manager\n */\nclass BroadcastManager {\n private connections = new Map<string, MinimalWebSocket>();\n\n register(clientId: string, ws: MinimalWebSocket) {\n this.connections.set(clientId, ws);\n }\n\n unregister(clientId: string) {\n this.connections.delete(clientId);\n }\n\n broadcast(message: BroadcastMessage, filter?: (clientId: string) => boolean) {\n const payload = JSON.stringify(message);\n\n for (const [clientId, ws] of this.connections.entries()) {\n if (filter && !filter(clientId)) continue;\n if (ws.readyState === 1) {\n // WebSocket.OPEN = 1\n ws.send(payload);\n }\n }\n }\n}\n\n/**\n * Main Polly Elysia plugin\n */\nexport function polly(config: PollyConfig = {}) {\n const isDev = process.env.NODE_ENV !== \"production\";\n const clock = createLamportClock(\"server\");\n const broadcaster = new BroadcastManager();\n const clientStateByConnection = new Map<string, Record<string, Signal<unknown>>>();\n\n const app = new Elysia({ name: \"polly\" })\n // Add state to context\n .decorate(\"pollyState\", {\n client: config.state?.client || {},\n server: config.state?.server || {},\n })\n .decorate(\"pollyClock\", clock)\n .decorate(\"pollyBroadcast\", broadcaster)\n\n // WebSocket endpoint for real-time updates\n .ws(config.websocketPath || \"/polly/ws\", {\n // @ts-expect-error - Elysia WebSocket types from optional peer dependency\n open(ws) {\n const clientId = ws.data.headers?.[\"x-client-id\"] || crypto.randomUUID();\n broadcaster.register(clientId, ws.raw);\n\n // Send initial state sync\n ws.send(\n JSON.stringify({\n type: \"state-sync\",\n state: config.state?.client || {},\n clock: clock.now(),\n })\n );\n },\n // @ts-expect-error - Elysia WebSocket types from optional peer dependency\n close(ws) {\n const clientId = ws.data.headers?.[\"x-client-id\"];\n if (clientId) {\n broadcaster.unregister(clientId);\n clientStateByConnection.delete(clientId);\n }\n },\n // @ts-expect-error - Elysia WebSocket types from optional peer dependency\n message(ws, message) {\n // Handle client state updates\n const data = JSON.parse(message as unknown as string);\n\n if (data.type === \"state-update\") {\n const clientId = ws.data.headers?.[\"x-client-id\"];\n if (clientId) {\n clientStateByConnection.set(clientId, data.state);\n }\n }\n },\n })\n\n // Authorization hook (runs before handler)\n // @ts-expect-error - Elysia context types from optional peer dependency\n .onBeforeHandle(async ({ request, pollyState, body, params }) => {\n const method = request.method;\n const path = new URL(request.url).pathname;\n\n const authHandler = findMatchingConfig(config.authorization, method, path);\n\n if (authHandler) {\n const allowed = await authHandler({\n state: pollyState,\n body,\n params,\n headers: Object.fromEntries(request.headers.entries()),\n });\n\n if (!allowed) {\n return new Response(\"Unauthorized\", { status: 403 });\n }\n }\n })\n\n // Response hook (runs after handler)\n // @ts-expect-error - Elysia context types from optional peer dependency\n .onAfterHandle(\n async ({ request, response, _pollyState, pollyClock, pollyBroadcast, _body, _params }) => {\n const method = request.method;\n const path = new URL(request.url).pathname;\n\n // Find matching effect config\n const effectConfig = findMatchingConfig(config.effects, method, path);\n\n // Tick clock\n pollyClock.tick();\n\n // If broadcast enabled, send to all connected clients\n // This works in both dev and prod for real-time updates\n if (effectConfig?.broadcast) {\n const broadcastMessage = {\n type: \"effect\",\n path,\n method,\n result: response,\n clock: pollyClock.now(),\n };\n\n if (effectConfig.broadcastFilter) {\n pollyBroadcast.broadcast(broadcastMessage, (clientId) => {\n const clientState = clientStateByConnection.get(clientId) || {};\n return effectConfig.broadcastFilter?.(clientState) ?? false;\n });\n } else {\n pollyBroadcast.broadcast(broadcastMessage);\n }\n }\n\n // In production, skip expensive metadata operations\n if (!isDev) {\n return response;\n }\n\n // DEV ONLY: Add Polly metadata to response for debugging/hot-reload\n const offlineConfig = findMatchingConfig(config.offline, method, path);\n const metadata: PollyResponseMetadata = {\n clientEffect: effectConfig\n ? {\n handler: serializeFunction(effectConfig.client),\n broadcast: effectConfig.broadcast || false,\n }\n : undefined,\n offline: offlineConfig,\n clock: pollyClock.now(),\n };\n\n // Attach metadata as header\n return new Response(JSON.stringify(response), {\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Polly-Metadata\": JSON.stringify(metadata),\n },\n });\n }\n );\n\n return app;\n}\n",
8
8
  "/**\n * Lamport Clock Implementation\n *\n * Provides logical timestamps for distributed systems to establish\n * causal ordering of events across different contexts (client/server).\n *\n * Key properties:\n * - Each event increments the local clock\n * - When receiving a message, clock = max(local, received) + 1\n * - If A happens before B, then timestamp(A) < timestamp(B)\n *\n * References:\n * - Lamport, L. (1978). \"Time, Clocks, and the Ordering of Events in a Distributed System\"\n * - https://lamport.azurewebsites.net/pubs/time-clocks.pdf\n */\n\n/**\n * Lamport clock state\n */\nexport interface LamportClock {\n tick: number;\n contextId: string;\n}\n\n/**\n * Lamport clock with operations\n */\nexport interface LamportClockOps {\n /**\n * Get current clock value\n */\n now(): LamportClock;\n\n /**\n * Increment the clock (before sending a message or performing an action)\n */\n tick(): number;\n\n /**\n * Update clock when receiving a message\n * Sets clock to max(local, received) + 1\n */\n update(receivedClock: LamportClock): void;\n}\n\n/**\n * Create a Lamport clock for a specific context\n *\n * @param contextId - Unique identifier for this context (e.g., \"client\", \"server\", \"worker-1\")\n * @returns Clock operations\n *\n * @example\n * ```typescript\n * const serverClock = createLamportClock(\"server\");\n *\n * // Before sending a message\n * serverClock.tick();\n * const timestamp = serverClock.now();\n * send({ data: \"...\", clock: timestamp });\n *\n * // When receiving a message\n * onReceive((message) => {\n * serverClock.update(message.clock);\n * // Process message with updated clock\n * });\n * ```\n */\nexport function createLamportClock(contextId: string): LamportClockOps {\n let tick = 0;\n\n return {\n now(): LamportClock {\n return { tick, contextId };\n },\n\n tick(): number {\n tick += 1;\n return tick;\n },\n\n update(receivedClock: LamportClock): void {\n tick = Math.max(tick, receivedClock.tick) + 1;\n },\n };\n}\n",
9
9
  "import serialize from \"serialize-javascript\";\n\n/**\n * Check if we're in development mode\n */\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * Serialize a function to send to client\n *\n * DEV ONLY: Used for hot reloading and debugging\n * PROD: No-op - client effects are baked into bundle at build time\n */\n// biome-ignore lint/complexity/noBannedTypes: Generic function serialization requires Function type\nexport function serializeFunction(fn: Function): string {\n if (!isDev) {\n // In production, return empty string - this won't be used\n return \"\";\n }\n\n return serialize(fn, { space: 0 });\n}\n\n/**\n * Deserialize a function received from server\n *\n * DEV ONLY: Eval serialized function source\n * PROD: Should never be called - effects come from bundle\n */\n// biome-ignore lint/complexity/noBannedTypes: Generic function deserialization requires Function type\nexport function deserializeFunction(serialized: string): Function {\n if (!isDev) {\n throw new Error(\n \"[Polly] deserializeFunction should not be called in production. \" +\n \"Client effects should be imported from your bundle.\"\n );\n }\n\n if (!serialized) {\n throw new Error(\"[Polly] Cannot deserialize empty function\");\n }\n\n // biome-ignore lint/security/noGlobalEval: Required for dev-mode function deserialization\n return eval(`(${serialized})`);\n}\n",
10
10
  "// @ts-nocheck - Optional peer dependencies (elysia, @elysiajs/eden)\n/**\n * signalingServer — Phase 2 Elysia plugin that exposes a stateless\n * WebSocket route for SDP/ICE relay between $meshState peers.\n *\n * The mesh transport is a star-of-data-channels: peers establish direct\n * WebRTC connections to each other and exchange document operations\n * peer-to-peer once those channels are open. WebRTC connection setup\n * needs an out-of-band channel for SDP offer/answer and ICE candidate\n * exchange, and that channel is what this plugin provides. The plugin\n * does not own any document state, does not hold any encryption keys,\n * and never inspects the contents of the messages it relays. It is a\n * pure pub-sub by peer id.\n *\n * Once two peers have completed the SDP exchange and opened a direct\n * data channel, the signalling server is no longer on the critical\n * path — the peers talk directly. The signalling server's role is\n * therefore intermittent: peers connect to it only during the brief\n * windows when they are establishing or re-establishing connections.\n *\n * Wire protocol:\n *\n * Client → server (join):\n * { type: \"join\", peerId: \"peer-alice\" }\n *\n * Client → server (signal to another peer):\n * { type: \"signal\", peerId: \"peer-alice\", targetPeerId: \"peer-bob\",\n * payload: { ... } }\n *\n * Server → client (delivered signal):\n * { type: \"signal\", peerId: \"peer-alice\", targetPeerId: \"peer-bob\",\n * payload: { ... } }\n *\n * Server → client (notification of unknown target):\n * { type: \"error\", reason: \"unknown-target\", targetPeerId: \"...\" }\n *\n * The `payload` is opaque to the signalling server — typically it\n * carries an SDP offer, SDP answer, or ICE candidate. Applications can\n * also use the relay for any other peer-to-peer message that needs an\n * intermediary, such as the initial handshake of a pairing flow.\n *\n * @example\n * ```ts\n * import { Elysia } from \"elysia\";\n * import { signalingServer } from \"@fairfox/polly/elysia\";\n *\n * const app = new Elysia()\n * .use(signalingServer({ path: \"/polly/signaling\" }))\n * .listen(8080);\n * ```\n */\n\nimport { Elysia } from \"elysia\";\n\n/** A signalling message. The `type` discriminates between join (peer\n * registration), signal (relayed message), and error (server response). */\nexport type SignalingMessage =\n | {\n type: \"join\";\n /** The peer registering itself with the signalling server. */\n peerId: string;\n }\n | {\n type: \"signal\";\n /** The peer sending the signal. */\n peerId: string;\n /** The peer the signal is being relayed to. */\n targetPeerId: string;\n /** Opaque payload, typically SDP or ICE. */\n payload: unknown;\n }\n | {\n type: \"error\";\n reason: \"unknown-target\" | \"not-joined\" | \"malformed\";\n targetPeerId?: string;\n };\n\nexport interface SignalingServerOptions {\n /** WebSocket route path. Defaults to \"/polly/signaling\". */\n path?: string;\n}\n\n/**\n * Construct the signalling-server Elysia plugin. The plugin keeps a\n * per-instance map of peer id → WebSocket connection so that incoming\n * \"signal\" messages can be routed to the right target socket. The map\n * is local to the plugin instance, not shared across processes; for\n * multi-instance deployments behind a load balancer, applications need\n * sticky connection routing or a shared backplane (Redis pub-sub or\n * similar). That is a follow-up.\n */\nexport function signalingServer(options: SignalingServerOptions = {}) {\n const path = options.path ?? \"/polly/signaling\";\n // Per-peer-id map of joined sockets. The inverse mapping is stored\n // directly on ws.data (a mutable property bag that Elysia preserves\n // across message callbacks for a given connection); the webrtc-p2p-chat\n // example in examples/ confirms this pattern is stable under Bun.\n const peerSockets = new Map<string, { send: (msg: unknown) => void }>();\n\n // Intentionally unnamed — Elysia deduplicates plugins by name, and each\n // signalingServer() call needs its own closure-captured peer map.\n const parseMessage = (raw: unknown): SignalingMessage | undefined => {\n try {\n return typeof raw === \"string\" ? JSON.parse(raw) : (raw as unknown as SignalingMessage);\n } catch {\n return undefined;\n }\n };\n\n const handleJoin = (ws: unknown, peerId: string): void => {\n peerSockets.set(peerId, ws as unknown as { send: (m: unknown) => void });\n const wsWithData = ws as unknown as { data: Record<string, unknown> };\n wsWithData.data.peerId = peerId;\n };\n\n const sendUnknownTarget = (ws: unknown, targetPeerId: string): void => {\n (ws as unknown as { send: (m: unknown) => void }).send({\n type: \"error\",\n reason: \"unknown-target\",\n targetPeerId,\n } as unknown as SignalingMessage);\n };\n\n /** Look up a target socket and confirm it is still open. */\n const findOpenTarget = (targetPeerId: string): { send: (msg: unknown) => void } | undefined => {\n const target = peerSockets.get(targetPeerId);\n if (!target) return undefined;\n const readyState = (target as unknown as { readyState?: number }).readyState;\n const OPEN = 1;\n if (readyState !== undefined && readyState !== OPEN) {\n peerSockets.delete(targetPeerId);\n return undefined;\n }\n return target;\n };\n\n const handleSignal = (ws: unknown, msg: Extract<SignalingMessage, { type: \"signal\" }>): void => {\n const wsWithData = ws as unknown as {\n data: Record<string, unknown>;\n send: (m: unknown) => void;\n };\n const senderId = wsWithData.data.peerId as unknown as string | undefined;\n if (!senderId) {\n wsWithData.send({ type: \"error\", reason: \"not-joined\" } as unknown as SignalingMessage);\n return;\n }\n const target = findOpenTarget(msg.targetPeerId);\n if (!target) {\n sendUnknownTarget(ws, msg.targetPeerId);\n return;\n }\n const relayed: SignalingMessage = {\n type: \"signal\",\n peerId: senderId,\n targetPeerId: msg.targetPeerId,\n payload: msg.payload,\n };\n try {\n target.send(relayed);\n } catch {\n peerSockets.delete(msg.targetPeerId);\n sendUnknownTarget(ws, msg.targetPeerId);\n }\n };\n\n return new Elysia().ws(path, {\n message(ws, raw) {\n const msg = parseMessage(raw);\n if (!msg) {\n ws.send({ type: \"error\", reason: \"malformed\" } as unknown as SignalingMessage);\n return;\n }\n if (msg.type === \"join\") {\n handleJoin(ws, msg.peerId);\n return;\n }\n if (msg.type === \"signal\") {\n handleSignal(ws, msg);\n return;\n }\n ws.send({ type: \"error\", reason: \"malformed\" } as unknown as SignalingMessage);\n },\n\n close(ws) {\n const peerId = (ws.data as unknown as Record<string, unknown>).peerId as unknown as\n | string\n | undefined;\n if (peerId) {\n // Only delete the entry if it still points at *this* socket, so a\n // stale close after a reconnect does not evict the new socket.\n if (peerSockets.get(peerId) === (ws as unknown as { send: (m: unknown) => void })) {\n peerSockets.delete(peerId);\n }\n }\n },\n });\n}\n"
11
11
  ],
12
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA;;;ACMA;AACA;AACA;AACA;AAiDA,eAAsB,oBAAoB,CACxC,SACyB;AAAA,EAKzB,MAAM,MAAM,OAAO,QAAQ,kBACvB,QAAQ,QAAQ,QAAQ,eAAe,IACvC,IAAI,QAAyB,CAAC,SAAS,WAAW;AAAA,IAChD,MAAM,UAA2B,IAAO,mBACtC;AAAA,MACE,MAAM,QAAQ;AAAA,SACV,QAAQ,SAAS,aAAa,EAAE,MAAM,QAAQ,KAAK;AAAA,IACzD,GACA,MAAM,QAAQ,OAAO,CACvB;AAAA,IACA,QAAQ,KAAK,SAAS,MAAM;AAAA,GAC7B;AAAA,EAOL,MAAM,UAAU,IAAI,uBAClB,GACF;AAAA,EACA,MAAM,UAAU,IAAI,qBAAqB,QAAQ,WAAW;AAAA,EAE5D,MAAM,OAAO,IAAI,KAAK;AAAA,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IAAI,CAAC,KAAK;AAAA,QACR,IAAG,KAAK,EAAE,MAAM,SAAS,QAAQ,YAAY,CAAgC;AAAA,QAC7E;AAAA,MACF;AAAA,MACA,IAAI,IAAI,SAAS,QAAQ;AAAA,QACvB,WAAW,KAAI,IAAI,MAAM;AAAA,QACzB;AAAA,MACF;AAAA,MACA,IAAI,IAAI,SAAS,UAAU;AAAA,QACzB,aAAa,KAAI,GAAG;AAAA,QACpB;AAAA,MACF;AAAA,MACA,IAAG,KAAK,EAAE,MAAM,SAAS,QAAQ,YAAY,CAAgC;AAAA;AAAA,IAG/E,KAAK,CAAC,KAAI;AAAA,MACR,MAAM,SAAU,IAAG,KAA4C;AAAA,MAG/D,IAAI,QAAQ;AAAA,QAGV,IAAI,YAAY,IAAI,MAAM,MAAO,KAAkD;AAAA,UACjF,YAAY,OAAO,MAAM;AAAA,QAC3B;AAAA,MACF;AAAA;AAAA,EAEJ,CAAC;AAAA;",
13
+ "debugId": "8580681D01EEB1A864756E2164756E21",
14
14
  "names": []
15
15
  }
@@ -47,7 +47,7 @@ export interface PeerRepoPluginOptions extends CreatePeerRepoServerOptions {
47
47
  */
48
48
  export declare function peerRepo(options: PeerRepoPluginOptions): Elysia<"", {
49
49
  decorator: {
50
- pollyPeerRepo: import("@automerge/automerge-repo").Repo | null;
50
+ pollyPeerRepo: import("@automerge/automerge-repo/slim").Repo | null;
51
51
  } & {
52
52
  pollyPeerServer: PeerRepoServer | null;
53
53
  };
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @fairfox/polly/mesh/node — Node/Bun conveniences for mesh state.
3
+ *
4
+ * The core mesh API (`createMeshClient`, `$meshState`, the keyring storage
5
+ * interface) is runtime-agnostic and ships from `@fairfox/polly/mesh`. This
6
+ * module adds the Node-specific wiring that makes CLIs, cron jobs, and
7
+ * always-on bridges first-class peers on the mesh:
8
+ *
9
+ * - {@link fileKeyringStorage} — durable, human-inspectable keyring store
10
+ * backed by `node:fs`. Atomic writes, missing-file returns `null`.
11
+ * - {@link bootstrapCliKeyring} — wraps {@link fileKeyringStorage} with the
12
+ * first-run pairing UX described in the RFC: generate an identity if
13
+ * no keyring exists, print the public-key fingerprint, read a pairing
14
+ * token from stdin, apply it, and save.
15
+ * - {@link readPairingTokenFromStdin} — low-level prompt helper for
16
+ * consumers that want to compose their own bootstrap.
17
+ *
18
+ * What this module deliberately does **not** do: pick a Node WebRTC
19
+ * implementation. `werift` (pure TypeScript, installs everywhere) and
20
+ * `@roamhq/wrtc` (C++ binding, faster DataChannel, platform-dependent
21
+ * binaries) are both valid choices; the consumer `bun add`s whichever fits
22
+ * their deployment and passes the class into `createMeshClient({ rtc })`.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { createMeshClient } from "@fairfox/polly/mesh";
27
+ * import { bootstrapCliKeyring, fileKeyringStorage } from "@fairfox/polly/mesh/node";
28
+ * import { RTCPeerConnection } from "werift";
29
+ *
30
+ * const storage = fileKeyringStorage("./keyring.json");
31
+ * const keyring = await bootstrapCliKeyring({ storage });
32
+ *
33
+ * const client = await createMeshClient({
34
+ * signaling: { url: "wss://example.com/polly/signaling", peerId: "cli-a1b2" },
35
+ * rtc: { RTCPeerConnection },
36
+ * keyring,
37
+ * });
38
+ * ```
39
+ */
40
+ import { type KeyringStorage } from "./shared/lib/keyring-storage";
41
+ import type { MeshKeyring } from "./shared/lib/mesh-network-adapter";
42
+ export type { KeyringStorage } from "./shared/lib/keyring-storage";
43
+ export { deserialiseKeyring, memoryKeyringStorage, serialiseKeyring, } from "./shared/lib/keyring-storage";
44
+ /**
45
+ * Filesystem-backed keyring storage. Reads and writes the serialised
46
+ * keyring at {@link path} using the canonical JSON+base64 format. The save
47
+ * path uses a write-to-tmp-then-rename dance so concurrent readers never
48
+ * observe a half-written file; a crash mid-write leaves the previous
49
+ * keyring intact.
50
+ */
51
+ export declare function fileKeyringStorage(path: string): KeyringStorage;
52
+ /** Options for {@link bootstrapCliKeyring}. */
53
+ export interface BootstrapCliKeyringOptions {
54
+ /** Where to persist the keyring. On subsequent runs this file is loaded
55
+ * and returned without prompting. */
56
+ storage: KeyringStorage;
57
+ /** Stream to print pairing prompts to. Defaults to `process.stderr` so
58
+ * pipelines that consume stdout are not polluted. */
59
+ promptStream?: NodeJS.WritableStream;
60
+ /** Stream to read the pairing token from. Defaults to `process.stdin`. */
61
+ inputStream?: NodeJS.ReadableStream;
62
+ /** Override the clock (for tests). Forwarded to {@link applyPairingToken}. */
63
+ now?: () => number;
64
+ }
65
+ /**
66
+ * First-run-or-return flow for Node CLIs.
67
+ *
68
+ * - If the storage has a keyring saved, load and return it.
69
+ * - Otherwise: generate a fresh Ed25519 identity, print the public-key
70
+ * fingerprint to `promptStream`, read one line from `inputStream`
71
+ * (expected to be a base64 pairing token), apply it, save, return.
72
+ *
73
+ * Token *issuance* is deliberately out of scope for this helper — the
74
+ * expected UX is that a trusted device (a browser on the authorising
75
+ * user's laptop) mints the token and the user pastes it into the CLI's
76
+ * stdin. Node processes that need to issue tokens can use
77
+ * {@link createPairingToken} from the main mesh export.
78
+ */
79
+ export declare function bootstrapCliKeyring(options: BootstrapCliKeyringOptions): Promise<MeshKeyring>;
80
+ /**
81
+ * Prompt for and read a pairing token from a readable stream (stdin by
82
+ * default). Returns the decoded, validated token. Throws
83
+ * {@link PairingError} on malformed input — callers should surface that
84
+ * message to the user and retry.
85
+ */
86
+ export declare function readPairingTokenFromStdin(options?: {
87
+ promptStream?: NodeJS.WritableStream;
88
+ inputStream?: NodeJS.ReadableStream;
89
+ }): Promise<import("./mesh").PairingToken>;