@rotorsoft/act-http 1.11.1 → 1.11.2

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 (63) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/@types/api/index.d.ts +3 -3
  3. package/dist/@types/api/sse-wiring.d.ts +2 -2
  4. package/dist/@types/receiver/extract.d.ts +4 -4
  5. package/dist/@types/receiver/hono/index.d.ts +1 -1
  6. package/dist/@types/receiver/verify.d.ts +2 -2
  7. package/dist/@types/sse/apply-patch.d.ts.map +1 -1
  8. package/dist/@types/sse/broadcast.d.ts +6 -24
  9. package/dist/@types/sse/broadcast.d.ts.map +1 -1
  10. package/dist/@types/sse/state-cache.d.ts +1 -1
  11. package/dist/@types/sse/types.d.ts +4 -5
  12. package/dist/@types/sse/types.d.ts.map +1 -1
  13. package/dist/@types/trpc/index.d.ts.map +1 -1
  14. package/dist/@types/webhook/index.d.ts +1 -1
  15. package/dist/@types/webhook/index.d.ts.map +1 -1
  16. package/dist/@types/webhook/types.d.ts +1 -1
  17. package/dist/api/index.cjs.map +1 -1
  18. package/dist/api/index.js +2 -2
  19. package/dist/{chunk-FSN52BXM.js → chunk-75DA7NJI.js} +2 -2
  20. package/dist/chunk-75DA7NJI.js.map +1 -0
  21. package/dist/{chunk-MKD3SM3N.js → chunk-BOJG4555.js} +1 -1
  22. package/dist/chunk-BOJG4555.js.map +1 -0
  23. package/dist/{chunk-EERALS5E.js → chunk-CVCTDLJA.js} +1 -1
  24. package/dist/chunk-CVCTDLJA.js.map +1 -0
  25. package/dist/{chunk-G5FNOSDX.js → chunk-ET2PACPO.js} +1 -1
  26. package/dist/chunk-ET2PACPO.js.map +1 -0
  27. package/dist/{chunk-TTVMQYNN.js → chunk-OEMQP5ZM.js} +2 -2
  28. package/dist/chunk-OEMQP5ZM.js.map +1 -0
  29. package/dist/{chunk-5KZI37IT.js → chunk-QM6YP2XH.js} +3 -3
  30. package/dist/hono/index.cjs.map +1 -1
  31. package/dist/hono/index.js +4 -4
  32. package/dist/hono/index.js.map +1 -1
  33. package/dist/openapi/index.cjs +2 -2
  34. package/dist/openapi/index.cjs.map +1 -1
  35. package/dist/openapi/index.js +2 -2
  36. package/dist/openapi/index.js.map +1 -1
  37. package/dist/receiver/express/index.cjs.map +1 -1
  38. package/dist/receiver/express/index.js +1 -1
  39. package/dist/receiver/fastify/index.cjs.map +1 -1
  40. package/dist/receiver/fastify/index.js +1 -1
  41. package/dist/receiver/hono/index.cjs.map +1 -1
  42. package/dist/receiver/hono/index.js +2 -2
  43. package/dist/receiver/index.cjs.map +1 -1
  44. package/dist/receiver/index.js +3 -3
  45. package/dist/receiver/index.js.map +1 -1
  46. package/dist/receiver/trpc/index.cjs.map +1 -1
  47. package/dist/receiver/trpc/index.js +1 -1
  48. package/dist/sse/index.cjs +7 -25
  49. package/dist/sse/index.cjs.map +1 -1
  50. package/dist/sse/index.js +8 -26
  51. package/dist/sse/index.js.map +1 -1
  52. package/dist/trpc/index.cjs.map +1 -1
  53. package/dist/trpc/index.js +4 -4
  54. package/dist/trpc/index.js.map +1 -1
  55. package/dist/webhook/index.cjs.map +1 -1
  56. package/dist/webhook/index.js.map +1 -1
  57. package/package.json +1 -1
  58. package/dist/chunk-EERALS5E.js.map +0 -1
  59. package/dist/chunk-FSN52BXM.js.map +0 -1
  60. package/dist/chunk-G5FNOSDX.js.map +0 -1
  61. package/dist/chunk-MKD3SM3N.js.map +0 -1
  62. package/dist/chunk-TTVMQYNN.js.map +0 -1
  63. /package/dist/{chunk-5KZI37IT.js.map → chunk-QM6YP2XH.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/receiver/index.ts","../../src/receiver/extract.ts","../../src/receiver/verify.ts","../../src/receiver/check.ts","../../src/receiver/start.ts","../../src/api/in-flight.ts","../../src/receiver/finalize.ts","../../src/receiver/hono/index.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/receiver\n *\n * Server-side helpers for the inbound HTTP role — the receiver that\n * sits on the other end of an `@rotorsoft/act-http/webhook` POST.\n *\n * The subpath exports:\n *\n * - {@link extractIdempotencyKey} — case-insensitive\n * `Idempotency-Key` parser; pair with `IdempotencyStore.claim`\n * from `@rotorsoft/act-ops/idempotency` for dedup.\n * - {@link verifyWebhook} — HMAC-SHA256 signature + timestamp\n * verifier; pair with `webhook({ secret })` from\n * `@rotorsoft/act-http/webhook` for authenticated, replay-resistant\n * delivery.\n * - {@link checkWebhook} — the framework-agnostic check for one request:\n * verify the signature, then extract and claim the key.\n * - {@link receiver} — the recommended factory: a fluent builder for a\n * receiving server.\n *\n * Per-framework adapters live in their own subpaths\n * (`./receiver/express`, `./receiver/fastify`, `./receiver/hono`,\n * `./receiver/trpc`).\n *\n * Sibling subpaths in the same package:\n *\n * - `@rotorsoft/act-http/webhook` — the sender side: outbound POSTs,\n * automatic `Idempotency-Key`, status-classified retries, optional\n * HMAC signing.\n * - `@rotorsoft/act-http/sse` — incremental state broadcast over\n * Server-Sent Events.\n *\n * The receiver subpath ships from the same package as `/webhook` so\n * a service that both sends and receives webhooks installs one\n * dependency. The dedup contract that links them lives in\n * `@rotorsoft/act-ops/idempotency`.\n */\n\nexport {\n type CheckFailureReason,\n type CheckResult,\n type CheckWebhookOptions,\n checkWebhook,\n} from \"./check.js\";\nexport { extractIdempotencyKey } from \"./extract.js\";\nexport { receiver } from \"./start.js\";\nexport {\n type VerifyOptions,\n type VerifyResult,\n verifyWebhook,\n} from \"./verify.js\";\n","/**\n * Pull the `Idempotency-Key` header from a Node-style headers bag,\n * case-insensitive. Returns `undefined` when any of the following\n * carries no usable key:\n *\n * - the header is missing\n * - its value is an array (ambiguous — can't pick one without a\n * policy the receiver hasn't declared)\n * - its value is the empty string (carries no idempotency\n * information; structurally equivalent to \"no header at all\")\n *\n * Pair with `IdempotencyStore.claim` from\n * `@rotorsoft/act-ops/idempotency`: extract the key from the inbound\n * request, claim it on the store, return a `deduped` marker when the\n * claim fails. The framework-agnostic middleware that wires these\n * together lands in #744.\n *\n * Validation beyond \"is there a usable key?\" (length bounds, format\n * checks, normalization) is intentionally out of scope. Receivers\n * picking a policy can layer it on top — or, when #744 ships, opt\n * into the middleware's opinionated defaults.\n */\nexport function extractIdempotencyKey(\n headers: Record<string, string | string[] | undefined>\n): string | undefined {\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() !== \"idempotency-key\") continue;\n if (Array.isArray(value)) return undefined;\n if (value === \"\") return undefined;\n return value;\n }\n return undefined;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Outcome of {@link verifyWebhook}. Either the request signature\n * checks out, or one of five distinct failure reasons applies. Each\n * reason maps to an operator-meaningful telemetry bucket — separated\n * deliberately so dashboards can distinguish \"client lost its secret\"\n * from \"client clock is wrong\" from \"this is a replay attack.\"\n */\nexport type VerifyResult =\n | { ok: true }\n | {\n ok: false;\n reason:\n | \"missing-signature\"\n | \"missing-timestamp\"\n | \"stale\"\n | \"future\"\n | \"bad-signature\";\n };\n\n/** Options for {@link verifyWebhook}. */\nexport type VerifyOptions = {\n /**\n * Maximum acceptable timestamp drift in either direction, in\n * seconds. Default: 300 (±5 minutes) — matches Stripe / GitHub /\n * Slack conventions. Tightening narrows the replay window;\n * loosening accommodates clients with worse clock sync.\n */\n maxAgeSeconds?: number;\n /**\n * Current Unix-seconds time. Exposed for tests; production\n * callers should leave it undefined so wall-clock is used.\n */\n now?: number;\n};\n\n/**\n * Verify an inbound webhook's signature and timestamp against the\n * shared secret. Pair with the sender side: configure\n * `webhook({ secret })` from `@rotorsoft/act-http/webhook`.\n *\n * Returns `{ ok: true }` on success or `{ ok: false; reason }` on\n * failure. The reasons are:\n *\n * - `missing-signature` — no `X-Webhook-Signature` header, value\n * was an array, or value was empty.\n * - `missing-timestamp` — no `X-Webhook-Timestamp` header, value\n * was empty, or value isn't a parseable integer.\n * - `stale` — timestamp older than `maxAgeSeconds` from `now`.\n * - `future` — timestamp more than `maxAgeSeconds` ahead of `now`.\n * - `bad-signature` — signature header didn't start with `sha256=`,\n * wasn't 64 hex chars, or the recomputed HMAC didn't match\n * (constant-time compare).\n *\n * The signed payload is `${timestamp}.${body}`, so `body` must be\n * the **raw request body bytes**. Any pre-parse normalization\n * (whitespace trimming, JSON re-stringification) would change the\n * hash and reject every otherwise-valid request. Framework adapters\n * in #744 will provide the raw body alongside the parsed one.\n *\n * Uses Node's `crypto.timingSafeEqual` for the final comparison to\n * avoid signature-equality timing attacks.\n */\nexport function verifyWebhook(\n headers: Record<string, string | string[] | undefined>,\n body: string,\n secret: string,\n options?: VerifyOptions\n): VerifyResult {\n const maxAgeSeconds = options?.maxAgeSeconds ?? 300;\n const now = options?.now ?? Math.floor(Date.now() / 1000);\n\n const signature = pick_header(headers, \"x-webhook-signature\");\n if (!signature) return { ok: false, reason: \"missing-signature\" };\n\n const timestamp_str = pick_header(headers, \"x-webhook-timestamp\");\n if (!timestamp_str) return { ok: false, reason: \"missing-timestamp\" };\n const timestamp = Number.parseInt(timestamp_str, 10);\n if (Number.isNaN(timestamp) || String(timestamp) !== timestamp_str) {\n return { ok: false, reason: \"missing-timestamp\" };\n }\n\n const delta = now - timestamp;\n if (delta > maxAgeSeconds) return { ok: false, reason: \"stale\" };\n if (delta < -maxAgeSeconds) return { ok: false, reason: \"future\" };\n\n if (!signature.startsWith(\"sha256=\")) {\n return { ok: false, reason: \"bad-signature\" };\n }\n const provided_hex = signature.slice(\"sha256=\".length);\n if (!/^[0-9a-fA-F]{64}$/.test(provided_hex)) {\n return { ok: false, reason: \"bad-signature\" };\n }\n\n const expected_hex = createHmac(\"sha256\", secret)\n .update(`${timestamp_str}.${body}`)\n .digest(\"hex\");\n\n const a = Buffer.from(provided_hex, \"hex\");\n const b = Buffer.from(expected_hex, \"hex\");\n if (!timingSafeEqual(a, b)) {\n return { ok: false, reason: \"bad-signature\" };\n }\n\n return { ok: true };\n}\n\nfunction pick_header(\n headers: Record<string, string | string[] | undefined>,\n lower_name: string\n): string | undefined {\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() !== lower_name) continue;\n if (Array.isArray(value) || value === undefined || value === \"\") {\n return undefined;\n }\n return value;\n }\n return undefined;\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport { extractIdempotencyKey } from \"./extract.js\";\nimport { type VerifyOptions, verifyWebhook } from \"./verify.js\";\n\n/**\n * Failure reasons returned by {@link checkWebhook}. The shape splits\n * client/configuration errors (`missing-key`, `empty-body` — HTTP 400)\n * from the five verification failures (authentication errors, HTTP 401)\n * so each maps to its own telemetry bucket. `empty-body` is the\n * misconfigured-raw-parser signal: `secret` is set but the resolved\n * body is empty, so hashing it would compute an HMAC over `${ts}.` and\n * reject every otherwise-valid signed request with a misleading\n * bad-signature — a distinct config error is far easier to diagnose.\n */\nexport type CheckFailureReason =\n | \"missing-key\"\n | \"empty-body\"\n | \"missing-signature\"\n | \"missing-timestamp\"\n | \"stale\"\n | \"future\"\n | \"bad-signature\";\n\n/**\n * Outcome of {@link checkWebhook}. Either the request passed every\n * configured check and carries a usable idempotency key, or it\n * failed one of them and the framework adapter should reply with the\n * corresponding HTTP status.\n */\nexport type CheckResult =\n | { ok: false; status: 400 | 401; reason: CheckFailureReason }\n | { ok: true; key: string; deduped: boolean };\n\n/** Options for {@link checkWebhook}. */\nexport type CheckWebhookOptions = {\n /** Idempotency store the framework-agnostic core claims the key on. */\n store: IdempotencyStore;\n /**\n * Optional HMAC-SHA256 secret. When set, the request's\n * `X-Webhook-Signature` and `X-Webhook-Timestamp` headers are\n * verified before the dedup claim. When omitted, signature\n * verification is skipped (unsigned receivers).\n */\n secret?: string;\n /**\n * Verification options forwarded to {@link verifyWebhook}. Only\n * meaningful when `secret` is set. Defaults to a ±300-second\n * timestamp window.\n */\n verify?: VerifyOptions;\n};\n\n/**\n * Framework-agnostic receiver check: verify the signature (when a\n * secret is configured), extract the `Idempotency-Key`, and claim\n * it on the store. Returns the request's fate as a discriminated\n * union the per-framework adapter translates into the framework's\n * idiomatic 4xx response or context injection.\n *\n * **Order of checks** (matters):\n *\n * 1. Verify signature + timestamp window (when `secret` is set).\n * Rejecting bad signatures *before* extracting and claiming the\n * key keeps attacker-supplied keys out of the dedup store —\n * otherwise a flood of spoofed POSTs would pollute the LRU.\n * 2. Extract the `Idempotency-Key`. Missing → reject with 400.\n * 3. Claim the key on the store. If already seen, return\n * `{ ok: true; deduped: true }` so the framework adapter can\n * short-circuit the handler without re-running side effects.\n *\n * The dedup store may be sync (`InMemoryIdempotencyStore`) or async\n * (durable adapters like a future `PostgresIdempotencyStore`); the\n * core awaits unconditionally so both shapes compose cleanly.\n */\nexport async function checkWebhook(\n headers: Record<string, string | string[] | undefined>,\n body: string,\n options: CheckWebhookOptions\n): Promise<CheckResult> {\n if (options.secret !== undefined) {\n // Raw body not captured (default JSON parser ate the bytes) but a\n // secret is configured — hashing the empty string is a guaranteed\n // bad-signature. Surface a distinct configuration error instead of a\n // misleading 401 so the operator mounts the raw-body parser.\n if (body === \"\") {\n return { ok: false, status: 400, reason: \"empty-body\" };\n }\n const verification = verifyWebhook(\n headers,\n body,\n options.secret,\n options.verify\n );\n if (!verification.ok) {\n return { ok: false, status: 401, reason: verification.reason };\n }\n }\n\n const key = extractIdempotencyKey(headers);\n if (!key) return { ok: false, status: 400, reason: \"missing-key\" };\n\n const claimed = await options.store.claim(key);\n return { ok: true, key, deduped: !claimed };\n}\n","import type {\n Receiver,\n ReceiverBuilder,\n ReceiverContext,\n ReceiverOptions,\n Validator,\n} from \"@rotorsoft/act-ops/receiver\";\nimport { Hono } from \"hono\";\nimport { track_in_flight } from \"../api/in-flight.js\";\nimport { webhookMiddleware } from \"./hono/index.js\";\n\n/**\n * Recommended factory for \"I want to receive webhooks.\" Returns a\n * {@link ReceiverBuilder} the operator configures fluently:\n *\n * ```ts\n * import { receiver } from \"@rotorsoft/act-http/receiver\";\n * import { InMemoryIdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n * import { z } from \"zod\";\n *\n * const r = receiver({\n * port: 4001,\n * store: new InMemoryIdempotencyStore(),\n * secret: process.env.WEBHOOK_SECRET,\n * })\n * .on(\"OrderConfirmed\", z.object({\n * orderId: z.string(),\n * total: z.number(),\n * }), async (event, ctx) => {\n * // event.orderId and event.total are typed\n * // ctx.key is the deduplicated Idempotency-Key\n * await process_order(event.orderId, event.total);\n * })\n * .build();\n *\n * await r.listen();\n * ```\n *\n * Matches Act's builder pattern: `receiver(...)` is the factory,\n * `.on()` registers handlers fluently, `.build()` finalizes and\n * produces an immutable {@link Receiver} — at which point the type\n * loses `.on()` and gains the runtime methods (`listen` / `close` /\n * `fetch`). The lifecycle phases are split at the type level.\n *\n * Internally uses Hono for routing — the universal-runtime choice\n * that gives one code path coverage across Node, AWS Lambda,\n * Cloudflare Workers, Vercel Edge, Bun, and Deno. For operators\n * with an existing tRPC / Express / Fastify / Hono app who need to\n * compose the receiver with their own middleware stack, the\n * lower-level `webhookMiddleware` from\n * `@rotorsoft/act-http/receiver/<framework>` is the escape hatch.\n *\n * `@hono/node-server` is imported lazily inside `.listen()` so\n * Lambda / edge consumers (who never call `.listen()`) don't need\n * it installed.\n */\nexport function receiver(options: ReceiverOptions): ReceiverBuilder {\n const app = new Hono<{\n Variables: { idempotency: { key: string; deduped: boolean } };\n }>();\n\n // Keys whose winning delivery is still running in this receiver. A\n // duplicate that loses the claim is either behind a committed success\n // (safe to answer 204, \"stop retrying\") or behind an attempt whose\n // outcome is still unknown. In the second case a 204 would end the\n // sender's retries, and if the original then fails and releases, the\n // delivery is lost. The store can't tell the two apart, so the receiver\n // remembers which claims it won and hasn't finalized yet.\n const tracker = track_in_flight(options.store);\n const middleware = webhookMiddleware({\n store: tracker.store,\n secret: options.secret,\n });\n\n let built = false;\n\n const builder: ReceiverBuilder = {\n on<T>(\n name: string,\n schema: Validator<T>,\n handler: (event: T, ctx: ReceiverContext) => Promise<void>\n ): ReceiverBuilder {\n if (built) {\n throw new Error(\n `Cannot register handler \"${name}\" after .build() — handlers are frozen once the receiver is built.`\n );\n }\n\n app.post(`/${name}`, middleware, async (c) => {\n let validated: T;\n try {\n const body = await c.req.json();\n validated = schema.parse(body);\n } catch (err) {\n return c.json(\n {\n error: \"validation-failed\",\n detail: (err as Error).message,\n },\n 422\n );\n }\n\n const idem = c.get(\"idempotency\");\n if (idem.deduped && tracker.in_flight(idem.key)) {\n // The original is still running and may yet fail. Ask the\n // sender to come back instead of telling it to stop: a 5xx is\n // retryable by every sender, including Act's webhook reaction.\n c.header(\"Retry-After\", \"1\");\n return c.json({ error: \"in-flight\" }, 503);\n }\n if (!idem.deduped) {\n try {\n await handler(validated, { key: idem.key });\n } catch (err) {\n // Transient failure: release the tentative claim so the\n // sender's retry re-processes instead of being deduped\n // into a silent success and permanently lost. Finalize through\n // the context's `settled`-guarded finalizer, NOT the raw store —\n // the `webhookMiddleware` this route mounts auto-finalizes after\n // `next()` too, and hitting the raw store here double-fires (a\n // stale second `release` can delete a concurrent retry's live\n // claim, breaking exactly-once). The guard collapses both into\n // one store call (#1293).\n await idem.release();\n return c.json(\n {\n error: \"handler-failed\",\n detail: (err as Error).message,\n },\n 500\n );\n }\n // Success: promote the tentative claim to a durable record so every\n // later retry of this key dedups — again via the guarded finalizer,\n // not the raw store (#1293).\n await idem.commit();\n }\n\n return c.body(null, 204);\n });\n\n return builder;\n },\n\n build(): Receiver {\n built = true;\n\n // `any`: server lifecycle handle from @hono/node-server\n let server: any | undefined;\n // The listen in progress, if any. `server` is only assigned after the\n // lazy import resolves, so without this a `close()` issued while\n // `listen()` is still pending would see no server, return, and leave\n // the port bound once the import finished; a second `listen()` would\n // also start a second server.\n let starting: Promise<void> | undefined;\n\n return {\n listen(): Promise<void> {\n starting ??= (async () => {\n const { serve } = await import(\"@hono/node-server\");\n const launched = serve({ fetch: app.fetch, port: options.port });\n server = launched;\n try {\n // A server that can't bind (EADDRINUSE, EACCES) emits `error`\n // and never `listening`: reject with it instead of hanging, so\n // the caller sees the failure and `close()` isn't left waiting\n // on a start that never finishes (#1783).\n await new Promise<void>((resolve, reject) => {\n launched.once(\"listening\", () => resolve());\n launched.once(\"error\", reject);\n });\n } catch (error) {\n server = undefined;\n starting = undefined;\n throw error;\n }\n })();\n return starting;\n },\n\n async close(): Promise<void> {\n if (starting) {\n const pending = starting;\n starting = undefined;\n // A start that failed has nothing to close.\n await pending.catch(() => {});\n }\n if (!server) return;\n const s = server;\n server = undefined;\n await new Promise<void>((resolve) => s.close(() => resolve()));\n },\n\n async fetch(request: Request): Promise<Response> {\n return app.fetch(request);\n },\n };\n },\n };\n\n return builder;\n}\n","/**\n * @module act-http/api/in-flight\n *\n * Tells a duplicate of a delivery that is still running apart from a\n * duplicate of one that already succeeded. An {@link IdempotencyStore}\n * can't: its `claim` returns `false` in both cases. Answering the first\n * \"accepted, stop retrying\" loses the delivery if the original then fails\n * and releases the key, so the receiver and the generated API both ask\n * the sender to retry while the original is in flight.\n *\n * Internal — not re-exported from the package. Process-local, which\n * matches `InMemoryIdempotencyStore`'s single-process scope.\n */\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/** A wrapped store plus the in-flight check it maintains. @internal */\nexport type InFlightTracker = {\n /** Pass this to the code that claims, commits, and releases. */\n readonly store: IdempotencyStore;\n /**\n * True while a claim on `key` is pending, or was won and is not yet\n * committed or released. Read it after your own claim lost.\n */\n in_flight(key: string): boolean;\n};\n\n/**\n * Wraps `store` so claims are counted per key. A key is counted **before**\n * the claim is awaited, not when its reply arrives: with an async store\n * the loser's `false` can arrive before the winner's `true`, and marking\n * only on the winner's reply would leave the loser a window to see the key\n * unmarked and be answered as a settled duplicate. A claim that loses (or\n * throws) uncounts itself at once; a claim that wins stays counted until\n * its commit or release lands.\n *\n * A concurrent duplicate of an already-committed key can therefore read\n * as in flight while another duplicate's claim is pending. That costs one\n * extra retry, never a lost delivery.\n *\n * @internal\n */\nexport function track_in_flight(store: IdempotencyStore): InFlightTracker {\n // One tracker per store, shared by every generator and receiver built on\n // it: a duplicate arriving through one generator while the original runs\n // in another must still read as in flight, which separate counts can't\n // see (#1782).\n let tracker = trackers.get(store);\n if (!tracker) {\n tracker = make_tracker(store);\n trackers.set(store, tracker);\n }\n return tracker;\n}\n\nconst trackers = new WeakMap<IdempotencyStore, InFlightTracker>();\n\nfunction make_tracker(store: IdempotencyStore): InFlightTracker {\n const pending = new Map<string, number>();\n const up = (key: string) => pending.set(key, (pending.get(key) ?? 0) + 1);\n const down = (key: string) => {\n const left = (pending.get(key) ?? 0) - 1;\n if (left > 0) pending.set(key, left);\n else pending.delete(key);\n };\n const settle = (key: string, won: boolean) => {\n if (!won) down(key);\n return won;\n };\n return {\n in_flight: (key) => pending.has(key),\n store: {\n claim(key, now) {\n up(key);\n let won: boolean | Promise<boolean>;\n try {\n won = store.claim(key, now);\n } catch (err) {\n down(key);\n throw err;\n }\n return typeof won === \"boolean\"\n ? settle(key, won)\n : won.then(\n (w) => settle(key, w),\n (err: unknown) => {\n down(key);\n throw err;\n }\n );\n },\n async commit(key, now) {\n try {\n await store.commit(key, now);\n } finally {\n down(key);\n }\n },\n async release(key) {\n try {\n await store.release(key);\n } finally {\n down(key);\n }\n },\n },\n };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * The two-phase finalizers a receiver adapter binds to a single\n * inbound delivery. The claim `checkWebhook` makes is *tentative*;\n * exactly one of these promotes or drops it once the business handler\n * resolves its outcome.\n */\nexport type Finalizers = {\n /**\n * Promote the tentative claim to a durable record so every later\n * retry of this key dedups. Call on handler success.\n */\n commit: () => void | Promise<void>;\n /**\n * Drop the tentative claim so the sender's retry re-processes.\n * Call on transient handler failure.\n */\n release: () => void | Promise<void>;\n};\n\n/**\n * The `idempotency` bag a receiver adapter hands its route for one\n * delivery: the claimed key, whether it was a duplicate, and the\n * {@link Finalizers}.\n */\nexport type Idempotency = { key: string; deduped: boolean } & Finalizers;\n\n/**\n * Build the {@link Idempotency} bag for one delivery that passed\n * `checkWebhook`.\n *\n * Guarantees:\n *\n * - **Deduped deliveries are inert.** When `deduped` is `true` the key\n * was already committed by an earlier delivery; both finalizers are\n * no-ops so a duplicate can never release someone else's committed\n * claim.\n * - **Finalize-once.** After the first `commit` or `release` fires,\n * further calls are no-ops — an adapter that both auto-finalizes and\n * lets the operator call `commit()`/`release()` can't double-fire.\n */\nexport function make_idempotency(\n store: IdempotencyStore,\n { key, deduped }: { key: string; deduped: boolean }\n): Idempotency {\n let settled = deduped;\n return {\n key,\n deduped,\n async commit() {\n if (settled) return;\n settled = true;\n await store.commit(key);\n },\n async release() {\n if (settled) return;\n settled = true;\n await store.release(key);\n },\n };\n}\n","/**\n * @packageDocumentation\n * @module act-http/receiver/hono\n *\n * Hono adapter for the receiver-side webhook check.\n *\n * Usage:\n *\n * ```ts\n * import { Hono } from \"hono\";\n * import { webhookMiddleware } from \"@rotorsoft/act-http/receiver/hono\";\n * import { InMemoryIdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n *\n * const app = new Hono();\n * const dedup = new InMemoryIdempotencyStore();\n *\n * app.post(\n * \"/webhooks/orders\",\n * webhookMiddleware({ store: dedup, secret: process.env.WEBHOOK_SECRET }),\n * async (c) => {\n * const idem = c.get(\"idempotency\") as { key: string; deduped: boolean };\n * if (idem.deduped) return c.json({ status: \"dedup-skipped\", key: idem.key });\n * // ... process the inbound event ...\n * return c.json({ status: \"processed\", key: idem.key });\n * }\n * );\n * ```\n *\n * On failure: returns `c.json({ error: <reason> }, status)` directly\n * (Hono short-circuits when middleware returns a Response). On\n * success: stashes `c.set(\"idempotency\", { key, deduped })` and\n * continues with `await next()`.\n *\n * **Two-phase dedup**: the claim `checkWebhook` makes is *tentative*.\n * Because Hono middleware wraps the downstream chain, this adapter\n * finalizes the claim automatically after `await next()`: a downstream\n * 2xx/3xx **commits** the key (later retries dedup); any **4xx or 5xx**\n * (or a thrown handler) **releases** it, so the sender's corrected retry\n * re-processes instead of being silently dropped (#1364). Fail-safe is\n * toward reprocessing: releasing a deterministic 4xx costs bounded\n * re-delivery, while committing it would lose a delivery the handler\n * never accepted (the shipped `receiver()` returns 422 on a schema\n * mismatch, where the handler never runs). Operators who need explicit\n * control can still call `c.get(\"idempotency\").commit()` / `.release()`.\n *\n * **Raw body**: Hono exposes `await c.req.text()` natively, which\n * the middleware reads when `secret` is configured. No extra setup\n * needed.\n */\nimport type { MiddlewareHandler } from \"hono\";\nimport { type CheckWebhookOptions, checkWebhook } from \"../check.js\";\nimport { make_idempotency } from \"../finalize.js\";\n\n/**\n * Variables this middleware contributes to the Hono context. The\n * generic on the returned {@link MiddlewareHandler} threads it\n * through so route handlers downstream of `app.post(..., webhookMiddleware(...), handler)`\n * see `c.get(\"idempotency\")` typed without a manual cast.\n *\n * `commit` / `release` finalize the tentative claim — call one after\n * the handler resolves its outcome. This adapter also finalizes\n * automatically based on the response status, so explicit calls are\n * only needed when the auto-detection doesn't fit.\n */\nexport type WebhookVariables = {\n idempotency: {\n key: string;\n deduped: boolean;\n commit: () => void | Promise<void>;\n release: () => void | Promise<void>;\n };\n};\n\n/**\n * Build a Hono middleware that verifies the request signature (when\n * `secret` is set), enforces `Idempotency-Key`, and claims the key\n * on the configured store. See the module-level docs for usage.\n */\nexport function webhookMiddleware(\n options: CheckWebhookOptions\n): MiddlewareHandler<{ Variables: WebhookVariables }> {\n return async function check(c, next) {\n const headers = headers_bag(c.req.raw.headers);\n const rawBody = await c.req.text();\n const result = await checkWebhook(headers, rawBody, options);\n if (!result.ok) {\n return c.json({ error: result.reason }, result.status);\n }\n const idempotency = make_idempotency(options.store, result);\n c.set(\"idempotency\", idempotency);\n try {\n await next();\n } catch (err) {\n await idempotency.release();\n throw err;\n }\n // Commit only a genuine success (2xx/3xx); release on any 4xx/5xx so a\n // failed delivery's corrected same-key retry re-processes instead of being\n // deduped into a silent success (#1364).\n if (c.res.status >= 400) await idempotency.release();\n else await idempotency.commit();\n };\n}\n\nfunction headers_bag(\n headers: Headers\n): Record<string, string | string[] | undefined> {\n const out: Record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GR,UAAI;AAMJ,UAAI;AAEJ,aAAO;AAAA,QACL,SAAwB;AACtB,wBAAc,YAAY;AACxB,kBAAM,EAAE,MAAM,IAAI,MAAM,OAAO,mBAAmB;AAClD,kBAAM,WAAW,MAAM,EAAE,OAAO,IAAI,OAAO,MAAM,QAAQ,KAAK,CAAC;AAC/D,qBAAS;AACT,gBAAI;AAKF,oBAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,yBAAS,KAAK,aAAa,MAAM,QAAQ,CAAC;AAC1C,yBAAS,KAAK,SAAS,MAAM;AAAA,cAC/B,CAAC;AAAA,YACH,SAAS,OAAO;AACd,uBAAS;AACT,yBAAW;AACX,oBAAM;AAAA,YACR;AAAA,UACF,GAAG;AACH,iBAAO;AAAA,QACT;AAAA,QAEA,MAAM,QAAuB;AAC3B,cAAI,UAAU;AACZ,kBAAM,UAAU;AAChB,uBAAW;AAEX,kBAAM,QAAQ,MAAM,MAAM;AAAA,YAAC,CAAC;AAAA,UAC9B;AACA,cAAI,CAAC,OAAQ;AACb,gBAAM,IAAI;AACV,mBAAS;AACT,gBAAM,IAAI,QAAc,CAAC,YAAY,EAAE,MAAM,MAAM,QAAQ,CAAC,CAAC;AAAA,QAC/D;AAAA,QAEA,MAAM,MAAM,SAAqC;AAC/C,iBAAO,IAAI,MAAM,OAAO;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/receiver/index.ts","../../src/receiver/extract.ts","../../src/receiver/verify.ts","../../src/receiver/check.ts","../../src/receiver/start.ts","../../src/api/in-flight.ts","../../src/receiver/finalize.ts","../../src/receiver/hono/index.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/receiver\n *\n * Server-side helpers for the inbound HTTP role — the receiver that\n * sits on the other end of an `@rotorsoft/act-http/webhook` POST.\n *\n * The subpath exports:\n *\n * - {@link extractIdempotencyKey} — case-insensitive\n * `Idempotency-Key` parser; pair with `IdempotencyStore.claim`\n * from `@rotorsoft/act-ops/idempotency` for dedup.\n * - {@link verifyWebhook} — HMAC-SHA256 signature + timestamp\n * verifier; pair with `webhook({ secret })` from\n * `@rotorsoft/act-http/webhook` for authenticated, replay-resistant\n * delivery.\n * - {@link checkWebhook} — the framework-agnostic check for one request:\n * verify the signature, then extract and claim the key.\n * - {@link receiver} — the recommended factory: a fluent builder for a\n * receiving server.\n *\n * Per-framework adapters live in their own subpaths\n * (`./receiver/express`, `./receiver/fastify`, `./receiver/hono`,\n * `./receiver/trpc`).\n *\n * Sibling subpaths in the same package:\n *\n * - `@rotorsoft/act-http/webhook` — the sender side: outbound POSTs,\n * automatic `Idempotency-Key`, status-classified retries, optional\n * HMAC signing.\n * - `@rotorsoft/act-http/sse` — incremental state broadcast over\n * Server-Sent Events.\n *\n * The receiver subpath ships from the same package as `/webhook` so\n * a service that both sends and receives webhooks installs one\n * dependency. The dedup contract that links them lives in\n * `@rotorsoft/act-ops/idempotency`.\n */\n\nexport {\n type CheckFailureReason,\n type CheckResult,\n type CheckWebhookOptions,\n checkWebhook,\n} from \"./check.js\";\nexport { extractIdempotencyKey } from \"./extract.js\";\nexport { receiver } from \"./start.js\";\nexport {\n type VerifyOptions,\n type VerifyResult,\n verifyWebhook,\n} from \"./verify.js\";\n","/**\n * Pull the `Idempotency-Key` header from a Node-style headers bag,\n * case-insensitive. Returns `undefined` when any of the following\n * carries no usable key:\n *\n * - the header is missing\n * - its value is an array (ambiguous — can't pick one without a\n * policy the receiver hasn't declared)\n * - its value is the empty string (carries no idempotency\n * information; structurally equivalent to \"no header at all\")\n *\n * Pair with `IdempotencyStore.claim` from\n * `@rotorsoft/act-ops/idempotency`: extract the key from the inbound\n * request, claim it on the store, return a `deduped` marker when the\n * claim fails. The receiver subpaths' `webhookMiddleware` wires these\n * together.\n *\n * Validation beyond \"is there a usable key?\" (length bounds, format\n * checks, normalization) is intentionally out of scope. Receivers\n * picking a policy can layer it on top, or use the middleware's\n * defaults.\n */\nexport function extractIdempotencyKey(\n headers: Record<string, string | string[] | undefined>\n): string | undefined {\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() !== \"idempotency-key\") continue;\n if (Array.isArray(value)) return undefined;\n if (value === \"\") return undefined;\n return value;\n }\n return undefined;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Outcome of {@link verifyWebhook}. Either the request signature\n * checks out, or one of five distinct failure reasons applies. Each\n * reason maps to an operator-meaningful telemetry bucket — separated\n * deliberately so dashboards can distinguish \"client lost its secret\"\n * from \"client clock is wrong\" from \"this is a replay attack.\"\n */\nexport type VerifyResult =\n | { ok: true }\n | {\n ok: false;\n reason:\n | \"missing-signature\"\n | \"missing-timestamp\"\n | \"stale\"\n | \"future\"\n | \"bad-signature\";\n };\n\n/** Options for {@link verifyWebhook}. */\nexport type VerifyOptions = {\n /**\n * Maximum acceptable timestamp drift in either direction, in\n * seconds. Default: 300 (±5 minutes) — matches Stripe / GitHub /\n * Slack conventions. Tightening narrows the replay window;\n * loosening accommodates clients with worse clock sync.\n */\n maxAgeSeconds?: number;\n /**\n * Current Unix-seconds time. Exposed for tests; production\n * callers should leave it undefined so wall-clock is used.\n */\n now?: number;\n};\n\n/**\n * Verify an inbound webhook's signature and timestamp against the\n * shared secret. Pair with the sender side: configure\n * `webhook({ secret })` from `@rotorsoft/act-http/webhook`.\n *\n * Returns `{ ok: true }` on success or `{ ok: false; reason }` on\n * failure. The reasons are:\n *\n * - `missing-signature` — no `X-Webhook-Signature` header, value\n * was an array, or value was empty.\n * - `missing-timestamp` — no `X-Webhook-Timestamp` header, value\n * was empty, or value isn't a parseable integer.\n * - `stale` — timestamp older than `maxAgeSeconds` from `now`.\n * - `future` — timestamp more than `maxAgeSeconds` ahead of `now`.\n * - `bad-signature` — signature header didn't start with `sha256=`,\n * wasn't 64 hex chars, or the recomputed HMAC didn't match\n * (constant-time compare).\n *\n * The signed payload is `${timestamp}.${body}`, so `body` must be\n * the **raw request body bytes**. Any pre-parse normalization\n * (whitespace trimming, JSON re-stringification) would change the\n * hash and reject every otherwise-valid request. The receiver\n * subpaths' adapters pass the raw body alongside the parsed one.\n *\n * Uses Node's `crypto.timingSafeEqual` for the final comparison to\n * avoid signature-equality timing attacks.\n */\nexport function verifyWebhook(\n headers: Record<string, string | string[] | undefined>,\n body: string,\n secret: string,\n options?: VerifyOptions\n): VerifyResult {\n const maxAgeSeconds = options?.maxAgeSeconds ?? 300;\n const now = options?.now ?? Math.floor(Date.now() / 1000);\n\n const signature = pick_header(headers, \"x-webhook-signature\");\n if (!signature) return { ok: false, reason: \"missing-signature\" };\n\n const timestamp_str = pick_header(headers, \"x-webhook-timestamp\");\n if (!timestamp_str) return { ok: false, reason: \"missing-timestamp\" };\n const timestamp = Number.parseInt(timestamp_str, 10);\n if (Number.isNaN(timestamp) || String(timestamp) !== timestamp_str) {\n return { ok: false, reason: \"missing-timestamp\" };\n }\n\n const delta = now - timestamp;\n if (delta > maxAgeSeconds) return { ok: false, reason: \"stale\" };\n if (delta < -maxAgeSeconds) return { ok: false, reason: \"future\" };\n\n if (!signature.startsWith(\"sha256=\")) {\n return { ok: false, reason: \"bad-signature\" };\n }\n const provided_hex = signature.slice(\"sha256=\".length);\n if (!/^[0-9a-fA-F]{64}$/.test(provided_hex)) {\n return { ok: false, reason: \"bad-signature\" };\n }\n\n const expected_hex = createHmac(\"sha256\", secret)\n .update(`${timestamp_str}.${body}`)\n .digest(\"hex\");\n\n const a = Buffer.from(provided_hex, \"hex\");\n const b = Buffer.from(expected_hex, \"hex\");\n if (!timingSafeEqual(a, b)) {\n return { ok: false, reason: \"bad-signature\" };\n }\n\n return { ok: true };\n}\n\nfunction pick_header(\n headers: Record<string, string | string[] | undefined>,\n lower_name: string\n): string | undefined {\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() !== lower_name) continue;\n if (Array.isArray(value) || value === undefined || value === \"\") {\n return undefined;\n }\n return value;\n }\n return undefined;\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport { extractIdempotencyKey } from \"./extract.js\";\nimport { type VerifyOptions, verifyWebhook } from \"./verify.js\";\n\n/**\n * Failure reasons returned by {@link checkWebhook}. The shape splits\n * client/configuration errors (`missing-key`, `empty-body` — HTTP 400)\n * from the five verification failures (authentication errors, HTTP 401)\n * so each maps to its own telemetry bucket. `empty-body` is the\n * misconfigured-raw-parser signal: `secret` is set but the resolved\n * body is empty, so hashing it would compute an HMAC over `${ts}.` and\n * reject every otherwise-valid signed request with a misleading\n * bad-signature — a distinct config error is far easier to diagnose.\n */\nexport type CheckFailureReason =\n | \"missing-key\"\n | \"empty-body\"\n | \"missing-signature\"\n | \"missing-timestamp\"\n | \"stale\"\n | \"future\"\n | \"bad-signature\";\n\n/**\n * Outcome of {@link checkWebhook}. Either the request passed every\n * configured check and carries a usable idempotency key, or it\n * failed one of them and the framework adapter should reply with the\n * corresponding HTTP status.\n */\nexport type CheckResult =\n | { ok: false; status: 400 | 401; reason: CheckFailureReason }\n | { ok: true; key: string; deduped: boolean };\n\n/** Options for {@link checkWebhook}. */\nexport type CheckWebhookOptions = {\n /** Idempotency store the framework-agnostic core claims the key on. */\n store: IdempotencyStore;\n /**\n * Optional HMAC-SHA256 secret. When set, the request's\n * `X-Webhook-Signature` and `X-Webhook-Timestamp` headers are\n * verified before the dedup claim. When omitted, signature\n * verification is skipped (unsigned receivers).\n */\n secret?: string;\n /**\n * Verification options forwarded to {@link verifyWebhook}. Only\n * meaningful when `secret` is set. Defaults to a ±300-second\n * timestamp window.\n */\n verify?: VerifyOptions;\n};\n\n/**\n * Framework-agnostic receiver check: verify the signature (when a\n * secret is configured), extract the `Idempotency-Key`, and claim\n * it on the store. Returns the request's fate as a discriminated\n * union the per-framework adapter translates into the framework's\n * idiomatic 4xx response or context injection.\n *\n * **Order of checks** (matters):\n *\n * 1. Verify signature + timestamp window (when `secret` is set).\n * Rejecting bad signatures *before* extracting and claiming the\n * key keeps attacker-supplied keys out of the dedup store —\n * otherwise a flood of spoofed POSTs would pollute the LRU.\n * 2. Extract the `Idempotency-Key`. Missing → reject with 400.\n * 3. Claim the key on the store. If already seen, return\n * `{ ok: true; deduped: true }` so the framework adapter can\n * short-circuit the handler without re-running side effects.\n *\n * The dedup store may be sync (`InMemoryIdempotencyStore`) or async\n * (durable adapters like a future `PostgresIdempotencyStore`); the\n * core awaits unconditionally so both shapes compose cleanly.\n */\nexport async function checkWebhook(\n headers: Record<string, string | string[] | undefined>,\n body: string,\n options: CheckWebhookOptions\n): Promise<CheckResult> {\n if (options.secret !== undefined) {\n // Raw body not captured (default JSON parser ate the bytes) but a\n // secret is configured — hashing the empty string is a guaranteed\n // bad-signature. Surface a distinct configuration error instead of a\n // misleading 401 so the operator mounts the raw-body parser.\n if (body === \"\") {\n return { ok: false, status: 400, reason: \"empty-body\" };\n }\n const verification = verifyWebhook(\n headers,\n body,\n options.secret,\n options.verify\n );\n if (!verification.ok) {\n return { ok: false, status: 401, reason: verification.reason };\n }\n }\n\n const key = extractIdempotencyKey(headers);\n if (!key) return { ok: false, status: 400, reason: \"missing-key\" };\n\n const claimed = await options.store.claim(key);\n return { ok: true, key, deduped: !claimed };\n}\n","import type {\n Receiver,\n ReceiverBuilder,\n ReceiverContext,\n ReceiverOptions,\n Validator,\n} from \"@rotorsoft/act-ops/receiver\";\nimport { Hono } from \"hono\";\nimport { track_in_flight } from \"../api/in-flight.js\";\nimport { webhookMiddleware } from \"./hono/index.js\";\n\n/**\n * Recommended factory for \"I want to receive webhooks.\" Returns a\n * {@link ReceiverBuilder} the operator configures fluently:\n *\n * ```ts\n * import { receiver } from \"@rotorsoft/act-http/receiver\";\n * import { InMemoryIdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n * import { z } from \"zod\";\n *\n * const r = receiver({\n * port: 4001,\n * store: new InMemoryIdempotencyStore(),\n * secret: process.env.WEBHOOK_SECRET,\n * })\n * .on(\"OrderConfirmed\", z.object({\n * orderId: z.string(),\n * total: z.number(),\n * }), async (event, ctx) => {\n * // event.orderId and event.total are typed\n * // ctx.key is the deduplicated Idempotency-Key\n * await process_order(event.orderId, event.total);\n * })\n * .build();\n *\n * await r.listen();\n * ```\n *\n * Matches Act's builder pattern: `receiver(...)` is the factory,\n * `.on()` registers handlers fluently, `.build()` finalizes and\n * produces an immutable {@link Receiver} — at which point the type\n * loses `.on()` and gains the runtime methods (`listen` / `close` /\n * `fetch`). The lifecycle phases are split at the type level.\n *\n * Internally uses Hono for routing — the universal-runtime choice\n * that gives one code path coverage across Node, AWS Lambda,\n * Cloudflare Workers, Vercel Edge, Bun, and Deno. For operators\n * with an existing tRPC / Express / Fastify / Hono app who need to\n * compose the receiver with their own middleware stack, the\n * lower-level `webhookMiddleware` from\n * `@rotorsoft/act-http/receiver/<framework>` is the escape hatch.\n *\n * `@hono/node-server` is imported lazily inside `.listen()` so\n * Lambda / edge consumers (who never call `.listen()`) don't need\n * it installed.\n */\nexport function receiver(options: ReceiverOptions): ReceiverBuilder {\n const app = new Hono<{\n Variables: { idempotency: { key: string; deduped: boolean } };\n }>();\n\n // Keys whose winning delivery is still running in this receiver. A\n // duplicate that loses the claim is either behind a committed success\n // (safe to answer 204, \"stop retrying\") or behind an attempt whose\n // outcome is still unknown. In the second case a 204 would end the\n // sender's retries, and if the original then fails and releases, the\n // delivery is lost. The store can't tell the two apart, so the receiver\n // remembers which claims it won and hasn't finalized yet.\n const tracker = track_in_flight(options.store);\n const middleware = webhookMiddleware({\n store: tracker.store,\n secret: options.secret,\n });\n\n let built = false;\n\n const builder: ReceiverBuilder = {\n on<T>(\n name: string,\n schema: Validator<T>,\n handler: (event: T, ctx: ReceiverContext) => Promise<void>\n ): ReceiverBuilder {\n if (built) {\n throw new Error(\n `Cannot register handler \"${name}\" after .build() — handlers are frozen once the receiver is built.`\n );\n }\n\n app.post(`/${name}`, middleware, async (c) => {\n let validated: T;\n try {\n const body = await c.req.json();\n validated = schema.parse(body);\n } catch (err) {\n return c.json(\n {\n error: \"validation-failed\",\n detail: (err as Error).message,\n },\n 422\n );\n }\n\n const idem = c.get(\"idempotency\");\n if (idem.deduped && tracker.in_flight(idem.key)) {\n // The original is still running and may yet fail. Ask the\n // sender to come back instead of telling it to stop: a 5xx is\n // retryable by every sender, including Act's webhook reaction.\n c.header(\"Retry-After\", \"1\");\n return c.json({ error: \"in-flight\" }, 503);\n }\n if (!idem.deduped) {\n try {\n await handler(validated, { key: idem.key });\n } catch (err) {\n // Transient failure: release the tentative claim so the\n // sender's retry re-processes instead of being deduped\n // into a silent success and permanently lost. Finalize through\n // the context's `settled`-guarded finalizer, NOT the raw store —\n // the `webhookMiddleware` this route mounts auto-finalizes after\n // `next()` too, and hitting the raw store here double-fires (a\n // stale second `release` can delete a concurrent retry's live\n // claim, breaking exactly-once). The guard collapses both into\n // one store call.\n await idem.release();\n return c.json(\n {\n error: \"handler-failed\",\n detail: (err as Error).message,\n },\n 500\n );\n }\n // Success: promote the tentative claim to a durable record so every\n // later retry of this key dedups — again via the guarded finalizer,\n // not the raw store.\n await idem.commit();\n }\n\n return c.body(null, 204);\n });\n\n return builder;\n },\n\n build(): Receiver {\n built = true;\n\n // `any`: server lifecycle handle from @hono/node-server\n let server: any | undefined;\n // The listen in progress, if any. `server` is only assigned after the\n // lazy import resolves, so without this a `close()` issued while\n // `listen()` is still pending would see no server, return, and leave\n // the port bound once the import finished; a second `listen()` would\n // also start a second server.\n let starting: Promise<void> | undefined;\n\n return {\n listen(): Promise<void> {\n starting ??= (async () => {\n const { serve } = await import(\"@hono/node-server\");\n const launched = serve({ fetch: app.fetch, port: options.port });\n server = launched;\n try {\n // A server that can't bind (EADDRINUSE, EACCES) emits `error`\n // and never `listening`: reject with it instead of hanging, so\n // the caller sees the failure and `close()` isn't left waiting\n // on a start that never finishes.\n await new Promise<void>((resolve, reject) => {\n launched.once(\"listening\", () => resolve());\n launched.once(\"error\", reject);\n });\n } catch (error) {\n server = undefined;\n starting = undefined;\n throw error;\n }\n })();\n return starting;\n },\n\n async close(): Promise<void> {\n if (starting) {\n const pending = starting;\n starting = undefined;\n // A start that failed has nothing to close.\n await pending.catch(() => {});\n }\n if (!server) return;\n const s = server;\n server = undefined;\n await new Promise<void>((resolve) => s.close(() => resolve()));\n },\n\n async fetch(request: Request): Promise<Response> {\n return app.fetch(request);\n },\n };\n },\n };\n\n return builder;\n}\n","/**\n * @module act-http/api/in-flight\n *\n * Tells a duplicate of a delivery that is still running apart from a\n * duplicate of one that already succeeded. An {@link IdempotencyStore}\n * can't: its `claim` returns `false` in both cases. Answering the first\n * \"accepted, stop retrying\" loses the delivery if the original then fails\n * and releases the key, so the receiver and the generated API both ask\n * the sender to retry while the original is in flight.\n *\n * Internal — not re-exported from the package. Process-local, which\n * matches `InMemoryIdempotencyStore`'s single-process scope.\n */\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/** A wrapped store plus the in-flight check it maintains. @internal */\nexport type InFlightTracker = {\n /** Pass this to the code that claims, commits, and releases. */\n readonly store: IdempotencyStore;\n /**\n * True while a claim on `key` is pending, or was won and is not yet\n * committed or released. Read it after your own claim lost.\n */\n in_flight(key: string): boolean;\n};\n\n/**\n * Wraps `store` so claims are counted per key. A key is counted **before**\n * the claim is awaited, not when its reply arrives: with an async store\n * the loser's `false` can arrive before the winner's `true`, and marking\n * only on the winner's reply would leave the loser a window to see the key\n * unmarked and be answered as a settled duplicate. A claim that loses (or\n * throws) uncounts itself at once; a claim that wins stays counted until\n * its commit or release lands.\n *\n * A concurrent duplicate of an already-committed key can therefore read\n * as in flight while another duplicate's claim is pending. That costs one\n * extra retry, never a lost delivery.\n *\n * @internal\n */\nexport function track_in_flight(store: IdempotencyStore): InFlightTracker {\n // One tracker per store, shared by every generator and receiver built on\n // it: a duplicate arriving through one generator while the original runs\n // in another must still read as in flight, which separate counts can't\n // see.\n let tracker = trackers.get(store);\n if (!tracker) {\n tracker = make_tracker(store);\n trackers.set(store, tracker);\n }\n return tracker;\n}\n\nconst trackers = new WeakMap<IdempotencyStore, InFlightTracker>();\n\nfunction make_tracker(store: IdempotencyStore): InFlightTracker {\n const pending = new Map<string, number>();\n const up = (key: string) => pending.set(key, (pending.get(key) ?? 0) + 1);\n const down = (key: string) => {\n const left = (pending.get(key) ?? 0) - 1;\n if (left > 0) pending.set(key, left);\n else pending.delete(key);\n };\n const settle = (key: string, won: boolean) => {\n if (!won) down(key);\n return won;\n };\n return {\n in_flight: (key) => pending.has(key),\n store: {\n claim(key, now) {\n up(key);\n let won: boolean | Promise<boolean>;\n try {\n won = store.claim(key, now);\n } catch (err) {\n down(key);\n throw err;\n }\n return typeof won === \"boolean\"\n ? settle(key, won)\n : won.then(\n (w) => settle(key, w),\n (err: unknown) => {\n down(key);\n throw err;\n }\n );\n },\n async commit(key, now) {\n try {\n await store.commit(key, now);\n } finally {\n down(key);\n }\n },\n async release(key) {\n try {\n await store.release(key);\n } finally {\n down(key);\n }\n },\n },\n };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * The two-phase finalizers a receiver adapter binds to a single\n * inbound delivery. The claim `checkWebhook` makes is *tentative*;\n * exactly one of these promotes or drops it once the business handler\n * resolves its outcome.\n */\nexport type Finalizers = {\n /**\n * Promote the tentative claim to a durable record so every later\n * retry of this key dedups. Call on handler success.\n */\n commit: () => void | Promise<void>;\n /**\n * Drop the tentative claim so the sender's retry re-processes.\n * Call on transient handler failure.\n */\n release: () => void | Promise<void>;\n};\n\n/**\n * The `idempotency` bag a receiver adapter hands its route for one\n * delivery: the claimed key, whether it was a duplicate, and the\n * {@link Finalizers}.\n */\nexport type Idempotency = { key: string; deduped: boolean } & Finalizers;\n\n/**\n * Build the {@link Idempotency} bag for one delivery that passed\n * `checkWebhook`.\n *\n * Guarantees:\n *\n * - **Deduped deliveries are inert.** When `deduped` is `true` the key\n * was already committed by an earlier delivery; both finalizers are\n * no-ops so a duplicate can never release someone else's committed\n * claim.\n * - **Finalize-once.** After the first `commit` or `release` fires,\n * further calls are no-ops — an adapter that both auto-finalizes and\n * lets the operator call `commit()`/`release()` can't double-fire.\n */\nexport function make_idempotency(\n store: IdempotencyStore,\n { key, deduped }: { key: string; deduped: boolean }\n): Idempotency {\n let settled = deduped;\n return {\n key,\n deduped,\n async commit() {\n if (settled) return;\n settled = true;\n await store.commit(key);\n },\n async release() {\n if (settled) return;\n settled = true;\n await store.release(key);\n },\n };\n}\n","/**\n * @packageDocumentation\n * @module act-http/receiver/hono\n *\n * Hono adapter for the receiver-side webhook check.\n *\n * Usage:\n *\n * ```ts\n * import { Hono } from \"hono\";\n * import { webhookMiddleware } from \"@rotorsoft/act-http/receiver/hono\";\n * import { InMemoryIdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n *\n * const app = new Hono();\n * const dedup = new InMemoryIdempotencyStore();\n *\n * app.post(\n * \"/webhooks/orders\",\n * webhookMiddleware({ store: dedup, secret: process.env.WEBHOOK_SECRET }),\n * async (c) => {\n * const idem = c.get(\"idempotency\") as { key: string; deduped: boolean };\n * if (idem.deduped) return c.json({ status: \"dedup-skipped\", key: idem.key });\n * // ... process the inbound event ...\n * return c.json({ status: \"processed\", key: idem.key });\n * }\n * );\n * ```\n *\n * On failure: returns `c.json({ error: <reason> }, status)` directly\n * (Hono short-circuits when middleware returns a Response). On\n * success: stashes `c.set(\"idempotency\", { key, deduped })` and\n * continues with `await next()`.\n *\n * **Two-phase dedup**: the claim `checkWebhook` makes is *tentative*.\n * Because Hono middleware wraps the downstream chain, this adapter\n * finalizes the claim automatically after `await next()`: a downstream\n * 2xx/3xx **commits** the key (later retries dedup); any **4xx or 5xx**\n * (or a thrown handler) **releases** it, so the sender's corrected retry\n * re-processes instead of being silently dropped. Fail-safe is\n * toward reprocessing: releasing a deterministic 4xx costs bounded\n * re-delivery, while committing it would lose a delivery the handler\n * never accepted (the shipped `receiver()` returns 422 on a schema\n * mismatch, where the handler never runs). Operators who need explicit\n * control can still call `c.get(\"idempotency\").commit()` / `.release()`.\n *\n * **Raw body**: Hono exposes `await c.req.text()` natively, which\n * the middleware reads when `secret` is configured. No extra setup\n * needed.\n */\nimport type { MiddlewareHandler } from \"hono\";\nimport { type CheckWebhookOptions, checkWebhook } from \"../check.js\";\nimport { make_idempotency } from \"../finalize.js\";\n\n/**\n * Variables this middleware contributes to the Hono context. The\n * generic on the returned {@link MiddlewareHandler} threads it\n * through so route handlers downstream of `app.post(..., webhookMiddleware(...), handler)`\n * see `c.get(\"idempotency\")` typed without a manual cast.\n *\n * `commit` / `release` finalize the tentative claim — call one after\n * the handler resolves its outcome. This adapter also finalizes\n * automatically based on the response status, so explicit calls are\n * only needed when the auto-detection doesn't fit.\n */\nexport type WebhookVariables = {\n idempotency: {\n key: string;\n deduped: boolean;\n commit: () => void | Promise<void>;\n release: () => void | Promise<void>;\n };\n};\n\n/**\n * Build a Hono middleware that verifies the request signature (when\n * `secret` is set), enforces `Idempotency-Key`, and claims the key\n * on the configured store. See the module-level docs for usage.\n */\nexport function webhookMiddleware(\n options: CheckWebhookOptions\n): MiddlewareHandler<{ Variables: WebhookVariables }> {\n return async function check(c, next) {\n const headers = headers_bag(c.req.raw.headers);\n const rawBody = await c.req.text();\n const result = await checkWebhook(headers, rawBody, options);\n if (!result.ok) {\n return c.json({ error: result.reason }, result.status);\n }\n const idempotency = make_idempotency(options.store, result);\n c.set(\"idempotency\", idempotency);\n try {\n await next();\n } catch (err) {\n await idempotency.release();\n throw err;\n }\n // Commit only a genuine success (2xx/3xx); release on any 4xx/5xx so a\n // failed delivery's corrected same-key retry re-processes instead of being\n // deduped into a silent success.\n if (c.res.status >= 400) await idempotency.release();\n else await idempotency.commit();\n };\n}\n\nfunction headers_bag(\n headers: Headers\n): Record<string, string | string[] | undefined> {\n const out: Record<string, string | string[] | undefined> = {};\n headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBO,SAA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AAO,MAAM,QAAQ,KAAK,CAAC;AAC/D,qBAAS;AACT,gBAAI;AAKF,oBAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,yBAAS,KAAK,aAAa,MAAM,QAAQ,CAAC;AAC1C,yBAAS,KAAK,SAAS,MAAM;AAAA,cAC/B,CAAC;AAAA,YACH,SAAS,OAAO;AACd,uBAAS;AACT,yBAAW;AACX,oBAAM;AAAA,YACR;AAAA,UACF,GAAG;AACH,iBAAO;AAAA,QACT;AAAA,QAEA,MAAM,QAAuB;AAC3B,cAAI,UAAU;AACZ,kBAAM,UAAU;AAChB,uBAAW;AAEX,kBAAM,QAAQ,MAAM,MAAM;AAAA,YAAC,CAAC;AAAA,UAC9B;AACA,cAAI,CAAC,OAAQ;AACb,gBAAM,IAAI;AACV,mBAAS;AACT,gBAAM,IAAI,QAAc,CAAC,YAAY,EAAE,MAAM,MAAM,QAAQ,CAAC,CAAC;AAAA,QAC/D;AAAA,QAEA,MAAM,MAAM,SAAqC;AAC/C,iBAAO,IAAI,MAAM,OAAO;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  webhookMiddleware
3
- } from "../chunk-TTVMQYNN.js";
3
+ } from "../chunk-OEMQP5ZM.js";
4
4
  import {
5
5
  track_in_flight
6
- } from "../chunk-EERALS5E.js";
6
+ } from "../chunk-CVCTDLJA.js";
7
7
  import {
8
8
  checkWebhook,
9
9
  extractIdempotencyKey,
10
10
  verifyWebhook
11
- } from "../chunk-G5FNOSDX.js";
11
+ } from "../chunk-ET2PACPO.js";
12
12
  import "../chunk-PZ5AY32C.js";
13
13
 
14
14
  // src/receiver/start.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/receiver/start.ts"],"sourcesContent":["import type {\n Receiver,\n ReceiverBuilder,\n ReceiverContext,\n ReceiverOptions,\n Validator,\n} from \"@rotorsoft/act-ops/receiver\";\nimport { Hono } from \"hono\";\nimport { track_in_flight } from \"../api/in-flight.js\";\nimport { webhookMiddleware } from \"./hono/index.js\";\n\n/**\n * Recommended factory for \"I want to receive webhooks.\" Returns a\n * {@link ReceiverBuilder} the operator configures fluently:\n *\n * ```ts\n * import { receiver } from \"@rotorsoft/act-http/receiver\";\n * import { InMemoryIdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n * import { z } from \"zod\";\n *\n * const r = receiver({\n * port: 4001,\n * store: new InMemoryIdempotencyStore(),\n * secret: process.env.WEBHOOK_SECRET,\n * })\n * .on(\"OrderConfirmed\", z.object({\n * orderId: z.string(),\n * total: z.number(),\n * }), async (event, ctx) => {\n * // event.orderId and event.total are typed\n * // ctx.key is the deduplicated Idempotency-Key\n * await process_order(event.orderId, event.total);\n * })\n * .build();\n *\n * await r.listen();\n * ```\n *\n * Matches Act's builder pattern: `receiver(...)` is the factory,\n * `.on()` registers handlers fluently, `.build()` finalizes and\n * produces an immutable {@link Receiver} — at which point the type\n * loses `.on()` and gains the runtime methods (`listen` / `close` /\n * `fetch`). The lifecycle phases are split at the type level.\n *\n * Internally uses Hono for routing — the universal-runtime choice\n * that gives one code path coverage across Node, AWS Lambda,\n * Cloudflare Workers, Vercel Edge, Bun, and Deno. For operators\n * with an existing tRPC / Express / Fastify / Hono app who need to\n * compose the receiver with their own middleware stack, the\n * lower-level `webhookMiddleware` from\n * `@rotorsoft/act-http/receiver/<framework>` is the escape hatch.\n *\n * `@hono/node-server` is imported lazily inside `.listen()` so\n * Lambda / edge consumers (who never call `.listen()`) don't need\n * it installed.\n */\nexport function receiver(options: ReceiverOptions): ReceiverBuilder {\n const app = new Hono<{\n Variables: { idempotency: { key: string; deduped: boolean } };\n }>();\n\n // Keys whose winning delivery is still running in this receiver. A\n // duplicate that loses the claim is either behind a committed success\n // (safe to answer 204, \"stop retrying\") or behind an attempt whose\n // outcome is still unknown. In the second case a 204 would end the\n // sender's retries, and if the original then fails and releases, the\n // delivery is lost. The store can't tell the two apart, so the receiver\n // remembers which claims it won and hasn't finalized yet.\n const tracker = track_in_flight(options.store);\n const middleware = webhookMiddleware({\n store: tracker.store,\n secret: options.secret,\n });\n\n let built = false;\n\n const builder: ReceiverBuilder = {\n on<T>(\n name: string,\n schema: Validator<T>,\n handler: (event: T, ctx: ReceiverContext) => Promise<void>\n ): ReceiverBuilder {\n if (built) {\n throw new Error(\n `Cannot register handler \"${name}\" after .build() — handlers are frozen once the receiver is built.`\n );\n }\n\n app.post(`/${name}`, middleware, async (c) => {\n let validated: T;\n try {\n const body = await c.req.json();\n validated = schema.parse(body);\n } catch (err) {\n return c.json(\n {\n error: \"validation-failed\",\n detail: (err as Error).message,\n },\n 422\n );\n }\n\n const idem = c.get(\"idempotency\");\n if (idem.deduped && tracker.in_flight(idem.key)) {\n // The original is still running and may yet fail. Ask the\n // sender to come back instead of telling it to stop: a 5xx is\n // retryable by every sender, including Act's webhook reaction.\n c.header(\"Retry-After\", \"1\");\n return c.json({ error: \"in-flight\" }, 503);\n }\n if (!idem.deduped) {\n try {\n await handler(validated, { key: idem.key });\n } catch (err) {\n // Transient failure: release the tentative claim so the\n // sender's retry re-processes instead of being deduped\n // into a silent success and permanently lost. Finalize through\n // the context's `settled`-guarded finalizer, NOT the raw store —\n // the `webhookMiddleware` this route mounts auto-finalizes after\n // `next()` too, and hitting the raw store here double-fires (a\n // stale second `release` can delete a concurrent retry's live\n // claim, breaking exactly-once). The guard collapses both into\n // one store call (#1293).\n await idem.release();\n return c.json(\n {\n error: \"handler-failed\",\n detail: (err as Error).message,\n },\n 500\n );\n }\n // Success: promote the tentative claim to a durable record so every\n // later retry of this key dedups — again via the guarded finalizer,\n // not the raw store (#1293).\n await idem.commit();\n }\n\n return c.body(null, 204);\n });\n\n return builder;\n },\n\n build(): Receiver {\n built = true;\n\n // `any`: server lifecycle handle from @hono/node-server\n let server: any | undefined;\n // The listen in progress, if any. `server` is only assigned after the\n // lazy import resolves, so without this a `close()` issued while\n // `listen()` is still pending would see no server, return, and leave\n // the port bound once the import finished; a second `listen()` would\n // also start a second server.\n let starting: Promise<void> | undefined;\n\n return {\n listen(): Promise<void> {\n starting ??= (async () => {\n const { serve } = await import(\"@hono/node-server\");\n const launched = serve({ fetch: app.fetch, port: options.port });\n server = launched;\n try {\n // A server that can't bind (EADDRINUSE, EACCES) emits `error`\n // and never `listening`: reject with it instead of hanging, so\n // the caller sees the failure and `close()` isn't left waiting\n // on a start that never finishes (#1783).\n await new Promise<void>((resolve, reject) => {\n launched.once(\"listening\", () => resolve());\n launched.once(\"error\", reject);\n });\n } catch (error) {\n server = undefined;\n starting = undefined;\n throw error;\n }\n })();\n return starting;\n },\n\n async close(): Promise<void> {\n if (starting) {\n const pending = starting;\n starting = undefined;\n // A start that failed has nothing to close.\n await pending.catch(() => {});\n }\n if (!server) return;\n const s = server;\n server = undefined;\n await new Promise<void>((resolve) => s.close(() => resolve()));\n },\n\n async fetch(request: Request): Promise<Response> {\n return app.fetch(request);\n },\n };\n },\n };\n\n return builder;\n}\n"],"mappings":";;;;;;;;;;;;;;AAOA,SAAS,YAAY;AAiDd,SAAS,SAAS,SAA2C;AAClE,QAAM,MAAM,IAAI,KAEb;AASH,QAAM,UAAU,gBAAgB,QAAQ,KAAK;AAC7C,QAAM,aAAa,kBAAkB;AAAA,IACnC,OAAO,QAAQ;AAAA,IACf,QAAQ,QAAQ;AAAA,EAClB,CAAC;AAED,MAAI,QAAQ;AAEZ,QAAM,UAA2B;AAAA,IAC/B,GACE,MACA,QACA,SACiB;AACjB,UAAI,OAAO;AACT,cAAM,IAAI;AAAA,UACR,4BAA4B,IAAI;AAAA,QAClC;AAAA,MACF;AAEA,UAAI,KAAK,IAAI,IAAI,IAAI,YAAY,OAAO,MAAM;AAC5C,YAAI;AACJ,YAAI;AACF,gBAAM,OAAO,MAAM,EAAE,IAAI,KAAK;AAC9B,sBAAY,OAAO,MAAM,IAAI;AAAA,QAC/B,SAAS,KAAK;AACZ,iBAAO,EAAE;AAAA,YACP;AAAA,cAC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AW;AAEX,kBAAM,QAAQ,MAAM,MAAM;AAAA,YAAC,CAAC;AAAA,UAC9B;AACA,cAAI,CAAC,OAAQ;AACb,gBAAM,IAAI;AACV,mBAAS;AACT,gBAAM,IAAI,QAAc,CAAC,YAAY,EAAE,MAAM,MAAM,QAAQ,CAAC,CAAC;AAAA,QAC/D;AAAA,QAEA,MAAM,MAAM,SAAqC;AAC/C,iBAAO,IAAI,MAAM,OAAO;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/receiver/start.ts"],"sourcesContent":["import type {\n Receiver,\n ReceiverBuilder,\n ReceiverContext,\n ReceiverOptions,\n Validator,\n} from \"@rotorsoft/act-ops/receiver\";\nimport { Hono } from \"hono\";\nimport { track_in_flight } from \"../api/in-flight.js\";\nimport { webhookMiddleware } from \"./hono/index.js\";\n\n/**\n * Recommended factory for \"I want to receive webhooks.\" Returns a\n * {@link ReceiverBuilder} the operator configures fluently:\n *\n * ```ts\n * import { receiver } from \"@rotorsoft/act-http/receiver\";\n * import { InMemoryIdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n * import { z } from \"zod\";\n *\n * const r = receiver({\n * port: 4001,\n * store: new InMemoryIdempotencyStore(),\n * secret: process.env.WEBHOOK_SECRET,\n * })\n * .on(\"OrderConfirmed\", z.object({\n * orderId: z.string(),\n * total: z.number(),\n * }), async (event, ctx) => {\n * // event.orderId and event.total are typed\n * // ctx.key is the deduplicated Idempotency-Key\n * await process_order(event.orderId, event.total);\n * })\n * .build();\n *\n * await r.listen();\n * ```\n *\n * Matches Act's builder pattern: `receiver(...)` is the factory,\n * `.on()` registers handlers fluently, `.build()` finalizes and\n * produces an immutable {@link Receiver} — at which point the type\n * loses `.on()` and gains the runtime methods (`listen` / `close` /\n * `fetch`). The lifecycle phases are split at the type level.\n *\n * Internally uses Hono for routing — the universal-runtime choice\n * that gives one code path coverage across Node, AWS Lambda,\n * Cloudflare Workers, Vercel Edge, Bun, and Deno. For operators\n * with an existing tRPC / Express / Fastify / Hono app who need to\n * compose the receiver with their own middleware stack, the\n * lower-level `webhookMiddleware` from\n * `@rotorsoft/act-http/receiver/<framework>` is the escape hatch.\n *\n * `@hono/node-server` is imported lazily inside `.listen()` so\n * Lambda / edge consumers (who never call `.listen()`) don't need\n * it installed.\n */\nexport function receiver(options: ReceiverOptions): ReceiverBuilder {\n const app = new Hono<{\n Variables: { idempotency: { key: string; deduped: boolean } };\n }>();\n\n // Keys whose winning delivery is still running in this receiver. A\n // duplicate that loses the claim is either behind a committed success\n // (safe to answer 204, \"stop retrying\") or behind an attempt whose\n // outcome is still unknown. In the second case a 204 would end the\n // sender's retries, and if the original then fails and releases, the\n // delivery is lost. The store can't tell the two apart, so the receiver\n // remembers which claims it won and hasn't finalized yet.\n const tracker = track_in_flight(options.store);\n const middleware = webhookMiddleware({\n store: tracker.store,\n secret: options.secret,\n });\n\n let built = false;\n\n const builder: ReceiverBuilder = {\n on<T>(\n name: string,\n schema: Validator<T>,\n handler: (event: T, ctx: ReceiverContext) => Promise<void>\n ): ReceiverBuilder {\n if (built) {\n throw new Error(\n `Cannot register handler \"${name}\" after .build() — handlers are frozen once the receiver is built.`\n );\n }\n\n app.post(`/${name}`, middleware, async (c) => {\n let validated: T;\n try {\n const body = await c.req.json();\n validated = schema.parse(body);\n } catch (err) {\n return c.json(\n {\n error: \"validation-failed\",\n detail: (err as Error).message,\n },\n 422\n );\n }\n\n const idem = c.get(\"idempotency\");\n if (idem.deduped && tracker.in_flight(idem.key)) {\n // The original is still running and may yet fail. Ask the\n // sender to come back instead of telling it to stop: a 5xx is\n // retryable by every sender, including Act's webhook reaction.\n c.header(\"Retry-After\", \"1\");\n return c.json({ error: \"in-flight\" }, 503);\n }\n if (!idem.deduped) {\n try {\n await handler(validated, { key: idem.key });\n } catch (err) {\n // Transient failure: release the tentative claim so the\n // sender's retry re-processes instead of being deduped\n // into a silent success and permanently lost. Finalize through\n // the context's `settled`-guarded finalizer, NOT the raw store —\n // the `webhookMiddleware` this route mounts auto-finalizes after\n // `next()` too, and hitting the raw store here double-fires (a\n // stale second `release` can delete a concurrent retry's live\n // claim, breaking exactly-once). The guard collapses both into\n // one store call.\n await idem.release();\n return c.json(\n {\n error: \"handler-failed\",\n detail: (err as Error).message,\n },\n 500\n );\n }\n // Success: promote the tentative claim to a durable record so every\n // later retry of this key dedups — again via the guarded finalizer,\n // not the raw store.\n await idem.commit();\n }\n\n return c.body(null, 204);\n });\n\n return builder;\n },\n\n build(): Receiver {\n built = true;\n\n // `any`: server lifecycle handle from @hono/node-server\n let server: any | undefined;\n // The listen in progress, if any. `server` is only assigned after the\n // lazy import resolves, so without this a `close()` issued while\n // `listen()` is still pending would see no server, return, and leave\n // the port bound once the import finished; a second `listen()` would\n // also start a second server.\n let starting: Promise<void> | undefined;\n\n return {\n listen(): Promise<void> {\n starting ??= (async () => {\n const { serve } = await import(\"@hono/node-server\");\n const launched = serve({ fetch: app.fetch, port: options.port });\n server = launched;\n try {\n // A server that can't bind (EADDRINUSE, EACCES) emits `error`\n // and never `listening`: reject with it instead of hanging, so\n // the caller sees the failure and `close()` isn't left waiting\n // on a start that never finishes.\n await new Promise<void>((resolve, reject) => {\n launched.once(\"listening\", () => resolve());\n launched.once(\"error\", reject);\n });\n } catch (error) {\n server = undefined;\n starting = undefined;\n throw error;\n }\n })();\n return starting;\n },\n\n async close(): Promise<void> {\n if (starting) {\n const pending = starting;\n starting = undefined;\n // A start that failed has nothing to close.\n await pending.catch(() => {});\n }\n if (!server) return;\n const s = server;\n server = undefined;\n await new Promise<void>((resolve) => s.close(() => resolve()));\n },\n\n async fetch(request: Request): Promise<Response> {\n return app.fetch(request);\n },\n };\n },\n };\n\n return builder;\n}\n"],"mappings":";;;;;;;;;;;;;;AAOA,SAAS,YAAY;AAiDd,SAAS,SAAS,SAA2C;AAClE,QAAM,MAAM,IAAI,KAEb;AASH,QAAM,UAAU,gBAAgB,QAAQ,KAAK;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BAAM,EAAE,MAAM,IAAI,MAAM,OAAO,mBAAmB;AAClD,kBAAM,WAAW,MAAM,EAAE,OAAO,IAAI,OAAO,MAAM,QAAQ,KAAK,CAAC;AAC/D,qBAAS;AACT,gBAAI;AAKF,oBAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,yBAAS,KAAK,aAAa,MAAM,QAAQ,CAAC;AAC1C,yBAAS,KAAK,SAAS,MAAM;AAAA,cAC/B,CAAC;AAAA,YACH,SAAS,OAAO;AACd,uBAAS;AACT,yBAAW;AACX,oBAAM;AAAA,YACR;AAAA,UACF,GAAG;AACH,iBAAO;AAAA,QACT;AAAA,QAEA,MAAM,QAAuB;AAC3B,cAAI,UAAU;AACZ,kBAAM,UAAU;AAChB,uBAAW;AAEX,kBAAM,QAAQ,MAAM,MAAM;AAAA,YAAC,CAAC;AAAA,UAC9B;AACA,cAAI,CAAC,OAAQ;AACb,gBAAM,IAAI;AACV,mBAAS;AACT,gBAAM,IAAI,QAAc,CAAC,YAAY,EAAE,MAAM,MAAM,QAAQ,CAAC,CAAC;AAAA,QAC/D;AAAA,QAEA,MAAM,MAAM,SAAqC;AAC/C,iBAAO,IAAI,MAAM,OAAO;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/receiver/trpc/index.ts","../../../src/receiver/extract.ts","../../../src/receiver/verify.ts","../../../src/receiver/check.ts","../../../src/receiver/finalize.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/receiver/trpc\n *\n * tRPC adapter for the receiver-side webhook check. Composes\n * `extractIdempotencyKey` + `verifyWebhook` + `IdempotencyStore.claim`\n * into a single middleware factory.\n *\n * Usage:\n *\n * ```ts\n * import { initTRPC, TRPCError } from \"@trpc/server\";\n * import { webhookMiddleware } from \"@rotorsoft/act-http/receiver/trpc\";\n * import { InMemoryIdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n *\n * type Ctx = {\n * headers: Record<string, string | string[] | undefined>;\n * rawBody: string;\n * };\n *\n * const t = initTRPC.context<Ctx>().create();\n * const dedup = new InMemoryIdempotencyStore();\n *\n * const idempotent = t.procedure.use(\n * webhookMiddleware({ store: dedup, secret: process.env.WEBHOOK_SECRET })\n * );\n * ```\n *\n * The middleware throws a `TRPCError` with `BAD_REQUEST` for\n * `missing-key` and `UNAUTHORIZED` for any verification failure.\n * On success it injects `{ key, deduped, commit, release }` into the\n * request context under the `idempotency` property.\n *\n * **Two-phase dedup**: the claim is *tentative*. Because a tRPC\n * middleware wraps `next()`, this adapter finalizes automatically:\n * the downstream resolver returning **commits** the key, and a thrown\n * error **releases** it so the sender's retry re-processes. The\n * bound `ctx.idempotency.commit()` / `.release()` are exposed for\n * resolvers that need to finalize a partial success explicitly.\n *\n * **Raw body requirement**: when `secret` is configured, the middleware\n * needs the raw request bytes for HMAC verification. Capture them in\n * `createContext` — most tRPC HTTP adapters expose the raw stream;\n * read it into a string and stash it on `ctx.rawBody`. Skip when\n * unsigned (no `secret`) — the middleware never reads `rawBody` in\n * that mode.\n */\nimport { TRPCError } from \"@trpc/server\";\nimport { type CheckWebhookOptions, checkWebhook } from \"../check.js\";\nimport { make_idempotency } from \"../finalize.js\";\n\n/**\n * Build a tRPC middleware that verifies the request signature (when\n * `secret` is set), enforces `Idempotency-Key`, and claims the key on\n * the configured store. See the module-level docs for usage.\n *\n * The returned function uses permissive `any` typing because tRPC's\n * `MiddlewareFunction` type lives in `unstable-core-do-not-import`\n * (internal namespace, not for external import). Type-safety at the\n * call site comes from `t.procedure.use(...)` validating the\n * middleware shape against the procedure's context — the operator's\n * tRPC context must include `headers` and `rawBody`, and downstream\n * handlers see `ctx.idempotency = { key, deduped }`.\n */\n// `any`: tRPC's internal middleware shape\nexport function webhookMiddleware(options: CheckWebhookOptions): any {\n return async function check(opts: {\n ctx: {\n headers: Record<string, string | string[] | undefined>;\n rawBody: string;\n };\n // `any`: see above\n next: (next: { ctx: any }) => Promise<any>;\n }) {\n const result = await checkWebhook(\n opts.ctx.headers,\n opts.ctx.rawBody,\n options\n );\n if (!result.ok) {\n throw new TRPCError({\n code: result.status === 400 ? \"BAD_REQUEST\" : \"UNAUTHORIZED\",\n message: result.reason,\n });\n }\n const idempotency = make_idempotency(options.store, result);\n let outcome: unknown;\n try {\n outcome = await opts.next({\n ctx: {\n ...opts.ctx,\n idempotency,\n },\n });\n } catch (err) {\n // Resolver threw — release the tentative claim so a retry\n // re-processes instead of being deduped into a silent success.\n await idempotency.release();\n throw err;\n }\n // tRPC middleware results carry `{ ok: boolean }`; an `ok: false`\n // result is an error the resolver returned rather than threw.\n if (\n typeof outcome === \"object\" &&\n outcome !== null &&\n \"ok\" in outcome &&\n (outcome as { ok: unknown }).ok === false\n ) {\n await idempotency.release();\n } else {\n await idempotency.commit();\n }\n return outcome;\n };\n}\n","/**\n * Pull the `Idempotency-Key` header from a Node-style headers bag,\n * case-insensitive. Returns `undefined` when any of the following\n * carries no usable key:\n *\n * - the header is missing\n * - its value is an array (ambiguous — can't pick one without a\n * policy the receiver hasn't declared)\n * - its value is the empty string (carries no idempotency\n * information; structurally equivalent to \"no header at all\")\n *\n * Pair with `IdempotencyStore.claim` from\n * `@rotorsoft/act-ops/idempotency`: extract the key from the inbound\n * request, claim it on the store, return a `deduped` marker when the\n * claim fails. The framework-agnostic middleware that wires these\n * together lands in #744.\n *\n * Validation beyond \"is there a usable key?\" (length bounds, format\n * checks, normalization) is intentionally out of scope. Receivers\n * picking a policy can layer it on top — or, when #744 ships, opt\n * into the middleware's opinionated defaults.\n */\nexport function extractIdempotencyKey(\n headers: Record<string, string | string[] | undefined>\n): string | undefined {\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() !== \"idempotency-key\") continue;\n if (Array.isArray(value)) return undefined;\n if (value === \"\") return undefined;\n return value;\n }\n return undefined;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Outcome of {@link verifyWebhook}. Either the request signature\n * checks out, or one of five distinct failure reasons applies. Each\n * reason maps to an operator-meaningful telemetry bucket — separated\n * deliberately so dashboards can distinguish \"client lost its secret\"\n * from \"client clock is wrong\" from \"this is a replay attack.\"\n */\nexport type VerifyResult =\n | { ok: true }\n | {\n ok: false;\n reason:\n | \"missing-signature\"\n | \"missing-timestamp\"\n | \"stale\"\n | \"future\"\n | \"bad-signature\";\n };\n\n/** Options for {@link verifyWebhook}. */\nexport type VerifyOptions = {\n /**\n * Maximum acceptable timestamp drift in either direction, in\n * seconds. Default: 300 (±5 minutes) — matches Stripe / GitHub /\n * Slack conventions. Tightening narrows the replay window;\n * loosening accommodates clients with worse clock sync.\n */\n maxAgeSeconds?: number;\n /**\n * Current Unix-seconds time. Exposed for tests; production\n * callers should leave it undefined so wall-clock is used.\n */\n now?: number;\n};\n\n/**\n * Verify an inbound webhook's signature and timestamp against the\n * shared secret. Pair with the sender side: configure\n * `webhook({ secret })` from `@rotorsoft/act-http/webhook`.\n *\n * Returns `{ ok: true }` on success or `{ ok: false; reason }` on\n * failure. The reasons are:\n *\n * - `missing-signature` — no `X-Webhook-Signature` header, value\n * was an array, or value was empty.\n * - `missing-timestamp` — no `X-Webhook-Timestamp` header, value\n * was empty, or value isn't a parseable integer.\n * - `stale` — timestamp older than `maxAgeSeconds` from `now`.\n * - `future` — timestamp more than `maxAgeSeconds` ahead of `now`.\n * - `bad-signature` — signature header didn't start with `sha256=`,\n * wasn't 64 hex chars, or the recomputed HMAC didn't match\n * (constant-time compare).\n *\n * The signed payload is `${timestamp}.${body}`, so `body` must be\n * the **raw request body bytes**. Any pre-parse normalization\n * (whitespace trimming, JSON re-stringification) would change the\n * hash and reject every otherwise-valid request. Framework adapters\n * in #744 will provide the raw body alongside the parsed one.\n *\n * Uses Node's `crypto.timingSafeEqual` for the final comparison to\n * avoid signature-equality timing attacks.\n */\nexport function verifyWebhook(\n headers: Record<string, string | string[] | undefined>,\n body: string,\n secret: string,\n options?: VerifyOptions\n): VerifyResult {\n const maxAgeSeconds = options?.maxAgeSeconds ?? 300;\n const now = options?.now ?? Math.floor(Date.now() / 1000);\n\n const signature = pick_header(headers, \"x-webhook-signature\");\n if (!signature) return { ok: false, reason: \"missing-signature\" };\n\n const timestamp_str = pick_header(headers, \"x-webhook-timestamp\");\n if (!timestamp_str) return { ok: false, reason: \"missing-timestamp\" };\n const timestamp = Number.parseInt(timestamp_str, 10);\n if (Number.isNaN(timestamp) || String(timestamp) !== timestamp_str) {\n return { ok: false, reason: \"missing-timestamp\" };\n }\n\n const delta = now - timestamp;\n if (delta > maxAgeSeconds) return { ok: false, reason: \"stale\" };\n if (delta < -maxAgeSeconds) return { ok: false, reason: \"future\" };\n\n if (!signature.startsWith(\"sha256=\")) {\n return { ok: false, reason: \"bad-signature\" };\n }\n const provided_hex = signature.slice(\"sha256=\".length);\n if (!/^[0-9a-fA-F]{64}$/.test(provided_hex)) {\n return { ok: false, reason: \"bad-signature\" };\n }\n\n const expected_hex = createHmac(\"sha256\", secret)\n .update(`${timestamp_str}.${body}`)\n .digest(\"hex\");\n\n const a = Buffer.from(provided_hex, \"hex\");\n const b = Buffer.from(expected_hex, \"hex\");\n if (!timingSafeEqual(a, b)) {\n return { ok: false, reason: \"bad-signature\" };\n }\n\n return { ok: true };\n}\n\nfunction pick_header(\n headers: Record<string, string | string[] | undefined>,\n lower_name: string\n): string | undefined {\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() !== lower_name) continue;\n if (Array.isArray(value) || value === undefined || value === \"\") {\n return undefined;\n }\n return value;\n }\n return undefined;\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport { extractIdempotencyKey } from \"./extract.js\";\nimport { type VerifyOptions, verifyWebhook } from \"./verify.js\";\n\n/**\n * Failure reasons returned by {@link checkWebhook}. The shape splits\n * client/configuration errors (`missing-key`, `empty-body` — HTTP 400)\n * from the five verification failures (authentication errors, HTTP 401)\n * so each maps to its own telemetry bucket. `empty-body` is the\n * misconfigured-raw-parser signal: `secret` is set but the resolved\n * body is empty, so hashing it would compute an HMAC over `${ts}.` and\n * reject every otherwise-valid signed request with a misleading\n * bad-signature — a distinct config error is far easier to diagnose.\n */\nexport type CheckFailureReason =\n | \"missing-key\"\n | \"empty-body\"\n | \"missing-signature\"\n | \"missing-timestamp\"\n | \"stale\"\n | \"future\"\n | \"bad-signature\";\n\n/**\n * Outcome of {@link checkWebhook}. Either the request passed every\n * configured check and carries a usable idempotency key, or it\n * failed one of them and the framework adapter should reply with the\n * corresponding HTTP status.\n */\nexport type CheckResult =\n | { ok: false; status: 400 | 401; reason: CheckFailureReason }\n | { ok: true; key: string; deduped: boolean };\n\n/** Options for {@link checkWebhook}. */\nexport type CheckWebhookOptions = {\n /** Idempotency store the framework-agnostic core claims the key on. */\n store: IdempotencyStore;\n /**\n * Optional HMAC-SHA256 secret. When set, the request's\n * `X-Webhook-Signature` and `X-Webhook-Timestamp` headers are\n * verified before the dedup claim. When omitted, signature\n * verification is skipped (unsigned receivers).\n */\n secret?: string;\n /**\n * Verification options forwarded to {@link verifyWebhook}. Only\n * meaningful when `secret` is set. Defaults to a ±300-second\n * timestamp window.\n */\n verify?: VerifyOptions;\n};\n\n/**\n * Framework-agnostic receiver check: verify the signature (when a\n * secret is configured), extract the `Idempotency-Key`, and claim\n * it on the store. Returns the request's fate as a discriminated\n * union the per-framework adapter translates into the framework's\n * idiomatic 4xx response or context injection.\n *\n * **Order of checks** (matters):\n *\n * 1. Verify signature + timestamp window (when `secret` is set).\n * Rejecting bad signatures *before* extracting and claiming the\n * key keeps attacker-supplied keys out of the dedup store —\n * otherwise a flood of spoofed POSTs would pollute the LRU.\n * 2. Extract the `Idempotency-Key`. Missing → reject with 400.\n * 3. Claim the key on the store. If already seen, return\n * `{ ok: true; deduped: true }` so the framework adapter can\n * short-circuit the handler without re-running side effects.\n *\n * The dedup store may be sync (`InMemoryIdempotencyStore`) or async\n * (durable adapters like a future `PostgresIdempotencyStore`); the\n * core awaits unconditionally so both shapes compose cleanly.\n */\nexport async function checkWebhook(\n headers: Record<string, string | string[] | undefined>,\n body: string,\n options: CheckWebhookOptions\n): Promise<CheckResult> {\n if (options.secret !== undefined) {\n // Raw body not captured (default JSON parser ate the bytes) but a\n // secret is configured — hashing the empty string is a guaranteed\n // bad-signature. Surface a distinct configuration error instead of a\n // misleading 401 so the operator mounts the raw-body parser.\n if (body === \"\") {\n return { ok: false, status: 400, reason: \"empty-body\" };\n }\n const verification = verifyWebhook(\n headers,\n body,\n options.secret,\n options.verify\n );\n if (!verification.ok) {\n return { ok: false, status: 401, reason: verification.reason };\n }\n }\n\n const key = extractIdempotencyKey(headers);\n if (!key) return { ok: false, status: 400, reason: \"missing-key\" };\n\n const claimed = await options.store.claim(key);\n return { ok: true, key, deduped: !claimed };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * The two-phase finalizers a receiver adapter binds to a single\n * inbound delivery. The claim `checkWebhook` makes is *tentative*;\n * exactly one of these promotes or drops it once the business handler\n * resolves its outcome.\n */\nexport type Finalizers = {\n /**\n * Promote the tentative claim to a durable record so every later\n * retry of this key dedups. Call on handler success.\n */\n commit: () => void | Promise<void>;\n /**\n * Drop the tentative claim so the sender's retry re-processes.\n * Call on transient handler failure.\n */\n release: () => void | Promise<void>;\n};\n\n/**\n * The `idempotency` bag a receiver adapter hands its route for one\n * delivery: the claimed key, whether it was a duplicate, and the\n * {@link Finalizers}.\n */\nexport type Idempotency = { key: string; deduped: boolean } & Finalizers;\n\n/**\n * Build the {@link Idempotency} bag for one delivery that passed\n * `checkWebhook`.\n *\n * Guarantees:\n *\n * - **Deduped deliveries are inert.** When `deduped` is `true` the key\n * was already committed by an earlier delivery; both finalizers are\n * no-ops so a duplicate can never release someone else's committed\n * claim.\n * - **Finalize-once.** After the first `commit` or `release` fires,\n * further calls are no-ops — an adapter that both auto-finalizes and\n * lets the operator call `commit()`/`release()` can't double-fire.\n */\nexport function make_idempotency(\n store: IdempotencyStore,\n { key, deduped }: { key: string; deduped: boolean }\n): Idempotency {\n let settled = deduped;\n return {\n key,\n deduped,\n async commit() {\n if (settled) return;\n settled = true;\n await store.commit(key);\n },\n async release() {\n if (settled) return;\n settled = true;\n await store.release(key);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA+CA,oBAA0B;;;ACzBnB,SAAS,sBACd,SACoB;AACpB,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AACnD,QAAI,KAAK,YAAY,MAAM,kBAAmB;AAC9C,QAAI,MAAM,QAAQ,KAAK,EAAG,QAAO;AACjC,QAAI,UAAU,GAAI,QAAO;AACzB,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AChCA,yBAA4C;AAgErC,SAAS,cACd,SACA,MACA,QACA,SACc;AACd,QAAM,gBAAgB,SAAS,iBAAiB;AAChD,QAAM,MAAM,SAAS,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAExD,QAAM,YAAY,YAAY,SAAS,qBAAqB;AAC5D,MAAI,CAAC,UAAW,QAAO,EAAE,IAAI,OAAO,QAAQ,oBAAoB;AAEhE,QAAM,gBAAgB,YAAY,SAAS,qBAAqB;AAChE,MAAI,CAAC,cAAe,QAAO,EAAE,IAAI,OAAO,QAAQ,oBAAoB;AACpE,QAAM,YAAY,OAAO,SAAS,eAAe,EAAE;AACnD,MAAI,OAAO,MAAM,SAAS,KAAK,OAAO,SAAS,MAAM,eAAe;AAClE,WAAO,EAAE,IAAI,OAAO,QAAQ,oBAAoB;AAAA,EAClD;AAEA,QAAM,QAAQ,MAAM;AACpB,MAAI,QAAQ,cAAe,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAC/D,MAAI,QAAQ,CAAC,cAAe,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAEjE,MAAI,CAAC,UAAU,WAAW,SAAS,GAAG;AACpC,WAAO,EAAE,IAAI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,QAAM,UAAU,MAAM,QAAQ,MAAM,MAAM,GAAG;AAC7C,SAAO,EAAE,IAAI,MAAM,KAAK,SAAS,CAAC,QAAQ;AAC5C;;;AC7DO,SAAS,iBACd,OACA,EAAE,KAAK,QAAQ,GACF;AACb,MAAI,UAAU;AACd,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,MAAM,SAAS;AACb,UAAI,QAAS;AACb,gBAAU;AACV,YAAM,MAAM,OAAO,GAAG;AAAA,IACxB;AAAA,IACA,MAAM,UAAU;AACd,UAAI,QAAS;AACb,gBAAU;AACV,YAAM,MAAM,QAAQ,GAAG;AAAA,IACzB;AAAA,EACF;AACF;;;AJIO,SAAS,kBAAkB,SAAmC;AACnE,SAAO,eAAe,MAAM,MAOzB;AACD,UAAM,SAAS,MAAM;AAAA,MACnB,KAAK,IAAI;AAAA,MACT,KAAK,IAAI;AAAA,MACT;AAAA,IACF;AACA,QAAI,CAAC,OAAO,IAAI;AACd,YAAM,IAAI,wBAAU;AAAA,QAClB,MAAM,OAAO,WAAW,MAAM,gBAAgB;AAAA,QAC9C,SAAS,OAAO;AAAA,MAClB,CAAC;AAAA,IACH;AACA,UAAM,cAAc,iBAAiB,QAAQ,OAAO,MAAM;AAC1D,QAAI;AACJ,QAAI;AACF,gBAAU,MAAM,KAAK,KAAK;AAAA,QACxB,KAAK;AAAA,UACH,GAAG,KAAK;AAAA,UACR;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH,SAAS,KAAK;AAGZ,YAAM,YAAY,QAAQ;AAC1B,YAAM;AAAA,IACR;AAGA,QACE,OAAO,YAAY,YACnB,YAAY,QACZ,QAAQ,WACP,QAA4B,OAAO,OACpC;AACA,YAAM,YAAY,QAAQ;AAAA,IAC5B,OAAO;AACL,YAAM,YAAY,OAAO;AAAA,IAC3B;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/receiver/trpc/index.ts","../../../src/receiver/extract.ts","../../../src/receiver/verify.ts","../../../src/receiver/check.ts","../../../src/receiver/finalize.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/receiver/trpc\n *\n * tRPC adapter for the receiver-side webhook check. Composes\n * `extractIdempotencyKey` + `verifyWebhook` + `IdempotencyStore.claim`\n * into a single middleware factory.\n *\n * Usage:\n *\n * ```ts\n * import { initTRPC, TRPCError } from \"@trpc/server\";\n * import { webhookMiddleware } from \"@rotorsoft/act-http/receiver/trpc\";\n * import { InMemoryIdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n *\n * type Ctx = {\n * headers: Record<string, string | string[] | undefined>;\n * rawBody: string;\n * };\n *\n * const t = initTRPC.context<Ctx>().create();\n * const dedup = new InMemoryIdempotencyStore();\n *\n * const idempotent = t.procedure.use(\n * webhookMiddleware({ store: dedup, secret: process.env.WEBHOOK_SECRET })\n * );\n * ```\n *\n * The middleware throws a `TRPCError` with `BAD_REQUEST` for\n * `missing-key` and `UNAUTHORIZED` for any verification failure.\n * On success it injects `{ key, deduped, commit, release }` into the\n * request context under the `idempotency` property.\n *\n * **Two-phase dedup**: the claim is *tentative*. Because a tRPC\n * middleware wraps `next()`, this adapter finalizes automatically:\n * the downstream resolver returning **commits** the key, and a thrown\n * error **releases** it so the sender's retry re-processes. The\n * bound `ctx.idempotency.commit()` / `.release()` are exposed for\n * resolvers that need to finalize a partial success explicitly.\n *\n * **Raw body requirement**: when `secret` is configured, the middleware\n * needs the raw request bytes for HMAC verification. Capture them in\n * `createContext` — most tRPC HTTP adapters expose the raw stream;\n * read it into a string and stash it on `ctx.rawBody`. Skip when\n * unsigned (no `secret`) — the middleware never reads `rawBody` in\n * that mode.\n */\nimport { TRPCError } from \"@trpc/server\";\nimport { type CheckWebhookOptions, checkWebhook } from \"../check.js\";\nimport { make_idempotency } from \"../finalize.js\";\n\n/**\n * Build a tRPC middleware that verifies the request signature (when\n * `secret` is set), enforces `Idempotency-Key`, and claims the key on\n * the configured store. See the module-level docs for usage.\n *\n * The returned function uses permissive `any` typing because tRPC's\n * `MiddlewareFunction` type lives in `unstable-core-do-not-import`\n * (internal namespace, not for external import). Type-safety at the\n * call site comes from `t.procedure.use(...)` validating the\n * middleware shape against the procedure's context — the operator's\n * tRPC context must include `headers` and `rawBody`, and downstream\n * handlers see `ctx.idempotency = { key, deduped }`.\n */\n// `any`: tRPC's internal middleware shape\nexport function webhookMiddleware(options: CheckWebhookOptions): any {\n return async function check(opts: {\n ctx: {\n headers: Record<string, string | string[] | undefined>;\n rawBody: string;\n };\n // `any`: see above\n next: (next: { ctx: any }) => Promise<any>;\n }) {\n const result = await checkWebhook(\n opts.ctx.headers,\n opts.ctx.rawBody,\n options\n );\n if (!result.ok) {\n throw new TRPCError({\n code: result.status === 400 ? \"BAD_REQUEST\" : \"UNAUTHORIZED\",\n message: result.reason,\n });\n }\n const idempotency = make_idempotency(options.store, result);\n let outcome: unknown;\n try {\n outcome = await opts.next({\n ctx: {\n ...opts.ctx,\n idempotency,\n },\n });\n } catch (err) {\n // Resolver threw — release the tentative claim so a retry\n // re-processes instead of being deduped into a silent success.\n await idempotency.release();\n throw err;\n }\n // tRPC middleware results carry `{ ok: boolean }`; an `ok: false`\n // result is an error the resolver returned rather than threw.\n if (\n typeof outcome === \"object\" &&\n outcome !== null &&\n \"ok\" in outcome &&\n (outcome as { ok: unknown }).ok === false\n ) {\n await idempotency.release();\n } else {\n await idempotency.commit();\n }\n return outcome;\n };\n}\n","/**\n * Pull the `Idempotency-Key` header from a Node-style headers bag,\n * case-insensitive. Returns `undefined` when any of the following\n * carries no usable key:\n *\n * - the header is missing\n * - its value is an array (ambiguous — can't pick one without a\n * policy the receiver hasn't declared)\n * - its value is the empty string (carries no idempotency\n * information; structurally equivalent to \"no header at all\")\n *\n * Pair with `IdempotencyStore.claim` from\n * `@rotorsoft/act-ops/idempotency`: extract the key from the inbound\n * request, claim it on the store, return a `deduped` marker when the\n * claim fails. The receiver subpaths' `webhookMiddleware` wires these\n * together.\n *\n * Validation beyond \"is there a usable key?\" (length bounds, format\n * checks, normalization) is intentionally out of scope. Receivers\n * picking a policy can layer it on top, or use the middleware's\n * defaults.\n */\nexport function extractIdempotencyKey(\n headers: Record<string, string | string[] | undefined>\n): string | undefined {\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() !== \"idempotency-key\") continue;\n if (Array.isArray(value)) return undefined;\n if (value === \"\") return undefined;\n return value;\n }\n return undefined;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Outcome of {@link verifyWebhook}. Either the request signature\n * checks out, or one of five distinct failure reasons applies. Each\n * reason maps to an operator-meaningful telemetry bucket — separated\n * deliberately so dashboards can distinguish \"client lost its secret\"\n * from \"client clock is wrong\" from \"this is a replay attack.\"\n */\nexport type VerifyResult =\n | { ok: true }\n | {\n ok: false;\n reason:\n | \"missing-signature\"\n | \"missing-timestamp\"\n | \"stale\"\n | \"future\"\n | \"bad-signature\";\n };\n\n/** Options for {@link verifyWebhook}. */\nexport type VerifyOptions = {\n /**\n * Maximum acceptable timestamp drift in either direction, in\n * seconds. Default: 300 (±5 minutes) — matches Stripe / GitHub /\n * Slack conventions. Tightening narrows the replay window;\n * loosening accommodates clients with worse clock sync.\n */\n maxAgeSeconds?: number;\n /**\n * Current Unix-seconds time. Exposed for tests; production\n * callers should leave it undefined so wall-clock is used.\n */\n now?: number;\n};\n\n/**\n * Verify an inbound webhook's signature and timestamp against the\n * shared secret. Pair with the sender side: configure\n * `webhook({ secret })` from `@rotorsoft/act-http/webhook`.\n *\n * Returns `{ ok: true }` on success or `{ ok: false; reason }` on\n * failure. The reasons are:\n *\n * - `missing-signature` — no `X-Webhook-Signature` header, value\n * was an array, or value was empty.\n * - `missing-timestamp` — no `X-Webhook-Timestamp` header, value\n * was empty, or value isn't a parseable integer.\n * - `stale` — timestamp older than `maxAgeSeconds` from `now`.\n * - `future` — timestamp more than `maxAgeSeconds` ahead of `now`.\n * - `bad-signature` — signature header didn't start with `sha256=`,\n * wasn't 64 hex chars, or the recomputed HMAC didn't match\n * (constant-time compare).\n *\n * The signed payload is `${timestamp}.${body}`, so `body` must be\n * the **raw request body bytes**. Any pre-parse normalization\n * (whitespace trimming, JSON re-stringification) would change the\n * hash and reject every otherwise-valid request. The receiver\n * subpaths' adapters pass the raw body alongside the parsed one.\n *\n * Uses Node's `crypto.timingSafeEqual` for the final comparison to\n * avoid signature-equality timing attacks.\n */\nexport function verifyWebhook(\n headers: Record<string, string | string[] | undefined>,\n body: string,\n secret: string,\n options?: VerifyOptions\n): VerifyResult {\n const maxAgeSeconds = options?.maxAgeSeconds ?? 300;\n const now = options?.now ?? Math.floor(Date.now() / 1000);\n\n const signature = pick_header(headers, \"x-webhook-signature\");\n if (!signature) return { ok: false, reason: \"missing-signature\" };\n\n const timestamp_str = pick_header(headers, \"x-webhook-timestamp\");\n if (!timestamp_str) return { ok: false, reason: \"missing-timestamp\" };\n const timestamp = Number.parseInt(timestamp_str, 10);\n if (Number.isNaN(timestamp) || String(timestamp) !== timestamp_str) {\n return { ok: false, reason: \"missing-timestamp\" };\n }\n\n const delta = now - timestamp;\n if (delta > maxAgeSeconds) return { ok: false, reason: \"stale\" };\n if (delta < -maxAgeSeconds) return { ok: false, reason: \"future\" };\n\n if (!signature.startsWith(\"sha256=\")) {\n return { ok: false, reason: \"bad-signature\" };\n }\n const provided_hex = signature.slice(\"sha256=\".length);\n if (!/^[0-9a-fA-F]{64}$/.test(provided_hex)) {\n return { ok: false, reason: \"bad-signature\" };\n }\n\n const expected_hex = createHmac(\"sha256\", secret)\n .update(`${timestamp_str}.${body}`)\n .digest(\"hex\");\n\n const a = Buffer.from(provided_hex, \"hex\");\n const b = Buffer.from(expected_hex, \"hex\");\n if (!timingSafeEqual(a, b)) {\n return { ok: false, reason: \"bad-signature\" };\n }\n\n return { ok: true };\n}\n\nfunction pick_header(\n headers: Record<string, string | string[] | undefined>,\n lower_name: string\n): string | undefined {\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() !== lower_name) continue;\n if (Array.isArray(value) || value === undefined || value === \"\") {\n return undefined;\n }\n return value;\n }\n return undefined;\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport { extractIdempotencyKey } from \"./extract.js\";\nimport { type VerifyOptions, verifyWebhook } from \"./verify.js\";\n\n/**\n * Failure reasons returned by {@link checkWebhook}. The shape splits\n * client/configuration errors (`missing-key`, `empty-body` — HTTP 400)\n * from the five verification failures (authentication errors, HTTP 401)\n * so each maps to its own telemetry bucket. `empty-body` is the\n * misconfigured-raw-parser signal: `secret` is set but the resolved\n * body is empty, so hashing it would compute an HMAC over `${ts}.` and\n * reject every otherwise-valid signed request with a misleading\n * bad-signature — a distinct config error is far easier to diagnose.\n */\nexport type CheckFailureReason =\n | \"missing-key\"\n | \"empty-body\"\n | \"missing-signature\"\n | \"missing-timestamp\"\n | \"stale\"\n | \"future\"\n | \"bad-signature\";\n\n/**\n * Outcome of {@link checkWebhook}. Either the request passed every\n * configured check and carries a usable idempotency key, or it\n * failed one of them and the framework adapter should reply with the\n * corresponding HTTP status.\n */\nexport type CheckResult =\n | { ok: false; status: 400 | 401; reason: CheckFailureReason }\n | { ok: true; key: string; deduped: boolean };\n\n/** Options for {@link checkWebhook}. */\nexport type CheckWebhookOptions = {\n /** Idempotency store the framework-agnostic core claims the key on. */\n store: IdempotencyStore;\n /**\n * Optional HMAC-SHA256 secret. When set, the request's\n * `X-Webhook-Signature` and `X-Webhook-Timestamp` headers are\n * verified before the dedup claim. When omitted, signature\n * verification is skipped (unsigned receivers).\n */\n secret?: string;\n /**\n * Verification options forwarded to {@link verifyWebhook}. Only\n * meaningful when `secret` is set. Defaults to a ±300-second\n * timestamp window.\n */\n verify?: VerifyOptions;\n};\n\n/**\n * Framework-agnostic receiver check: verify the signature (when a\n * secret is configured), extract the `Idempotency-Key`, and claim\n * it on the store. Returns the request's fate as a discriminated\n * union the per-framework adapter translates into the framework's\n * idiomatic 4xx response or context injection.\n *\n * **Order of checks** (matters):\n *\n * 1. Verify signature + timestamp window (when `secret` is set).\n * Rejecting bad signatures *before* extracting and claiming the\n * key keeps attacker-supplied keys out of the dedup store —\n * otherwise a flood of spoofed POSTs would pollute the LRU.\n * 2. Extract the `Idempotency-Key`. Missing → reject with 400.\n * 3. Claim the key on the store. If already seen, return\n * `{ ok: true; deduped: true }` so the framework adapter can\n * short-circuit the handler without re-running side effects.\n *\n * The dedup store may be sync (`InMemoryIdempotencyStore`) or async\n * (durable adapters like a future `PostgresIdempotencyStore`); the\n * core awaits unconditionally so both shapes compose cleanly.\n */\nexport async function checkWebhook(\n headers: Record<string, string | string[] | undefined>,\n body: string,\n options: CheckWebhookOptions\n): Promise<CheckResult> {\n if (options.secret !== undefined) {\n // Raw body not captured (default JSON parser ate the bytes) but a\n // secret is configured — hashing the empty string is a guaranteed\n // bad-signature. Surface a distinct configuration error instead of a\n // misleading 401 so the operator mounts the raw-body parser.\n if (body === \"\") {\n return { ok: false, status: 400, reason: \"empty-body\" };\n }\n const verification = verifyWebhook(\n headers,\n body,\n options.secret,\n options.verify\n );\n if (!verification.ok) {\n return { ok: false, status: 401, reason: verification.reason };\n }\n }\n\n const key = extractIdempotencyKey(headers);\n if (!key) return { ok: false, status: 400, reason: \"missing-key\" };\n\n const claimed = await options.store.claim(key);\n return { ok: true, key, deduped: !claimed };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * The two-phase finalizers a receiver adapter binds to a single\n * inbound delivery. The claim `checkWebhook` makes is *tentative*;\n * exactly one of these promotes or drops it once the business handler\n * resolves its outcome.\n */\nexport type Finalizers = {\n /**\n * Promote the tentative claim to a durable record so every later\n * retry of this key dedups. Call on handler success.\n */\n commit: () => void | Promise<void>;\n /**\n * Drop the tentative claim so the sender's retry re-processes.\n * Call on transient handler failure.\n */\n release: () => void | Promise<void>;\n};\n\n/**\n * The `idempotency` bag a receiver adapter hands its route for one\n * delivery: the claimed key, whether it was a duplicate, and the\n * {@link Finalizers}.\n */\nexport type Idempotency = { key: string; deduped: boolean } & Finalizers;\n\n/**\n * Build the {@link Idempotency} bag for one delivery that passed\n * `checkWebhook`.\n *\n * Guarantees:\n *\n * - **Deduped deliveries are inert.** When `deduped` is `true` the key\n * was already committed by an earlier delivery; both finalizers are\n * no-ops so a duplicate can never release someone else's committed\n * claim.\n * - **Finalize-once.** After the first `commit` or `release` fires,\n * further calls are no-ops — an adapter that both auto-finalizes and\n * lets the operator call `commit()`/`release()` can't double-fire.\n */\nexport function make_idempotency(\n store: IdempotencyStore,\n { key, deduped }: { key: string; deduped: boolean }\n): Idempotency {\n let settled = deduped;\n return {\n key,\n deduped,\n async commit() {\n if (settled) return;\n settled = true;\n await store.commit(key);\n },\n async release() {\n if (settled) return;\n settled = true;\n await store.release(key);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA+CA,oBAA0B;;;ACzBnB,SAAS,sBACd,SACoB;AACpB,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AACnD,QAAI,KAAK,YAAY,MAAM,kBAAmB;AAC9C,QAAI,MAAM,QAAQ,KAAK,EAAG,QAAO;AACjC,QAAI,UAAU,GAAI,QAAO;AACzB,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AChCA,yBAA4C;AAgErC,SAAS,cACd,SACA,MACA,QACA,SACc;AACd,QAAM,gBAAgB,SAAS,iBAAiB;AAChD,QAAM,MAAM,SAAS,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAExD,QAAM,YAAY,YAAY,SAAS,qBAAqB;AAC5D,MAAI,CAAC,UAAW,QAAO,EAAE,IAAI,OAAO,QAAQ,oBAAoB;AAEhE,QAAM,gBAAgB,YAAY,SAAS,qBAAqB;AAChE,MAAI,CAAC,cAAe,QAAO,EAAE,IAAI,OAAO,QAAQ,oBAAoB;AACpE,QAAM,YAAY,OAAO,SAAS,eAAe,EAAE;AACnD,MAAI,OAAO,MAAM,SAA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AAGZ,YAAM,YAAY,QAAQ;AAC1B,YAAM;AAAA,IACR;AAGA,QACE,OAAO,YAAY,YACnB,YAAY,QACZ,QAAQ,WACP,QAA4B,OAAO,OACpC;AACA,YAAM,YAAY,QAAQ;AAAA,IAC5B,OAAO;AACL,YAAM,YAAY,OAAO;AAAA,IAC3B;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  checkWebhook,
3
3
  make_idempotency
4
- } from "../../chunk-G5FNOSDX.js";
4
+ } from "../../chunk-ET2PACPO.js";
5
5
  import "../../chunk-PZ5AY32C.js";
6
6
 
7
7
  // src/receiver/trpc/index.ts
@@ -72,7 +72,7 @@ var StateCache = class {
72
72
  * @param maxSize - Max entries before the LRU drops its oldest.
73
73
  * @param onEvict - Called with the entry the LRU just dropped. Eviction is
74
74
  * the moment cached-only data is lost, so it is the only place a caller
75
- * can still see what went (#1648).
75
+ * can still see what went.
76
76
  */
77
77
  constructor(maxSize = 50, onEvict = () => {
78
78
  }) {
@@ -184,16 +184,9 @@ var BroadcastChannel = class {
184
184
  );
185
185
  }
186
186
  /**
187
- * The LRU dropped an entry. If it carried overlay-contributed keys, that
188
- * data existed only in the cache and is now gone: a later `publish()` has
189
- * no baseline to carry it from, and the reseed a reconnecting client gets
190
- * would silently lack presence a live client is still showing (#1648).
191
- *
192
- * `overlay()` was hardened for the same loss on its own path (#1423);
193
- * catching it here covers `publish()` too, and does it at the moment the
194
- * data is lost rather than at a later commit that may never come. Reading
195
- * the marker off the entry being evicted is what avoids the parallel
196
- * bookkeeping structure the `OVERLAY_KEYS` design explicitly rejected.
187
+ * The LRU dropped an entry. Overlay-contributed keys lived only in the
188
+ * cache, so their loss is reported now, when it happens, rather than at a
189
+ * later commit that may never come.
197
190
  */
198
191
  on_cache_evict(streamId, dropped) {
199
192
  if (!dropped[OVERLAY_KEYS]?.size) return;
@@ -201,20 +194,9 @@ var BroadcastChannel = class {
201
194
  }
202
195
  /**
203
196
  * Overlay-contributed state for `streamId` is gone. Recover first, report
204
- * second.
205
- *
206
- * The resync goes out before the host hook runs, and the hook is contained
207
- * the way `fan_out` contains subscribers: a bad consumer must not break the
208
- * publisher (#1423), and the same applies to a bad observer. Without this,
209
- * a throwing `onOverlayMiss` escapes on the eviction path — which runs
210
- * inside `publish()`, before that stream's own `fan_out` — so one host bug
211
- * costs the evicted stream its recovery frame *and* an unrelated stream the
212
- * frame for a version already written to the cache. The evicted stream's
213
- * clients never self-heal from that, which is the silent loss #1648 exists
214
- * to end.
215
- *
216
- * Routing the throw to `onSubscriberError` rather than swallowing it keeps
217
- * it wherever the host already reads framework delivery failures.
197
+ * second: the resync goes out before the host hook, and a throwing hook is
198
+ * routed to `onSubscriberError`. Eviction runs inside `publish()` for
199
+ * another stream, so an escaping throw would cost that stream its frame.
218
200
  */
219
201
  report_overlay_miss(streamId) {
220
202
  this.broadcast_resync(streamId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sse/index.ts","../../src/sse/apply-patch.ts","../../src/sse/broadcast.ts","../../src/sse/state-cache.ts","../../src/sse/types.ts","../../src/sse/presence.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/sse\n *\n * Incremental state broadcast over SSE for act event-sourced apps.\n *\n * Server-side broadcast with domain patch forwarding, an LRU state cache,\n * presence tracking, and a client-side patch applicator with version\n * validation and resync detection.\n *\n * ## Architecture\n *\n * ```\n * app.do() → snapshots (each carries its domain patch)\n * │\n * ▼\n * deriveState(snap) ← app-specific (overlay presence, deadlines, etc.)\n * state._v = snap.event.version\n * │\n * ▼\n * broadcast.publish(streamId, state, patches)\n * │\n * ├── version-key each patch: { [baseV+1]: patch1, [baseV+2]: patch2 }\n * └── push to all SSE subscribers\n * │\n * ▼\n * Client: applyPatchMessage(msg, cached)\n * │\n * ├── contiguous → deep-merge patches in version order\n * ├── stale → skip (client already ahead)\n * └── behind → resync (client missed versions)\n * ```\n *\n * ## Version Contract\n *\n * `_v` is always the event store stream version (`snap.event.version`).\n * No separate version counters. The event store is the single source of truth.\n */\n\nexport { patch } from \"@rotorsoft/act-patch\";\nexport type { ApplyResult } from \"./apply-patch.js\";\nexport { applyPatchMessage } from \"./apply-patch.js\";\nexport { BroadcastChannel } from \"./broadcast.js\";\nexport { PresenceTracker } from \"./presence.js\";\nexport { StateCache } from \"./state-cache.js\";\nexport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n","import { patch as deep_merge } from \"@rotorsoft/act-patch\";\nimport type { BroadcastState, PatchMessage } from \"./types.js\";\n\n/**\n * Result of applying a patch message to cached client state.\n */\nexport type ApplyResult<S extends BroadcastState = BroadcastState> =\n | { ok: true; state: S }\n | { ok: false; reason: \"stale\" | \"behind\" };\n\n/**\n * Apply a version-keyed patch message to the client's cached state.\n *\n * ## Version logic\n *\n * - All patches older than cached → \"stale\" (client already ahead)\n * - Gap between cached version and first patch → \"behind\" (client missed versions, must resync)\n * - Contiguous from cached version → apply in order\n * - No baseline (fresh client) → the genesis patch (version 0) folds onto init\n * state; a first patch at version ≥ 1 is \"behind\" (can't build from init)\n * - Overlay frame ({@link PatchMessage._overlay}) at the current version →\n * merged on top of cached state, `_v` unchanged (presence / computed\n * fields reach caught-up clients instead of being dropped as stale)\n *\n * ## Usage (React Query)\n *\n * ```typescript\n * onData: (msg) => {\n * const cached = utils.get_state.get_data({ streamId });\n * const result = applyPatchMessage(msg, cached);\n * if (result.ok) {\n * utils.get_state.setData({ streamId }, result.state);\n * } else if (result.reason === \"behind\") {\n * utils.get_state.invalidate({ streamId }); // trigger full refetch\n * }\n * // \"stale\" → no-op, client already has newer state\n * }\n * ```\n */\nexport function applyPatchMessage<S extends BroadcastState>(\n msg: PatchMessage<S>,\n cached: S | null | undefined\n): ApplyResult<S> {\n // Distinguish an *absent* baseline from a real version-0 baseline (#1346).\n // Act assigns the first event of any stream `version = 0`, so a fresh client\n // (no cache) must resume from a pre-baseline watermark of -1 — otherwise the\n // `?? 0` default collides with a genuine version-0 genesis patch and drops\n // it as \"stale\". A present baseline keeps its own `_v`.\n const hasBaseline = cached != null;\n const cachedV = cached?._v ?? -1;\n // `overlay` is a non-numeric marker key, not a version — exclude it.\n const versions = Object.keys(msg)\n .map(Number)\n .filter((v) => Number.isInteger(v))\n .sort((a, b) => a - b);\n\n // Server-forced resync: it could not construct a patch (e.g. `overlay()`\n // found the baseline evicted), so the client must refetch. Checked before\n // anything else — a resync frame carries no versions, and the empty-frame\n // branch below would otherwise report it as `stale`, which is the one\n // answer that does NOT refetch (#1423).\n if (msg._resync) return { ok: false, reason: \"behind\" };\n\n // An empty frame carries nothing to apply. For a client that already has a\n // baseline that is genuinely `stale` — a no-op, don't refetch. For one with\n // NO baseline there is nothing to be stale relative to, and `stale` is the\n // one answer that does not refetch, so it would strand the client (#1474).\n // Both the doc-comment below and `real-time.md` already say a fresh client\n // is never stale; this is the branch that made that false.\n if (!versions.length)\n return { ok: false, reason: hasBaseline ? \"stale\" : \"behind\" };\n\n const minV = versions[0];\n const maxV = versions[versions.length - 1];\n\n // Overlay frame: a version-neutral update (presence, computed field) at the\n // current version. Handled EXHAUSTIVELY here — an overlay must never reach\n // the contiguous fold below, which would apply its payload as if it were\n // that version's domain patch. At exactly `cachedV + 1` that fold made the\n // client adopt presence data as version N, stamp itself caught up, and\n // never refetch — the real update for N lost permanently (#1419).\n if (msg._overlay) {\n // No baseline to merge onto: the client must fetch one.\n if (!cached) return { ok: false, reason: \"behind\" };\n // Caught up: merge on top, keeping _v (an overlay changes no version).\n if (maxV === cachedV)\n return {\n ok: true,\n state: { ...deep_merge(cached, msg[maxV]), _v: cachedV },\n };\n // Ahead by any amount: the client missed at least one domain patch.\n if (maxV > cachedV) return { ok: false, reason: \"behind\" };\n // Older than the baseline: genuinely stale.\n return { ok: false, reason: \"stale\" };\n }\n\n // A present baseline that already covers these versions is stale. A fresh\n // client (no baseline, cachedV = -1) can never be stale — its first\n // contiguous update is the genesis version 0.\n if (hasBaseline && maxV <= cachedV) return { ok: false, reason: \"stale\" };\n // A gap between the baseline (or the init floor -1) and the first patch means\n // missed versions — resync. For a fresh client this admits the genesis patch\n // (minV 0 === -1 + 1) but rejects a first patch at version >= 1, which cannot\n // be built from init state alone.\n if (minV > cachedV + 1) return { ok: false, reason: \"behind\" };\n\n // No baseline → fold the genesis patch(es) onto init state ({}).\n let state = (cached ?? {}) as S;\n for (const v of versions) {\n if (v <= cachedV) continue;\n state = { ...deep_merge(state, msg[v]), _v: v } as S;\n }\n return { ok: true, state };\n}\n","import { patch as apply_patch } from \"@rotorsoft/act-patch\";\nimport { StateCache } from \"./state-cache.js\";\nimport {\n type BroadcastState,\n type PatchMessage,\n resync_frame,\n type Subscriber,\n} from \"./types.js\";\n\n/**\n * Deliver a frame to every subscriber, containing each one individually.\n *\n * SSE subscribers are the least-trusted callbacks in the system — one per\n * connection, driven by network state. The unguarded loop this replaces let\n * the first thrower abort iteration, so every later subscriber lost the\n * frame and the exception escaped into the host's commit path (#1423). Same\n * containment principle the orchestrator applies to lifecycle listeners.\n * Guarding each callback rather than the loop is the point: one guard around\n * the whole loop would still let the first throw suppress the rest.\n *\n * @internal\n */\nfunction fan_out<S extends BroadcastState>(\n subs: Set<Subscriber<S>> | undefined,\n msg: PatchMessage<S>,\n on_error: (error: unknown) => void\n): void {\n if (!subs?.size) return;\n for (const cb of subs) {\n try {\n cb(msg);\n } catch (error) {\n on_error(error);\n }\n }\n}\n\n/**\n * Rewrite `undefined`-valued keys to `null`, recursively.\n *\n * `@rotorsoft/act-patch` treats `undefined` and `null` as the same delete\n * signal, but `JSON.stringify` drops `undefined`-valued keys entirely — and\n * every SSE transport serializes frames as JSON. A reducer that clears a\n * field the idiomatic way (`{ left: undefined }`) therefore produced a frame\n * with no mention of `left` at all, so a live client kept the stale value\n * while stamping the new version — believing itself caught up, and never\n * refetching (#1471).\n *\n * `null` reaches the same `delete` branch in the patch applicator and\n * survives JSON, so normalizing here makes the two spellings equivalent on\n * the wire as they already are in memory.\n *\n * One walker serves both destinations. The frame and the cached state\n * agree on every encoding except the delete: see `wire_safe` /\n * `cache_safe` below.\n */\nconst normalize = <T>(value: T, nulls: boolean): T => {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value.map((v) => normalize(v, nulls)) as T;\n // A Set has exactly one sensible JSON encoding, and `JSON.stringify` gives\n // it the wrong one: `{}`. The framework's own `PresenceTracker.online()`\n // returns a Set and the presence recipe feeds it straight to `overlay()`,\n // so the documented way to broadcast presence shipped an empty object to\n // every client — and then froze, because a client holding `{}` treats\n // every later empty patch as a no-op (#1472).\n if (value instanceof Set)\n return [...value].map((v) => normalize(v, nulls)) as T;\n // Everything else non-plain (Date, Map, class instances) is left to\n // whatever the host's serializer already does with it. `Date` has a\n // defined encoding; `Map` does not have an unambiguous one (entries or\n // object?), so guessing would trade a visible bug for a silent choice.\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return value;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>))\n out[k] = v === undefined && nulls ? null : normalize(v, nulls);\n return out as T;\n};\n\n/**\n * Frame-bound normalization: Sets become arrays, and `undefined` becomes\n * `null` so a delete survives `JSON.stringify` (#1471).\n */\nconst wire_safe = <T>(patch: T): T => normalize(patch, true);\n\n/**\n * Cache-bound normalization: Sets become arrays, `undefined` is left alone.\n *\n * The cached state is what a reconnecting client reseeds from, and #1471\n * settled that it must keep a cleared key *absent* rather than `null`, so\n * the wire's delete encoding is exactly the part the cache must not adopt.\n * That single difference is why `nulls` is a parameter instead of two\n * separate walkers — a second copy would drift the moment either side grew\n * a case.\n *\n * Non-enumerable properties are invisible to `Object.entries`, so the\n * `OVERLAY_KEYS` marker is neither copied nor clobbered here; callers tag\n * after normalizing.\n */\nconst cache_safe = <T>(state: T): T => normalize(state, false);\n\n/**\n * Keys an `overlay()` contributed to a stream's cached state, carried on the\n * cached object itself.\n *\n * `publish()` replaces the cache entry with host-derived state, so overlay\n * data — presence, computed fields — vanished from the cache while live\n * clients, which had already applied the overlay frame, kept it. A\n * reconnecting client then reseeded WITHOUT it and had no way to notice: its\n * `_v` matches the server's, so nothing classifies as `behind` (#1473).\n *\n * A symbol keeps this out of `Object.keys`, `JSON.stringify` and therefore\n * off the wire; living on the cached object means it is evicted with the\n * entry rather than needing a parallel structure to prune.\n */\nconst OVERLAY_KEYS = Symbol(\"act.sse.overlay_keys\");\n\ntype WithOverlayKeys = { [OVERLAY_KEYS]?: ReadonlySet<string> };\n\n/**\n * Default `onSubscriberError`. This module shares the `sse` subpath with\n * `applyPatchMessage`, which browser code imports, so it never imports the\n * framework: a bundler would follow that into a browser build. Pass\n * `onSubscriberError` to send these to your logger.\n */\nconst default_subscriber_error = (error: unknown, streamId: string): void => {\n // biome-ignore lint/suspicious/noConsole: the default can't reach the framework logger (see above)\n console.error(`sse subscriber threw for \"${streamId}\"`, error);\n};\n\n/** Record which keys an overlay owns, accumulating across overlays. */\nconst tag_overlay_keys = <S extends object>(\n state: S,\n prev: S | undefined,\n keys: readonly string[]\n): S => {\n const carried = (prev as WithOverlayKeys | undefined)?.[OVERLAY_KEYS];\n Object.defineProperty(state, OVERLAY_KEYS, {\n value: new Set([...(carried ?? []), ...keys]),\n enumerable: false,\n configurable: true,\n });\n return state;\n};\n\n/**\n * Server-side broadcast channel for incremental state sync over SSE.\n *\n * Manages per-stream subscriber sets and an LRU state cache. When state\n * changes, forwards domain patches (from event handlers) to all subscribers\n * as version-keyed messages.\n *\n * ## Usage\n *\n * ```typescript\n * const broadcast = new BroadcastChannel<MyState>();\n *\n * // After every app.do():\n * const snaps = await app.do(...);\n * const patches = snaps.map(s => s.patch).filter(Boolean);\n * const state = deriveState(snaps.at(-1));\n * broadcast.publish(streamId, state, patches);\n *\n * // In SSE subscription:\n * const cleanup = broadcast.subscribe(streamId, (msg) => {\n * pending = msg;\n * resolve?.();\n * });\n *\n * // Initial state for reconnects:\n * const cached = broadcast.state(streamId);\n * ```\n *\n * ## Version Contract\n *\n * The `_v` field on state MUST be set from `snap.event.version` (the event\n * store's monotonic stream version) BEFORE calling `publish()`. This is the\n * single source of truth for ordering — no separate version counters.\n */\nexport class BroadcastChannel<S extends BroadcastState = BroadcastState> {\n private channels = new Map<string, Set<Subscriber<S>>>();\n private state_cache: StateCache<S>;\n private on_subscriber_error: (error: unknown, streamId: string) => void;\n private on_overlay_miss: (streamId: string) => void;\n\n constructor(options?: {\n /** Max number of stream states kept in the LRU cache (default 50). */\n cacheSize?: number;\n /**\n * Called when overlay-contributed state is lost, on either of the two\n * paths that can lose it: `overlay()` finding no cached baseline, and\n * the LRU evicting an entry that carried overlay keys — the latter from\n * inside `publish()`, for a stream other than the one being published.\n *\n * Live subscribers of the affected stream are sent a resync frame, so\n * they refetch rather than keep showing state the server has forgotten.\n * The hook is observability on top of that recovery: a steady stream of\n * calls means `cacheSize` is too small for the working set.\n *\n * A throw is caught and routed to `onSubscriberError` — the resync has\n * already gone out, and a host bug must not cost the publishing stream\n * its own frame. Defaults to a no-op.\n */\n onOverlayMiss?: (streamId: string) => void;\n /**\n * Called when a subscriber callback throws. The frame is still delivered\n * to every other subscriber and the publish still returns normally — a\n * bad consumer must not break the publisher. Defaults to `console.error`;\n * pass your logger here to route it with the rest of your logs.\n */\n onSubscriberError?: (error: unknown, streamId: string) => void;\n /**\n * Deprecated alias of `cacheSize` — removal in the next major. When\n * both are given, `cacheSize` wins.\n * @deprecated use `cacheSize`\n */\n cache_size?: number;\n }) {\n this.state_cache = new StateCache<S>(\n options?.cacheSize ?? options?.cache_size ?? 50,\n (streamId, dropped) => this.on_cache_evict(streamId, dropped)\n );\n this.on_overlay_miss = options?.onOverlayMiss ?? (() => {});\n this.on_subscriber_error =\n options?.onSubscriberError ?? default_subscriber_error;\n }\n\n /**\n * Fan a resync out to a stream's live subscribers. `applyPatchMessage`\n * always reports `behind` for it, so they refetch.\n */\n private broadcast_resync(streamId: string): void {\n fan_out(this.channels.get(streamId), resync_frame<S>(), (error) =>\n this.on_subscriber_error(error, streamId)\n );\n }\n\n /**\n * The LRU dropped an entry. If it carried overlay-contributed keys, that\n * data existed only in the cache and is now gone: a later `publish()` has\n * no baseline to carry it from, and the reseed a reconnecting client gets\n * would silently lack presence a live client is still showing (#1648).\n *\n * `overlay()` was hardened for the same loss on its own path (#1423);\n * catching it here covers `publish()` too, and does it at the moment the\n * data is lost rather than at a later commit that may never come. Reading\n * the marker off the entry being evicted is what avoids the parallel\n * bookkeeping structure the `OVERLAY_KEYS` design explicitly rejected.\n */\n private on_cache_evict(streamId: string, dropped: S): void {\n if (!(dropped as S & WithOverlayKeys)[OVERLAY_KEYS]?.size) return;\n this.report_overlay_miss(streamId);\n }\n\n /**\n * Overlay-contributed state for `streamId` is gone. Recover first, report\n * second.\n *\n * The resync goes out before the host hook runs, and the hook is contained\n * the way `fan_out` contains subscribers: a bad consumer must not break the\n * publisher (#1423), and the same applies to a bad observer. Without this,\n * a throwing `onOverlayMiss` escapes on the eviction path — which runs\n * inside `publish()`, before that stream's own `fan_out` — so one host bug\n * costs the evicted stream its recovery frame *and* an unrelated stream the\n * frame for a version already written to the cache. The evicted stream's\n * clients never self-heal from that, which is the silent loss #1648 exists\n * to end.\n *\n * Routing the throw to `onSubscriberError` rather than swallowing it keeps\n * it wherever the host already reads framework delivery failures.\n */\n private report_overlay_miss(streamId: string): void {\n this.broadcast_resync(streamId);\n try {\n this.on_overlay_miss(streamId);\n } catch (error) {\n this.on_subscriber_error(error, streamId);\n }\n }\n\n /**\n * Publish domain patches from a commit.\n * patches[i] corresponds to version baseV + i + 1.\n *\n * @param streamId - The event store stream ID\n * @param state - Full state with `_v` set from `snap.event.version`\n * @param patches - Array of domain patches, one per emitted event\n */\n publish(\n streamId: string,\n state: S,\n patches: Partial<S>[] = []\n ): PatchMessage<S> {\n // Carry overlay-contributed keys across the commit (#1473). Only keys\n // an `overlay()` actually owns, and only when the new domain state does\n // not speak to them — so a publisher that drops or overwrites a key\n // still wins, and presence survives a commit as the docs imply.\n // Normalize once, up front: the cache entry and the frame are both\n // derived from this, so the reseed a reconnecting client gets cannot\n // disagree with what a live client applied (#1646). `overlay()` already\n // normalized before its own cache write; `publish()` did not, so a Set\n // shipped as an array live and as `{}` on reseed — and then froze.\n const safe_state = cache_safe(state);\n const prev = this.state_cache.get(streamId) as\n | (S & WithOverlayKeys)\n | undefined;\n const overlay_keys = prev?.[OVERLAY_KEYS];\n let cached = safe_state;\n if (overlay_keys?.size && prev) {\n const carried = { ...safe_state } as S;\n const kept: string[] = [];\n for (const key of overlay_keys)\n if (!(key in safe_state) && key in prev) {\n (carried as Record<string, unknown>)[key] = (\n prev as Record<string, unknown>\n )[key];\n kept.push(key);\n }\n cached = tag_overlay_keys(carried, undefined, kept);\n }\n this.state_cache.set(streamId, cached);\n\n const baseV = state._v - patches.length;\n const msg: PatchMessage<S> = {};\n patches.forEach((p, i) => {\n msg[baseV + i + 1] = wire_safe(p);\n });\n\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Publish a state update that doesn't change the event version\n * (e.g. presence overlay, computed field refresh).\n * Uses the same version as the cached state, single entry.\n */\n overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n const prev = this.state_cache.get(streamId);\n if (!prev) {\n // No baseline to read-modify-write, so nothing is broadcast — and\n // because no frame is emitted there is nothing for a live client to\n // classify as `behind`, so it never refetches either. Unlike a domain\n // commit (which repopulates the cache via `publish`), an overlay-only\n // stream never recovers. The defaults make this reachable rather than\n // exotic: `cacheSize` is 50 while a host may hold far more live\n // subscriptions, and cache promotion happens at connect time, so a\n // busy-but-not-committing stream ages out while fully subscribed.\n //\n // Emit a resync frame so live subscribers refetch instead of silently\n // missing the update forever (#1423). The host hook still fires so a\n // host can count these — a steady stream of them means `cacheSize` is\n // too small for the working set.\n this.report_overlay_miss(streamId);\n // Still `undefined`: no overlay state was produced, and callers use the\n // return value as \"the patch I broadcast\", which a resync is not.\n return undefined;\n }\n\n // Normalize BEFORE applying to the cache, so a reconnecting client's\n // reseed and a live client's frame agree (#1472). `apply_patch` treats\n // `null` and `undefined` as the same delete signal, so normalizing first\n // does not change the delete semantics — it only fixes the encodings\n // that would not survive JSON.\n const safe_patch = wire_safe(overlay_patch);\n const state = apply_patch(prev, safe_patch) as S;\n this.state_cache.set(\n streamId,\n tag_overlay_keys(state, prev, Object.keys(safe_patch as object))\n );\n\n // `_overlay: true` marks this as a version-neutral update so a caught-up\n // client applies it at the current version instead of dropping it as\n // stale (the key equals the client's cachedV). Ordinary patches omit it.\n const msg: PatchMessage<S> = {\n [state._v]: safe_patch,\n _overlay: true,\n };\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Subscribe to broadcast messages for a stream.\n * Returns a cleanup function that removes the subscription.\n */\n subscribe(streamId: string, cb: Subscriber<S>): () => void {\n if (!this.channels.has(streamId)) this.channels.set(streamId, new Set());\n this.channels.get(streamId)!.add(cb);\n return () => {\n this.channels.get(streamId)?.delete(cb);\n if (this.channels.get(streamId)?.size === 0) {\n this.channels.delete(streamId);\n }\n };\n }\n\n /** Get the number of subscribers for a stream. */\n subscriberCount(streamId: string): number {\n return this.channels.get(streamId)?.size ?? 0;\n }\n\n /** Get the cached state for a stream (for reconnects / initial SSE yield). */\n state(streamId: string): S | undefined {\n return this.state_cache.get(streamId);\n }\n\n /** @deprecated use `overlay` — removal in the next major */\n publish_overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n return this.overlay(streamId, overlay_patch);\n }\n\n /** @deprecated use `subscriberCount` — removal in the next major */\n get_subscriber_count(streamId: string): number {\n return this.subscriberCount(streamId);\n }\n\n /** @deprecated use `state` — removal in the next major */\n get_state(streamId: string): S | undefined {\n return this.state(streamId);\n }\n\n /** Direct access to the state cache (for app-specific reads like presence). */\n get cache(): StateCache<S> {\n return this.state_cache;\n }\n}\n","import type { BroadcastState } from \"./types.js\";\n\n/**\n * Generic LRU cache for aggregate state objects.\n *\n * Keyed by stream ID. Each entry stores the full state (with `_v` from the\n * event store). Used as the \"previous state\" baseline for computing patches,\n * and as the fast path for reconnects.\n *\n * The cache is shared between the broadcast hot path and read queries.\n * Projections should maintain their own cache to avoid double-apply bugs.\n */\nexport class StateCache<S extends BroadcastState = BroadcastState> {\n private cache = new Map<string, S>();\n private maxSize: number;\n private on_evict: (key: string, state: S) => void;\n\n /**\n * @param maxSize - Max entries before the LRU drops its oldest.\n * @param onEvict - Called with the entry the LRU just dropped. Eviction is\n * the moment cached-only data is lost, so it is the only place a caller\n * can still see what went (#1648).\n */\n constructor(\n maxSize = 50,\n onEvict: (key: string, state: S) => void = () => {}\n ) {\n this.maxSize = maxSize;\n this.on_evict = onEvict;\n }\n\n /** Get a cached state, promoting it to MRU position. */\n get(key: string): S | undefined {\n const s = this.cache.get(key);\n if (s) {\n this.cache.delete(key);\n this.cache.set(key, s);\n }\n return s;\n }\n\n /** Set a cached state, evicting the LRU entry if at capacity. */\n set(key: string, state: S): void {\n this.cache.delete(key);\n this.cache.set(key, state);\n if (this.cache.size > this.maxSize) {\n const oldest = this.cache.keys().next().value!;\n const dropped = this.cache.get(oldest)!;\n this.cache.delete(oldest);\n this.on_evict(oldest, dropped);\n }\n }\n\n /** Remove a cached entry. */\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n /** Check if a key exists in the cache. */\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n /** Current number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Direct access to the underlying map (for iteration). */\n entries(): IterableIterator<[string, S]> {\n return this.cache.entries();\n }\n}\n","import type { DeepPartial } from \"@rotorsoft/act-patch\";\n\n/**\n * Base constraint for state objects managed by the broadcast system.\n * Apps extend this with their own domain state shape.\n */\nexport type BroadcastState = Record<string, unknown> & {\n /** Event store stream version — set by the broadcast layer from snap.event.version */\n _v: number;\n};\n\n/**\n * SSE message: version-keyed domain patches.\n * Keys are stringified version numbers, values are domain patches (deep partials).\n * Multi-event commits produce multiple version-keyed entries.\n *\n * The optional `_overlay` marker flags a version-neutral update (presence,\n * computed-field refresh) emitted by {@link BroadcastChannel.overlay} — a\n * single entry keyed at the *current* version. It tells `applyPatchMessage`\n * to merge the entry on top of the client's caught-up state instead of\n * rejecting it as stale (a same-version patch WITHOUT the marker stays\n * stale). Ordinary version-bumping patches from `publish()` omit it.\n *\n * `_resync` carries no versions at all. The server emits it when it cannot\n * construct a patch — today, when `overlay()` finds the stream's baseline\n * evicted from the LRU. A client that receives one always reports `behind`\n * and refetches. Without it the server had nothing to say in that case, so\n * live subscribers silently stopped receiving presence updates and had no\n * way to notice (#1423).\n */\nexport type PatchMessage<S extends BroadcastState = BroadcastState> = Record<\n number,\n DeepPartial<S>\n> & { readonly _overlay?: true; readonly _resync?: true };\n\n/**\n * Subscriber callback — receives version-keyed patch messages.\n */\nexport type Subscriber<S extends BroadcastState = BroadcastState> = (\n msg: PatchMessage<S>\n) => void;\n\n/**\n * The frame that tells a client to refetch: no versions, so\n * `applyPatchMessage` always reports `behind`.\n *\n * Every producer of a resync uses this — `overlay()` on a missing baseline,\n * the cache on evicting overlay state, and the SSE backlog when it cannot\n * drop a frame without losing it silently. One factory so the shape cannot\n * drift between them.\n */\nexport const resync_frame = <S extends BroadcastState>(): PatchMessage<S> =>\n ({ _resync: true }) as PatchMessage<S>;\n\n/**\n * Whether a frame carries no versions, so `applyPatchMessage` can never\n * classify it as a gap.\n *\n * A version-keyed patch that goes missing is self-announcing: the next frame\n * skips a version and the client refetches. An `_overlay` or `_resync` frame\n * is not, which is why anything that drops frames has to tell them apart.\n */\nexport const is_version_neutral = <S extends BroadcastState>(\n msg: PatchMessage<S>\n): boolean => msg._overlay === true || msg._resync === true;\n","/**\n * Generic presence tracker — ref-counted online status per stream per identity.\n *\n * Supports multi-tab: each subscribe increments the ref count, each\n * unsubscribe decrements it. An identity is considered online when\n * ref count > 0.\n *\n * ## Usage\n *\n * ```typescript\n * const presence = new PresenceTracker();\n *\n * // On SSE connect:\n * presence.add(game_id, player_id);\n *\n * // On SSE disconnect:\n * presence.remove(game_id, player_id);\n *\n * // Query:\n * presence.online(game_id); // Set<string>\n * ```\n */\nexport class PresenceTracker {\n private streams = new Map<string, Map<string, number>>();\n\n /** Increment ref count for an identity on a stream. */\n add(streamId: string, identity_id: string): void {\n if (!this.streams.has(streamId)) this.streams.set(streamId, new Map());\n const counts = this.streams.get(streamId)!;\n counts.set(identity_id, (counts.get(identity_id) ?? 0) + 1);\n }\n\n /** Decrement ref count. Removes the identity when count reaches 0. */\n remove(streamId: string, identity_id: string): void {\n const counts = this.streams.get(streamId);\n if (!counts) return;\n const n = (counts.get(identity_id) ?? 1) - 1;\n if (n <= 0) counts.delete(identity_id);\n else counts.set(identity_id, n);\n if (counts.size === 0) this.streams.delete(streamId);\n }\n\n /** Get the set of online identity IDs for a stream. */\n online(streamId: string): Set<string> {\n const counts = this.streams.get(streamId);\n return counts ? new Set(counts.keys()) : new Set();\n }\n\n /** Check if a specific identity is online for a stream. */\n isOnline(streamId: string, identity_id: string): boolean {\n return (this.streams.get(streamId)?.get(identity_id) ?? 0) > 0;\n }\n\n /** @deprecated use `online` — removal in the next major */\n get_online(streamId: string): Set<string> {\n return this.online(streamId);\n }\n\n /** @deprecated use `isOnline` — removal in the next major */\n is_online(streamId: string, identity_id: string): boolean {\n return this.isOnline(streamId, identity_id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuCA,IAAAA,oBAAsB;;;ACvCtB,uBAAoC;AAuC7B,SAAS,kBACd,KACA,QACgB;AAMhB,QAAM,cAAc,UAAU;AAC9B,QAAM,UAAU,QAAQ,MAAM;AAE9B,QAAM,WAAW,OAAO,KAAK,GAAG,EAC7B,IAAI,MAAM,EACV,OAAO,CAAC,MAAM,OAAO,UAAU,CAAC,CAAC,EACjC,KAAK,CAAC,GAAG,MAAM,IAAI,CAA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K,QAAQ,IAAI,QAAQ,GAAG,IAAI,WAAW,KAAK,KAAK;AAAA,EAC/D;AAAA;AAAA,EAGA,WAAW,UAA+B;AACxC,WAAO,KAAK,OAAO,QAAQ;AAAA,EAC7B;AAAA;AAAA,EAGA,UAAU,UAAkB,aAA8B;AACxD,WAAO,KAAK,SAAS,UAAU,WAAW;AAAA,EAC5C;AACF;","names":["import_act_patch","deep_merge","import_act_patch","patch","apply_patch"]}
1
+ {"version":3,"sources":["../../src/sse/index.ts","../../src/sse/apply-patch.ts","../../src/sse/broadcast.ts","../../src/sse/state-cache.ts","../../src/sse/types.ts","../../src/sse/presence.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/sse\n *\n * Incremental state broadcast over SSE for act event-sourced apps.\n *\n * Server-side broadcast with domain patch forwarding, an LRU state cache,\n * presence tracking, and a client-side patch applicator with version\n * validation and resync detection.\n *\n * ## Architecture\n *\n * ```\n * app.do() → snapshots (each carries its domain patch)\n * │\n * ▼\n * deriveState(snap) ← app-specific (overlay presence, deadlines, etc.)\n * state._v = snap.event.version\n * │\n * ▼\n * broadcast.publish(streamId, state, patches)\n * │\n * ├── version-key each patch: { [baseV+1]: patch1, [baseV+2]: patch2 }\n * └── push to all SSE subscribers\n * │\n * ▼\n * Client: applyPatchMessage(msg, cached)\n * │\n * ├── contiguous → deep-merge patches in version order\n * ├── stale → skip (client already ahead)\n * └── behind → resync (client missed versions)\n * ```\n *\n * ## Version Contract\n *\n * `_v` is always the event store stream version (`snap.event.version`).\n * No separate version counters. The event store is the single source of truth.\n */\n\nexport { patch } from \"@rotorsoft/act-patch\";\nexport type { ApplyResult } from \"./apply-patch.js\";\nexport { applyPatchMessage } from \"./apply-patch.js\";\nexport { BroadcastChannel } from \"./broadcast.js\";\nexport { PresenceTracker } from \"./presence.js\";\nexport { StateCache } from \"./state-cache.js\";\nexport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n","import { patch as deep_merge } from \"@rotorsoft/act-patch\";\nimport type { BroadcastState, PatchMessage } from \"./types.js\";\n\n/**\n * Result of applying a patch message to cached client state.\n */\nexport type ApplyResult<S extends BroadcastState = BroadcastState> =\n | { ok: true; state: S }\n | { ok: false; reason: \"stale\" | \"behind\" };\n\n/**\n * Apply a version-keyed patch message to the client's cached state.\n *\n * ## Version logic\n *\n * - All patches older than cached → \"stale\" (client already ahead)\n * - Gap between cached version and first patch → \"behind\" (client missed versions, must resync)\n * - Contiguous from cached version → apply in order\n * - No baseline (fresh client) → the genesis patch (version 0) folds onto init\n * state; a first patch at version ≥ 1 is \"behind\" (can't build from init)\n * - Overlay frame ({@link PatchMessage._overlay}) at the current version →\n * merged on top of cached state, `_v` unchanged (presence / computed\n * fields reach caught-up clients instead of being dropped as stale)\n *\n * ## Usage (React Query)\n *\n * ```typescript\n * onData: (msg) => {\n * const cached = utils.get_state.get_data({ streamId });\n * const result = applyPatchMessage(msg, cached);\n * if (result.ok) {\n * utils.get_state.setData({ streamId }, result.state);\n * } else if (result.reason === \"behind\") {\n * utils.get_state.invalidate({ streamId }); // trigger full refetch\n * }\n * // \"stale\" → no-op, client already has newer state\n * }\n * ```\n */\nexport function applyPatchMessage<S extends BroadcastState>(\n msg: PatchMessage<S>,\n cached: S | null | undefined\n): ApplyResult<S> {\n // A stream's first event is version 0, so a client with no baseline\n // resumes from -1; defaulting to 0 would drop that first patch as stale.\n const hasBaseline = cached != null;\n const cachedV = cached?._v ?? -1;\n // `overlay` is a non-numeric marker key, not a version — exclude it.\n const versions = Object.keys(msg)\n .map(Number)\n .filter((v) => Number.isInteger(v))\n .sort((a, b) => a - b);\n\n // Server-forced resync: it could not construct a patch (e.g. `overlay()`\n // found the baseline evicted), so the client must refetch. Checked before\n // anything else: a resync frame carries no versions, and the empty-frame\n // branch below would report it as `stale`, the one answer that doesn't\n // refetch.\n if (msg._resync) return { ok: false, reason: \"behind\" };\n\n // An empty frame carries nothing to apply: `stale` for a client with a\n // baseline, `behind` for one without, which must fetch one.\n if (!versions.length)\n return { ok: false, reason: hasBaseline ? \"stale\" : \"behind\" };\n\n const minV = versions[0];\n const maxV = versions[versions.length - 1];\n\n // Overlay frame: a version-neutral update (presence, computed field) at the\n // current version. Handled entirely here: the contiguous fold below would\n // apply its payload as that version's domain patch, and a client at\n // `cachedV + 1` would stamp itself caught up and never get the real one.\n if (msg._overlay) {\n // No baseline to merge onto: the client must fetch one.\n if (!cached) return { ok: false, reason: \"behind\" };\n // Caught up: merge on top, keeping _v (an overlay changes no version).\n if (maxV === cachedV)\n return {\n ok: true,\n state: { ...deep_merge(cached, msg[maxV]), _v: cachedV },\n };\n // Ahead by any amount: the client missed at least one domain patch.\n if (maxV > cachedV) return { ok: false, reason: \"behind\" };\n // Older than the baseline: genuinely stale.\n return { ok: false, reason: \"stale\" };\n }\n\n // A present baseline that already covers these versions is stale. A fresh\n // client (no baseline, cachedV = -1) can never be stale — its first\n // contiguous update is the genesis version 0.\n if (hasBaseline && maxV <= cachedV) return { ok: false, reason: \"stale\" };\n // A gap between the baseline (or the init floor -1) and the first patch means\n // missed versions — resync. For a fresh client this admits the genesis patch\n // (minV 0 === -1 + 1) but rejects a first patch at version >= 1, which cannot\n // be built from init state alone.\n if (minV > cachedV + 1) return { ok: false, reason: \"behind\" };\n\n // No baseline → fold the genesis patch(es) onto init state ({}).\n let state = (cached ?? {}) as S;\n for (const v of versions) {\n if (v <= cachedV) continue;\n state = { ...deep_merge(state, msg[v]), _v: v } as S;\n }\n return { ok: true, state };\n}\n","import { patch as apply_patch } from \"@rotorsoft/act-patch\";\nimport { StateCache } from \"./state-cache.js\";\nimport {\n type BroadcastState,\n type PatchMessage,\n resync_frame,\n type Subscriber,\n} from \"./types.js\";\n\n/**\n * Deliver a frame to every subscriber, containing each one: a subscriber\n * that throws must not cost the others the frame or escape into the\n * publisher. One guard around the loop would let the first throw stop it.\n *\n * @internal\n */\nfunction fan_out<S extends BroadcastState>(\n subs: Set<Subscriber<S>> | undefined,\n msg: PatchMessage<S>,\n on_error: (error: unknown) => void\n): void {\n if (!subs?.size) return;\n for (const cb of subs) {\n try {\n cb(msg);\n } catch (error) {\n on_error(error);\n }\n }\n}\n\n/**\n * Rewrite values that don't survive JSON, recursively: Sets become arrays,\n * and with `nulls`, `undefined` becomes `null`.\n *\n * `@rotorsoft/act-patch` deletes a key on either `undefined` or `null`, but\n * `JSON.stringify` drops `undefined` keys, so a cleared field would vanish\n * from the frame and a live client would keep the stale value. One walker\n * serves the frame and the cache, which differ only in that delete encoding\n * (see `wire_safe` / `cache_safe`).\n */\nconst normalize = <T>(value: T, nulls: boolean): T => {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value.map((v) => normalize(v, nulls)) as T;\n // `JSON.stringify` encodes a Set as `{}`; presence (`PresenceTracker.online()`)\n // is a Set, so it would reach clients empty.\n if (value instanceof Set)\n return [...value].map((v) => normalize(v, nulls)) as T;\n // Other non-plain values (Date, Map, class instances) are left to the\n // host's serializer: a Map has no single obvious JSON encoding to guess.\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return value;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>))\n out[k] = v === undefined && nulls ? null : normalize(v, nulls);\n return out as T;\n};\n\n/**\n * Frame-bound normalization: Sets become arrays, and `undefined` becomes\n * `null` so a delete survives `JSON.stringify`.\n */\nconst wire_safe = <T>(patch: T): T => normalize(patch, true);\n\n/**\n * Cache-bound normalization: Sets become arrays, `undefined` is left alone,\n * because a reconnecting client reseeds from the cache and a cleared key\n * must stay absent there, not `null`.\n *\n * `Object.entries` skips the non-enumerable `OVERLAY_KEYS` marker, so\n * callers tag after normalizing.\n */\nconst cache_safe = <T>(state: T): T => normalize(state, false);\n\n/**\n * Keys an `overlay()` contributed to a stream's cached state, carried on the\n * cached object itself, so `publish()` can keep them when it replaces the\n * entry: a reconnecting client reseeds at the same `_v` and couldn't tell\n * the overlay data was missing.\n *\n * A symbol keeps it off the wire, and living on the entry means it is\n * evicted with it.\n */\nconst OVERLAY_KEYS = Symbol(\"act.sse.overlay_keys\");\n\ntype WithOverlayKeys = { [OVERLAY_KEYS]?: ReadonlySet<string> };\n\n/**\n * Default `onSubscriberError`. This module shares the `sse` subpath with\n * `applyPatchMessage`, which browser code imports, so it never imports the\n * framework: a bundler would follow that into a browser build. Pass\n * `onSubscriberError` to send these to your logger.\n */\nconst default_subscriber_error = (error: unknown, streamId: string): void => {\n // biome-ignore lint/suspicious/noConsole: the default can't reach the framework logger (see above)\n console.error(`sse subscriber threw for \"${streamId}\"`, error);\n};\n\n/** Record which keys an overlay owns, accumulating across overlays. */\nconst tag_overlay_keys = <S extends object>(\n state: S,\n prev: S | undefined,\n keys: readonly string[]\n): S => {\n const carried = (prev as WithOverlayKeys | undefined)?.[OVERLAY_KEYS];\n Object.defineProperty(state, OVERLAY_KEYS, {\n value: new Set([...(carried ?? []), ...keys]),\n enumerable: false,\n configurable: true,\n });\n return state;\n};\n\n/**\n * Server-side broadcast channel for incremental state sync over SSE.\n *\n * Manages per-stream subscriber sets and an LRU state cache. When state\n * changes, forwards domain patches (from event handlers) to all subscribers\n * as version-keyed messages.\n *\n * ## Usage\n *\n * ```typescript\n * const broadcast = new BroadcastChannel<MyState>();\n *\n * // After every app.do():\n * const snaps = await app.do(...);\n * const patches = snaps.map(s => s.patch).filter(Boolean);\n * const state = deriveState(snaps.at(-1));\n * broadcast.publish(streamId, state, patches);\n *\n * // In SSE subscription:\n * const cleanup = broadcast.subscribe(streamId, (msg) => {\n * pending = msg;\n * resolve?.();\n * });\n *\n * // Initial state for reconnects:\n * const cached = broadcast.state(streamId);\n * ```\n *\n * ## Version Contract\n *\n * The `_v` field on state MUST be set from `snap.event.version` (the event\n * store's monotonic stream version) BEFORE calling `publish()`. This is the\n * single source of truth for ordering — no separate version counters.\n */\nexport class BroadcastChannel<S extends BroadcastState = BroadcastState> {\n private channels = new Map<string, Set<Subscriber<S>>>();\n private state_cache: StateCache<S>;\n private on_subscriber_error: (error: unknown, streamId: string) => void;\n private on_overlay_miss: (streamId: string) => void;\n\n constructor(options?: {\n /** Max number of stream states kept in the LRU cache (default 50). */\n cacheSize?: number;\n /**\n * Called when overlay-contributed state is lost, on either of the two\n * paths that can lose it: `overlay()` finding no cached baseline, and\n * the LRU evicting an entry that carried overlay keys — the latter from\n * inside `publish()`, for a stream other than the one being published.\n *\n * Live subscribers of the affected stream are sent a resync frame, so\n * they refetch rather than keep showing state the server has forgotten.\n * The hook is observability on top of that recovery: a steady stream of\n * calls means `cacheSize` is too small for the working set.\n *\n * A throw is caught and routed to `onSubscriberError` — the resync has\n * already gone out, and a host bug must not cost the publishing stream\n * its own frame. Defaults to a no-op.\n */\n onOverlayMiss?: (streamId: string) => void;\n /**\n * Called when a subscriber callback throws. The frame is still delivered\n * to every other subscriber and the publish still returns normally — a\n * bad consumer must not break the publisher. Defaults to `console.error`;\n * pass your logger here to route it with the rest of your logs.\n */\n onSubscriberError?: (error: unknown, streamId: string) => void;\n /**\n * Deprecated alias of `cacheSize` — removal in the next major. When\n * both are given, `cacheSize` wins.\n * @deprecated use `cacheSize`\n */\n cache_size?: number;\n }) {\n this.state_cache = new StateCache<S>(\n options?.cacheSize ?? options?.cache_size ?? 50,\n (streamId, dropped) => this.on_cache_evict(streamId, dropped)\n );\n this.on_overlay_miss = options?.onOverlayMiss ?? (() => {});\n this.on_subscriber_error =\n options?.onSubscriberError ?? default_subscriber_error;\n }\n\n /**\n * Fan a resync out to a stream's live subscribers. `applyPatchMessage`\n * always reports `behind` for it, so they refetch.\n */\n private broadcast_resync(streamId: string): void {\n fan_out(this.channels.get(streamId), resync_frame<S>(), (error) =>\n this.on_subscriber_error(error, streamId)\n );\n }\n\n /**\n * The LRU dropped an entry. Overlay-contributed keys lived only in the\n * cache, so their loss is reported now, when it happens, rather than at a\n * later commit that may never come.\n */\n private on_cache_evict(streamId: string, dropped: S): void {\n if (!(dropped as S & WithOverlayKeys)[OVERLAY_KEYS]?.size) return;\n this.report_overlay_miss(streamId);\n }\n\n /**\n * Overlay-contributed state for `streamId` is gone. Recover first, report\n * second: the resync goes out before the host hook, and a throwing hook is\n * routed to `onSubscriberError`. Eviction runs inside `publish()` for\n * another stream, so an escaping throw would cost that stream its frame.\n */\n private report_overlay_miss(streamId: string): void {\n this.broadcast_resync(streamId);\n try {\n this.on_overlay_miss(streamId);\n } catch (error) {\n this.on_subscriber_error(error, streamId);\n }\n }\n\n /**\n * Publish domain patches from a commit.\n * patches[i] corresponds to version baseV + i + 1.\n *\n * @param streamId - The event store stream ID\n * @param state - Full state with `_v` set from `snap.event.version`\n * @param patches - Array of domain patches, one per emitted event\n */\n publish(\n streamId: string,\n state: S,\n patches: Partial<S>[] = []\n ): PatchMessage<S> {\n // Normalize once, so the reseed and the live frame agree. Then carry the\n // keys an `overlay()` owns across the commit, unless the new domain state\n // sets them, so presence survives a commit and the publisher still wins.\n const safe_state = cache_safe(state);\n const prev = this.state_cache.get(streamId) as\n | (S & WithOverlayKeys)\n | undefined;\n const overlay_keys = prev?.[OVERLAY_KEYS];\n let cached = safe_state;\n if (overlay_keys?.size && prev) {\n const carried = { ...safe_state } as S;\n const kept: string[] = [];\n for (const key of overlay_keys)\n if (!(key in safe_state) && key in prev) {\n (carried as Record<string, unknown>)[key] = (\n prev as Record<string, unknown>\n )[key];\n kept.push(key);\n }\n cached = tag_overlay_keys(carried, undefined, kept);\n }\n this.state_cache.set(streamId, cached);\n\n const baseV = state._v - patches.length;\n const msg: PatchMessage<S> = {};\n patches.forEach((p, i) => {\n msg[baseV + i + 1] = wire_safe(p);\n });\n\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Publish a state update that doesn't change the event version\n * (e.g. presence overlay, computed field refresh).\n * Uses the same version as the cached state, single entry.\n */\n overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n const prev = this.state_cache.get(streamId);\n if (!prev) {\n // No baseline to patch, and a stream that only gets overlays never\n // refills the cache, so its live clients would miss every update. A\n // resync makes them refetch. `undefined`: no overlay was broadcast.\n this.report_overlay_miss(streamId);\n return undefined;\n }\n\n // Normalize before patching the cache, so the reseed and the live frame\n // agree; `apply_patch` deletes on `null` as on `undefined`.\n const safe_patch = wire_safe(overlay_patch);\n const state = apply_patch(prev, safe_patch) as S;\n this.state_cache.set(\n streamId,\n tag_overlay_keys(state, prev, Object.keys(safe_patch as object))\n );\n\n // `_overlay: true` marks this as a version-neutral update so a caught-up\n // client applies it at the current version instead of dropping it as\n // stale (the key equals the client's cachedV). Ordinary patches omit it.\n const msg: PatchMessage<S> = {\n [state._v]: safe_patch,\n _overlay: true,\n };\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Subscribe to broadcast messages for a stream.\n * Returns a cleanup function that removes the subscription.\n */\n subscribe(streamId: string, cb: Subscriber<S>): () => void {\n if (!this.channels.has(streamId)) this.channels.set(streamId, new Set());\n this.channels.get(streamId)!.add(cb);\n return () => {\n this.channels.get(streamId)?.delete(cb);\n if (this.channels.get(streamId)?.size === 0) {\n this.channels.delete(streamId);\n }\n };\n }\n\n /** Get the number of subscribers for a stream. */\n subscriberCount(streamId: string): number {\n return this.channels.get(streamId)?.size ?? 0;\n }\n\n /** Get the cached state for a stream (for reconnects / initial SSE yield). */\n state(streamId: string): S | undefined {\n return this.state_cache.get(streamId);\n }\n\n /** @deprecated use `overlay` — removal in the next major */\n publish_overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n return this.overlay(streamId, overlay_patch);\n }\n\n /** @deprecated use `subscriberCount` — removal in the next major */\n get_subscriber_count(streamId: string): number {\n return this.subscriberCount(streamId);\n }\n\n /** @deprecated use `state` — removal in the next major */\n get_state(streamId: string): S | undefined {\n return this.state(streamId);\n }\n\n /** Direct access to the state cache (for app-specific reads like presence). */\n get cache(): StateCache<S> {\n return this.state_cache;\n }\n}\n","import type { BroadcastState } from \"./types.js\";\n\n/**\n * Generic LRU cache for aggregate state objects.\n *\n * Keyed by stream ID. Each entry stores the full state (with `_v` from the\n * event store). Used as the \"previous state\" baseline for computing patches,\n * and as the fast path for reconnects.\n *\n * The cache is shared between the broadcast hot path and read queries.\n * Projections should maintain their own cache to avoid double-apply bugs.\n */\nexport class StateCache<S extends BroadcastState = BroadcastState> {\n private cache = new Map<string, S>();\n private maxSize: number;\n private on_evict: (key: string, state: S) => void;\n\n /**\n * @param maxSize - Max entries before the LRU drops its oldest.\n * @param onEvict - Called with the entry the LRU just dropped. Eviction is\n * the moment cached-only data is lost, so it is the only place a caller\n * can still see what went.\n */\n constructor(\n maxSize = 50,\n onEvict: (key: string, state: S) => void = () => {}\n ) {\n this.maxSize = maxSize;\n this.on_evict = onEvict;\n }\n\n /** Get a cached state, promoting it to MRU position. */\n get(key: string): S | undefined {\n const s = this.cache.get(key);\n if (s) {\n this.cache.delete(key);\n this.cache.set(key, s);\n }\n return s;\n }\n\n /** Set a cached state, evicting the LRU entry if at capacity. */\n set(key: string, state: S): void {\n this.cache.delete(key);\n this.cache.set(key, state);\n if (this.cache.size > this.maxSize) {\n const oldest = this.cache.keys().next().value!;\n const dropped = this.cache.get(oldest)!;\n this.cache.delete(oldest);\n this.on_evict(oldest, dropped);\n }\n }\n\n /** Remove a cached entry. */\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n /** Check if a key exists in the cache. */\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n /** Current number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Direct access to the underlying map (for iteration). */\n entries(): IterableIterator<[string, S]> {\n return this.cache.entries();\n }\n}\n","import type { DeepPartial } from \"@rotorsoft/act-patch\";\n\n/**\n * Base constraint for state objects managed by the broadcast system.\n * Apps extend this with their own domain state shape.\n */\nexport type BroadcastState = Record<string, unknown> & {\n /** Event store stream version — set by the broadcast layer from snap.event.version */\n _v: number;\n};\n\n/**\n * SSE message: version-keyed domain patches.\n * Keys are stringified version numbers, values are domain patches (deep partials).\n * Multi-event commits produce multiple version-keyed entries.\n *\n * The optional `_overlay` marker flags a version-neutral update (presence,\n * computed-field refresh) emitted by {@link BroadcastChannel.overlay} — a\n * single entry keyed at the *current* version. It tells `applyPatchMessage`\n * to merge the entry on top of the client's caught-up state instead of\n * rejecting it as stale (a same-version patch WITHOUT the marker stays\n * stale). Ordinary version-bumping patches from `publish()` omit it.\n *\n * `_resync` carries no versions at all. The server emits it when it cannot\n * construct a patch: when overlay-contributed state is lost, because\n * `overlay()` finds no cached baseline or the LRU evicts an entry that\n * carried overlay keys. A client that receives one always reports `behind`\n * and refetches, so live subscribers don't silently miss updates.\n */\nexport type PatchMessage<S extends BroadcastState = BroadcastState> = Record<\n number,\n DeepPartial<S>\n> & { readonly _overlay?: true; readonly _resync?: true };\n\n/**\n * Subscriber callback — receives version-keyed patch messages.\n */\nexport type Subscriber<S extends BroadcastState = BroadcastState> = (\n msg: PatchMessage<S>\n) => void;\n\n/**\n * The frame that tells a client to refetch: no versions, so\n * `applyPatchMessage` always reports `behind`.\n *\n * Every producer of a resync uses this — `overlay()` on a missing baseline,\n * the cache on evicting overlay state, and the SSE backlog when it cannot\n * drop a frame without losing it silently. One factory so the shape cannot\n * drift between them.\n */\nexport const resync_frame = <S extends BroadcastState>(): PatchMessage<S> =>\n ({ _resync: true }) as PatchMessage<S>;\n\n/**\n * Whether a frame carries no versions, so `applyPatchMessage` can never\n * classify it as a gap.\n *\n * A version-keyed patch that goes missing is self-announcing: the next frame\n * skips a version and the client refetches. An `_overlay` or `_resync` frame\n * is not, which is why anything that drops frames has to tell them apart.\n */\nexport const is_version_neutral = <S extends BroadcastState>(\n msg: PatchMessage<S>\n): boolean => msg._overlay === true || msg._resync === true;\n","/**\n * Generic presence tracker — ref-counted online status per stream per identity.\n *\n * Supports multi-tab: each subscribe increments the ref count, each\n * unsubscribe decrements it. An identity is considered online when\n * ref count > 0.\n *\n * ## Usage\n *\n * ```typescript\n * const presence = new PresenceTracker();\n *\n * // On SSE connect:\n * presence.add(game_id, player_id);\n *\n * // On SSE disconnect:\n * presence.remove(game_id, player_id);\n *\n * // Query:\n * presence.online(game_id); // Set<string>\n * ```\n */\nexport class PresenceTracker {\n private streams = new Map<string, Map<string, number>>();\n\n /** Increment ref count for an identity on a stream. */\n add(streamId: string, identity_id: string): void {\n if (!this.streams.has(streamId)) this.streams.set(streamId, new Map());\n const counts = this.streams.get(streamId)!;\n counts.set(identity_id, (counts.get(identity_id) ?? 0) + 1);\n }\n\n /** Decrement ref count. Removes the identity when count reaches 0. */\n remove(streamId: string, identity_id: string): void {\n const counts = this.streams.get(streamId);\n if (!counts) return;\n const n = (counts.get(identity_id) ?? 1) - 1;\n if (n <= 0) counts.delete(identity_id);\n else counts.set(identity_id, n);\n if (counts.size === 0) this.streams.delete(streamId);\n }\n\n /** Get the set of online identity IDs for a stream. */\n online(streamId: string): Set<string> {\n const counts = this.streams.get(streamId);\n return counts ? new Set(counts.keys()) : new Set();\n }\n\n /** Check if a specific identity is online for a stream. */\n isOnline(streamId: string, identity_id: string): boolean {\n return (this.streams.get(streamId)?.get(identity_id) ?? 0) > 0;\n }\n\n /** @deprecated use `online` — removal in the next major */\n get_online(streamId: string): Set<string> {\n return this.online(streamId);\n }\n\n /** @deprecated use `isOnline` — removal in the next major */\n is_online(streamId: string, identity_id: string): boolean {\n return this.isOnline(streamId, identity_id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuCA,IAAAA,oBAAsB;;;ACvCtB,uBAAoC;AAuC7B,SAAS,kBACd,KACA,QACgB;AAGhB,QAAM,cAAc,UAAU;AAC9B,QAAM,UAAU,QAAQ,MAAM;AAE9B,QAAM,WAAW,OAAO,KAAK,GAAG,EAC7B,IAAI,MAAM,EACV,OAAO,CAAC,MAAM,OAAO,UAAU,CAAC,CAAC,EACjC,KAAK,CAAC,GAAG,MAAM,I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