@rotorsoft/act-http 1.10.21 → 1.10.22

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 (54) hide show
  1. package/README.md +4 -4
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/@types/api/sse-wiring.d.ts +1 -1
  4. package/dist/@types/hono/index.d.ts +18 -18
  5. package/dist/@types/hono/index.d.ts.map +1 -1
  6. package/dist/@types/openapi/index.d.ts +17 -17
  7. package/dist/@types/openapi/index.d.ts.map +1 -1
  8. package/dist/@types/receiver/express/index.d.ts.map +1 -1
  9. package/dist/@types/receiver/fastify/index.d.ts.map +1 -1
  10. package/dist/@types/receiver/finalize.d.ts +15 -2
  11. package/dist/@types/receiver/finalize.d.ts.map +1 -1
  12. package/dist/@types/receiver/hono/index.d.ts.map +1 -1
  13. package/dist/@types/receiver/index.d.ts +8 -4
  14. package/dist/@types/receiver/index.d.ts.map +1 -1
  15. package/dist/@types/receiver/trpc/index.d.ts.map +1 -1
  16. package/dist/@types/trpc/index.d.ts +38 -38
  17. package/dist/@types/trpc/index.d.ts.map +1 -1
  18. package/dist/api/index.cjs.map +1 -1
  19. package/dist/api/index.js +1 -1
  20. package/dist/{chunk-DMDU25DN.js → chunk-G5FNOSDX.js} +5 -3
  21. package/dist/{chunk-DMDU25DN.js.map → chunk-G5FNOSDX.js.map} +1 -1
  22. package/dist/{chunk-KC2NW7XQ.js → chunk-TTVMQYNN.js} +8 -17
  23. package/dist/chunk-TTVMQYNN.js.map +1 -0
  24. package/dist/{chunk-BGXQRSSQ.js → chunk-ZQGGGU4E.js} +1 -1
  25. package/dist/chunk-ZQGGGU4E.js.map +1 -0
  26. package/dist/hono/index.cjs.map +1 -1
  27. package/dist/hono/index.js +1 -1
  28. package/dist/hono/index.js.map +1 -1
  29. package/dist/openapi/index.cjs.map +1 -1
  30. package/dist/openapi/index.js.map +1 -1
  31. package/dist/receiver/express/index.cjs +4 -12
  32. package/dist/receiver/express/index.cjs.map +1 -1
  33. package/dist/receiver/express/index.js +3 -13
  34. package/dist/receiver/express/index.js.map +1 -1
  35. package/dist/receiver/fastify/index.cjs +4 -12
  36. package/dist/receiver/fastify/index.cjs.map +1 -1
  37. package/dist/receiver/fastify/index.js +3 -13
  38. package/dist/receiver/fastify/index.js.map +1 -1
  39. package/dist/receiver/hono/index.cjs +8 -15
  40. package/dist/receiver/hono/index.cjs.map +1 -1
  41. package/dist/receiver/hono/index.js +2 -2
  42. package/dist/receiver/index.cjs +8 -15
  43. package/dist/receiver/index.cjs.map +1 -1
  44. package/dist/receiver/index.js +2 -2
  45. package/dist/receiver/trpc/index.cjs +8 -15
  46. package/dist/receiver/trpc/index.cjs.map +1 -1
  47. package/dist/receiver/trpc/index.js +7 -16
  48. package/dist/receiver/trpc/index.js.map +1 -1
  49. package/dist/trpc/index.cjs.map +1 -1
  50. package/dist/trpc/index.js +1 -1
  51. package/dist/trpc/index.js.map +1 -1
  52. package/package.json +2 -2
  53. package/dist/chunk-BGXQRSSQ.js.map +0 -1
  54. package/dist/chunk-KC2NW7XQ.js.map +0 -1
@@ -4,7 +4,7 @@ import {
4
4
  runSseSubscription,
5
5
  toApiError,
6
6
  withIdempotency
7
- } from "../chunk-BGXQRSSQ.js";
7
+ } from "../chunk-ZQGGGU4E.js";
8
8
  import {
9
9
  external_exports
10
10
  } from "../chunk-WZ6QI2OI.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/trpc/index.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/trpc\n *\n * tRPC subpath for the auto-generated API epic (#835). Walks the\n * registry of a built `Act` once at function call and emits a typed\n * router that exposes every registered action as a flat `mutation`,\n * matching the shape hand-written tRPC routers in the Act ecosystem\n * already use.\n *\n * Usage:\n *\n * ```ts\n * import { trpc } from \"@rotorsoft/act-http/trpc\";\n *\n * const router = trpc(app, {\n * actor: (ctx) => ({ id: ctx.user.id, name: ctx.user.name }),\n * stream: (action, input, ctx) => input.stream ?? ctx.tenant,\n * });\n *\n * // Client sees:\n * // appRouter.PressKey.mutate({ key: \"5\" })\n * // appRouter.OpenTicket.mutate({ title: \"...\" })\n * ```\n *\n * The route shape is flat: one procedure per registered action at\n * the top level. Action names are the unique identifiers across\n * the registry (the framework already enforces no duplicates), so\n * an extra namespace tier would be overhead in the common case.\n * Pure mutations for this slice; query/projection wiring lives in\n * a follow-up. See `libs/act-http/README.md` for the full surface\n * walkthrough.\n *\n * **Actor lives on the context.** The generator wires an internal\n * tRPC middleware that runs the host's\n * {@link TrpcOptions.actor | actor extractor} once per call and\n * injects the resolved {@link Actor} onto the downstream context as\n * `ctx.actor`. Every generated mutation reads from there — auth\n * resolves at the procedure boundary, not inside each action body,\n * and any composed middleware (logging, tracing) sees the same\n * `ctx.actor`. The middleware factory is also exported as\n * {@link authenticated} for hosts that need to compose it into\n * their own procedure chain.\n *\n * Composes the shared utilities at `@rotorsoft/act-http/api`:\n * {@link ActorExtractor} for the auth seam, {@link toApiError} for\n * the uniform error→status/code mapping, {@link withIdempotency}\n * for `Idempotency-Key` dedup. Three transports (this one, Hono,\n * OpenAPI) ride the same utilities so a client talking to two\n * transports never sees two error shapes for the same framework\n * error.\n */\nimport { type Actor, type Target, validate } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport {\n type AnyTRPCMiddlewareFunction,\n type AnyTRPCMutationProcedure,\n type AnyTRPCRootTypes,\n initTRPC,\n type TRPCBuiltRouter,\n TRPCError,\n} from \"@trpc/server\";\nimport { z } from \"zod\";\nimport { track_in_flight } from \"../api/in-flight.js\";\nimport {\n type ActorExtractor,\n resolveSseConfig,\n runSseSubscription,\n SseConnectionCounter,\n type SseOptions,\n toApiError,\n withIdempotency,\n} from \"../api/index.js\";\n\n/**\n * Per-call options for {@link trpc}. The host supplies the three\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the tRPC context, returns the\n * `Actor` that flows onto `ctx.actor` for every generated\n * procedure (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated action input, and the original tRPC context; returns\n * the target stream. Singleton aggregates return a constant;\n * per-tenant aggregates pull from input or context.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * When set, the procedure threads the resolved value through\n * `target.expectedVersion` so `app.do` refuses to commit if the\n * stream has moved. Hosts typically read it from an `If-Match`\n * header on the underlying HTTP request, or pull it from the\n * client's last-known snapshot. Returning `undefined` skips the\n * check for that call — handy when only some actions are\n * concurrency-sensitive.\n * - `idempotency` (optional) — when set, the procedure honors\n * `Idempotency-Key` via the shared\n * {@link withIdempotency} helper. The host supplies the\n * `IdempotencyStore` and a `keyFrom` extractor that reads the key\n * out of the tRPC context (typically a header). A duplicate of a key\n * that already succeeded throws a `CONFLICT` `TRPCError` — the\n * receiver-side convention of \"ack the duplicate\" doesn't carry\n * over because the contract intentionally does not cache the\n * original handler's result. A duplicate that arrives while the\n * original is still running throws a retryable\n * `SERVICE_UNAVAILABLE` (503) instead: the original may yet fail and\n * release the key, and a client told \"already used\" would never retry.\n *\n * @template Ctx The host's tRPC context shape. Flows end-to-end —\n * procedures see this exact context type (plus `actor`) at\n * runtime.\n */\nexport type TrpcOptions<Ctx> = {\n readonly actor: ActorExtractor;\n readonly stream: (\n action_name: string,\n input: unknown,\n ctx: Ctx\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n ctx: Ctx\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom: (ctx: Ctx) => string | undefined;\n };\n /**\n * Optional SSE wiring. When set, the generator emits one\n * subscription per unique state name in the registry, grouped on\n * the returned router as\n * `router.subscribe.<stateName>.useSubscription({ stream })`.\n * Each subscription yields `{ kind: \"state\", data }` once with\n * the cached state (when present) and then `{ kind: \"patch\",\n * data }` for every patch the shared\n * {@link SseOptions.channel} publishes. The per-process\n * connection cap surfaces as a `TOO_MANY_REQUESTS` `TRPCError`.\n *\n * Off by default — most APIs don't expose live state to every\n * client, and opening one is widening both the auth and cost\n * surface.\n */\n readonly sse?: SseOptions;\n};\n\n/**\n * Build a tRPC middleware that runs an {@link ActorExtractor} once\n * per call and forwards the resolved {@link Actor} on the\n * downstream context as `ctx.actor`. The generator at\n * {@link trpc} uses this internally; it's also exported so hosts\n * that want to compose their own procedure chain (logging,\n * tracing, custom auth flavors) can wire it directly:\n *\n * ```ts\n * import { initTRPC } from \"@trpc/server\";\n * import { authenticated } from \"@rotorsoft/act-http/trpc\";\n *\n * type Ctx = { user?: { id: string; name: string } };\n * const t = initTRPC.context<Ctx>().create();\n *\n * const authed = t.procedure.use(\n * authenticated((ctx) => {\n * if (!ctx.user) throw new Error(\"not authenticated\");\n * return { id: ctx.user.id, name: ctx.user.name };\n * })\n * );\n *\n * // Inside any procedure built off `authed`, `ctx.actor: Actor`.\n * ```\n *\n * The middleware is unaware of the host's `t` instance — it returns\n * a structurally-typed function that any tRPC `procedure.use(...)`\n * accepts. Errors thrown by the extractor surface unchanged\n * (typically wrap them as `TRPCError({ code: \"UNAUTHORIZED\" })`\n * in the extractor body).\n */\nexport function authenticated(\n extractor: ActorExtractor\n): AnyTRPCMiddlewareFunction {\n // tRPC's middleware function type lives behind\n // `unstable-core-do-not-import`; we satisfy it structurally with the\n // shape `procedure.use(...)` actually requires (an `{ ctx, next }`\n // bag whose `next` callback is invoked once with the augmented ctx)\n // and cast the structurally-typed result up to the named export. The\n // type cast carries no `any`; both sides are structurally compatible\n // at the call site.\n const middleware = async function actor_middleware({\n ctx,\n next,\n }: {\n ctx: object;\n next: (opts: { ctx: object }) => Promise<unknown>;\n }) {\n const actor = await extractor(ctx);\n return next({ ctx: { ...ctx, actor } });\n };\n return middleware as unknown as AnyTRPCMiddlewareFunction;\n}\n\n/**\n * Map a thrown framework error onto a `TRPCError`. Known errors get\n * their conventional tRPC code (`ConcurrencyError` → `PRECONDITION_FAILED`,\n * `StreamClosedError` → `NOT_FOUND`, `ValidationError` →\n * `UNPROCESSABLE_CONTENT`, etc.); unknown throws\n * surface as `INTERNAL_SERVER_ERROR`. Every transport in the\n * act-http epic passes through the same {@link toApiError} table,\n * so a client talking to both this subpath and the REST sibling\n * sees one envelope per framework error.\n *\n * @internal\n */\nfunction to_trpc_error(err: unknown): TRPCError {\n const { status, body } = toApiError(err);\n const code = status_to_trpc_code(status);\n return new TRPCError({\n code,\n message: body.detail ?? body.error,\n cause: err instanceof Error ? err : undefined,\n });\n}\n\n/**\n * Minimal status → tRPC code map. Only the statuses\n * {@link ERROR_MAP} produces (plus 500) appear here; anything else\n * collapses to `INTERNAL_SERVER_ERROR`.\n *\n * @internal\n */\nfunction status_to_trpc_code(status: number): TRPCError[\"code\"] {\n switch (status) {\n case 400:\n return \"BAD_REQUEST\";\n case 409:\n return \"CONFLICT\";\n case 410:\n // StreamClosedError is HTTP 410 Gone. tRPC has no 410 code, so map to\n // NOT_FOUND (404) — its closest \"resource is gone\" semantics. This is\n // the one unavoidable cross-transport status difference (Hono/OpenAPI\n // keep 410); see auto-generated-api.md.\n return \"NOT_FOUND\";\n case 412:\n // ConcurrencyError is HTTP 412 Precondition Failed. Map by error\n // identity, not by round-tripping the status: PRECONDITION_FAILED\n // serializes back to 412, matching Hono/OpenAPI (#1280).\n return \"PRECONDITION_FAILED\";\n case 422:\n return \"UNPROCESSABLE_CONTENT\";\n default:\n return \"INTERNAL_SERVER_ERROR\";\n }\n}\n\n/**\n * Build a typed tRPC router from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one flat mutation per\n * action under `router.<actionName>`. The framework already enforces\n * no duplicate action names across states, so a flat tier reads\n * cleanly at the client and matches the hand-written router shape\n * adopters already have. Each mutation:\n *\n * 1. Runs the internal {@link authenticated} — `options.actor`\n * resolves the {@link Actor} once and injects it onto\n * `ctx.actor`.\n * 2. Resolves the target stream via `options.stream(name, input, ctx)`.\n * 3. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — throws `CONFLICT` on a duplicate of a\n * committed key, `SERVICE_UNAVAILABLE` on one still in flight.\n * 4. Calls `app.do(name, { stream, actor: ctx.actor }, input)`.\n * 5. Maps any thrown framework error onto a `TRPCError` via\n * {@link toApiError}.\n *\n * The returned router's procedure inputs come straight from each\n * action's Zod schema; outputs are the framework's\n * `Snapshot<TState, TEvents>[]` shape. Strong typing flows\n * end-to-end via tRPC's normal inference path — the client sees\n * `appRouter.Calculator.PressKey.mutate({ key: \"5\" })` as a typed\n * call without any codegen.\n *\n * @template Ctx The tRPC context shape the host's runtime feeds in.\n * Flows through `actor`, `stream`, and `idempotency.keyFrom` so\n * the operator's existing context types just work. The internal\n * middleware augments `Ctx` with `{ actor: Actor }` on the\n * downstream procedure context.\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, and (optional) idempotency seams.\n * @returns A tRPC router covering every registered action, grouped\n * by owning state.\n */\n/**\n * Structural shape of the Act surface this generator walks at\n * runtime — the registry's action-name → owning-state map plus the\n * `do(...)` dispatch. Letting TApp infer to the caller's concrete\n * `Act<...>` against this structural bound (instead of forcing it\n * to fit a narrow framework-typed upper bound) keeps the variance\n * of nested types like `PatchHandler` from leaking — and avoids\n * `any` in the signature.\n *\n * @internal\n */\ntype ActSurface = {\n readonly registry: {\n actions: Record<\n string,\n {\n readonly name: string;\n readonly actions: Record<string, unknown>;\n }\n >;\n };\n do(action: string, target: Target, payload: unknown): Promise<unknown>;\n};\n\n/**\n * Generated router type — one mutation procedure per action name in\n * `TApp`'s registry. Mapped over the concrete action keys so\n * `createTRPCReact<typeof router>()` sees specific procedure names\n * (`PressKey`, `Clear`, …) instead of a wide `Record<string, ...>`\n * index signature — which is what trips tRPC React's\n * \"useContext / Provider / useUtils collides\" check on widely-typed\n * routers.\n *\n * @internal\n */\ntype GeneratedRouter<TApp> = TRPCBuiltRouter<\n AnyTRPCRootTypes,\n TApp extends { registry: { actions: infer TActions } }\n ? { [K in keyof TActions]: AnyTRPCMutationProcedure }\n : Record<string, AnyTRPCMutationProcedure>\n>;\n\nexport function trpc<\n Ctx extends object = object,\n TApp extends ActSurface = ActSurface,\n>(app: TApp, options: TrpcOptions<Ctx>): GeneratedRouter<TApp> {\n const t = initTRPC.context<Ctx>().create();\n // Counts claims per key so a duplicate of a still-running action can be\n // told apart from a duplicate of a committed one (see `track_in_flight`).\n const tracker = options.idempotency\n ? track_in_flight(options.idempotency.store)\n : undefined;\n\n // Resolve the actor inline per mutation instead of via\n // `t.procedure.use(authenticated(...))`. The middleware path threads\n // tRPC's internal `Unwrap` type into each procedure's inferred shape,\n // which the d.ts emitter can't name portably (`unstable-core-do-not-\n // import` has a hashed file name that varies per build). Inlining\n // sidesteps the issue entirely — the standalone `authenticated`\n // export still works for hosts who want middleware composition.\n /**\n * Run the actor extractor for a generated procedure, mapping a\n * \"throw to deny\" onto `UNAUTHORIZED` rather than a framework 500.\n *\n * Shared by mutations and subscriptions on purpose. Each used to carry\n * its own copy of this block, and the subscription copy was simply\n * missing — a denied caller got a live subscription and the cached\n * state frame with it (#1620). One helper is what keeps the two paths\n * from drifting again.\n */\n const resolve_actor = async (host_ctx: Ctx): Promise<Actor> => {\n try {\n return await options.actor(host_ctx);\n } catch (err) {\n throw new TRPCError({\n code: \"UNAUTHORIZED\",\n message: err instanceof Error ? err.message : undefined,\n cause: err instanceof Error ? err : undefined,\n });\n }\n };\n\n const handlers: Record<\n string,\n ReturnType<ReturnType<typeof t.procedure.input>[\"mutation\"]>\n > = {};\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n const action_schema = state.actions[action_name];\n handlers[action_name] = t.procedure\n // Passthrough parser: tRPC's own `.input()` validation is deliberately\n // bypassed because a Zod failure there surfaces as a hardcoded\n // BAD_REQUEST (400) that never reaches `to_trpc_error`. Validation runs\n // in the resolver (below) instead, so a malformed body maps to the SAME\n // 422 / ApiError a `ValidationError` thrown inside `app.do` produces —\n // cross-transport parity with Hono/OpenAPI (#1295).\n .input((raw: unknown) => raw)\n .mutation(async ({ input, ctx }) => {\n const host_ctx = ctx as unknown as Ctx;\n // Resolve the actor first, mirroring Hono's `authenticated` middleware:\n // a \"throw to deny\" from the extractor is 401 UNAUTHORIZED, not a 500.\n // The actor step is auth — distinct from a framework error inside\n // `app.do`, which the main try below maps via `to_trpc_error` (#1286).\n const actor: Actor = await resolve_actor(host_ctx);\n try {\n // Validate the payload before the stream / expectedVersion resolvers\n // see it, mirroring Hono's zValidator-then-handler order. `validate`\n // throws the framework `ValidationError`, which `to_trpc_error` maps\n // to 422 / UNPROCESSABLE_CONTENT with the shared ApiError envelope\n // (#1295). The resolvers get the parsed value, but `app.do` gets the\n // raw `input`: it parses again itself, and a second parse of the\n // output would run every `.transform()` twice.\n const validated = validate(\n action_name,\n input as never,\n action_schema as never\n );\n const stream = await options.stream(action_name, validated, host_ctx);\n const expected_version = options.expectedVersion\n ? await options.expectedVersion(action_name, validated, host_ctx)\n : undefined;\n const target =\n expected_version === undefined\n ? { stream, actor }\n : { stream, actor, expectedVersion: expected_version };\n\n if (options.idempotency) {\n const key = options.idempotency.keyFrom(host_ctx);\n if (!key) {\n throw new TRPCError({\n code: \"BAD_REQUEST\",\n message: \"Idempotency-Key required\",\n });\n }\n const outcome = await withIdempotency(tracker!.store, key, () =>\n app.do(action_name as never, target as never, input as never)\n );\n if (outcome.deduped && tracker!.in_flight(key)) {\n throw new TRPCError({\n code: \"SERVICE_UNAVAILABLE\",\n message:\n \"Idempotency-Key in flight; the original request has not finished, retry later\",\n });\n }\n if (outcome.deduped) {\n throw new TRPCError({\n code: \"CONFLICT\",\n message:\n \"Idempotency-Key already used; original result not cached\",\n });\n }\n return outcome.result;\n }\n\n return await app.do(\n action_name as never,\n target as never,\n input as never\n );\n } catch (err) {\n if (err instanceof TRPCError) throw err;\n throw to_trpc_error(err);\n }\n });\n }\n\n if (options.sse) {\n // SSE subscriptions mount under the `subscribe` key of the same router\n // as the action mutations, so an action named `subscribe` would be\n // silently replaced. Refuse it at generation instead.\n if (\"subscribe\" in app.registry.actions)\n throw new Error(\n 'trpc: an action named \"subscribe\" collides with the SSE subscription router (router.subscribe.<stateName>); rename the action or generate the router without `sse`.'\n );\n const sse_config = resolveSseConfig(options.sse);\n const sse_counter = new SseConnectionCounter(sse_config.maxConnections);\n const state_names = new Set<string>();\n for (const action of Object.values(app.registry.actions)) {\n state_names.add(action.name);\n }\n const sse_handlers: Record<string, unknown> = {};\n for (const state_name of state_names) {\n sse_handlers[state_name] = t.procedure\n .input(z.object({ stream: z.string().min(1) }))\n .subscription(async function* ({ input, ctx, signal }) {\n // Step 1 of the documented subscription contract: the actor\n // extractor runs before a slot is taken or a frame is yielded,\n // so a denying extractor denies the open. Hono gets this from\n // the `authenticated` middleware it mounts across `/api/*`;\n // this generator is where the same rule lives for tRPC, which\n // resolves the actor inline rather than through middleware.\n await resolve_actor(ctx as unknown as Ctx);\n yield* runSseSubscription(\n sse_config.channel,\n input.stream,\n sse_counter,\n signal,\n {\n maxPending: sse_config.maxPendingPerConnection,\n on_cap_exceeded: () => {\n throw new TRPCError({\n code: \"TOO_MANY_REQUESTS\",\n message: \"max concurrent SSE subscriptions reached\",\n });\n },\n }\n );\n });\n }\n handlers.subscribe = t.router(sse_handlers as never) as never;\n }\n\n // The runtime router IS structurally compatible with\n // `GeneratedRouter<TApp>` (one mutation per action key), but tRPC's\n // `BuiltRouter` carries an internal `Unwrap<Ctx>` that the d.ts\n // emitter can't name portably. Bridging through `unknown` keeps the\n // caller-visible type clean (specific procedure names, no\n // index-signature widening that trips React tRPC's collision check).\n return t.router(handlers) as unknown as GeneratedRouter<TApp>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoDA,SAAkC,gBAAgB;AAElD;AAAA,EAIE;AAAA,EAEA;AAAA,OACK;AAkHA,SAAS,cACd,WAC2B;AAQ3B,QAAM,aAAa,eAAe,iBAAiB;AAAA,IACjD;AAAA,IACA;AAAA,EACF,GAGG;AACD,UAAM,QAAQ,MAAM,UAAU,GAAG;AACjC,WAAO,KAAK,EAAE,KAAK,EAAE,GAAG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IAAI,qBAAqB,WAAW,cAAc;AACtE,UAAM,cAAc,oBAAI,IAAY;AACpC,eAAW,UAAU,OAAO,OAAO,IAAI,SAAS,OAAO,GAAG;AACxD,kBAAY,IAAI,OAAO,IAAI;AAAA,IAC7B;AACA,UAAM,eAAwC,CAAC;AAC/C,eAAW,cAAc,aAAa;AACpC,mBAAa,UAAU,IAAI,EAAE,UAC1B,MAAM,iBAAE,OAAO,EAAE,QAAQ,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,EAC7C,aAAa,iBAAiB,EAAE,OAAO,KAAK,OAAO,GAAG;AAOrD,cAAM,cAAc,GAAqB;AACzC,eAAO;AAAA,UACL,WAAW;AAAA,UACX,MAAM;AAAA,UACN;AAAA,UACA;AAAA,UACA;AAAA,YACE,YAAY,WAAW;AAAA,YACvB,iBAAiB,MAAM;AACrB,oBAAM,IAAI,UAAU;AAAA,gBAClB,MAAM;AAAA,gBACN,SAAS;AAAA,cACX,CAAC;AAAA,YACH;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACL;AACA,aAAS,YAAY,EAAE,OAAO,YAAqB;AAAA,EACrD;AAQA,SAAO,EAAE,OAAO,QAAQ;AAC1B;","names":[]}
1
+ {"version":3,"sources":["../../src/trpc/index.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/trpc\n *\n * tRPC subpath for the auto-generated API epic (#835). Walks the\n * registry of a built `Act` once at function call and emits a typed\n * router that exposes every registered action as a flat `mutation`,\n * matching the shape hand-written tRPC routers in the Act ecosystem\n * already use.\n *\n * Usage:\n *\n * ```ts\n * import { trpc } from \"@rotorsoft/act-http/trpc\";\n *\n * const router = trpc(app, {\n * actor: (ctx) => ({ id: ctx.user.id, name: ctx.user.name }),\n * stream: (action, input, ctx) => input.stream ?? ctx.tenant,\n * });\n *\n * // Client sees:\n * // appRouter.PressKey.mutate({ key: \"5\" })\n * // appRouter.OpenTicket.mutate({ title: \"...\" })\n * ```\n *\n * The route shape is flat: one procedure per registered action at\n * the top level. Action names are the unique identifiers across\n * the registry (the framework already enforces no duplicates), so\n * an extra namespace tier would be overhead in the common case.\n * Pure mutations for this slice; query/projection wiring lives in\n * a follow-up. See `libs/act-http/README.md` for the full surface\n * walkthrough.\n *\n * **Actor lives on the context.** The generator wires an internal\n * tRPC middleware that runs the host's\n * {@link TrpcOptions.actor | actor extractor} once per call and\n * injects the resolved {@link Actor} onto the downstream context as\n * `ctx.actor`. Every generated mutation reads from there — auth\n * resolves at the procedure boundary, not inside each action body,\n * and any composed middleware (logging, tracing) sees the same\n * `ctx.actor`. The middleware factory is also exported as\n * {@link authenticated} for hosts that need to compose it into\n * their own procedure chain.\n *\n * Composes the shared utilities at `@rotorsoft/act-http/api`:\n * {@link ActorExtractor} for the auth seam, {@link toApiError} for\n * the uniform error→status/code mapping, {@link withIdempotency}\n * for `Idempotency-Key` dedup. Three transports (this one, Hono,\n * OpenAPI) ride the same utilities so a client talking to two\n * transports never sees two error shapes for the same framework\n * error.\n */\nimport { type Actor, type Target, validate } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport {\n type AnyTRPCMiddlewareFunction,\n type AnyTRPCMutationProcedure,\n type AnyTRPCRootTypes,\n initTRPC,\n type TRPCBuiltRouter,\n TRPCError,\n} from \"@trpc/server\";\nimport { z } from \"zod\";\nimport { track_in_flight } from \"../api/in-flight.js\";\nimport {\n type ActorExtractor,\n resolveSseConfig,\n runSseSubscription,\n SseConnectionCounter,\n type SseOptions,\n toApiError,\n withIdempotency,\n} from \"../api/index.js\";\n\n/**\n * Per-call options for {@link trpc}. The host supplies the three\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the tRPC context, returns the\n * `Actor` that flows onto `ctx.actor` for every generated\n * procedure (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated action input, and the original tRPC context; returns\n * the target stream. Singleton aggregates return a constant;\n * per-tenant aggregates pull from input or context.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * When set, the procedure threads the resolved value through\n * `target.expectedVersion` so `app.do` refuses to commit if the\n * stream has moved. Hosts typically read it from an `If-Match`\n * header on the underlying HTTP request, or pull it from the\n * client's last-known snapshot. Returning `undefined` skips the\n * check for that call — handy when only some actions are\n * concurrency-sensitive.\n * - `idempotency` (optional) — when set, the procedure honors\n * `Idempotency-Key` via the shared\n * {@link withIdempotency} helper. The host supplies the\n * `IdempotencyStore` and a `keyFrom` extractor that reads the key\n * out of the tRPC context (typically a header). A duplicate of a key\n * that already succeeded throws a `CONFLICT` `TRPCError` — the\n * receiver-side convention of \"ack the duplicate\" doesn't carry\n * over because the contract intentionally does not cache the\n * original handler's result. A duplicate that arrives while the\n * original is still running throws a retryable\n * `SERVICE_UNAVAILABLE` (503) instead: the original may yet fail and\n * release the key, and a client told \"already used\" would never retry.\n *\n * @template Ctx The host's tRPC context shape. Flows end-to-end —\n * procedures see this exact context type (plus `actor`) at\n * runtime.\n */\nexport type TrpcOptions<Ctx> = {\n readonly actor: ActorExtractor;\n readonly stream: (\n action_name: string,\n input: unknown,\n ctx: Ctx\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n ctx: Ctx\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom: (ctx: Ctx) => string | undefined;\n };\n /**\n * Optional SSE wiring. When set, the generator emits one\n * subscription per unique state name in the registry, grouped on\n * the returned router as\n * `router.subscribe.<stateName>.useSubscription({ stream })`.\n * Each subscription yields `{ kind: \"state\", data }` once with\n * the cached state (when present) and then `{ kind: \"patch\",\n * data }` for every patch the shared\n * {@link SseOptions.channel} publishes. The per-process\n * connection cap surfaces as a `TOO_MANY_REQUESTS` `TRPCError`.\n *\n * Off by default — most APIs don't expose live state to every\n * client, and opening one is widening both the auth and cost\n * surface.\n */\n readonly sse?: SseOptions;\n};\n\n/**\n * Build a tRPC middleware that runs an {@link ActorExtractor} once\n * per call and forwards the resolved {@link Actor} on the\n * downstream context as `ctx.actor`. The generator at\n * {@link trpc} uses this internally; it's also exported so hosts\n * that want to compose their own procedure chain (logging,\n * tracing, custom auth flavors) can wire it directly:\n *\n * ```ts\n * import { initTRPC } from \"@trpc/server\";\n * import { authenticated } from \"@rotorsoft/act-http/trpc\";\n *\n * type Ctx = { user?: { id: string; name: string } };\n * const t = initTRPC.context<Ctx>().create();\n *\n * const authed = t.procedure.use(\n * authenticated((ctx) => {\n * if (!ctx.user) throw new Error(\"not authenticated\");\n * return { id: ctx.user.id, name: ctx.user.name };\n * })\n * );\n *\n * // Inside any procedure built off `authed`, `ctx.actor: Actor`.\n * ```\n *\n * The middleware is unaware of the host's `t` instance — it returns\n * a structurally-typed function that any tRPC `procedure.use(...)`\n * accepts. Errors thrown by the extractor surface unchanged\n * (typically wrap them as `TRPCError({ code: \"UNAUTHORIZED\" })`\n * in the extractor body).\n */\nexport function authenticated(\n extractor: ActorExtractor\n): AnyTRPCMiddlewareFunction {\n // tRPC's middleware function type lives behind\n // `unstable-core-do-not-import`; we satisfy it structurally with the\n // shape `procedure.use(...)` actually requires (an `{ ctx, next }`\n // bag whose `next` callback is invoked once with the augmented ctx)\n // and cast the structurally-typed result up to the named export. The\n // type cast carries no `any`; both sides are structurally compatible\n // at the call site.\n const middleware = async function actor_middleware({\n ctx,\n next,\n }: {\n ctx: object;\n next: (opts: { ctx: object }) => Promise<unknown>;\n }) {\n const actor = await extractor(ctx);\n return next({ ctx: { ...ctx, actor } });\n };\n return middleware as unknown as AnyTRPCMiddlewareFunction;\n}\n\n/**\n * Map a thrown framework error onto a `TRPCError`. Known errors get\n * their conventional tRPC code (`ConcurrencyError` → `PRECONDITION_FAILED`,\n * `StreamClosedError` → `NOT_FOUND`, `ValidationError` →\n * `UNPROCESSABLE_CONTENT`, etc.); unknown throws\n * surface as `INTERNAL_SERVER_ERROR`. Every transport in the\n * act-http epic passes through the same {@link toApiError} table,\n * so a client talking to both this subpath and the REST sibling\n * sees one envelope per framework error.\n *\n * @internal\n */\nfunction to_trpc_error(err: unknown): TRPCError {\n const { status, body } = toApiError(err);\n const code = status_to_trpc_code(status);\n return new TRPCError({\n code,\n message: body.detail ?? body.error,\n cause: err instanceof Error ? err : undefined,\n });\n}\n\n/**\n * Minimal status → tRPC code map. Only the statuses\n * {@link ERROR_MAP} produces (plus 500) appear here; anything else\n * collapses to `INTERNAL_SERVER_ERROR`.\n *\n * @internal\n */\nfunction status_to_trpc_code(status: number): TRPCError[\"code\"] {\n switch (status) {\n case 400:\n return \"BAD_REQUEST\";\n case 409:\n return \"CONFLICT\";\n case 410:\n // StreamClosedError is HTTP 410 Gone. tRPC has no 410 code, so map to\n // NOT_FOUND (404) — its closest \"resource is gone\" semantics. This is\n // the one unavoidable cross-transport status difference (Hono/OpenAPI\n // keep 410); see auto-generated-api.md.\n return \"NOT_FOUND\";\n case 412:\n // ConcurrencyError is HTTP 412 Precondition Failed. Map by error\n // identity, not by round-tripping the status: PRECONDITION_FAILED\n // serializes back to 412, matching Hono/OpenAPI (#1280).\n return \"PRECONDITION_FAILED\";\n case 422:\n return \"UNPROCESSABLE_CONTENT\";\n default:\n return \"INTERNAL_SERVER_ERROR\";\n }\n}\n\n/**\n * Structural shape of the Act surface this generator walks at\n * runtime — the registry's action-name → owning-state map plus the\n * `do(...)` dispatch. Letting TApp infer to the caller's concrete\n * `Act<...>` against this structural bound (instead of forcing it\n * to fit a narrow framework-typed upper bound) keeps the variance\n * of nested types like `PatchHandler` from leaking — and avoids\n * `any` in the signature.\n *\n * @internal\n */\ntype ActSurface = {\n readonly registry: {\n actions: Record<\n string,\n {\n readonly name: string;\n readonly actions: Record<string, unknown>;\n }\n >;\n };\n do(action: string, target: Target, payload: unknown): Promise<unknown>;\n};\n\n/**\n * Generated router type — one mutation procedure per action name in\n * `TApp`'s registry. Mapped over the concrete action keys so\n * `createTRPCReact<typeof router>()` sees specific procedure names\n * (`PressKey`, `Clear`, …) instead of a wide `Record<string, ...>`\n * index signature — which is what trips tRPC React's\n * \"useContext / Provider / useUtils collides\" check on widely-typed\n * routers.\n *\n * @internal\n */\ntype GeneratedRouter<TApp> = TRPCBuiltRouter<\n AnyTRPCRootTypes,\n TApp extends { registry: { actions: infer TActions } }\n ? { [K in keyof TActions]: AnyTRPCMutationProcedure }\n : Record<string, AnyTRPCMutationProcedure>\n>;\n\n/**\n * Build a typed tRPC router from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one flat mutation per\n * action under `router.<actionName>`. The framework already enforces\n * no duplicate action names across states, so a flat tier reads\n * cleanly at the client and matches the hand-written router shape\n * adopters already have. Each mutation:\n *\n * 1. Runs the internal {@link authenticated} — `options.actor`\n * resolves the {@link Actor} once and injects it onto\n * `ctx.actor`.\n * 2. Resolves the target stream via `options.stream(name, input, ctx)`.\n * 3. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — throws `CONFLICT` on a duplicate of a\n * committed key, `SERVICE_UNAVAILABLE` on one still in flight.\n * 4. Calls `app.do(name, { stream, actor: ctx.actor }, input)`.\n * 5. Maps any thrown framework error onto a `TRPCError` via\n * {@link toApiError}.\n *\n * The returned router's procedure inputs come straight from each\n * action's Zod schema; outputs are the framework's\n * `Snapshot<TState, TEvents>[]` shape. Strong typing flows\n * end-to-end via tRPC's normal inference path — the client sees\n * `appRouter.Calculator.PressKey.mutate({ key: \"5\" })` as a typed\n * call without any codegen.\n *\n * @template Ctx The tRPC context shape the host's runtime feeds in.\n * Flows through `actor`, `stream`, and `idempotency.keyFrom` so\n * the operator's existing context types just work. The internal\n * middleware augments `Ctx` with `{ actor: Actor }` on the\n * downstream procedure context.\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, and (optional) idempotency seams.\n * @returns A tRPC router covering every registered action, grouped\n * by owning state.\n */\nexport function trpc<\n Ctx extends object = object,\n TApp extends ActSurface = ActSurface,\n>(app: TApp, options: TrpcOptions<Ctx>): GeneratedRouter<TApp> {\n const t = initTRPC.context<Ctx>().create();\n // Counts claims per key so a duplicate of a still-running action can be\n // told apart from a duplicate of a committed one (see `track_in_flight`).\n const tracker = options.idempotency\n ? track_in_flight(options.idempotency.store)\n : undefined;\n\n // Resolve the actor inline per mutation instead of via\n // `t.procedure.use(authenticated(...))`. The middleware path threads\n // tRPC's internal `Unwrap` type into each procedure's inferred shape,\n // which the d.ts emitter can't name portably (`unstable-core-do-not-\n // import` has a hashed file name that varies per build). Inlining\n // sidesteps the issue entirely — the standalone `authenticated`\n // export still works for hosts who want middleware composition.\n /**\n * Run the actor extractor for a generated procedure, mapping a\n * \"throw to deny\" onto `UNAUTHORIZED` rather than a framework 500.\n *\n * Shared by mutations and subscriptions on purpose. Each used to carry\n * its own copy of this block, and the subscription copy was simply\n * missing — a denied caller got a live subscription and the cached\n * state frame with it (#1620). One helper is what keeps the two paths\n * from drifting again.\n */\n const resolve_actor = async (host_ctx: Ctx): Promise<Actor> => {\n try {\n return await options.actor(host_ctx);\n } catch (err) {\n throw new TRPCError({\n code: \"UNAUTHORIZED\",\n message: err instanceof Error ? err.message : undefined,\n cause: err instanceof Error ? err : undefined,\n });\n }\n };\n\n const handlers: Record<\n string,\n ReturnType<ReturnType<typeof t.procedure.input>[\"mutation\"]>\n > = {};\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n const action_schema = state.actions[action_name];\n handlers[action_name] = t.procedure\n // Passthrough parser: tRPC's own `.input()` validation is deliberately\n // bypassed because a Zod failure there surfaces as a hardcoded\n // BAD_REQUEST (400) that never reaches `to_trpc_error`. Validation runs\n // in the resolver (below) instead, so a malformed body maps to the SAME\n // 422 / ApiError a `ValidationError` thrown inside `app.do` produces —\n // cross-transport parity with Hono/OpenAPI (#1295).\n .input((raw: unknown) => raw)\n .mutation(async ({ input, ctx }) => {\n const host_ctx = ctx as unknown as Ctx;\n // Resolve the actor first, mirroring Hono's `authenticated` middleware:\n // a \"throw to deny\" from the extractor is 401 UNAUTHORIZED, not a 500.\n // The actor step is auth — distinct from a framework error inside\n // `app.do`, which the main try below maps via `to_trpc_error` (#1286).\n const actor: Actor = await resolve_actor(host_ctx);\n try {\n // Validate the payload before the stream / expectedVersion resolvers\n // see it, mirroring Hono's zValidator-then-handler order. `validate`\n // throws the framework `ValidationError`, which `to_trpc_error` maps\n // to 422 / UNPROCESSABLE_CONTENT with the shared ApiError envelope\n // (#1295). The resolvers get the parsed value, but `app.do` gets the\n // raw `input`: it parses again itself, and a second parse of the\n // output would run every `.transform()` twice.\n const validated = validate(\n action_name,\n input as never,\n action_schema as never\n );\n const stream = await options.stream(action_name, validated, host_ctx);\n const expected_version = options.expectedVersion\n ? await options.expectedVersion(action_name, validated, host_ctx)\n : undefined;\n const target =\n expected_version === undefined\n ? { stream, actor }\n : { stream, actor, expectedVersion: expected_version };\n\n if (options.idempotency) {\n const key = options.idempotency.keyFrom(host_ctx);\n if (!key) {\n throw new TRPCError({\n code: \"BAD_REQUEST\",\n message: \"Idempotency-Key required\",\n });\n }\n const outcome = await withIdempotency(tracker!.store, key, () =>\n app.do(action_name as never, target as never, input as never)\n );\n if (outcome.deduped && tracker!.in_flight(key)) {\n throw new TRPCError({\n code: \"SERVICE_UNAVAILABLE\",\n message:\n \"Idempotency-Key in flight; the original request has not finished, retry later\",\n });\n }\n if (outcome.deduped) {\n throw new TRPCError({\n code: \"CONFLICT\",\n message:\n \"Idempotency-Key already used; original result not cached\",\n });\n }\n return outcome.result;\n }\n\n return await app.do(\n action_name as never,\n target as never,\n input as never\n );\n } catch (err) {\n if (err instanceof TRPCError) throw err;\n throw to_trpc_error(err);\n }\n });\n }\n\n if (options.sse) {\n // SSE subscriptions mount under the `subscribe` key of the same router\n // as the action mutations, so an action named `subscribe` would be\n // silently replaced. Refuse it at generation instead.\n if (\"subscribe\" in app.registry.actions)\n throw new Error(\n 'trpc: an action named \"subscribe\" collides with the SSE subscription router (router.subscribe.<stateName>); rename the action or generate the router without `sse`.'\n );\n const sse_config = resolveSseConfig(options.sse);\n const sse_counter = new SseConnectionCounter(sse_config.maxConnections);\n const state_names = new Set<string>();\n for (const action of Object.values(app.registry.actions)) {\n state_names.add(action.name);\n }\n const sse_handlers: Record<string, unknown> = {};\n for (const state_name of state_names) {\n sse_handlers[state_name] = t.procedure\n .input(z.object({ stream: z.string().min(1) }))\n .subscription(async function* ({ input, ctx, signal }) {\n // Step 1 of the documented subscription contract: the actor\n // extractor runs before a slot is taken or a frame is yielded,\n // so a denying extractor denies the open. Hono gets this from\n // the `authenticated` middleware it mounts across `/api/*`;\n // this generator is where the same rule lives for tRPC, which\n // resolves the actor inline rather than through middleware.\n await resolve_actor(ctx as unknown as Ctx);\n yield* runSseSubscription(\n sse_config.channel,\n input.stream,\n sse_counter,\n signal,\n {\n maxPending: sse_config.maxPendingPerConnection,\n on_cap_exceeded: () => {\n throw new TRPCError({\n code: \"TOO_MANY_REQUESTS\",\n message: \"max concurrent SSE subscriptions reached\",\n });\n },\n }\n );\n });\n }\n handlers.subscribe = t.router(sse_handlers as never) as never;\n }\n\n // The runtime router IS structurally compatible with\n // `GeneratedRouter<TApp>` (one mutation per action key), but tRPC's\n // `BuiltRouter` carries an internal `Unwrap<Ctx>` that the d.ts\n // emitter can't name portably. Bridging through `unknown` keeps the\n // caller-visible type clean (specific procedure names, no\n // index-signature widening that trips React tRPC's collision check).\n return t.router(handlers) as unknown as GeneratedRouter<TApp>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoDA,SAAkC,gBAAgB;AAElD;AAAA,EAIE;AAAA,EAEA;AAAA,OACK;AAkHA,SAAS,cACd,WAC2B;AAQ3B,QAAM,aAAa,eAAe,iBAAiB;AAAA,IACjD;AAAA,IACA;AAAA,EACF,GAGG;AACD,UAAM,QAAQ,MAAM,UAAU,GAAG;AACjC,WAAO,KAAK,EAAE,KAAK,EAAE,GAAG,KAAK,MAAM,EAAE,CAAC;AAAA,EACxC;AACA,SAAO;AACT;AAcA,SAAS,cAAc,KAAyB;AAC9C,QAAM,EAAE,QAAQ,KAAK,I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AACxD,kBAAY,IAAI,OAAO,IAAI;AAAA,IAC7B;AACA,UAAM,eAAwC,CAAC;AAC/C,eAAW,cAAc,aAAa;AACpC,mBAAa,UAAU,IAAI,EAAE,UAC1B,MAAM,iBAAE,OAAO,EAAE,QAAQ,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,EAC7C,aAAa,iBAAiB,EAAE,OAAO,KAAK,OAAO,GAAG;AAOrD,cAAM,cAAc,GAAqB;AACzC,eAAO;AAAA,UACL,WAAW;AAAA,UACX,MAAM;AAAA,UACN;AAAA,UACA;AAAA,UACA;AAAA,YACE,YAAY,WAAW;AAAA,YACvB,iBAAiB,MAAM;AACrB,oBAAM,IAAI,UAAU;AAAA,gBAClB,MAAM;AAAA,gBACN,SAAS;AAAA,cACX,CAAC;AAAA,YACH;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACL;AACA,aAAS,YAAY,EAAE,OAAO,YAAqB;AAAA,EACrD;AAQA,SAAO,EAAE,OAAO,QAAQ;AAC1B;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rotorsoft/act-http",
3
3
  "type": "module",
4
- "version": "1.10.21",
4
+ "version": "1.10.22",
5
5
  "description": "HTTP integrations for act apps — webhooks and SSE",
6
6
  "keywords": [
7
7
  "typescript",
@@ -91,7 +91,7 @@
91
91
  },
92
92
  "peerDependencies": {
93
93
  "@hono/node-server": "^2.1.5",
94
- "@rotorsoft/act": "^1.33.10",
94
+ "@rotorsoft/act": "^1.33.16",
95
95
  "@rotorsoft/act-ops": "^0.2.10",
96
96
  "@trpc/server": ">=11.19.0",
97
97
  "express": "^5.3.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/api/errors.ts","../src/api/idempotency.ts","../src/api/sse-wiring.ts"],"sourcesContent":["import {\n ConcurrencyError,\n InvariantError,\n NonRetryableError,\n StreamClosedError,\n ValidationError,\n} from \"@rotorsoft/act\";\n\n/**\n * Uniform error envelope shipped over the wire by every act-http\n * transport. Hosts get the same shape from REST, tRPC, and OpenAPI —\n * a client that talks to two transports doesn't have to invent two\n * error parsers.\n *\n * - `error` — the framework error name (`\"ValidationError\"`,\n * `\"InvariantError\"`, …). Stable identifier, safe to switch on.\n * - `detail` — the framework's message text. Human-readable; not\n * parsed by clients.\n * - `code` — a machine-readable status code from {@link ERROR_MAP}\n * for clients that prefer enum-style branching over name strings.\n */\nexport type ApiError = {\n error: string;\n detail?: string;\n code?: string;\n};\n\n/**\n * Status + code pair for one known framework error.\n */\nexport type ErrorMapEntry = {\n status: number;\n code: string;\n};\n\n/**\n * The single table that maps framework error types to HTTP status\n * codes and machine-readable codes. One table, three consumers\n * (Hono, tRPC, OpenAPI) — cross-transport consistency by\n * construction.\n *\n * Operators wanting different mappings wrap the generated transport\n * rather than mutating this — the consistency is the load-bearing\n * property, not the specific status codes.\n */\nexport const ERROR_MAP = {\n ValidationError: { status: 422, code: \"VALIDATION\" },\n InvariantError: { status: 409, code: \"INVARIANT\" },\n ConcurrencyError: { status: 412, code: \"CONCURRENCY\" },\n StreamClosedError: { status: 410, code: \"STREAM_CLOSED\" },\n NonRetryableError: { status: 400, code: \"NON_RETRYABLE\" },\n} as const satisfies Record<string, ErrorMapEntry>;\n\nconst lookup_known = (\n err: unknown\n): { name: keyof typeof ERROR_MAP } | null => {\n if (err instanceof ValidationError) return { name: \"ValidationError\" };\n if (err instanceof InvariantError) return { name: \"InvariantError\" };\n if (err instanceof ConcurrencyError) return { name: \"ConcurrencyError\" };\n if (err instanceof StreamClosedError) return { name: \"StreamClosedError\" };\n if (err instanceof NonRetryableError) return { name: \"NonRetryableError\" };\n return null;\n};\n\n/**\n * Translate an unknown thrown value into the canonical\n * {@link ApiError} envelope plus HTTP status. Each transport's error\n * boundary calls this once and forwards the result to the wire.\n *\n * Known framework errors map per {@link ERROR_MAP}. Everything else\n * surfaces as a 500 with `code: \"INTERNAL\"`; the `detail` field is\n * populated when the throw was an `Error` instance, omitted\n * otherwise (a thrown string or object doesn't get to leak its\n * payload to the client).\n */\nexport function toApiError(err: unknown): { status: number; body: ApiError } {\n const known = lookup_known(err);\n if (known) {\n const entry = ERROR_MAP[known.name];\n return {\n status: entry.status,\n body: {\n error: known.name,\n detail: (err as Error).message,\n code: entry.code,\n },\n };\n }\n if (err instanceof Error) {\n return {\n status: 500,\n body: { error: \"InternalError\", detail: err.message, code: \"INTERNAL\" },\n };\n }\n return {\n status: 500,\n body: { error: \"InternalError\", code: \"INTERNAL\" },\n };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * Result of a {@link withIdempotency} call.\n *\n * - `{ deduped: false, result }` — the claim was fresh; the handler\n * ran and produced `result`.\n * - `{ deduped: true }` — the claim was already taken; the handler\n * was *not* invoked. The caller decides how to respond (typically\n * a 2xx with no body, matching the receiver-side convention).\n *\n * Note: the contract does not cache the previous response. A\n * duplicate call returns the deduped marker only — replaying the\n * original handler's output would require a response-caching\n * adapter, which is out of scope here. The receiver-side convention\n * (and the convention the generated transports follow) is \"ack the\n * duplicate; do nothing else.\"\n */\nexport type IdempotencyResult<T> =\n | { deduped: false; result: T }\n | { deduped: true };\n\n/**\n * Wrap an action handler so the framework honors `Idempotency-Key`\n * dedup. Acquires the key via {@link IdempotencyStore.claim} (a\n * *tentative* reservation), runs the handler exactly when the claim\n * was fresh, and skips the handler entirely on a duplicate.\n *\n * The claim is finalized two-phase: on handler success the key is\n * {@link IdempotencyStore.commit committed} so later retries dedup;\n * on handler failure it is {@link IdempotencyStore.release released}\n * and the rejection re-thrown, so the sender's retry re-processes\n * instead of the delivery being permanently dropped. The tentative\n * claim still dedups a concurrent duplicate mid-flight.\n *\n * Reuses the contract `@rotorsoft/act-ops/idempotency` already\n * defines for the receiver-side `Idempotency-Key` story. A single\n * `IdempotencyStore` implementation covers both halves of the \"Act\n * over the wire\" surface — receiver and generated API.\n */\nexport async function withIdempotency<T>(\n store: IdempotencyStore,\n key: string,\n handler: () => Promise<T>\n): Promise<IdempotencyResult<T>> {\n const fresh = await store.claim(key);\n if (!fresh) {\n return { deduped: true };\n }\n let result: T;\n try {\n result = await handler();\n } catch (err) {\n await store.release(key);\n throw err;\n }\n await store.commit(key);\n return { deduped: false, result };\n}\n","import { z } from \"zod\";\nimport type { BroadcastChannel } from \"../sse/broadcast.js\";\nimport {\n type BroadcastState,\n is_version_neutral,\n type PatchMessage,\n resync_frame,\n} from \"../sse/types.js\";\n\n/**\n * SSE wiring options shared by the auto-generated `trpc` and `hono`\n * transports. When supplied, each transport emits one streaming\n * subscription per registered state name, all reading from the same\n * host-supplied {@link BroadcastChannel}.\n *\n * The host owns publication: every `app.do(...)` call site must\n * forward the resulting snapshots to `channel.publish(...)` for\n * subscribers to see updates. The framework deliberately doesn't\n * auto-publish because the derived state usually needs app-specific\n * overlays (presence, computed fields) that only the host can supply.\n *\n * Defaults are sized for typical business-app dashboards (dozens to\n * hundreds of human viewers per process). Both numeric knobs are\n * validated at transport-function construction; out-of-range values\n * throw `ZodError` immediately so misconfiguration surfaces at startup\n * instead of at first connection (the framework-wide convention for\n * config bags — see CLAUDE.md § Config-validation schemas).\n */\nexport type SseOptions = {\n /**\n * The {@link BroadcastChannel} the generator's subscriptions hook\n * into. Host owns its lifecycle; the generator does not construct\n * one for you because the channel's `<S>` shape is app-specific and\n * passing it in keeps the type chain typed end-to-end at the host.\n */\n // `any`: the channel's BroadcastState shape is opaque to the generator — narrowing it would force every state into one structural bound that doesn't fit real apps\n readonly channel: BroadcastChannel<any>;\n /**\n * Hard cap on concurrent open subscriptions per generator\n * instance. The 501st simultaneous open returns `503` (Hono) or\n * throws `TOO_MANY_REQUESTS` (tRPC) — never a silent stall.\n *\n * Default `500`. Validated range `[1, 10_000]`. Above 10k the\n * framework refuses to construct: at that point the FD ceiling\n * and per-connection memory force horizontal scaling regardless\n * of tuning, so the right move is sticky LB + per-process cap,\n * not a higher single-process limit.\n */\n readonly maxConnections?: number;\n /**\n * Keep-alive cadence in milliseconds. Most reverse proxies idle\n * connections out after ~60 seconds; the default `30_000` stays\n * comfortably under.\n *\n * Validated range `[15_000, 300_000]`. Under 15 s wastes\n * bandwidth on a business workload; over 5 min risks proxy drops.\n */\n readonly heartbeatMs?: number;\n /**\n * Hard cap on the per-connection in-memory backlog of undelivered\n * broadcast frames. A consumer that stalls (slow client, paused\n * tab) can't drain frames as fast as a busy stream publishes them;\n * without a bound the backlog grows until the process runs out of\n * memory. When the backlog is full the oldest **version-keyed** frame\n * is dropped to make room for the newest: the consumer sees the\n * version gap, reports `behind`, and refetches, so it still converges\n * on current state having skipped intermediate versions it was too\n * slow to see.\n *\n * Version-neutral frames (`_overlay`, `_resync`) are never dropped\n * silently — they create no gap to notice, so a backlog made only of\n * them collapses into a single `_resync` instead (#1649).\n *\n * Default `256`. Validated range `[1, 100_000]`.\n */\n readonly maxPendingPerConnection?: number;\n};\n\n/**\n * Resolved SSE configuration after validation and default expansion.\n * Internal — the resolved values are what every transport actually\n * runs against.\n *\n * @internal\n */\nexport type SseConfig = {\n readonly channel: BroadcastChannel<BroadcastState>;\n readonly maxConnections: number;\n readonly heartbeatMs: number;\n readonly maxPendingPerConnection: number;\n};\n\n/**\n * Default cap on concurrent open subscriptions per generator\n * instance. Sized for typical business-app dashboards (dozens to a\n * few hundred viewers); high enough not to surprise small\n * deployments, low enough not to mask a missing horizontal-scale\n * strategy on big ones.\n */\nexport const DEFAULT_SSE_MAX_CONNECTIONS = 500;\n\n/**\n * Default keep-alive cadence (30 s). Sits comfortably under the\n * 60 s idle timeout most reverse proxies impose.\n */\nexport const DEFAULT_SSE_HEARTBEAT_MS = 30_000;\n\n/**\n * Default cap on the per-connection undelivered-frame backlog. Sized\n * so a briefly-stalled consumer on a busy stream keeps recent history\n * without letting a permanently-wedged client pin unbounded memory.\n * At overflow the oldest version-keyed frame is dropped: it is a full\n * version-keyed patch, so the consumer sees the gap and converges on\n * current state regardless of which intermediate versions it missed.\n * Version-neutral frames create no gap, so they collapse into a\n * `_resync` rather than being dropped silently (#1649).\n */\nexport const DEFAULT_SSE_MAX_PENDING_PER_CONNECTION = 256;\n\n/**\n * Zod schema for the numeric knobs on {@link SseOptions}. Defaults,\n * ranges, and (eventual) integer constraints live in one place — same\n * declarative-validation pattern the rest of the framework uses for\n * configuration shapes.\n *\n * @internal\n */\nconst SseOptionsSchema = z.object({\n maxConnections: z\n .number()\n .int()\n .min(1)\n .max(10_000)\n .default(DEFAULT_SSE_MAX_CONNECTIONS),\n heartbeatMs: z\n .number()\n .int()\n .min(15_000)\n .max(300_000)\n .default(DEFAULT_SSE_HEARTBEAT_MS),\n maxPendingPerConnection: z\n .number()\n .int()\n .min(1)\n .max(100_000)\n .default(DEFAULT_SSE_MAX_PENDING_PER_CONNECTION),\n});\n\n/**\n * Validate and apply defaults to host-supplied {@link SseOptions}.\n *\n * Out-of-range values throw at the call site — each transport calls\n * this once at the start of `hono(...)` / `trpc(...)` so\n * misconfiguration surfaces at construction, not at first\n * connection.\n */\nexport function resolveSseConfig(options: SseOptions): SseConfig {\n const parsed = SseOptionsSchema.parse({\n maxConnections: options.maxConnections,\n heartbeatMs: options.heartbeatMs,\n maxPendingPerConnection: options.maxPendingPerConnection,\n });\n return {\n channel: options.channel,\n maxConnections: parsed.maxConnections,\n heartbeatMs: parsed.heartbeatMs,\n maxPendingPerConnection: parsed.maxPendingPerConnection,\n };\n}\n\n/**\n * Per-generator concurrent-open counter. Constructed once inside\n * `hono(...)` / `trpc(...)` and consulted at every subscription\n * open: failure to acquire means the cap has been hit and the\n * transport reports `503` / `TOO_MANY_REQUESTS` to the caller.\n *\n * The counter is intentionally process-local. SSE doesn't multiplex\n * across processes; operators wanting more than `maxConnections`\n * viewers run multiple processes behind a sticky load balancer.\n */\nexport class SseConnectionCounter {\n public readonly limit: number;\n private _open = 0;\n\n constructor(limit: number) {\n this.limit = limit;\n }\n\n /**\n * Reserve one slot. Returns `true` when accepted (caller must\n * eventually {@link release} the slot, even on error paths) or\n * `false` when the cap is already reached.\n */\n acquire(): boolean {\n if (this._open >= this.limit) return false;\n this._open++;\n return true;\n }\n\n /**\n * Free a previously-{@link acquire}d slot. Always runs from a\n * `finally` block in the transport's subscription handler so\n * crashed handlers don't leak count.\n */\n release(): void {\n if (this._open > 0) this._open--;\n }\n\n /** Currently-open count. Test/observability hook. */\n get open(): number {\n return this._open;\n }\n}\n\n/**\n * Wrap a fire-and-forget Promise-returning operation so its\n * rejection is swallowed in place of leaking an unhandled\n * rejection. Used by the Hono heartbeat tick (the interval callback\n * isn't `await`ed, so its rejection has nowhere to go) and by any\n * other \"best-effort write\" the transports run.\n *\n * Pure: same input → same output, no side effects on the caller.\n * Returns the chained Promise so the caller can also `await`\n * completion if they want to (the Hono heartbeat doesn't).\n */\nexport function fireAndForget<T>(op: () => Promise<T>): Promise<T | undefined> {\n return op().catch(() => undefined);\n}\n\n/**\n * Frame yielded by the per-state SSE subscription generator. The\n * initial cached state (when present) arrives as `kind: \"state\"`;\n * every subsequent broadcast publication arrives as `kind: \"patch\"`\n * with the channel's `PatchMessage` payload.\n */\nexport type SseSubscriptionFrame<S> =\n | { readonly kind: \"state\"; readonly data: S }\n | { readonly kind: \"patch\"; readonly data: unknown };\n\n/**\n * Subscription accounting hook. Implementations have a chance to\n * acquire a slot before the loop starts and to release it once the\n * loop's `finally` block runs — used by the tRPC side to enforce\n * `maxConnections` from inside the generator, where it can throw\n * `TRPCError` cleanly. Hono enforces the cap outside the loop (so a\n * full counter returns `503` *before* streamSSE writes headers), then\n * passes `undefined` here.\n */\nexport type SseAccounting = {\n acquire(): boolean;\n release(): void;\n};\n\n/**\n * Per-subscription knobs for {@link runSseSubscription}, bundled so the\n * two transports (and their tests) pass one options object rather than\n * a growing positional tail.\n */\nexport type RunSseOptions = {\n /**\n * Invoked when {@link SseAccounting.acquire} returns `false` (the\n * connection cap is full). tRPC throws `TRPCError` here to reject the\n * subscription cleanly from inside the generator; Hono enforces the\n * cap outside the loop and omits this.\n */\n readonly on_cap_exceeded?: () => never;\n /**\n * Upper bound on the per-connection undelivered-frame backlog. When\n * the backlog reaches this many frames the oldest is dropped to make\n * room for the newest (drop-oldest). Defaults to\n * {@link DEFAULT_SSE_MAX_PENDING_PER_CONNECTION} when omitted.\n */\n readonly maxPending?: number;\n};\n\n/**\n * The shared subscription loop both transports run. Optionally\n * acquires one slot on the supplied {@link SseAccounting}, yields the\n * cached state (when present), then forwards every channel\n * publication as a `kind: \"patch\"` frame until either the consumer\n * breaks (calling `iter.return()`) or the supplied abort signal fires.\n *\n * Exported as the testable seam — the Hono and tRPC sibling\n * generators wrap this so the signal-driven cleanup and counter\n * accounting live in one place.\n */\n// `any`: the channel's BroadcastState shape is opaque to the loop — narrowing it would force every state into one structural bound that doesn't fit real apps\nexport async function* runSseSubscription<S extends { _v: number } = any>(\n channel: BroadcastChannel<S>,\n stream_id: string,\n accounting: SseAccounting | undefined,\n signal: AbortSignal | undefined,\n options?: RunSseOptions\n): AsyncGenerator<SseSubscriptionFrame<S>> {\n // Track whether we actually reserved a slot. Releasing in `finally`\n // unconditionally would decrement the counter below the true open\n // count when acquire() fails without an `on_cap_exceeded` handler —\n // inflating the effective cap over time. Only release what we\n // acquired.\n let acquired = false;\n if (accounting) {\n acquired = accounting.acquire();\n if (!acquired && options?.on_cap_exceeded) {\n options.on_cap_exceeded();\n }\n }\n const max_pending =\n options?.maxPending ?? DEFAULT_SSE_MAX_PENDING_PER_CONNECTION;\n const pending: unknown[] = [];\n let resolve_wait: (() => void) | null = null;\n const unsubscribe = channel.subscribe(stream_id, (msg) => {\n enqueue(msg as PatchMessage<never>);\n resolve_wait?.();\n });\n /**\n * Bound the per-connection backlog: a stalled consumer (slow client,\n * paused tab) can't drain as fast as a busy stream publishes, so a frame\n * has to go.\n *\n * Which frame is not arbitrary. A version-keyed patch can be dropped\n * safely — the client sees the version gap, reports `behind`, and\n * refetches. A version-neutral frame (`_overlay`, `_resync`) carries no\n * versions at all, so dropping one leaves no gap to notice and the update\n * is lost silently (#1649). So: evict the oldest version-keyed frame if\n * there is one, and only if the whole backlog is version-neutral collapse\n * it into the single frame that says \"you missed something\".\n */\n const enqueue = (msg: PatchMessage<never>) => {\n if (pending.length < max_pending) {\n pending.push(msg);\n return;\n }\n const versioned = pending.findIndex(\n (m) => !is_version_neutral(m as PatchMessage<never>)\n );\n if (versioned >= 0) {\n pending.splice(versioned, 1);\n pending.push(msg);\n return;\n }\n // Every pending frame is version-neutral. Collapsing them into one\n // resync loses no signal — a resync supersedes anything it replaces,\n // including `msg` when the cap leaves no room for it.\n pending.splice(0, pending.length, resync_frame());\n if (pending.length < max_pending) pending.push(msg);\n };\n\n const on_abort = () => resolve_wait?.();\n signal?.addEventListener(\"abort\", on_abort);\n try {\n const cached = channel.state(stream_id);\n if (cached !== undefined) {\n yield { kind: \"state\", data: cached };\n }\n while (!signal?.aborted) {\n if (pending.length === 0) {\n await new Promise<void>((resolve) => {\n resolve_wait = resolve;\n });\n if (signal?.aborted) break;\n }\n const msg = pending.shift();\n yield { kind: \"patch\", data: msg };\n }\n } finally {\n signal?.removeEventListener(\"abort\", on_abort);\n unsubscribe();\n if (acquired) accounting?.release();\n }\n}\n"],"mappings":";;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuCA,IAAM,YAAY;AAAA,EACvB,iBAAiB,EAAE,QAAQ,KAAK,MAAM,aAAa;AAAA,EACnD,gBAAgB,EAAE,QAAQ,KAAK,MAAM,YAAY;AAAA,EACjD,kBAAkB,EAAE,QAAQ,KAAK,MAAM,cAAc;AAAA,EACrD,mBAAmB,EAAE,QAAQ,KAAK,MAAM,gBAAgB;AAAA,EACxD,mBAAmB,EAAE,QAAQ,KAAK,MAAM,gBAAgB;AAC1D;AAEA,IAAM,eAAe,CACnB,QAC4C;AAC5C,MAAI,eAAe,gBAAiB,QAAO,EAAE,MAAM,kBAAkB;AACrE,MAAI,eAAe,eAAgB,QAAO,EAAE,MAAM,iBAAiB;AACnE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oC;AACxC,QAAM,cAAc,QAAQ,UAAU,WAAW,CAAC,QAAQ;AACxD,YAAQ,GAA0B;AAClC,mBAAe;AAAA,EACjB,CAAC;AAcD,QAAM,UAAU,CAAC,QAA6B;AAC5C,QAAI,QAAQ,SAAS,aAAa;AAChC,cAAQ,KAAK,GAAG;AAChB;AAAA,IACF;AACA,UAAM,YAAY,QAAQ;AAAA,MACxB,CAAC,MAAM,CAAC,mBAAmB,CAAwB;AAAA,IACrD;AACA,QAAI,aAAa,GAAG;AAClB,cAAQ,OAAO,WAAW,CAAC;AAC3B,cAAQ,KAAK,GAAG;AAChB;AAAA,IACF;AAIA,YAAQ,OAAO,GAAG,QAAQ,QAAQ,aAAa,CAAC;AAChD,QAAI,QAAQ,SAAS,YAAa,SAAQ,KAAK,GAAG;AAAA,EACpD;AAEA,QAAM,WAAW,MAAM,eAAe;AACtC,UAAQ,iBAAiB,SAAS,QAAQ;AAC1C,MAAI;AACF,UAAM,SAAS,QAAQ,MAAM,SAAS;AACtC,QAAI,WAAW,QAAW;AACxB,YAAM,EAAE,MAAM,SAAS,MAAM,OAAO;AAAA,IACtC;AACA,WAAO,CAAC,QAAQ,SAAS;AACvB,UAAI,QAAQ,WAAW,GAAG;AACxB,cAAM,IAAI,QAAc,CAAC,YAAY;AACnC,yBAAe;AAAA,QACjB,CAAC;AACD,YAAI,QAAQ,QAAS;AAAA,MACvB;AACA,YAAM,MAAM,QAAQ,MAAM;AAC1B,YAAM,EAAE,MAAM,SAAS,MAAM,IAAI;AAAA,IACnC;AAAA,EACF,UAAE;AACA,YAAQ,oBAAoB,SAAS,QAAQ;AAC7C,gBAAY;AACZ,QAAI,SAAU,aAAY,QAAQ;AAAA,EACpC;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/receiver/hono/index.ts"],"sourcesContent":["/**\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_finalizers } 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 { commit, release } = make_finalizers(\n options.store,\n result.key,\n result.deduped\n );\n c.set(\"idempotency\", {\n key: result.key,\n deduped: result.deduped,\n commit,\n release,\n });\n try {\n await next();\n } catch (err) {\n await 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 release();\n else await 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":";;;;;;AA8EO,SAAS,kBACd,SACoD;AACpD,SAAO,eAAe,MAAM,GAAG,MAAM;AACnC,UAAM,UAAU,YAAY,EAAE,IAAI,IAAI,OAAO;AAC7C,UAAM,UAAU,MAAM,EAAE,IAAI,KAAK;AACjC,UAAM,SAAS,MAAM,aAAa,SAAS,SAAS,OAAO;AAC3D,QAAI,CAAC,OAAO,IAAI;AACd,aAAO,EAAE,KAAK,EAAE,OAAO,OAAO,OAAO,GAAG,OAAO,MAAM;AAAA,IACvD;AACA,UAAM,EAAE,QAAQ,QAAQ,IAAI;AAAA,MAC1B,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,OAAO;AAAA,IACT;AACA,MAAE,IAAI,eAAe;AAAA,MACnB,KAAK,OAAO;AAAA,MACZ,SAAS,OAAO;AAAA,MAChB;AAAA,MACA;AAAA,IACF,CAAC;AACD,QAAI;AACF,YAAM,KAAK;AAAA,IACb,SAAS,KAAK;AACZ,YAAM,QAAQ;AACd,YAAM;AAAA,IACR;AAIA,QAAI,EAAE,IAAI,UAAU,IAAK,OAAM,QAAQ;AAAA,QAClC,OAAM,OAAO;AAAA,EACpB;AACF;AAEA,SAAS,YACP,SAC+C;AAC/C,QAAM,MAAqD,CAAC;AAC5D,UAAQ,QAAQ,CAAC,OAAO,QAAQ;AAC9B,QAAI,GAAG,IAAI;AAAA,EACb,CAAC;AACD,SAAO;AACT;","names":[]}