@rotorsoft/act-http 1.8.5 → 1.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/@types/api/errors.d.ts.map +1 -1
- package/dist/@types/api/index.d.ts +1 -1
- package/dist/@types/api/index.d.ts.map +1 -1
- package/dist/@types/api/sse-wiring.d.ts +45 -1
- package/dist/@types/api/sse-wiring.d.ts.map +1 -1
- package/dist/@types/hono/index.d.ts.map +1 -1
- package/dist/@types/sse/broadcast.d.ts.map +1 -1
- package/dist/@types/sse/presence.d.ts.map +1 -1
- package/dist/@types/sse/state-cache.d.ts.map +1 -1
- package/dist/@types/trpc/index.d.ts.map +1 -1
- package/dist/@types/webhook/types.d.ts.map +1 -1
- package/dist/api/index.cjs +19 -7
- package/dist/api/index.cjs.map +1 -1
- package/dist/api/index.js +3 -1
- package/dist/{chunk-FIYLGJAE.js → chunk-IKLTEKBL.js} +19 -8
- package/dist/chunk-IKLTEKBL.js.map +1 -0
- package/dist/hono/index.cjs +19 -8
- package/dist/hono/index.cjs.map +1 -1
- package/dist/hono/index.js +3 -2
- package/dist/hono/index.js.map +1 -1
- package/dist/trpc/index.cjs +25 -12
- package/dist/trpc/index.cjs.map +1 -1
- package/dist/trpc/index.js +9 -6
- package/dist/trpc/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-FIYLGJAE.js.map +0 -1
package/dist/hono/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
runSseSubscription,
|
|
6
6
|
toApiError,
|
|
7
7
|
withIdempotency
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-IKLTEKBL.js";
|
|
9
9
|
import "../chunk-WGFX4G27.js";
|
|
10
10
|
import "../chunk-PZ5AY32C.js";
|
|
11
11
|
|
|
@@ -104,7 +104,8 @@ function hono(app, options) {
|
|
|
104
104
|
sse_config.channel,
|
|
105
105
|
stream_id,
|
|
106
106
|
void 0,
|
|
107
|
-
controller.signal
|
|
107
|
+
controller.signal,
|
|
108
|
+
{ maxPending: sse_config.maxPendingPerConnection }
|
|
108
109
|
)) {
|
|
109
110
|
await sse_stream.writeSSE({
|
|
110
111
|
event: frame.kind,
|
package/dist/hono/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../node_modules/.pnpm/@hono+zod-validator@0.8.0_hono@4.12.27_zod@4.4.3/node_modules/@hono/zod-validator/src/index.ts","../../src/hono/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Context, Env, Input, MiddlewareHandler, TypedResponse, ValidationTargets } from 'hono'\nimport { validator } from 'hono/validator'\nimport type * as v3 from 'zod/v3'\nimport type { ZodSafeParseResult as v4ZodSafeParseResult } from 'zod/v4'\nimport type * as v4 from 'zod/v4/core'\nimport type { InferInput } from './utils'\n\ntype ZodSchema = v3.ZodType | v4.$ZodType\ntype ZodError<T extends ZodSchema> = T extends v4.$ZodType\n ? v4.$ZodError<v4.output<T>>\n : v3.ZodError\ntype ZodSafeParseResult<T, T2, T3 extends ZodSchema> = T3 extends v4.$ZodType\n ? v4ZodSafeParseResult<T>\n : v3.SafeParseReturnType<T, T2>\ntype zInput<T> = T extends v3.ZodType ? v3.input<T> : T extends v4.$ZodType ? v4.input<T> : never\ntype zOutput<T> = T extends v3.ZodType ? v3.output<T> : T extends v4.$ZodType ? v4.output<T> : never\ntype zInfer<T> = T extends v3.ZodType ? v3.infer<T> : T extends v4.$ZodType ? v4.infer<T> : never\n\n// Failure variant of `safeParseAsync`'s return value.\n// Mirrors the runtime body returned by `c.json(result, 400)` on validation failure.\ntype ZodValidatorFailureBody<T extends ZodSchema> = T extends v4.$ZodType\n ? Extract<v4ZodSafeParseResult<v4.output<T>>, { success: false }>\n : T extends v3.ZodType\n ? Extract<v3.SafeParseReturnType<v3.input<T>, v3.output<T>>, { success: false }>\n : never\n\ntype ZodValidatorFailureResponse<T extends ZodSchema> = Response &\n TypedResponse<ZodValidatorFailureBody<T>, 400, 'json'>\n\nexport type Hook<\n T,\n E extends Env,\n P extends string,\n Target extends keyof ValidationTargets = keyof ValidationTargets,\n O = {},\n Schema extends ZodSchema = any,\n> = (\n result: ({ success: true; data: T } | { success: false; error: ZodError<Schema>; data: T }) & {\n target: Target\n },\n c: Context<E, P>\n) => Response | void | TypedResponse<O> | Promise<Response | void | TypedResponse<O>>\n\ntype HasUndefined<T> = undefined extends T ? true : false\n\ntype ExtractValidationResponse<VF> = VF extends (value: any, c: any) => infer R\n ? R extends Promise<infer PR>\n ? PR extends TypedResponse<infer T, infer S, infer F>\n ? Response & TypedResponse<T, S, F>\n : PR extends Response\n ? PR\n : PR extends undefined\n ? never\n : never\n : R extends TypedResponse<infer T, infer S, infer F>\n ? Response & TypedResponse<T, S, F>\n : R extends Response\n ? R\n : R extends undefined\n ? never\n : never\n : never\n\ntype ValidationFunctionOption<T extends ZodSchema, Target extends keyof ValidationTargets> = {\n validationFunction: (\n schema: T,\n value: ValidationTargets[Target]\n ) => ZodSafeParseResult<any, any, T> | Promise<ZodSafeParseResult<any, any, T>>\n}\n\ntype DefaultInput<Target extends keyof ValidationTargets, In, Out> = {\n in: HasUndefined<In> extends true\n ? {\n [K in Target]?: [In] extends [ValidationTargets[K]] ? In : InferInput<In, K>\n }\n : {\n [K in Target]: [In] extends [ValidationTargets[K]] ? In : InferInput<In, K>\n }\n out: { [K in Target]: Out }\n}\n\n// without hook (with or without options)\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n>(\n target: Target,\n schema: T,\n hook?: undefined,\n options?: ValidationFunctionOption<T, Target>\n): MiddlewareHandler<E, P, V, ZodValidatorFailureResponse<T>>\n\n// with hook and options\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n HookFn extends Hook<InferredValue, E, P, Target, {}, T>,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n InferredValue = zInfer<T>,\n>(\n target: Target,\n schema: T,\n hook?: HookFn,\n options?: ValidationFunctionOption<T, Target>\n): MiddlewareHandler<E, P, V, ExtractValidationResponse<HookFn>>\n\n// implementation\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n HookFn extends Hook<InferredValue, E, P, Target, {}, T>,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n InferredValue = zInfer<T>,\n>(\n target: Target,\n schema: T,\n hook?: HookFn,\n options?: ValidationFunctionOption<T, Target>\n):\n | MiddlewareHandler<E, P, V, ZodValidatorFailureResponse<T>>\n | MiddlewareHandler<E, P, V, ExtractValidationResponse<HookFn>> {\n // @ts-expect-error not typed well\n return validator(target, async (value: ValidationTargets[Target], c) => {\n let validatorValue = value\n\n // in case where our `target` === `header`, Hono parses all of the headers into lowercase.\n // this might not match the Zod schema, so we want to make sure that we account for that when parsing the schema.\n if ((target === 'header' && '_def' in schema) || (target === 'header' && '_zod' in schema)) {\n // create an object that maps lowercase schema keys to lowercase\n // @ts-expect-error the schema is a Zod Schema\n const schemaKeys = Object.keys('in' in schema ? schema.in.shape : schema.shape)\n const caseInsensitiveKeymap = Object.fromEntries(\n schemaKeys.map((key) => [key.toLowerCase(), key])\n )\n\n validatorValue = Object.fromEntries(\n Object.entries(value).map(([key, value]) => [caseInsensitiveKeymap[key] || key, value])\n )\n }\n\n const result =\n options && options.validationFunction\n ? await options.validationFunction(schema, validatorValue)\n : // @ts-expect-error z4.$ZodType has safeParseAsync\n await schema.safeParseAsync(validatorValue)\n\n if (hook) {\n const hookResult = await hook({ data: validatorValue, ...result, target }, c)\n if (hookResult) {\n if (hookResult instanceof Response) {\n return hookResult\n }\n\n if ('response' in hookResult) {\n return hookResult.response\n }\n }\n }\n\n if (!result.success) {\n return c.json(result, 400)\n }\n\n return result.data as zInfer<T>\n })\n}\n\nexport const zValidator: typeof zValidatorFunction = zValidatorFunction\n","/**\n * @packageDocumentation\n * @module act-http/hono\n *\n * Hono subpath for the auto-generated API epic (#835). Walks the\n * registry of a built `Act` once at function call and emits a Hono\n * app with one `POST /actions/<name>` route per registered action,\n * Zod-validated bodies, and the shared error envelope.\n *\n * Usage:\n *\n * ```ts\n * import { hono } from \"@rotorsoft/act-http/hono\";\n *\n * const api = hono(app, {\n * actor: (c) => ({ id: c.req.header(\"x-user-id\")!, name: \"...\" }),\n * stream: (action, input, c) => `tenant-${c.req.header(\"x-tenant\")}`,\n * });\n *\n * // Mounts at /api by default — pass `basePath` to override.\n * // POST /api/actions/OpenTicket body: { title } → 200 Snapshot[] | 4xx ApiError\n * ```\n *\n * The route shape matches the flat tRPC sibling at\n * `@rotorsoft/act-http/trpc`: one endpoint per action, no\n * state-name tier. Action names are unique across the registry —\n * the framework enforces no duplicates — so an extra namespace\n * level would be overhead. Queries live in a follow-up; this\n * slice is mutations only.\n *\n * **Actor lives on the context.** The generator wires an internal\n * middleware that runs the host's\n * {@link HonoOptions.actor | actor extractor} once per call and\n * stashes the resolved {@link Actor} under `c.get(\"actor\")`. Every\n * generated route reads from there — auth resolves at one seam,\n * downstream middleware (logging, tracing) sees the same actor.\n * The middleware factory is also exported as {@link authenticated}\n * for hosts that want to compose it into their own Hono chain\n * alongside hand-written routes.\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 (tRPC, this one,\n * OpenAPI) ride the same utilities so a client speaking two of\n * them never sees two shapes for the same framework error.\n */\nimport { zValidator } from \"@hono/zod-validator\";\nimport type { Actor, Target } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport { Hono } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport {\n type ActorExtractor,\n type ApiError,\n fireAndForget,\n resolveSseConfig,\n runSseSubscription,\n SseConnectionCounter,\n type SseOptions,\n toApiError,\n withIdempotency,\n} from \"../api/index.js\";\n\n/**\n * Hono context variables this subpath contributes. The generic on\n * the returned middleware threads it through so routes downstream\n * of {@link authenticated} see `c.get(\"actor\")` typed without a\n * manual cast.\n */\nexport type ActMiddlewareVariables = {\n actor: Actor;\n};\n\n/**\n * Per-call options for {@link hono}. The host supplies the four\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the Hono context, returns the\n * `Actor` that flows onto `c.get(\"actor\")` for every generated\n * route (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated body, and the Hono context; returns the target\n * stream. Singleton aggregates return a constant; per-tenant\n * aggregates pull from headers, path, or body.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * Hosts typically read it from an `If-Match` header on the\n * request, or from the client's last-known snapshot. Returning\n * `undefined` skips the check for that call — handy when only\n * some actions are concurrency-sensitive.\n * - `idempotency` (optional) — when set, the route honors\n * `Idempotency-Key` via {@link withIdempotency}. The host\n * supplies the `IdempotencyStore`; `keyFrom` defaults to reading\n * the `Idempotency-Key` header. On a duplicate claim, the route\n * responds `409 Conflict` — the contract intentionally doesn't\n * cache the original handler's result, matching the\n * receiver-side \"ack the duplicate\" semantics.\n * - `basePath` (optional, default `\"/api\"`) — Hono basePath the\n * routes mount under.\n */\nexport type HonoOptions = {\n readonly actor: ActorExtractor;\n readonly stream: (\n action_name: string,\n input: unknown,\n c: Context\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n c: Context\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom?: (c: Context) => string | undefined;\n };\n /**\n * Optional SSE wiring. When set, the generator emits one\n * `GET <basePath>/sse/<stateName>?stream=<streamId>` per unique\n * state name in the registry. The endpoint runs the host\n * {@link actor} extractor, looks up the streamId from\n * `?stream=...`, opens a `text/event-stream`, yields the cached\n * state (if any), and forwards every patch published to the\n * shared {@link SseOptions.channel}. A heartbeat keeps proxies\n * from idling the connection out; the per-process connection cap\n * returns `503 Service Unavailable` (with `Retry-After: 1`) when\n * full so operators never see silent stalls.\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 readonly basePath?: string;\n};\n\n/**\n * Build a Hono middleware that runs an {@link ActorExtractor} once\n * per call and stashes the resolved {@link Actor} under\n * `c.set(\"actor\", ...)` so downstream routes can read it via\n * `c.get(\"actor\")`. The generator at {@link hono} uses this\n * internally; it's also exported so hosts that want to compose\n * their own route chain (logging, tracing, custom auth flavors)\n * can wire it directly:\n *\n * ```ts\n * import { Hono } from \"hono\";\n * import { authenticated, type ActMiddlewareVariables } from \"@rotorsoft/act-http/hono\";\n *\n * const api = new Hono<{ Variables: ActMiddlewareVariables }>();\n * api.use(\"*\", authenticated((c) => resolveUserFromJwt(c)));\n * api.get(\"/me\", (c) => c.json(c.get(\"actor\"))); // typed\n * ```\n *\n * Errors thrown by the extractor surface as `401 Unauthorized` with\n * the shared {@link ApiError} envelope.\n */\nexport function authenticated(\n extractor: ActorExtractor\n): MiddlewareHandler<{ Variables: ActMiddlewareVariables }> {\n return async (c, next) => {\n try {\n const actor = await extractor(c);\n c.set(\"actor\", actor);\n await next();\n } catch (err) {\n const body: ApiError = {\n error: \"Unauthorized\",\n detail: err instanceof Error ? err.message : undefined,\n code: \"UNAUTHORIZED\",\n };\n return c.json(body, 401);\n }\n };\n}\n\nconst default_key_from = (c: Context): string | undefined =>\n c.req.header(\"idempotency-key\");\n\n/**\n * Build a typed Hono REST surface from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one\n * `POST /actions/<actionName>` per action under the configured\n * `basePath` (default `/api`). Each route:\n *\n * 1. Runs the internal {@link authenticated} middleware —\n * `options.actor` resolves the {@link Actor} once and stashes\n * it under `c.get(\"actor\")`.\n * 2. Validates the JSON body against the action's Zod schema via\n * `@hono/zod-validator`. Failures short-circuit with `422`.\n * 3. Resolves the target stream via\n * `options.stream(name, input, c)`.\n * 4. (Optionally) resolves `expectedVersion` for optimistic\n * concurrency.\n * 5. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — responds `409` on duplicate.\n * 6. Calls\n * `app.do(name, { stream, actor, expectedVersion? }, input)`.\n * 7. Maps any thrown framework error onto the shared\n * {@link ApiError} envelope via {@link toApiError}, returning\n * the conventional HTTP status (`409` / `412` for concurrency,\n * `422` for validation, `400` for non-retryable, etc.).\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, expected-version, idempotency, and\n * base-path seams.\n * @returns A Hono app covering every registered action under\n * `<basePath>/actions/<name>`.\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 keeps nested variance\n * out of the signature and avoids `any` in either direction.\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\nexport function hono<TApp extends ActSurface = ActSurface>(\n app: TApp,\n options: HonoOptions\n): Hono<{ Variables: ActMiddlewareVariables }> {\n const base_path = options.basePath ?? \"/api\";\n const api = new Hono<{ Variables: ActMiddlewareVariables }>().basePath(\n base_path\n );\n api.use(\"*\", authenticated(options.actor));\n\n const key_from = options.idempotency?.keyFrom ?? default_key_from;\n\n // Wire SSE subscriptions before the mutation routes so the\n // `/sse/*` paths sit alongside `/actions/*`. The cap counter is\n // shared by every state-name's GET route on this generator\n // instance so a noisy room on one state doesn't get a free pass\n // on another.\n if (options.sse) {\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 for (const state_name of state_names) {\n api.get(`/sse/${state_name}`, async (c) => {\n const stream_id = c.req.query(\"stream\");\n if (!stream_id) {\n const body: ApiError = {\n error: \"BadRequest\",\n detail: \"stream query parameter is required\",\n code: \"BAD_REQUEST\",\n };\n return c.json(body, 400);\n }\n if (!sse_counter.acquire()) {\n c.header(\"Retry-After\", \"1\");\n const body: ApiError = {\n error: \"ServiceUnavailable\",\n detail: \"max concurrent SSE connections reached\",\n code: \"SSE_BUSY\",\n };\n return c.json(body, 503);\n }\n // The route already acquired the slot above so streamSSE\n // could return `503` before writing headers if the cap was\n // full. The shared loop runs without accounting; the route\n // releases the slot in `finally`.\n const controller = new AbortController();\n return streamSSE(c, async (sse_stream) => {\n sse_stream.onAbort(() => controller.abort());\n const heartbeat = setInterval(() => {\n fireAndForget(() =>\n sse_stream.writeSSE({ event: \"ping\", data: \"\" })\n );\n }, sse_config.heartbeatMs);\n try {\n for await (const frame of runSseSubscription(\n sse_config.channel,\n stream_id,\n undefined,\n controller.signal\n )) {\n await sse_stream.writeSSE({\n event: frame.kind,\n data: JSON.stringify(frame.data),\n });\n }\n } finally {\n clearInterval(heartbeat);\n sse_counter.release();\n }\n });\n });\n }\n }\n\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n const schema = state.actions[action_name];\n api.post(\n `/actions/${action_name}`,\n // Custom hook funnels body-schema failures through the same\n // ApiError envelope + 422 status an in-`do` ValidationError maps\n // to (ERROR_MAP.ValidationError). Without it, @hono/zod-validator\n // short-circuits with its own 400 + raw body — two statuses and\n // two shapes for the same \"malformed input\" failure class on one\n // endpoint. The OpenAPI doc only documents the 422/ApiError path.\n zValidator(\"json\", schema as never, (result, c) => {\n if (!result.success) {\n // `result.error` is a ZodError; the schema's `never` typing\n // erases its shape, so read `.message` through a narrow cast.\n const message = (result.error as { message?: string }).message;\n const body: ApiError = {\n error: \"ValidationError\",\n detail: message,\n code: \"VALIDATION\",\n };\n return c.json(body, 422);\n }\n }),\n async (c) => {\n try {\n const input = c.req.valid(\"json\" as never) as unknown;\n const actor = c.get(\"actor\");\n const stream = await options.stream(action_name, input, c);\n const expected_version = options.expectedVersion\n ? await options.expectedVersion(action_name, input, c)\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 = key_from(c);\n if (!key) {\n const body: ApiError = {\n error: \"BadRequest\",\n detail: \"Idempotency-Key required\",\n code: \"BAD_REQUEST\",\n };\n return c.json(body, 400);\n }\n const outcome = await withIdempotency(\n options.idempotency.store,\n key,\n () =>\n app.do(action_name as never, target as never, input as never)\n );\n if (outcome.deduped) {\n const body: ApiError = {\n error: \"Conflict\",\n detail:\n \"Idempotency-Key already used; original result not cached\",\n code: \"CONFLICT\",\n };\n return c.json(body, 409);\n }\n return c.json(outcome.result);\n }\n\n const snapshots = await app.do(\n action_name as never,\n target as never,\n input as never\n );\n return c.json(snapshots);\n } catch (err) {\n const { status, body } = toApiError(err);\n // Hono types narrow `status` to its known status-number union;\n // `toApiError` returns a numeric status from a closed set that\n // matches but TypeScript can't prove it through the union.\n return c.json(body, status as 400 | 409 | 410 | 412 | 422 | 500);\n }\n }\n );\n }\n\n return api;\n}\n"],"mappings":";;;;;;;;;;;;;AAuHA,SAAS,mBAYP,QACA,QACA,MACA,SAGgE;AAEhE,SAAO,UAAU,QAAQ,OAAO,OAAkC,MAAM;AACtE,QAAI,iBAAiB;AAIrB,QAAK,WAAW,YAAY,UAAU,UAAY,WAAW,YAAY,UAAU,QAAS;AAG1F,YAAM,aAAa,OAAO,KAAK,QAAQ,SAAS,OAAO,GAAG,QAAQ,OAAO,KAAA;AACzE,YAAM,wBAAwB,OAAO,YACnC,WAAW,IAAA,CAAK,QAAQ,CAA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E;AACA,gBAAI,QAAQ,SAAS;AACnB,oBAAM,OAAiB;AAAA,gBACrB,OAAO;AAAA,gBACP,QACE;AAAA,gBACF,MAAM;AAAA,cACR;AACA,qBAAO,EAAE,KAAK,MAAM,GAAG;AAAA,YACzB;AACA,mBAAO,EAAE,KAAK,QAAQ,MAAM;AAAA,UAC9B;AAEA,gBAAM,YAAY,MAAM,IAAI;AAAA,YAC1B;AAAA,YACA;AAAA,YACA;AAAA,UACF;AACA,iBAAO,EAAE,KAAK,SAAS;AAAA,QACzB,SAAS,KAAK;AACZ,gBAAM,EAAE,QAAQ,KAAK,IAAI,WAAW,GAAG;AAIvC,iBAAO,EAAE,KAAK,MAAM,MAA2C;AAAA,QACjE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["value","zValidator: typeof zValidatorFunction"]}
|
|
1
|
+
{"version":3,"sources":["../../../../node_modules/.pnpm/@hono+zod-validator@0.8.0_hono@4.12.27_zod@4.4.3/node_modules/@hono/zod-validator/src/index.ts","../../src/hono/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Context, Env, Input, MiddlewareHandler, TypedResponse, ValidationTargets } from 'hono'\nimport { validator } from 'hono/validator'\nimport type * as v3 from 'zod/v3'\nimport type { ZodSafeParseResult as v4ZodSafeParseResult } from 'zod/v4'\nimport type * as v4 from 'zod/v4/core'\nimport type { InferInput } from './utils'\n\ntype ZodSchema = v3.ZodType | v4.$ZodType\ntype ZodError<T extends ZodSchema> = T extends v4.$ZodType\n ? v4.$ZodError<v4.output<T>>\n : v3.ZodError\ntype ZodSafeParseResult<T, T2, T3 extends ZodSchema> = T3 extends v4.$ZodType\n ? v4ZodSafeParseResult<T>\n : v3.SafeParseReturnType<T, T2>\ntype zInput<T> = T extends v3.ZodType ? v3.input<T> : T extends v4.$ZodType ? v4.input<T> : never\ntype zOutput<T> = T extends v3.ZodType ? v3.output<T> : T extends v4.$ZodType ? v4.output<T> : never\ntype zInfer<T> = T extends v3.ZodType ? v3.infer<T> : T extends v4.$ZodType ? v4.infer<T> : never\n\n// Failure variant of `safeParseAsync`'s return value.\n// Mirrors the runtime body returned by `c.json(result, 400)` on validation failure.\ntype ZodValidatorFailureBody<T extends ZodSchema> = T extends v4.$ZodType\n ? Extract<v4ZodSafeParseResult<v4.output<T>>, { success: false }>\n : T extends v3.ZodType\n ? Extract<v3.SafeParseReturnType<v3.input<T>, v3.output<T>>, { success: false }>\n : never\n\ntype ZodValidatorFailureResponse<T extends ZodSchema> = Response &\n TypedResponse<ZodValidatorFailureBody<T>, 400, 'json'>\n\nexport type Hook<\n T,\n E extends Env,\n P extends string,\n Target extends keyof ValidationTargets = keyof ValidationTargets,\n O = {},\n Schema extends ZodSchema = any,\n> = (\n result: ({ success: true; data: T } | { success: false; error: ZodError<Schema>; data: T }) & {\n target: Target\n },\n c: Context<E, P>\n) => Response | void | TypedResponse<O> | Promise<Response | void | TypedResponse<O>>\n\ntype HasUndefined<T> = undefined extends T ? true : false\n\ntype ExtractValidationResponse<VF> = VF extends (value: any, c: any) => infer R\n ? R extends Promise<infer PR>\n ? PR extends TypedResponse<infer T, infer S, infer F>\n ? Response & TypedResponse<T, S, F>\n : PR extends Response\n ? PR\n : PR extends undefined\n ? never\n : never\n : R extends TypedResponse<infer T, infer S, infer F>\n ? Response & TypedResponse<T, S, F>\n : R extends Response\n ? R\n : R extends undefined\n ? never\n : never\n : never\n\ntype ValidationFunctionOption<T extends ZodSchema, Target extends keyof ValidationTargets> = {\n validationFunction: (\n schema: T,\n value: ValidationTargets[Target]\n ) => ZodSafeParseResult<any, any, T> | Promise<ZodSafeParseResult<any, any, T>>\n}\n\ntype DefaultInput<Target extends keyof ValidationTargets, In, Out> = {\n in: HasUndefined<In> extends true\n ? {\n [K in Target]?: [In] extends [ValidationTargets[K]] ? In : InferInput<In, K>\n }\n : {\n [K in Target]: [In] extends [ValidationTargets[K]] ? In : InferInput<In, K>\n }\n out: { [K in Target]: Out }\n}\n\n// without hook (with or without options)\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n>(\n target: Target,\n schema: T,\n hook?: undefined,\n options?: ValidationFunctionOption<T, Target>\n): MiddlewareHandler<E, P, V, ZodValidatorFailureResponse<T>>\n\n// with hook and options\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n HookFn extends Hook<InferredValue, E, P, Target, {}, T>,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n InferredValue = zInfer<T>,\n>(\n target: Target,\n schema: T,\n hook?: HookFn,\n options?: ValidationFunctionOption<T, Target>\n): MiddlewareHandler<E, P, V, ExtractValidationResponse<HookFn>>\n\n// implementation\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n HookFn extends Hook<InferredValue, E, P, Target, {}, T>,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n InferredValue = zInfer<T>,\n>(\n target: Target,\n schema: T,\n hook?: HookFn,\n options?: ValidationFunctionOption<T, Target>\n):\n | MiddlewareHandler<E, P, V, ZodValidatorFailureResponse<T>>\n | MiddlewareHandler<E, P, V, ExtractValidationResponse<HookFn>> {\n // @ts-expect-error not typed well\n return validator(target, async (value: ValidationTargets[Target], c) => {\n let validatorValue = value\n\n // in case where our `target` === `header`, Hono parses all of the headers into lowercase.\n // this might not match the Zod schema, so we want to make sure that we account for that when parsing the schema.\n if ((target === 'header' && '_def' in schema) || (target === 'header' && '_zod' in schema)) {\n // create an object that maps lowercase schema keys to lowercase\n // @ts-expect-error the schema is a Zod Schema\n const schemaKeys = Object.keys('in' in schema ? schema.in.shape : schema.shape)\n const caseInsensitiveKeymap = Object.fromEntries(\n schemaKeys.map((key) => [key.toLowerCase(), key])\n )\n\n validatorValue = Object.fromEntries(\n Object.entries(value).map(([key, value]) => [caseInsensitiveKeymap[key] || key, value])\n )\n }\n\n const result =\n options && options.validationFunction\n ? await options.validationFunction(schema, validatorValue)\n : // @ts-expect-error z4.$ZodType has safeParseAsync\n await schema.safeParseAsync(validatorValue)\n\n if (hook) {\n const hookResult = await hook({ data: validatorValue, ...result, target }, c)\n if (hookResult) {\n if (hookResult instanceof Response) {\n return hookResult\n }\n\n if ('response' in hookResult) {\n return hookResult.response\n }\n }\n }\n\n if (!result.success) {\n return c.json(result, 400)\n }\n\n return result.data as zInfer<T>\n })\n}\n\nexport const zValidator: typeof zValidatorFunction = zValidatorFunction\n","/**\n * @packageDocumentation\n * @module act-http/hono\n *\n * Hono subpath for the auto-generated API epic (#835). Walks the\n * registry of a built `Act` once at function call and emits a Hono\n * app with one `POST /actions/<name>` route per registered action,\n * Zod-validated bodies, and the shared error envelope.\n *\n * Usage:\n *\n * ```ts\n * import { hono } from \"@rotorsoft/act-http/hono\";\n *\n * const api = hono(app, {\n * actor: (c) => ({ id: c.req.header(\"x-user-id\")!, name: \"...\" }),\n * stream: (action, input, c) => `tenant-${c.req.header(\"x-tenant\")}`,\n * });\n *\n * // Mounts at /api by default — pass `basePath` to override.\n * // POST /api/actions/OpenTicket body: { title } → 200 Snapshot[] | 4xx ApiError\n * ```\n *\n * The route shape matches the flat tRPC sibling at\n * `@rotorsoft/act-http/trpc`: one endpoint per action, no\n * state-name tier. Action names are unique across the registry —\n * the framework enforces no duplicates — so an extra namespace\n * level would be overhead. Queries live in a follow-up; this\n * slice is mutations only.\n *\n * **Actor lives on the context.** The generator wires an internal\n * middleware that runs the host's\n * {@link HonoOptions.actor | actor extractor} once per call and\n * stashes the resolved {@link Actor} under `c.get(\"actor\")`. Every\n * generated route reads from there — auth resolves at one seam,\n * downstream middleware (logging, tracing) sees the same actor.\n * The middleware factory is also exported as {@link authenticated}\n * for hosts that want to compose it into their own Hono chain\n * alongside hand-written routes.\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 (tRPC, this one,\n * OpenAPI) ride the same utilities so a client speaking two of\n * them never sees two shapes for the same framework error.\n */\nimport { zValidator } from \"@hono/zod-validator\";\nimport type { Actor, Target } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport { Hono } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport {\n type ActorExtractor,\n type ApiError,\n fireAndForget,\n resolveSseConfig,\n runSseSubscription,\n SseConnectionCounter,\n type SseOptions,\n toApiError,\n withIdempotency,\n} from \"../api/index.js\";\n\n/**\n * Hono context variables this subpath contributes. The generic on\n * the returned middleware threads it through so routes downstream\n * of {@link authenticated} see `c.get(\"actor\")` typed without a\n * manual cast.\n */\nexport type ActMiddlewareVariables = {\n actor: Actor;\n};\n\n/**\n * Per-call options for {@link hono}. The host supplies the four\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the Hono context, returns the\n * `Actor` that flows onto `c.get(\"actor\")` for every generated\n * route (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated body, and the Hono context; returns the target\n * stream. Singleton aggregates return a constant; per-tenant\n * aggregates pull from headers, path, or body.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * Hosts typically read it from an `If-Match` header on the\n * request, or from the client's last-known snapshot. Returning\n * `undefined` skips the check for that call — handy when only\n * some actions are concurrency-sensitive.\n * - `idempotency` (optional) — when set, the route honors\n * `Idempotency-Key` via {@link withIdempotency}. The host\n * supplies the `IdempotencyStore`; `keyFrom` defaults to reading\n * the `Idempotency-Key` header. On a duplicate claim, the route\n * responds `409 Conflict` — the contract intentionally doesn't\n * cache the original handler's result, matching the\n * receiver-side \"ack the duplicate\" semantics.\n * - `basePath` (optional, default `\"/api\"`) — Hono basePath the\n * routes mount under.\n */\nexport type HonoOptions = {\n readonly actor: ActorExtractor;\n readonly stream: (\n action_name: string,\n input: unknown,\n c: Context\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n c: Context\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom?: (c: Context) => string | undefined;\n };\n /**\n * Optional SSE wiring. When set, the generator emits one\n * `GET <basePath>/sse/<stateName>?stream=<streamId>` per unique\n * state name in the registry. The endpoint runs the host\n * {@link actor} extractor, looks up the streamId from\n * `?stream=...`, opens a `text/event-stream`, yields the cached\n * state (if any), and forwards every patch published to the\n * shared {@link SseOptions.channel}. A heartbeat keeps proxies\n * from idling the connection out; the per-process connection cap\n * returns `503 Service Unavailable` (with `Retry-After: 1`) when\n * full so operators never see silent stalls.\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 readonly basePath?: string;\n};\n\n/**\n * Build a Hono middleware that runs an {@link ActorExtractor} once\n * per call and stashes the resolved {@link Actor} under\n * `c.set(\"actor\", ...)` so downstream routes can read it via\n * `c.get(\"actor\")`. The generator at {@link hono} uses this\n * internally; it's also exported so hosts that want to compose\n * their own route chain (logging, tracing, custom auth flavors)\n * can wire it directly:\n *\n * ```ts\n * import { Hono } from \"hono\";\n * import { authenticated, type ActMiddlewareVariables } from \"@rotorsoft/act-http/hono\";\n *\n * const api = new Hono<{ Variables: ActMiddlewareVariables }>();\n * api.use(\"*\", authenticated((c) => resolveUserFromJwt(c)));\n * api.get(\"/me\", (c) => c.json(c.get(\"actor\"))); // typed\n * ```\n *\n * Errors thrown by the extractor surface as `401 Unauthorized` with\n * the shared {@link ApiError} envelope.\n */\nexport function authenticated(\n extractor: ActorExtractor\n): MiddlewareHandler<{ Variables: ActMiddlewareVariables }> {\n return async (c, next) => {\n try {\n const actor = await extractor(c);\n c.set(\"actor\", actor);\n await next();\n } catch (err) {\n const body: ApiError = {\n error: \"Unauthorized\",\n detail: err instanceof Error ? err.message : undefined,\n code: \"UNAUTHORIZED\",\n };\n return c.json(body, 401);\n }\n };\n}\n\nconst default_key_from = (c: Context): string | undefined =>\n c.req.header(\"idempotency-key\");\n\n/**\n * Build a typed Hono REST surface from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one\n * `POST /actions/<actionName>` per action under the configured\n * `basePath` (default `/api`). Each route:\n *\n * 1. Runs the internal {@link authenticated} middleware —\n * `options.actor` resolves the {@link Actor} once and stashes\n * it under `c.get(\"actor\")`.\n * 2. Validates the JSON body against the action's Zod schema via\n * `@hono/zod-validator`. Failures short-circuit with `422`.\n * 3. Resolves the target stream via\n * `options.stream(name, input, c)`.\n * 4. (Optionally) resolves `expectedVersion` for optimistic\n * concurrency.\n * 5. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — responds `409` on duplicate.\n * 6. Calls\n * `app.do(name, { stream, actor, expectedVersion? }, input)`.\n * 7. Maps any thrown framework error onto the shared\n * {@link ApiError} envelope via {@link toApiError}, returning\n * the conventional HTTP status (`409` / `412` for concurrency,\n * `422` for validation, `400` for non-retryable, etc.).\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, expected-version, idempotency, and\n * base-path seams.\n * @returns A Hono app covering every registered action under\n * `<basePath>/actions/<name>`.\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 keeps nested variance\n * out of the signature and avoids `any` in either direction.\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\nexport function hono<TApp extends ActSurface = ActSurface>(\n app: TApp,\n options: HonoOptions\n): Hono<{ Variables: ActMiddlewareVariables }> {\n const base_path = options.basePath ?? \"/api\";\n const api = new Hono<{ Variables: ActMiddlewareVariables }>().basePath(\n base_path\n );\n api.use(\"*\", authenticated(options.actor));\n\n const key_from = options.idempotency?.keyFrom ?? default_key_from;\n\n // Wire SSE subscriptions before the mutation routes so the\n // `/sse/*` paths sit alongside `/actions/*`. The cap counter is\n // shared by every state-name's GET route on this generator\n // instance so a noisy room on one state doesn't get a free pass\n // on another.\n if (options.sse) {\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 for (const state_name of state_names) {\n api.get(`/sse/${state_name}`, async (c) => {\n const stream_id = c.req.query(\"stream\");\n if (!stream_id) {\n const body: ApiError = {\n error: \"BadRequest\",\n detail: \"stream query parameter is required\",\n code: \"BAD_REQUEST\",\n };\n return c.json(body, 400);\n }\n if (!sse_counter.acquire()) {\n c.header(\"Retry-After\", \"1\");\n const body: ApiError = {\n error: \"ServiceUnavailable\",\n detail: \"max concurrent SSE connections reached\",\n code: \"SSE_BUSY\",\n };\n return c.json(body, 503);\n }\n // The route already acquired the slot above so streamSSE\n // could return `503` before writing headers if the cap was\n // full. The shared loop runs without accounting; the route\n // releases the slot in `finally`.\n const controller = new AbortController();\n return streamSSE(c, async (sse_stream) => {\n sse_stream.onAbort(() => controller.abort());\n const heartbeat = setInterval(() => {\n fireAndForget(() =>\n sse_stream.writeSSE({ event: \"ping\", data: \"\" })\n );\n }, sse_config.heartbeatMs);\n try {\n for await (const frame of runSseSubscription(\n sse_config.channel,\n stream_id,\n undefined,\n controller.signal,\n { maxPending: sse_config.maxPendingPerConnection }\n )) {\n await sse_stream.writeSSE({\n event: frame.kind,\n data: JSON.stringify(frame.data),\n });\n }\n } finally {\n clearInterval(heartbeat);\n sse_counter.release();\n }\n });\n });\n }\n }\n\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n const schema = state.actions[action_name];\n api.post(\n `/actions/${action_name}`,\n // Custom hook funnels body-schema failures through the same\n // ApiError envelope + 422 status an in-`do` ValidationError maps\n // to (ERROR_MAP.ValidationError). Without it, @hono/zod-validator\n // short-circuits with its own 400 + raw body — two statuses and\n // two shapes for the same \"malformed input\" failure class on one\n // endpoint. The OpenAPI doc only documents the 422/ApiError path.\n zValidator(\"json\", schema as never, (result, c) => {\n if (!result.success) {\n // `result.error` is a ZodError; the schema's `never` typing\n // erases its shape, so read `.message` through a narrow cast.\n const message = (result.error as { message?: string }).message;\n const body: ApiError = {\n error: \"ValidationError\",\n detail: message,\n code: \"VALIDATION\",\n };\n return c.json(body, 422);\n }\n }),\n async (c) => {\n try {\n const input = c.req.valid(\"json\" as never) as unknown;\n const actor = c.get(\"actor\");\n const stream = await options.stream(action_name, input, c);\n const expected_version = options.expectedVersion\n ? await options.expectedVersion(action_name, input, c)\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 = key_from(c);\n if (!key) {\n const body: ApiError = {\n error: \"BadRequest\",\n detail: \"Idempotency-Key required\",\n code: \"BAD_REQUEST\",\n };\n return c.json(body, 400);\n }\n const outcome = await withIdempotency(\n options.idempotency.store,\n key,\n () =>\n app.do(action_name as never, target as never, input as never)\n );\n if (outcome.deduped) {\n const body: ApiError = {\n error: \"Conflict\",\n detail:\n \"Idempotency-Key already used; original result not cached\",\n code: \"CONFLICT\",\n };\n return c.json(body, 409);\n }\n return c.json(outcome.result);\n }\n\n const snapshots = await app.do(\n action_name as never,\n target as never,\n input as never\n );\n return c.json(snapshots);\n } catch (err) {\n const { status, body } = toApiError(err);\n // Hono types narrow `status` to its known status-number union;\n // `toApiError` returns a numeric status from a closed set that\n // matches but TypeScript can't prove it through the union.\n return c.json(body, status as 400 | 409 | 410 | 412 | 422 | 500);\n }\n }\n );\n }\n\n return api;\n}\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AE,QAAQ,OAAO,iBAAiB,iBAAiB;AAEzD,cAAI,QAAQ,aAAa;AACvB,kBAAM,MAAM,SAAS,CAAC;AACtB,gBAAI,CAAC,KAAK;AACR,oBAAM,OAAiB;AAAA,gBACrB,OAAO;AAAA,gBACP,QAAQ;AAAA,gBACR,MAAM;AAAA,cACR;AACA,qBAAO,EAAE,KAAK,MAAM,GAAG;AAAA,YACzB;AACA,kBAAM,UAAU,MAAM;AAAA,cACpB,QAAQ,YAAY;AAAA,cACpB;AAAA,cACA,MACE,IAAI,GAAG,aAAsB,QAAiB,KAAc;AAAA,YAChE;AACA,gBAAI,QAAQ,SAAS;AACnB,oBAAM,OAAiB;AAAA,gBACrB,OAAO;AAAA,gBACP,QACE;AAAA,gBACF,MAAM;AAAA,cACR;AACA,qBAAO,EAAE,KAAK,MAAM,GAAG;AAAA,YACzB;AACA,mBAAO,EAAE,KAAK,QAAQ,MAAM;AAAA,UAC9B;AAEA,gBAAM,YAAY,MAAM,IAAI;AAAA,YAC1B;AAAA,YACA;AAAA,YACA;AAAA,UACF;AACA,iBAAO,EAAE,KAAK,SAAS;AAAA,QACzB,SAAS,KAAK;AACZ,gBAAM,EAAE,QAAQ,KAAK,IAAI,WAAW,GAAG;AAIvC,iBAAO,EAAE,KAAK,MAAM,MAA2C;AAAA,QACjE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["value","zValidator: typeof zValidatorFunction"]}
|
package/dist/trpc/index.cjs
CHANGED
|
@@ -14602,19 +14602,23 @@ async function withIdempotency(store, key, handler) {
|
|
|
14602
14602
|
// src/api/sse-wiring.ts
|
|
14603
14603
|
var DEFAULT_SSE_MAX_CONNECTIONS = 500;
|
|
14604
14604
|
var DEFAULT_SSE_HEARTBEAT_MS = 3e4;
|
|
14605
|
+
var DEFAULT_SSE_MAX_PENDING_PER_CONNECTION = 256;
|
|
14605
14606
|
var SseOptionsSchema = external_exports.object({
|
|
14606
14607
|
maxConnections: external_exports.number().int().min(1).max(1e4).default(DEFAULT_SSE_MAX_CONNECTIONS),
|
|
14607
|
-
heartbeatMs: external_exports.number().int().min(15e3).max(3e5).default(DEFAULT_SSE_HEARTBEAT_MS)
|
|
14608
|
+
heartbeatMs: external_exports.number().int().min(15e3).max(3e5).default(DEFAULT_SSE_HEARTBEAT_MS),
|
|
14609
|
+
maxPendingPerConnection: external_exports.number().int().min(1).max(1e5).default(DEFAULT_SSE_MAX_PENDING_PER_CONNECTION)
|
|
14608
14610
|
});
|
|
14609
14611
|
function resolveSseConfig(options) {
|
|
14610
14612
|
const parsed = SseOptionsSchema.parse({
|
|
14611
14613
|
maxConnections: options.maxConnections,
|
|
14612
|
-
heartbeatMs: options.heartbeatMs
|
|
14614
|
+
heartbeatMs: options.heartbeatMs,
|
|
14615
|
+
maxPendingPerConnection: options.maxPendingPerConnection
|
|
14613
14616
|
});
|
|
14614
14617
|
return {
|
|
14615
14618
|
channel: options.channel,
|
|
14616
14619
|
maxConnections: parsed.maxConnections,
|
|
14617
|
-
heartbeatMs: parsed.heartbeatMs
|
|
14620
|
+
heartbeatMs: parsed.heartbeatMs,
|
|
14621
|
+
maxPendingPerConnection: parsed.maxPendingPerConnection
|
|
14618
14622
|
};
|
|
14619
14623
|
}
|
|
14620
14624
|
var SseConnectionCounter = class {
|
|
@@ -14646,13 +14650,19 @@ var SseConnectionCounter = class {
|
|
|
14646
14650
|
return this._open;
|
|
14647
14651
|
}
|
|
14648
14652
|
};
|
|
14649
|
-
async function* runSseSubscription(channel, stream_id, accounting, signal,
|
|
14650
|
-
|
|
14651
|
-
|
|
14653
|
+
async function* runSseSubscription(channel, stream_id, accounting, signal, options) {
|
|
14654
|
+
let acquired = false;
|
|
14655
|
+
if (accounting) {
|
|
14656
|
+
acquired = accounting.acquire();
|
|
14657
|
+
if (!acquired && options?.on_cap_exceeded) {
|
|
14658
|
+
options.on_cap_exceeded();
|
|
14659
|
+
}
|
|
14652
14660
|
}
|
|
14661
|
+
const max_pending = options?.maxPending ?? DEFAULT_SSE_MAX_PENDING_PER_CONNECTION;
|
|
14653
14662
|
const pending = [];
|
|
14654
14663
|
let resolve_wait = null;
|
|
14655
14664
|
const unsubscribe = channel.subscribe(stream_id, (msg) => {
|
|
14665
|
+
if (pending.length >= max_pending) pending.shift();
|
|
14656
14666
|
pending.push(msg);
|
|
14657
14667
|
resolve_wait?.();
|
|
14658
14668
|
});
|
|
@@ -14676,7 +14686,7 @@ async function* runSseSubscription(channel, stream_id, accounting, signal, on_ca
|
|
|
14676
14686
|
} finally {
|
|
14677
14687
|
signal?.removeEventListener("abort", on_abort);
|
|
14678
14688
|
unsubscribe();
|
|
14679
|
-
accounting?.release();
|
|
14689
|
+
if (acquired) accounting?.release();
|
|
14680
14690
|
}
|
|
14681
14691
|
}
|
|
14682
14692
|
|
|
@@ -14774,11 +14784,14 @@ function trpc(app, options) {
|
|
|
14774
14784
|
input.stream,
|
|
14775
14785
|
sse_counter,
|
|
14776
14786
|
signal,
|
|
14777
|
-
|
|
14778
|
-
|
|
14779
|
-
|
|
14780
|
-
|
|
14781
|
-
|
|
14787
|
+
{
|
|
14788
|
+
maxPending: sse_config.maxPendingPerConnection,
|
|
14789
|
+
on_cap_exceeded: () => {
|
|
14790
|
+
throw new import_server.TRPCError({
|
|
14791
|
+
code: "TOO_MANY_REQUESTS",
|
|
14792
|
+
message: "max concurrent SSE subscriptions reached"
|
|
14793
|
+
});
|
|
14794
|
+
}
|
|
14782
14795
|
}
|
|
14783
14796
|
)
|
|
14784
14797
|
);
|