@forinda/kickjs 10.12.0 → 10.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-DiJfCKXU.d.mts → adapter-g_vQffKr.d.mts} +7 -5
- package/dist/adapter-g_vQffKr.d.mts.map +1 -0
- package/dist/{application-W8fhRn97.mjs → application-dhmb3PMx.mjs} +3 -3
- package/dist/{application-W8fhRn97.mjs.map → application-dhmb3PMx.mjs.map} +1 -1
- package/dist/{application-Rb6jeTAp.d.mts → application-r0VMb-A5.d.mts} +7 -7
- package/dist/{application-Rb6jeTAp.d.mts.map → application-r0VMb-A5.d.mts.map} +1 -1
- package/dist/{body-policy-cWfUReGC.mjs → body-policy-BK8PLFhR.mjs} +2 -2
- package/dist/{body-policy-cWfUReGC.mjs.map → body-policy-BK8PLFhR.mjs.map} +1 -1
- package/dist/{bootstrap-Cg3-PXxu.mjs → bootstrap-Cm4Tv-uh.mjs} +3 -3
- package/dist/{bootstrap-Cg3-PXxu.mjs.map → bootstrap-Cm4Tv-uh.mjs.map} +1 -1
- package/dist/{bounded-counters-BIrM6PXT.mjs → bounded-counters-DhDwQV9i.mjs} +2 -2
- package/dist/{bounded-counters-BIrM6PXT.mjs.map → bounded-counters-DhDwQV9i.mjs.map} +1 -1
- package/dist/{client-ip-BAtoGmC3.mjs → client-ip-gBC8rx8G.mjs} +2 -2
- package/dist/{client-ip-BAtoGmC3.mjs.map → client-ip-gBC8rx8G.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-DCjeCuL2.mjs → config-CufiDd1o.mjs} +3 -3
- package/dist/{config-DCjeCuL2.mjs.map → config-CufiDd1o.mjs.map} +1 -1
- package/dist/context-Vy_DYHAM.mjs +12 -0
- package/dist/context-Vy_DYHAM.mjs.map +1 -0
- package/dist/{context-errors-BULDLnr1.mjs → context-errors-BNm2NUfA.mjs} +2 -2
- package/dist/{context-errors-BULDLnr1.mjs.map → context-errors-BNm2NUfA.mjs.map} +1 -1
- package/dist/{contributor-runner-CKv5LriN.mjs → contributor-runner-BwBRcB65.mjs} +3 -3
- package/dist/{contributor-runner-CKv5LriN.mjs.map → contributor-runner-BwBRcB65.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +2 -2
- package/dist/{core-Kqw_11xA.mjs → core-uD7kn0hF.mjs} +3 -3
- package/dist/{core-Kqw_11xA.mjs.map → core-uD7kn0hF.mjs.map} +1 -1
- package/dist/{csrf-w5bc-PGs.d.mts → csrf-DOAaYozG.d.mts} +17 -2
- package/dist/csrf-DOAaYozG.d.mts.map +1 -0
- package/dist/{decorate-Dji9dYab.mjs → decorate-7rlBW7PY.mjs} +3 -3
- package/dist/{decorate-Dji9dYab.mjs.map → decorate-7rlBW7PY.mjs.map} +1 -1
- package/dist/{define-adapter-DqTV48jK.mjs → define-adapter-rcNang-q.mjs} +2 -2
- package/dist/{define-adapter-DqTV48jK.mjs.map → define-adapter-rcNang-q.mjs.map} +1 -1
- package/dist/{di-hooks-CUWf3HlQ.mjs → di-hooks-CdmCtJWu.mjs} +2 -2
- package/dist/{di-hooks-CUWf3HlQ.mjs.map → di-hooks-CdmCtJWu.mjs.map} +1 -1
- package/dist/{disposables-D7NlxYjq.mjs → disposables-tpEyEZ9s.mjs} +1 -1
- package/dist/driver-C8ZOdZck.mjs +12 -0
- package/dist/driver-C8ZOdZck.mjs.map +1 -0
- package/dist/{error-handler-OfxVJX3s.d.mts → error-handler-vox7HLaR.d.mts} +2 -2
- package/dist/{error-handler-OfxVJX3s.d.mts.map → error-handler-vox7HLaR.d.mts.map} +1 -1
- package/dist/express-DjX6B-HB.mjs +12 -0
- package/dist/{express-B6jvEdCZ.mjs.map → express-DjX6B-HB.mjs.map} +1 -1
- package/dist/{express-lazy-BE10FhlA.mjs → express-lazy-DBLuSOgw.mjs} +3 -3
- package/dist/{express-lazy-BE10FhlA.mjs.map → express-lazy-DBLuSOgw.mjs.map} +1 -1
- package/dist/handler-CHJs4HZ3.mjs +12 -0
- package/dist/handler-CHJs4HZ3.mjs.map +1 -0
- package/dist/{host-B5w-Sz-2.mjs → host-BxUGat0u.mjs} +2 -2
- package/dist/{host-B5w-Sz-2.mjs.map → host-BxUGat0u.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +1 -1
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +2 -2
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.d.mts +1 -1
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +2 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +2 -2
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/index.d.mts +9 -9
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{is-production-D0kfhCW4.mjs → is-production-WunZdVDZ.mjs} +2 -2
- package/dist/{is-production-D0kfhCW4.mjs.map → is-production-WunZdVDZ.mjs.map} +1 -1
- package/dist/{jobs-F8vpXQt7.mjs → jobs-DxkFQkZG.mjs} +3 -3
- package/dist/{jobs-F8vpXQt7.mjs.map → jobs-DxkFQkZG.mjs.map} +1 -1
- package/dist/{kv-stores-BN7c9bt9.d.mts → kv-stores-B6KIUgPS.d.mts} +3 -3
- package/dist/{kv-stores-BN7c9bt9.d.mts.map → kv-stores-B6KIUgPS.d.mts.map} +1 -1
- package/dist/{kv-stores-DxVO4y2v.mjs → kv-stores-C4YUttef.mjs} +3 -3
- package/dist/{kv-stores-DxVO4y2v.mjs.map → kv-stores-C4YUttef.mjs.map} +1 -1
- package/dist/{lazy-serve-static-BeucQAk2.mjs → lazy-serve-static-BBO3lkBi.mjs} +3 -3
- package/dist/{lazy-serve-static-BeucQAk2.mjs.map → lazy-serve-static-BBO3lkBi.mjs.map} +1 -1
- package/dist/{metadata-DeXrp8uO.mjs → metadata-s6adg8tp.mjs} +1 -1
- package/dist/{observers-DL7RRlLR.mjs → observers-Dn36QtbG.mjs} +2 -2
- package/dist/{observers-DL7RRlLR.mjs.map → observers-Dn36QtbG.mjs.map} +1 -1
- package/dist/{precompressed-CYkmmoRU.mjs → precompressed-Dn3S9e-q.mjs} +2 -2
- package/dist/{precompressed-CYkmmoRU.mjs.map → precompressed-Dn3S9e-q.mjs.map} +1 -1
- package/dist/{query-Coc1hIiS.mjs → query-BukuyQDW.mjs} +2 -2
- package/dist/{query-Coc1hIiS.mjs.map → query-BukuyQDW.mjs.map} +1 -1
- package/dist/{reply-Bg1gyBtE.mjs → reply-DDoHPeGF.mjs} +3 -3
- package/dist/{reply-Bg1gyBtE.mjs.map → reply-DDoHPeGF.mjs.map} +1 -1
- package/dist/{request-scope-R9FuLLnB.mjs → request-scope-BmUpBk1z.mjs} +3 -3
- package/dist/{request-scope-R9FuLLnB.mjs.map → request-scope-BmUpBk1z.mjs.map} +1 -1
- package/dist/{respond-BDd0h6bG.mjs → respond-Bo3vSCwu.mjs} +2 -2
- package/dist/{respond-BDd0h6bG.mjs.map → respond-Bo3vSCwu.mjs.map} +1 -1
- package/dist/{rolldown-runtime-OjcH9Gd_.mjs → rolldown-runtime-DHJmXo5e.mjs} +1 -1
- package/dist/{route-flag-ECQsPj4x.mjs → route-flag-Cwckim1c.mjs} +3 -3
- package/dist/{route-flag-ECQsPj4x.mjs.map → route-flag-Cwckim1c.mjs.map} +1 -1
- package/dist/{route-policy-0ZBRrh9x.mjs → route-policy-CycYu5mR.mjs} +2 -2
- package/dist/{route-policy-0ZBRrh9x.mjs.map → route-policy-CycYu5mR.mjs.map} +1 -1
- package/dist/{router-builder-abKMvAmP.mjs → router-builder--PLE0eDf.mjs} +3 -3
- package/dist/{router-builder-abKMvAmP.mjs.map → router-builder--PLE0eDf.mjs.map} +1 -1
- package/dist/{router-builder-DtGrng_X.d.mts → router-builder-DdfPBl09.d.mts} +2 -2
- package/dist/{router-builder-DtGrng_X.d.mts.map → router-builder-DdfPBl09.d.mts.map} +1 -1
- package/dist/runtime-OgMPp4md.mjs +12 -0
- package/dist/runtime-OgMPp4md.mjs.map +1 -0
- package/dist/{session-8uNRCplB.d.mts → session-DQG72vCf.d.mts} +7 -25
- package/dist/session-DQG72vCf.d.mts.map +1 -0
- package/dist/{settings-vuB5TedF.mjs → settings-Dn9iQ-BU.mjs} +3 -3
- package/dist/{settings-vuB5TedF.mjs.map → settings-Dn9iQ-BU.mjs.map} +1 -1
- package/dist/{token-BJJiF3_2.mjs → token-B3xWBu0S.mjs} +1 -1
- package/dist/{upload-C9IfY1aQ.d.mts → upload-DodgN_Ef.d.mts} +2 -2
- package/dist/{upload-C9IfY1aQ.d.mts.map → upload-DodgN_Ef.d.mts.map} +1 -1
- package/dist/{upload-config-TFTYQPaH.mjs → upload-config-BrbOOmcm.mjs} +2 -2
- package/dist/{upload-config-TFTYQPaH.mjs.map → upload-config-BrbOOmcm.mjs.map} +1 -1
- package/dist/{url-for-kZidAFyr.mjs → url-for-1SdTJZzK.mjs} +3 -3
- package/dist/{url-for-kZidAFyr.mjs.map → url-for-1SdTJZzK.mjs.map} +1 -1
- package/dist/{view-renderer-CSPD7F-f.mjs → view-renderer-Caqy9XY5.mjs} +3 -3
- package/dist/{view-renderer-CSPD7F-f.mjs.map → view-renderer-Caqy9XY5.mjs.map} +1 -1
- package/dist/{web-crypto-Q0WFs8ua.mjs → web-crypto-DnhQ8LCv.mjs} +2 -2
- package/dist/{web-crypto-Q0WFs8ua.mjs.map → web-crypto-DnhQ8LCv.mjs.map} +1 -1
- package/dist/web.d.mts +2 -2
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/adapter-DiJfCKXU.d.mts.map +0 -1
- package/dist/context-Cc6k0gsM.mjs +0 -12
- package/dist/context-Cc6k0gsM.mjs.map +0 -1
- package/dist/csrf-w5bc-PGs.d.mts.map +0 -1
- package/dist/express-B6jvEdCZ.mjs +0 -12
- package/dist/handler-BpMOjmfq.mjs +0 -12
- package/dist/handler-BpMOjmfq.mjs.map +0 -1
- package/dist/session-8uNRCplB.d.mts.map +0 -1
package/dist/web.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.mjs","names":[],"sources":["../src/web.ts"],"sourcesContent":["// `@forinda/kickjs/web` — the web-standard fetch entry for edge runtimes\n// (Cloudflare Workers), Bun, and Deno.\n//\n// PURITY CONTRACT: this entry's import graph must stay free of node-only\n// runtime imports — no `node:http`, `node:cluster`, `node:fs`, `node:module`,\n// no `express`, no `Application`/`bootstrap`. The single sanctioned node API\n// is `node:async_hooks` (AsyncLocalStorage — available on Workers with\n// `nodejs_compat`, Deno, and Bun). Enforced by the bundle-graph purity test.\n//\n// ```ts\n// // Cloudflare Workers (wrangler.toml: compatibility_flags = [\"nodejs_compat\"])\n// import { createWebApp } from '@forinda/kickjs/web'\n// import * as h3 from 'h3'\n// import { modules } from './modules'\n//\n// const app = createWebApp({ h3, modules })\n// export default { fetch: (req: Request) => app.fetch(req) }\n//\n// // Bun\n// Bun.serve({ fetch: (req) => app.fetch(req) })\n// ```\n\nimport { Container } from './core/container'\nimport { MutableModuleRegistry } from './core/module-registry'\nimport type { AppModule, AppModuleClass, AppModuleEntry } from './core/app-module'\nimport type { ContributorRegistrations } from './core/context-decorator'\nimport type { MiddlewareHandler } from './core/decorators'\nimport type { SourcedRegistration } from './core/contributor-pipeline'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './http/router-builder'\nimport { requestStore } from './http/request-store'\nimport { forwardBackgroundWork, type PlatformContext } from './http/background'\nimport { runCronJobs } from './core/cron'\nimport { runJob } from './core/jobs'\nimport { compileWebRoute, headFromGet } from './http/web/handler'\nimport { ROUTE_URLS, RouteUrls } from './http/url-for'\nimport { loadSettings, type SettingsDeclaration } from './config/settings'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './http/body-policy'\nimport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nimport { notFoundHandler, type MountedRoute } from './http/middleware/error-handler'\nimport type { ValidationErrorFactory } from './http/middleware/validate'\nimport { buildMountPath } from './core/path'\nimport { moduleName } from './core/define-module'\n\nexport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nexport { compileWebRoute } from './http/web/handler'\n// Return-value handler helpers — edge consumers can't import the main barrel.\nexport {\n reply,\n isReply,\n type Reply,\n type ReplyHeaders,\n type ReplyOptions,\n type InferHandlerResponse,\n} from './http/reply'\nexport type { SseHandler } from './http/context'\nexport { waitUntil, type PlatformContext } from './http/background'\nexport { runCronJobs, type CronRun } from './core/cron'\nexport { matchesBearer } from './core/web-crypto'\nexport {\n runJob,\n registerJobContext,\n stampJobContext,\n JOB_CONTEXT_FIELD,\n type JobLike,\n type JobContextCarrier,\n} from './core/jobs'\n// Edge-safe stores + ctx-style rate limiter (zero runtime imports).\nexport {\n KvRateLimitStore,\n KvSessionStore,\n type KvLike,\n type KvRateLimitStoreOptions,\n type KvSessionStoreOptions,\n} from './http/middleware/kv-stores'\nexport { rateLimitGuard, type RateLimitGuardOptions } from './http/middleware/rate-limit-guard'\n\n// Minimal structural surface of h3 v2 used here (kept local so this entry\n// never imports the node-coupled h3 runtime module).\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request\n url: URL\n context: { params?: Record<string, string> }\n}\n\nexport interface CreateWebAppOptions {\n /**\n * The h3 v2 module, statically imported by the caller:\n * `import * as h3 from 'h3'`. Passed in (rather than loaded here) because\n * edge bundlers have no `createRequire`, and a static `import 'h3'` inside\n * this entry would force the peer on every consumer of the subpath.\n */\n h3: unknown\n /** App modules — same shapes `bootstrap({ modules })` accepts. */\n modules: AppModuleEntry[]\n /** Route prefix (default '/api') — parity with bootstrap. */\n apiPrefix?: string\n /**\n * Default route version (default 1) — parity with bootstrap. `false` opts\n * out of URL versioning; a module's own `version` still overrides it.\n */\n defaultVersion?: number | false\n /** Global Context Contributors — parity with `bootstrap({ contributors })`. */\n contributors?: ContributorRegistrations\n /**\n * Env values for ConfigService/@Value resolution. On Workers, pass the\n * `env` binding from the fetch handler (see `createFetchHandler`); on\n * Bun/Deno, ambient `process.env` already works and this can be omitted.\n */\n env?: Record<string, string | undefined>\n /**\n * Global `(ctx, next)` middlewares, run before route middlewares on every\n * route — the web-entry counterpart of `bootstrap({ middlewares })`. Only\n * ctx-style handlers are accepted (no connect/express middleware here).\n */\n middlewares?: MiddlewareHandler[]\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`)\n * — parity with `bootstrap({ jsonLimit })`. A larger body answers 413.\n */\n jsonLimit?: string | number\n /** App-wide settings sections — parity with `bootstrap({ settings })`. */\n settings?: SettingsDeclaration[]\n /** What a failed route validation throws — parity with `bootstrap({ validationError })`. */\n validationError?: ValidationErrorFactory\n}\n\nexport interface WebApp {\n /**\n * Web-standard entry: `Request` in, `Response` out. Pass the platform\n * context (Workers `ctx`, Netlify `context`) so work handed to\n * `ctx.waitUntil()` finishes after the response.\n */\n fetch: (request: Request, platform?: PlatformContext) => Promise<Response>\n /** The underlying h3 v2 app, for advanced composition. */\n h3: unknown\n}\n\n/**\n * Build a KickJS app as a web-standard fetch handler — no node http server,\n * no Application/bootstrap. Module registration, DI, and the contributor\n * pipeline behave exactly like `bootstrap()`; routes are compiled once here\n * and served through h3 v2's router.\n */\nexport function createWebApp(options: CreateWebAppOptions): WebApp {\n const h3mod = options.h3 as { H3?: new () => H3AppLike }\n if (typeof h3mod?.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs/web: pass the h3 v2 module — `createWebApp({ h3: await import(\"h3\"), ... })`. ' +\n \"The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.\",\n )\n }\n\n const container = Container.getInstance()\n // Route names for ctx.urlFor() / the ROUTE_URLS token — bound before modules\n // register so their services can inject it.\n const routeUrls = new RouteUrls()\n container.registerInstance(ROUTE_URLS, routeUrls)\n // Wire ConfigService/@Value env resolution when the platform has no\n // ambient process.env (Workers). Latest-wins like loadEnv().\n if (options.env) {\n const env = options.env\n Container.setEnvResolver((key: string) => env[key])\n }\n\n // Request-scope provider — same wiring Application.setup() performs.\n Container.setRequestStoreProvider(() => requestStore.getStore() ?? null)\n\n // Module mounting — mirrors Application.setup() steps 1:1 for the module\n // path (plugins/adapters are out of scope for the edge entry at launch).\n const registry = new MutableModuleRegistry()\n for (const m of options.modules) registry.mount(m)\n const modules = registry.entries.map((entry) =>\n typeof entry === 'function' ? new (entry as AppModuleClass)() : (entry as AppModule),\n )\n // Declared settings sections — app-wide and mounted modules' — from the\n // platform env (Workers bindings) when given, bound before modules register.\n const settingsEnv = (options.env ??\n (typeof process !== 'undefined' ? process.env : {})) as NodeJS.ProcessEnv\n for (const [section, value] of loadSettings(\n [...(options.settings ?? []), ...modules.flatMap((mod) => mod.settings?.() ?? [])],\n settingsEnv,\n )) {\n container.registerInstance(section, value)\n }\n for (const mod of modules) mod.register?.(container)\n container.bootstrap()\n\n const app = new h3mod.H3()\n const getUrls: Array<{ url: string; handler: (event: H3EventLike) => unknown }> = []\n const apiPrefix = options.apiPrefix ?? '/api'\n const defaultVersion = options.defaultVersion ?? 1\n const globalMiddleware = options.middlewares ?? []\n const bodyLimit = parseByteSize(options.jsonLimit ?? DEFAULT_BODY_LIMIT)\n\n const globalSources: SourcedRegistration[] = (options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration: registration as SourcedRegistration['registration'],\n label: 'createWebApp',\n }),\n )\n\n // Duplicate-route guard (KICK006) — same boot-time check as the node path.\n const seenRoutes = new Map<string, string>()\n // For the catch-all: a known path with the wrong verb is a 405, not a 404.\n const mounted: MountedRoute[] = []\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n\n _setExternalContributorSources([...moduleSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue\n const routeSets = Array.isArray(result) ? result : [result]\n for (const route of routeSets) {\n if (!route.controller) {\n throw new Error(\n `@forinda/kickjs/web: module route at '${route.path}' has no controller. ` +\n 'Express-style `router` mounts are not supported on the web entry.',\n )\n }\n const version = route.version ?? defaultVersion\n // `prefix: false` mounts at the root — parity with Application.\n const mountPath = buildMountPath(\n route.prefix === false ? '' : apiPrefix,\n version,\n route.path,\n )\n for (const entry of buildRouteTable(route.controller, { mountFlags: route.flags })) {\n const url = joinPath(mountPath, entry.path)\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${route.controller.name ?? 'controller'}.${String(entry.meta.handlerName ?? '?')}`\n assertRouteUnique(seenRoutes, entry.method, url, owner)\n mounted.push({ method: entry.method, path: url })\n if (globalMiddleware.length > 0) {\n entry.middlewares = [...globalMiddleware, ...entry.middlewares]\n }\n entry.validationError = options.validationError\n entry.urls = routeUrls\n routeUrls.add(owner, url)\n const run = compileWebRoute(entry, undefined, { bodyLimit })\n const handler = (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n })\n app.on(entry.method, url, handler)\n if (entry.method === 'GET') getUrls.push({ url, handler })\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // HEAD answers every GET route, as on the node engines.\n for (const { url, handler } of getUrls) {\n app.on('HEAD', url, (event: H3EventLike) => headFromGet(handler(event) as Promise<Response>))\n }\n\n // Anything no route answered: the same 404 / 405 problem details as the\n // node engines, instead of h3's own 404 body.\n const notFound = notFoundHandler(mounted)\n app.all('/**', (event: H3EventLike) => {\n const driver = new WebResponseDriver(event.req.signal)\n notFound(new WebRequestShim(event.req, event.url), driver, () => {})\n return driver.ready\n })\n\n return {\n fetch: async (request: Request, platform?: PlatformContext) => {\n const response = await app.fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n h3: app,\n }\n}\n\n/**\n * Cloudflare Workers convenience: lazily build the app on the first request\n * so the Workers `env` binding can seed config before any module resolves.\n *\n * The Workers execution context (third argument) is forwarded, so work\n * handed to `ctx.waitUntil()` keeps running after the response.\n *\n * `scheduled` runs the `@Cron` jobs whose expression equals the trigger's\n * `event.cron` — list the same expressions under `[triggers] crons` in\n * wrangler.toml.\n *\n * `queue` consumes Cloudflare Queues: each message goes to the `@Job` class\n * for the batch's queue via `runJob`, and is acked when its handler\n * succeeds or retried when it throws. A message body of `{ name, data }`\n * picks the `@Process(name)` method; any other body goes to the queue's\n * catch-all `@Process()` as `data`.\n *\n * ```ts\n * export default createFetchHandler((env) => ({ h3, modules, env }))\n * ```\n */\nexport function createFetchHandler(\n build: (env: Record<string, string | undefined>) => CreateWebAppOptions,\n): {\n fetch: (\n request: Request,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<Response>\n scheduled: (\n event: { cron: string },\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n queue: (\n batch: QueueBatch,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n} {\n let app: WebApp | undefined\n return {\n fetch: (request, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n return app.fetch(request, ctx)\n },\n scheduled: async (event, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n const run = runCronJobs(Container.getInstance(), { expression: event.cron }, 'workers').then(\n () => {},\n )\n ctx?.waitUntil?.(run)\n await run\n },\n queue: async (batch, env = {}) => {\n app ??= createWebApp(build(env))\n const container = Container.getInstance()\n await Promise.all(\n batch.messages.map(async (message) => {\n const body = message.body as { name?: unknown; data?: unknown } | null\n const named = body !== null && typeof body === 'object' && typeof body.name === 'string'\n try {\n await runJob(container, batch.queue, {\n name: named ? (body!.name as string) : '',\n data: named ? body!.data : message.body,\n id: message.id,\n })\n message.ack()\n } catch {\n // Reported by runJob; Cloudflare redelivers per the queue's retry settings.\n message.retry()\n }\n }),\n )\n },\n }\n}\n\n/** The part of a Cloudflare Queues `MessageBatch` the consumer uses. */\nexport interface QueueBatch {\n readonly queue: string\n readonly messages: ReadonlyArray<{\n readonly id: string\n readonly body: unknown\n ack(): void\n retry(): void\n }>\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;ikCAwJA,SAAgB,aAAa,QAAsC,CACjE,IAAM,MAAQ,QAAQ,GACtB,GAAI,OAAO,OAAO,IAAO,WACvB,MAAU,MACR,0KAEF,EAGF,IAAM,UAAY,UAAU,YAAY,EAGlC,UAAY,IAAI,UAItB,GAHA,UAAU,iBAAiB,WAAY,SAAS,EAG5C,QAAQ,IAAK,CACf,IAAM,IAAM,QAAQ,IACpB,UAAU,eAAgB,KAAgB,IAAI,IAAI,CACpD,CAGA,UAAU,4BAA8B,aAAa,SAAS,GAAK,IAAI,EAIvE,IAAM,SAAW,IAAI,sBACrB,IAAK,IAAM,KAAK,QAAQ,QAAS,SAAS,MAAM,CAAC,EACjD,IAAM,QAAU,SAAS,QAAQ,IAAK,OACpC,OAAO,OAAU,WAAa,IAAK,MAA8B,KACnE,EAGM,YAAe,QAAQ,MAC1B,OAAO,QAAY,IAAc,QAAQ,IAAM,CAAC,GACnD,IAAK,GAAM,CAAC,QAAS,SAAU,aAC7B,CAAC,GAAI,QAAQ,UAAY,CAAC,EAAI,GAAG,QAAQ,QAAS,KAAQ,IAAI,WAAW,GAAK,CAAC,CAAC,CAAC,EACjF,WACF,EACE,UAAU,iBAAiB,QAAS,KAAK,EAE3C,IAAK,IAAM,OAAO,QAAS,IAAI,WAAW,SAAS,EACnD,UAAU,UAAU,EAEpB,IAAM,IAAM,IAAI,MAAM,GAChB,QAA4E,CAAC,EAC7E,UAAY,QAAQ,WAAa,OACjC,eAAiB,QAAQ,gBAAkB,EAC3C,iBAAmB,QAA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,GAAG,CAAC,EAC/B,IAAM,UAAY,UAAU,YAAY,EACxC,MAAM,QAAQ,IACZ,MAAM,SAAS,IAAI,KAAO,UAAY,CACpC,IAAM,KAAO,QAAQ,KACf,MAAyB,OAAO,MAAS,YAAjC,MAA6C,OAAO,KAAK,MAAS,SAChF,GAAI,CACF,MAAM,OAAO,UAAW,MAAM,MAAO,CACnC,KAAM,MAAS,KAAM,KAAkB,GACvC,KAAM,MAAQ,KAAM,KAAO,QAAQ,KACnC,GAAI,QAAQ,EACd,CAAC,EACD,QAAQ,IAAI,CACd,MAAQ,CAEN,QAAQ,MAAM,CAChB,CACF,CAAC,CACH,CACF,CACF,CACF,CAcA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
|
|
1
|
+
{"version":3,"file":"web.mjs","names":[],"sources":["../src/web.ts"],"sourcesContent":["// `@forinda/kickjs/web` — the web-standard fetch entry for edge runtimes\n// (Cloudflare Workers), Bun, and Deno.\n//\n// PURITY CONTRACT: this entry's import graph must stay free of node-only\n// runtime imports — no `node:http`, `node:cluster`, `node:fs`, `node:module`,\n// no `express`, no `Application`/`bootstrap`. The single sanctioned node API\n// is `node:async_hooks` (AsyncLocalStorage — available on Workers with\n// `nodejs_compat`, Deno, and Bun). Enforced by the bundle-graph purity test.\n//\n// ```ts\n// // Cloudflare Workers (wrangler.toml: compatibility_flags = [\"nodejs_compat\"])\n// import { createWebApp } from '@forinda/kickjs/web'\n// import * as h3 from 'h3'\n// import { modules } from './modules'\n//\n// const app = createWebApp({ h3, modules })\n// export default { fetch: (req: Request) => app.fetch(req) }\n//\n// // Bun\n// Bun.serve({ fetch: (req) => app.fetch(req) })\n// ```\n\nimport { Container } from './core/container'\nimport { MutableModuleRegistry } from './core/module-registry'\nimport type { AppModule, AppModuleClass, AppModuleEntry } from './core/app-module'\nimport type { ContributorRegistrations } from './core/context-decorator'\nimport type { MiddlewareHandler } from './core/decorators'\nimport type { SourcedRegistration } from './core/contributor-pipeline'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './http/router-builder'\nimport { requestStore } from './http/request-store'\nimport { forwardBackgroundWork, type PlatformContext } from './http/background'\nimport { runCronJobs } from './core/cron'\nimport { runJob } from './core/jobs'\nimport { compileWebRoute, headFromGet } from './http/web/handler'\nimport { ROUTE_URLS, RouteUrls } from './http/url-for'\nimport { loadSettings, type SettingsDeclaration } from './config/settings'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './http/body-policy'\nimport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nimport { notFoundHandler, type MountedRoute } from './http/middleware/error-handler'\nimport type { ValidationErrorFactory } from './http/middleware/validate'\nimport { buildMountPath } from './core/path'\nimport { moduleName } from './core/define-module'\n\nexport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nexport { compileWebRoute } from './http/web/handler'\n// Return-value handler helpers — edge consumers can't import the main barrel.\nexport {\n reply,\n isReply,\n type Reply,\n type ReplyHeaders,\n type ReplyOptions,\n type InferHandlerResponse,\n} from './http/reply'\nexport type { SseHandler } from './http/context'\nexport { waitUntil, type PlatformContext } from './http/background'\nexport { runCronJobs, type CronRun } from './core/cron'\nexport { matchesBearer } from './core/web-crypto'\nexport {\n runJob,\n registerJobContext,\n stampJobContext,\n JOB_CONTEXT_FIELD,\n type JobLike,\n type JobContextCarrier,\n} from './core/jobs'\n// Edge-safe stores + ctx-style rate limiter (zero runtime imports).\nexport {\n KvRateLimitStore,\n KvSessionStore,\n type KvLike,\n type KvRateLimitStoreOptions,\n type KvSessionStoreOptions,\n} from './http/middleware/kv-stores'\nexport { rateLimitGuard, type RateLimitGuardOptions } from './http/middleware/rate-limit-guard'\n\n// Minimal structural surface of h3 v2 used here (kept local so this entry\n// never imports the node-coupled h3 runtime module).\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request\n url: URL\n context: { params?: Record<string, string> }\n}\n\nexport interface CreateWebAppOptions {\n /**\n * The h3 v2 module, statically imported by the caller:\n * `import * as h3 from 'h3'`. Passed in (rather than loaded here) because\n * edge bundlers have no `createRequire`, and a static `import 'h3'` inside\n * this entry would force the peer on every consumer of the subpath.\n */\n h3: unknown\n /** App modules — same shapes `bootstrap({ modules })` accepts. */\n modules: AppModuleEntry[]\n /** Route prefix (default '/api') — parity with bootstrap. */\n apiPrefix?: string\n /**\n * Default route version (default 1) — parity with bootstrap. `false` opts\n * out of URL versioning; a module's own `version` still overrides it.\n */\n defaultVersion?: number | false\n /** Global Context Contributors — parity with `bootstrap({ contributors })`. */\n contributors?: ContributorRegistrations\n /**\n * Env values for ConfigService/@Value resolution. On Workers, pass the\n * `env` binding from the fetch handler (see `createFetchHandler`); on\n * Bun/Deno, ambient `process.env` already works and this can be omitted.\n */\n env?: Record<string, string | undefined>\n /**\n * Global `(ctx, next)` middlewares, run before route middlewares on every\n * route — the web-entry counterpart of `bootstrap({ middlewares })`. Only\n * ctx-style handlers are accepted (no connect/express middleware here).\n */\n middlewares?: MiddlewareHandler[]\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`)\n * — parity with `bootstrap({ jsonLimit })`. A larger body answers 413.\n */\n jsonLimit?: string | number\n /** App-wide settings sections — parity with `bootstrap({ settings })`. */\n settings?: SettingsDeclaration[]\n /** What a failed route validation throws — parity with `bootstrap({ validationError })`. */\n validationError?: ValidationErrorFactory\n}\n\nexport interface WebApp {\n /**\n * Web-standard entry: `Request` in, `Response` out. Pass the platform\n * context (Workers `ctx`, Netlify `context`) so work handed to\n * `ctx.waitUntil()` finishes after the response.\n */\n fetch: (request: Request, platform?: PlatformContext) => Promise<Response>\n /** The underlying h3 v2 app, for advanced composition. */\n h3: unknown\n}\n\n/**\n * Build a KickJS app as a web-standard fetch handler — no node http server,\n * no Application/bootstrap. Module registration, DI, and the contributor\n * pipeline behave exactly like `bootstrap()`; routes are compiled once here\n * and served through h3 v2's router.\n */\nexport function createWebApp(options: CreateWebAppOptions): WebApp {\n const h3mod = options.h3 as { H3?: new () => H3AppLike }\n if (typeof h3mod?.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs/web: pass the h3 v2 module — `createWebApp({ h3: await import(\"h3\"), ... })`. ' +\n \"The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.\",\n )\n }\n\n const container = Container.getInstance()\n // Route names for ctx.urlFor() / the ROUTE_URLS token — bound before modules\n // register so their services can inject it.\n const routeUrls = new RouteUrls()\n container.registerInstance(ROUTE_URLS, routeUrls)\n // Wire ConfigService/@Value env resolution when the platform has no\n // ambient process.env (Workers). Latest-wins like loadEnv().\n if (options.env) {\n const env = options.env\n Container.setEnvResolver((key: string) => env[key])\n }\n\n // Request-scope provider — same wiring Application.setup() performs.\n Container.setRequestStoreProvider(() => requestStore.getStore() ?? null)\n\n // Module mounting — mirrors Application.setup() steps 1:1 for the module\n // path (plugins/adapters are out of scope for the edge entry at launch).\n const registry = new MutableModuleRegistry()\n for (const m of options.modules) registry.mount(m)\n const modules = registry.entries.map((entry) =>\n typeof entry === 'function' ? new (entry as AppModuleClass)() : (entry as AppModule),\n )\n // Declared settings sections — app-wide and mounted modules' — from the\n // platform env (Workers bindings) when given, bound before modules register.\n const settingsEnv = (options.env ??\n (typeof process !== 'undefined' ? process.env : {})) as NodeJS.ProcessEnv\n for (const [section, value] of loadSettings(\n [...(options.settings ?? []), ...modules.flatMap((mod) => mod.settings?.() ?? [])],\n settingsEnv,\n )) {\n container.registerInstance(section, value)\n }\n for (const mod of modules) mod.register?.(container)\n container.bootstrap()\n\n const app = new h3mod.H3()\n const getUrls: Array<{ url: string; handler: (event: H3EventLike) => unknown }> = []\n const apiPrefix = options.apiPrefix ?? '/api'\n const defaultVersion = options.defaultVersion ?? 1\n const globalMiddleware = options.middlewares ?? []\n const bodyLimit = parseByteSize(options.jsonLimit ?? DEFAULT_BODY_LIMIT)\n\n const globalSources: SourcedRegistration[] = (options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration: registration as SourcedRegistration['registration'],\n label: 'createWebApp',\n }),\n )\n\n // Duplicate-route guard (KICK006) — same boot-time check as the node path.\n const seenRoutes = new Map<string, string>()\n // For the catch-all: a known path with the wrong verb is a 405, not a 404.\n const mounted: MountedRoute[] = []\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n\n _setExternalContributorSources([...moduleSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue\n const routeSets = Array.isArray(result) ? result : [result]\n for (const route of routeSets) {\n if (!route.controller) {\n throw new Error(\n `@forinda/kickjs/web: module route at '${route.path}' has no controller. ` +\n 'Express-style `router` mounts are not supported on the web entry.',\n )\n }\n const version = route.version ?? defaultVersion\n // `prefix: false` mounts at the root — parity with Application.\n const mountPath = buildMountPath(\n route.prefix === false ? '' : apiPrefix,\n version,\n route.path,\n )\n for (const entry of buildRouteTable(route.controller, { mountFlags: route.flags })) {\n const url = joinPath(mountPath, entry.path)\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${route.controller.name ?? 'controller'}.${String(entry.meta.handlerName ?? '?')}`\n assertRouteUnique(seenRoutes, entry.method, url, owner)\n mounted.push({ method: entry.method, path: url })\n if (globalMiddleware.length > 0) {\n entry.middlewares = [...globalMiddleware, ...entry.middlewares]\n }\n entry.validationError = options.validationError\n entry.urls = routeUrls\n routeUrls.add(owner, url)\n const run = compileWebRoute(entry, undefined, { bodyLimit })\n const handler = (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n })\n app.on(entry.method, url, handler)\n if (entry.method === 'GET') getUrls.push({ url, handler })\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // HEAD answers every GET route, as on the node engines.\n for (const { url, handler } of getUrls) {\n app.on('HEAD', url, (event: H3EventLike) => headFromGet(handler(event) as Promise<Response>))\n }\n\n // Anything no route answered: the same 404 / 405 problem details as the\n // node engines, instead of h3's own 404 body.\n const notFound = notFoundHandler(mounted)\n app.all('/**', (event: H3EventLike) => {\n const driver = new WebResponseDriver(event.req.signal)\n notFound(new WebRequestShim(event.req, event.url), driver, () => {})\n return driver.ready\n })\n\n return {\n fetch: async (request: Request, platform?: PlatformContext) => {\n const response = await app.fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n h3: app,\n }\n}\n\n/**\n * Cloudflare Workers convenience: lazily build the app on the first request\n * so the Workers `env` binding can seed config before any module resolves.\n *\n * The Workers execution context (third argument) is forwarded, so work\n * handed to `ctx.waitUntil()` keeps running after the response.\n *\n * `scheduled` runs the `@Cron` jobs whose expression equals the trigger's\n * `event.cron` — list the same expressions under `[triggers] crons` in\n * wrangler.toml.\n *\n * `queue` consumes Cloudflare Queues: each message goes to the `@Job` class\n * for the batch's queue via `runJob`, and is acked when its handler\n * succeeds or retried when it throws. A message body of `{ name, data }`\n * picks the `@Process(name)` method; any other body goes to the queue's\n * catch-all `@Process()` as `data`.\n *\n * ```ts\n * export default createFetchHandler((env) => ({ h3, modules, env }))\n * ```\n */\nexport function createFetchHandler(\n build: (env: Record<string, string | undefined>) => CreateWebAppOptions,\n): {\n fetch: (\n request: Request,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<Response>\n scheduled: (\n event: { cron: string },\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n queue: (\n batch: QueueBatch,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n} {\n let app: WebApp | undefined\n return {\n fetch: (request, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n return app.fetch(request, ctx)\n },\n scheduled: async (event, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n const run = runCronJobs(Container.getInstance(), { expression: event.cron }, 'workers').then(\n () => {},\n )\n ctx?.waitUntil?.(run)\n await run\n },\n queue: async (batch, env = {}) => {\n app ??= createWebApp(build(env))\n const container = Container.getInstance()\n await Promise.all(\n batch.messages.map(async (message) => {\n const body = message.body as { name?: unknown; data?: unknown } | null\n const named = body !== null && typeof body === 'object' && typeof body.name === 'string'\n try {\n await runJob(container, batch.queue, {\n name: named ? (body!.name as string) : '',\n data: named ? body!.data : message.body,\n id: message.id,\n })\n message.ack()\n } catch {\n // Reported by runJob; Cloudflare redelivers per the queue's retry settings.\n message.retry()\n }\n }),\n )\n },\n }\n}\n\n/** The part of a Cloudflare Queues `MessageBatch` the consumer uses. */\nexport interface QueueBatch {\n readonly queue: string\n readonly messages: ReadonlyArray<{\n readonly id: string\n readonly body: unknown\n ack(): void\n retry(): void\n }>\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;omCAwJA,SAAgB,aAAa,QAAsC,CACjE,IAAM,MAAQ,QAAQ,GACtB,GAAI,OAAO,OAAO,IAAO,WACvB,MAAU,MACR,0KAEF,EAGF,IAAM,UAAY,UAAU,YAAY,EAGlC,UAAY,IAAI,UAItB,GAHA,UAAU,iBAAiB,WAAY,SAAS,EAG5C,QAAQ,IAAK,CACf,IAAM,IAAM,QAAQ,IACpB,UAAU,eAAgB,KAAgB,IAAI,IAAI,CACpD,CAGA,UAAU,4BAA8B,aAAa,SAAS,GAAK,IAAI,EAIvE,IAAM,SAAW,IAAI,sBACrB,IA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+0,0 @@
|
|
|
1
|
-
{"version":3,"file":"adapter-DiJfCKXU.d.mts","names":["Container","Container","_0","NextFunction","Request","RequestHandler","ErrorRequestHandler","Container"],"sources":["../src/core/adapter-conditions.ts","../src/core/failure-analysis.ts","../src/core/observers.ts","../src/core/introspect.ts","../src/core/augmentation.ts","../src/core/module-registry.ts","../src/core/plugin.ts","../src/core/define-plugin.ts","../src/core/define-module.ts","../src/core/define-modules.ts","../src/core/contributor-pipeline.ts","../src/core/contributor-runner.ts","../src/core/define-adapter.ts","../src/http/view-renderer.ts","../src/http/url-for.ts","../src/http/conditional.ts","../src/http/middleware/upload-config.ts","../src/http/context.ts","../src/http/runtime.ts","../src/core/adapter.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;KAcY;;UAGK;EACf;EACA;;EAEA;;;;;;;;iBASc,MAAM,cAAc,iBAAiB;;;;;;;iBAiBrC,UAAU,eAAe;;iBAqBzB,SAAS,YAAY,qBAAqB;;;;;;;;;;UC5DzC;EACf;EACA;EACA;;;;;KCSU;UAQK;EACf,QAAQ;EACR;EACA;;EAEA;;EAEA;;EAEA;;EAEA,UAAU;;UAGK;EACf;EACA;;EAEA;EACA;EACA;EACA;;;;;;;;iBAiFc,YAAY,gBAAgB,MAAM;;iBAKlC,eAAe,MAAM;;;;;;;;;;;;;;;;;;;;;UCrHpB;;;;;;;;;;EAUf;;EAEA;;EAEA,MAAM;;EAEN;;;;;EAKA,QAAQ;;EAER;IAAW;IAA6B;;;;;;EAKxC,UAAU;;EAEV;;;;;;;;KASU;;;;;;KAOA,qBAAqB,wBAAwB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;UC3ChD;;;;;;;;;KAUL,yBAAyB,oDAE3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCAO;;;;;;;;;;;EAWf,MAAM,QAAQ;;;;;;;;;;;cAYH,iCAAiC;WACnC,SAAS;EAElB,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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aAAa,KAAK,wBAAwB;;;;;EAM1C,cAAc,iBAAiB,aAAa;;;;;;;;;;;;;EAc5C,aAAa,KAAK,wBAAwB;;;;;;;;;;;;;;;EAgB1C,YAAY,KAAK,wBAAwB;;;;;EAMzC,kBAAkB;IAAU;IAAc;;;;;;;;;EAS1C,SAAS,gBAAgB,MAAM,mBAAmB;;;;;EAKlD,YAAY,MAAM,sBAAsB;;;;;;;;;;;;;;;;EAiBxC,aAAa;;;;;;;;;;;;;EAcb,eAAe,wBAAwB,QAAQ;;;;;;;;;;;EAY/C;;;KAIU,4BAA4B"}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.12.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{HttpException,normalizeProblem}from"./core/errors.mjs";import{t as ROUTE_SLOT}from"./route-flag-ECQsPj4x.mjs";import{r as MissingContextValueError}from"./context-errors-BULDLnr1.mjs";import{t as isProduction}from"./is-production-D0kfhCW4.mjs";import{a as viewRendererFor,f as requestStore,i as setPendingResponse,l as waitUntil}from"./view-renderer-CSPD7F-f.mjs";import{t as resolveClientIp}from"./client-ip-BAtoGmC3.mjs";import{a as parseQuery}from"./query-Coc1hIiS.mjs";function header(headers,name){let value=headers[name];return Array.isArray(value)?value.join(`, `):value}function normalizeEtag(etag){if(/^(W\/)?".*"$/.test(etag))return etag;let weak=etag.startsWith(`W/`),bare=(weak?etag.slice(2):etag).replaceAll(`"`,``);return`${weak?`W/`:``}"${bare}"`}const opaque=tag=>tag.replace(/^W\//,``),isWeak=tag=>tag.startsWith(`W/`);function tagsOf(value){return value.match(/\*|(?:W\/)?"[^"]*"/g)??[]}function dateOf(value){if(!value)return;let ms=Date.parse(value);return Number.isNaN(ms)?void 0:ms}const seconds=date=>Math.floor(date.getTime()/1e3)*1e3;function evaluatePreconditions(method,headers,validators){let etag=validators.etag===void 0?void 0:normalizeEtag(validators.etag),modified=validators.lastModified?seconds(validators.lastModified):void 0,safe=method===`GET`||method===`HEAD`,ifMatch=header(headers,`if-match`);if(ifMatch!==void 0){let tags=tagsOf(ifMatch);if(!(tags.includes(`*`)||etag!==void 0&&!isWeak(etag)&&tags.some(t=>!isWeak(t)&&t===etag)))return 412}else{let since=dateOf(header(headers,`if-unmodified-since`));if(since!==void 0&&modified!==void 0&&modified>since)return 412}let ifNoneMatch=header(headers,`if-none-match`);if(ifNoneMatch!==void 0){let tags=tagsOf(ifNoneMatch);return tags.includes(`*`)||etag!==void 0&&tags.some(t=>opaque(t)===opaque(etag))?safe?304:412:200}if(safe){let since=dateOf(header(headers,`if-modified-since`));if(since!==void 0&&modified!==void 0&&modified<=since)return 304}return 200}function publishMatchedRoute(req,entry){let route=matchedRoutes.get(entry);route||(route=Object.freeze({method:entry.method,path:entry.path,controller:entry.meta.controller,handlerName:entry.meta.handlerName,flags:entry.meta.flags??EMPTY_FLAGS,pattern:entry.meta.pattern??entry.path,urls:entry.urls}),matchedRoutes.set(entry,route)),req[ROUTE_SLOT]=route}const matchedRoutes=/* @__PURE__ */ new WeakMap,EMPTY_FLAGS=/* @__PURE__ */ new Map;function isBigIntJsonError(err){return err instanceof TypeError&&/BigInt/.test(err.message)}function stringifyJson(data){try{return JSON.stringify(data)}catch(err){if(!isBigIntJsonError(err))throw err;return JSON.stringify(data,(_key,value)=>typeof value==`bigint`?value.toString():value)}}function sortSignature(sort){return sort.map(s=>`${s.field}:${s.direction}`).join(`,`)}function isPrimitive(value){return value===null||[`string`,`number`,`boolean`].includes(typeof value)}function encodeCursor(position,signature){let bytes=new TextEncoder().encode(JSON.stringify({v:position,s:signature})),binary=``;for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function decodeCursor(raw,signature,keys){let invalid=()=>HttpException.badRequest(`Invalid pagination cursor`);if(typeof raw!=`string`||!/^[A-Za-z0-9_-]+$/.test(raw))throw invalid();let parsed;try{let binary=atob(raw.replace(/-/g,`+`).replace(/_/g,`/`)),bytes=Uint8Array.from(binary,c=>c.charCodeAt(0));parsed=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(bytes))}catch{throw invalid()}if(typeof parsed!=`object`||!parsed)throw invalid();let{v,s}=parsed;if(typeof v!=`object`||!v||Array.isArray(v)||!Object.values(v).every(isPrimitive)||keys&&(Object.keys(v).length!==keys.length||!keys.every(k=>Object.hasOwn(v,k))))throw invalid();if(s!==signature)throw HttpException.badRequest(`Pagination cursor was issued for a different sort`);return v}function pageLink(rawUrl,key,value){let url=parseUrl(rawUrl),kept=url.search.slice(1).split(`&`).filter(part=>part!==``&¶mName(part)!==key);return value!==null&&kept.push(`${key}=${encodeURIComponent(value)}`),kept.length?`${url.pathname}?${kept.join(`&`)}`:url.pathname}function selfLink(rawUrl){let url=parseUrl(rawUrl);return url.pathname+url.search}function parseUrl(rawUrl){let url=new URL(rawUrl,`http://localhost`);return url.pathname=url.pathname.replace(/^\/+/,`/`),url}function paramName(part){let name=part.split(`=`,1)[0].replace(/\+/g,` `);try{return decodeURIComponent(name)}catch{return name}}const signalControllerKey=Symbol.for(`kickjs.requestContext.signalController`),readOnlyProxyCacheKey=Symbol.for(`kickjs.requestContext.readOnlyProxyCache`);function isPlainObjectOrArray(v){if(typeof v!=`object`||!v)return!1;if(Array.isArray(v))return!0;let proto=Object.getPrototypeOf(v);return proto===Object.prototype||proto===null}function makeReadOnlyProxy(target,req,label){if(isProduction()||!isPlainObjectOrArray(target))return target;let reqObj=req,cache=reqObj[readOnlyProxyCacheKey];cache||(cache=/* @__PURE__ */ new WeakMap,reqObj[readOnlyProxyCacheKey]=cache);let targetObj=target,cached=cache.get(targetObj);if(cached)return cached;let warnWrite=(verb,prop)=>{console.warn(`[kickjs] Attempted to ${verb} \`ctx.${label}.${String(prop)}\` — request data is read-only. Stash computed values via \`ctx.set('key', value)\` or a Context Contributor, or reach \`ctx.req.${label}\` if you genuinely need the raw mutable handle.`)},proxy=new Proxy(targetObj,{get(t,prop,receiver){let value=Reflect.get(t,prop,receiver);return isPlainObjectOrArray(value)?makeReadOnlyProxy(value,req,`${label}.${String(prop)}`):value},set(_t,prop){return warnWrite(`assign`,prop),!0},deleteProperty(_t,prop){return warnWrite(`delete`,prop),!0},defineProperty(_t,prop){return warnWrite(`Object.defineProperty on`,prop),!0}});return cache.set(targetObj,proxy),proxy}var RequestContext=class{req;res;next;_response;get route(){return this.req?.[ROUTE_SLOT]}constructor(req,res,next,responseDriver){this.req=req,this.res=res,this.next=next,this._response=responseDriver??res}_qsMemo;_problem;metadataReadOnly(){return requestStore.getStore()?.values??null}metadataForWrite(){let store=requestStore.getStore();if(store)return store.values;throw Error(`RequestContext.set called outside an AsyncLocalStorage frame. Mount requestScopeMiddleware() before constructing RequestContext, or wrap test setup in requestStore.run({ requestId, instances: new Map(), values: new Map() }, () => ...).`)}get body(){return makeReadOnlyProxy(this.req.body,this.req,`body`)}get params(){return makeReadOnlyProxy(this.req.params,this.req,`params`)}get query(){return makeReadOnlyProxy(this.req.query,this.req,`query`)}get headers(){return makeReadOnlyProxy(this.req.headers,this.req,`headers`)}get requestId(){return this.req.requestId??this.req.headers[`x-request-id`]}get signal(){let req=this.req,cached=req[signalControllerKey];if(cached)return cached.signal;let ctrl=new AbortController;req[signalControllerKey]=ctrl;let abort=()=>ctrl.abort(`request closed`);return this.req.once(`close`,abort),this._response.once(`close`,abort),ctrl.signal}get session(){return this.req.session}get user(){return this.metadataReadOnly()?.get(`user`)??this.req.user}get tenantId(){return this.user?.tenantId}get roles(){let u=this.user;return u?.tenantRoles??u?.roles??[]}qs(fieldConfig,options){let memo=this._qsMemo;if(memo&&memo.config===fieldConfig&&memo.options===options)return memo.result;let effective={...options,onReject:options?.onReject??(rejection=>{let id=this.requestId?`[${this.requestId}] `:``;console.warn(`${id}query ${rejection.kind} '${rejection.field}' rejected (${rejection.reason})`)})},result=parseQuery(this.req.query,fieldConfig,effective);return this._qsMemo={config:fieldConfig,options,result},result}get file(){let f=this.req.file;return f?makeReadOnlyProxy(f,this.req,`file`):void 0}get files(){let f=this.req.files;if(Array.isArray(f))return makeReadOnlyProxy(f,this.req,`files`)}get(key){return this.metadataReadOnly()?.get(key)}require(key){let value=this.metadataReadOnly()?.get(key);if(value===void 0)throw new MissingContextValueError(key,this.routeLabel());return value}routeLabel(){let req=this.req,method=typeof req?.method==`string`?req.method:void 0,url=typeof req?.url==`string`?req.url:void 0;return method&&url?`${method} ${url}`:method??url}set(key,value){this.metadataForWrite().set(key,value)}setHeader(name,value){return this._response.setHeader(name,value),this}json(data,status=200){return this.sendJson(status,data)}created(data){return this.sendJson(201,data)}sendJson(status,data){try{return this._response.status(status).json(data)}catch(err){if(!isBigIntJsonError(err)||this._response.headersSent)throw err;return this._response.status(status).json(JSON.parse(stringifyJson(data)))}}noContent(){return this._response.status(204).end()}urlFor(name,...args){let urls=this.route?.urls;if(!urls)throw Error(`ctx.urlFor() is only available inside a matched route`);let[params,query]=args;return urls.build(name,params,query)}conditional(validators){validators.etag!==void 0&&this.setHeader(`ETag`,normalizeEtag(validators.etag)),validators.lastModified&&this.setHeader(`Last-Modified`,validators.lastModified.toUTCString());let outcome=evaluatePreconditions(String(this.req.method??`GET`).toUpperCase(),this.headers,validators);return outcome===304?(this._response.status(304).end(),!0):outcome===412&&(this.sendProblem({status:412,detail:`The resource changed since the version this request is based on.`}),!0)}notFound(message=`Not Found`){return this._response.status(404).json({message})}badRequest(message){return this._response.status(400).json({message})}get problem(){if(this._problem)return this._problem;let send=input=>this.sendProblem(input);return send.badRequest=(input={})=>this.sendProblem({status:400,...input}),send.unauthorized=(input={})=>this.sendProblem({status:401,...input}),send.forbidden=(input={})=>this.sendProblem({status:403,...input}),send.notFound=(input={})=>this.sendProblem({status:404,...input}),send.conflict=(input={})=>this.sendProblem({status:409,...input}),send.unprocessable=(input={})=>this.sendProblem({status:422,...input}),send.tooManyRequests=(input={})=>this.sendProblem({status:429,...input}),send.internal=(input={})=>this.sendProblem({status:500,...input}),send.validation=(issues,input={})=>{let errors=(issues||[]).map(issue=>({field:issue.path?.join?.(`.`)??``,message:issue.message??``,code:issue.code}));return this.sendProblem({status:422,detail:issues?.[0]?.message,...input,errors})},this._problem=send,this._problem}sendProblem(input){let body=normalizeProblem(input);return this._response.setHeader(`Content-Type`,`application/problem+json`),this._response.status(body.status).json(body)}get ip(){return resolveClientIp(this.req)}redirect(url,status=302){return this._response.status(status).setHeader(`location`,url),this._response.end()}html(content,status=200){return this._response.status(status).type(`text/html; charset=utf-8`).send(content)}send(body,options={}){return this._response.status(options.status??200).type(options.type??`text/plain; charset=utf-8`).send(body)}download(buffer,filename,contentType=`application/octet-stream`){return this._response.setHeader(`Content-Disposition`,contentDisposition(filename)),this._response.setHeader(`Content-Type`,contentType),this._response.send(buffer)}render(template,data={},opts={}){let renderer=viewRendererFor(this.req);if(!renderer)return this._response.render(template,data);let done=renderer(template,data,opts,this).then(html=>{if(html===void 0)this._response.render(template,data);else{for(let[name,value]of Object.entries(opts.headers??{}))this.setHeader(name,value);this.html(html,opts.status??200)}});return setPendingResponse(this,done),done.catch(()=>{}),done}async paginate(fetcher,fieldConfig){let parsed=this.qs(fieldConfig),{data,total}=await fetcher(parsed),{page,limit}=parsed.pagination,totalPages=Math.ceil(total/limit)||1,response={data,meta:{page,limit,total,totalPages,hasNext:page<totalPages,hasPrev:page>1},links:{self:selfLink(this.requestUrl()),next:page<totalPages?pageLink(this.requestUrl(),`page`,page+1):null,prev:page>1?pageLink(this.requestUrl(),`page`,page-1):null}};return this.json(response),response}async paginateCursor(fetcher,fieldConfig,options){let{pagination,...parsed}=this.qs(fieldConfig),{limit}=pagination,idField=options?.idField??`id`,signature=sortSignature(parsed.sort),keys=options?.cursorKey?void 0:[.../* @__PURE__ */ new Set([...parsed.sort.map(s=>s.field),idField])],raw=this.req.query?.cursor,cursor=raw===void 0||raw===``?null:decodeCursor(raw,signature,keys),rows=await fetcher({...parsed,cursor,limit}),hasNext=rows.length>limit,data=hasNext?rows.slice(0,limit):rows,last=data.at(-1),nextCursor=null;hasNext&&last!==void 0&&(nextCursor=encodeCursor(cursorValues(last,keys??[],options?.cursorKey),signature));let url=this.requestUrl(),response={data,meta:{limit,hasNext,nextCursor},links:{self:selfLink(url),next:nextCursor?pageLink(url,`cursor`,nextCursor):null}};return this.json(response),response}requestUrl(){let req=this.req;return typeof req.originalUrl==`string`?req.originalUrl:typeof req.url==`string`?req.url:`/`}async sendResponse(response){let headers={};response.headers.forEach((value,name)=>{name!==`set-cookie`&&(headers[name]=value)});let cookies=response.headers.getSetCookie();if(cookies.length>0&&(headers[`set-cookie`]=cookies),!response.body){this._response.status(response.status);for(let[name,value]of Object.entries(headers))this._response.setHeader(name,value);this._response.send(``);return}this._response.writeHead(response.status,headers),this._response.flushHeaders();let reader=response.body.getReader(),stop=()=>{reader.cancel().catch(()=>{})};this.signal.addEventListener(`abort`,stop,{once:!0});try{for(;;){let{done,value}=await reader.read();if(done)break;this._response.write(Buffer.from(value))===!1&&!this.signal.aborted&&await new Promise(resolve=>{let resume=()=>{this.signal.removeEventListener(`abort`,resume),resolve()};this._response.once(`drain`,resume),this.signal.addEventListener(`abort`,resume,{once:!0})})}}finally{this.signal.removeEventListener(`abort`,stop),this._response.end()}}waitUntil(promise){waitUntil(promise)}sse(){this._response.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}),this._response.flushHeaders();let closeCallbacks=[];return this.req.on(`close`,()=>{for(let cb of closeCallbacks)cb()}),{send:(data,event,id)=>{id&&this._response.write(`id: ${id}\n`),event&&this._response.write(`event: ${event}\n`),this._response.write(`data: ${JSON.stringify(data)}\n\n`)},comment:text=>{this._response.write(`: ${text}\n\n`)},onClose:fn=>{closeCallbacks.push(fn)},close:()=>{this._response.end()}}}};function contentDisposition(filename){return`attachment; filename="${filename.replace(/[^\x20-\x7e]|["\\]/g,`_`)}"; filename*=UTF-8''${encodeURIComponent(filename).replace(/['()*]/g,c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`}function cursorValues(row,keys,cursorKey){if(cursorKey)return cursorKey(row);let values={};for(let key of keys){let value=row[key];if(value===void 0)throw Error(`paginateCursor: row has no '${key}' — return the sort fields and the id field on every row, or pass options.cursorKey / options.idField`);values[key]=value instanceof Date?value.toISOString():typeof value==`bigint`?value.toString():value}return values}export{evaluatePreconditions as a,stringifyJson as i,contentDisposition as n,publishMatchedRoute as r,RequestContext as t};
|
|
12
|
-
//# sourceMappingURL=context-Cc6k0gsM.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-Cc6k0gsM.mjs","names":[],"sources":["../src/http/conditional.ts","../src/http/runtime.ts","../src/http/query/cursor.ts","../src/http/context.ts"],"sourcesContent":["/**\n * Conditional requests (RFC 9110 §13): answer `304 Not Modified` when the\n * client's copy is current, and `412 Precondition Failed` when a write was\n * based on a stale one. Decided from validators the handler supplies — an\n * ETag, a last-modified time — before it does the expensive part.\n *\n * @module @forinda/kickjs/http/conditional\n */\n\n/** What identifies the current version of a resource. */\nexport interface Validators {\n /**\n * An entity tag. Quoted for you if bare: `'v42'` → `\"v42\"`. Prefix with\n * `W/` for a weak tag (same meaning, not byte-identical).\n */\n etag?: string\n /** When the resource last changed. Compared to the second, as HTTP dates are. */\n lastModified?: Date\n}\n\n/** 200: go on and respond. 304 / 412: answer with that status, no body. */\nexport type ConditionalOutcome = 200 | 304 | 412\n\ntype Headers = Record<string, string | string[] | undefined>\n\nfunction header(headers: Headers, name: string): string | undefined {\n const value = headers[name]\n return Array.isArray(value) ? value.join(', ') : value\n}\n\n/** `\"v1\"` and `W/\"v1\"` stay; bare `v1` becomes `\"v1\"`, bare `W/v1` becomes `W/\"v1\"`. */\nexport function normalizeEtag(etag: string): string {\n if (/^(W\\/)?\".*\"$/.test(etag)) return etag\n // Keep a weak prefix weak: quoting `W/v1` whole would make `\"W/v1\"`, a\n // strong tag, and change how If-Match compares it.\n const weak = etag.startsWith('W/')\n const bare = (weak ? etag.slice(2) : etag).replaceAll('\"', '')\n return `${weak ? 'W/' : ''}\"${bare}\"`\n}\n\nconst opaque = (tag: string) => tag.replace(/^W\\//, '')\nconst isWeak = (tag: string) => tag.startsWith('W/')\n\n/** The tags in an If-Match / If-None-Match list (`*` kept as is). */\nfunction tagsOf(value: string): string[] {\n return value.match(/\\*|(?:W\\/)?\"[^\"]*\"/g) ?? []\n}\n\n/** An HTTP date, or undefined when it doesn't parse — an invalid one is ignored. */\nfunction dateOf(value: string | undefined): number | undefined {\n if (!value) return undefined\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? undefined : ms\n}\n\n/** HTTP dates have one-second resolution. */\nconst seconds = (date: Date) => Math.floor(date.getTime() / 1000) * 1000\n\n/**\n * The outcome of a request's preconditions against the current validators,\n * evaluated in RFC 9110 §13.2.2 order.\n */\nexport function evaluatePreconditions(\n method: string,\n headers: Headers,\n validators: Validators,\n): ConditionalOutcome {\n const etag = validators.etag === undefined ? undefined : normalizeEtag(validators.etag)\n const modified = validators.lastModified ? seconds(validators.lastModified) : undefined\n const safe = method === 'GET' || method === 'HEAD'\n\n // 1. If-Match — strong comparison; `*` matches any current representation.\n const ifMatch = header(headers, 'if-match')\n if (ifMatch !== undefined) {\n const tags = tagsOf(ifMatch)\n const matched =\n tags.includes('*') ||\n (etag !== undefined && !isWeak(etag) && tags.some((t) => !isWeak(t) && t === etag))\n if (!matched) return 412\n } else {\n // 2. If-Unmodified-Since, only without If-Match.\n const since = dateOf(header(headers, 'if-unmodified-since'))\n if (since !== undefined && modified !== undefined && modified > since) return 412\n }\n\n // 3. If-None-Match — weak comparison.\n const ifNoneMatch = header(headers, 'if-none-match')\n if (ifNoneMatch !== undefined) {\n const tags = tagsOf(ifNoneMatch)\n const matched =\n tags.includes('*') || (etag !== undefined && tags.some((t) => opaque(t) === opaque(etag)))\n if (matched) return safe ? 304 : 412\n return 200\n }\n\n // 4. If-Modified-Since, only for GET/HEAD and only without If-None-Match.\n if (safe) {\n const since = dateOf(header(headers, 'if-modified-since'))\n if (since !== undefined && modified !== undefined && modified <= since) return 304\n }\n return 200\n}\n","// The HttpRuntime seam.\n//\n// Decorators no longer emit an `express.Router` directly. `buildRouteTable()`\n// turns controller metadata into a plain-data `RouteEntry[]`; an `HttpRuntime`\n// materializes that table onto whatever engine it owns. Express is the default\n// runtime and the only one shipped in M1 — its materializer reproduces the exact\n// handler chain the old `buildRoutes()` built, so behavior is unchanged.\n//\n// Fastify / h3 runtimes (later milestones) consume the SAME `RouteEntry` data\n// and the SAME `HttpRuntime` contract; the request/response driver abstraction\n// that lets `RequestContext` run engine-agnostically lands with them (M3), since\n// under Express the drivers ARE the Express request/response objects already.\n//\n// Why a seam: running Fastify / h3 behind an Express-compat layer\n// (`@fastify/express`, h3's node bridge) bypasses their router and\n// serialization, and rebuilding `ctx` over web-standard Request/Response\n// would break SSE / streaming, multer uploads and `ctx.res` for every adopter.\n// The seam keeps `ctx` and swaps only the engine underneath it.\n\nimport { ROUTE_SLOT, type RouteFlags } from '../core/route-flag'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { ConnectMiddleware, ConnectRequest, ConnectResponse } from './connect'\n\nimport type { Constructor, FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core'\nimport type { RequestContext } from './context'\nimport type { ValidationErrorFactory } from './middleware/validate'\nimport type { RouteUrls } from './url-for'\nimport type { ContributorSource } from '../core/contributor-pipeline'\n\n/** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */\nexport type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n\n/**\n * A context-based handler: the runtime-neutral unit of the request pipeline.\n * Contributors, route middleware (via {@link MiddlewareHandler}), and the\n * terminal controller call all reduce to this shape. The runtime owns how a\n * `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,\n * next)`; Fastify in its own handler).\n */\nexport type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>\n\n/**\n * Connect-style middleware — the portable middleware format. Built-in\n * middleware and adopter-supplied Express middleware are this shape. The\n * Express runtime hands them straight to `app.use`; the others bridge them\n * (Fastify via `@fastify/middie`, h3 via its node adapter). See `./connect`.\n */\nexport type { ConnectMiddleware }\n\n/**\n * One materialized route, as plain data. Produced by {@link buildRouteTable}\n * from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.\n *\n * The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`\n * keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),\n * `contributorRunner` is a closure over the pre-built pipeline + container (the\n * pipeline is built — and any cycle / missing-dep error thrown — at table-build\n * time, i.e. boot), and `validation` / `upload` stay as metadata the runtime\n * materializes its own way. Faithfully reproducing the legacy Express chain —\n * not collapsing it — is what keeps M1 behavior-neutral.\n */\nexport interface RouteEntry {\n method: RouteMethod\n /** Path with `:param` segments — the portable subset all engines accept. */\n path: string\n /** Class + method middleware, in execution order; each receives `(ctx, next)`. */\n middlewares: MiddlewareHandler[]\n /**\n * Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),\n * or `null` when no contributors apply. Closes over the built pipeline and\n * the DI container so it stays engine-neutral; the runtime advances the\n * chain (Express: call `next()`) once it resolves.\n */\n contributorRunner: CtxHandler | null\n /**\n * Contributors registered with `beforeValidation: true`. Runtimes run this\n * right after publishing the matched route — before validation, upload and\n * middleware — so a rejection (401) lands before a malformed body's 422.\n * Absent or `null` when no contributor asks for it.\n */\n earlyContributorRunner?: CtxHandler | null\n /** The app's `validationError` — what this route's validation failure throws. */\n validationError?: ValidationErrorFactory\n /** The app's route names → paths, for `ctx.urlFor()`. */\n urls?: RouteUrls\n /** Terminal handler: resolves the controller per-request and invokes it. */\n handler: CtxHandler\n /** Introspection + runtime-materialized concerns (swagger/typegen read this). */\n meta: RouteMeta\n}\n\n/** Per-route metadata: introspection refs plus runtime-materialized concerns. */\n/**\n * One context contributor on a route, as introspection sees it: the\n * contributors a request runs, in execution order. Built with the route.\n */\nexport interface RouteContributor {\n /** The key it sets with `ctx.set(...)`. */\n key: string\n /** Where it was registered — `method` / `class` decorators, or a module, adapter or global list. */\n source: ContributorSource\n /** The registering site, e.g. `UsersController.show#0(tenant)` or a module name. */\n label?: string\n dependsOn: readonly string[]\n /** Runs before validation (`beforeValidation: true`). */\n beforeValidation: boolean\n /** Lower-precedence registrations of the same key this one replaced. */\n overrides: ReadonlyArray<{ source: ContributorSource; label?: string }>\n}\n\nexport interface RouteMeta {\n /**\n * Owning controller class — for DI resolution and adapter introspection.\n * Absent for ad-hoc routes registered through {@link AdapterHttp.route},\n * which have no controller class behind them.\n */\n controller?: Constructor\n /** Handler method name on the controller, when there is one. */\n handlerName?: string\n /** The route's context contributors, in execution order — for devtools / introspection. */\n contributors?: readonly RouteContributor[]\n /** Zod/JSON-schema validation config from the route decorator, if any. */\n validation?: RouteDefinition['validation']\n /** `@FileUpload` config, if present — the runtime supplies the backend. */\n upload?: FileUploadConfig\n /**\n * Route flags in force here, resolved at build time (method over class).\n * Enabled flags only: a flag declared `false` at a higher-precedence site is\n * absent rather than present-and-false, so `has()` is always the right\n * question. See `core/route-flag.ts`.\n */\n flags?: RouteFlags\n /**\n * The full mounted pattern (`/api/v1/users/:id`) — set by the Application\n * for controller routes. `path` is relative to the module mount.\n */\n pattern?: string\n}\n\n/**\n * The route a request matched, published on `ctx.route`.\n *\n * Everything that holds a {@link RequestContext} — handlers, `@Middleware()`,\n * guards, contributors — can read it, which is what lets one declaration on a\n * route serve every consumer.\n */\n/**\n * Publish the matched route on the request, for `ctx.route` to read.\n *\n * Called by each runtime once per dispatch, before it builds a RequestContext.\n * It lives on `req` rather than on the ctx because the Express runtime\n * constructs a fresh RequestContext per middleware step — anything written to\n * one ctx would be invisible to the next and to the handler.\n */\nexport function publishMatchedRoute(req: unknown, entry: RouteEntry): void {\n // One object per route, shared by its requests — every field comes from the\n // entry, which is final once mounted. Frozen, since it is shared.\n let route = matchedRoutes.get(entry)\n if (!route) {\n route = Object.freeze({\n method: entry.method,\n path: entry.path,\n controller: entry.meta.controller,\n handlerName: entry.meta.handlerName,\n flags: entry.meta.flags ?? EMPTY_FLAGS,\n pattern: entry.meta.pattern ?? entry.path,\n urls: entry.urls,\n })\n matchedRoutes.set(entry, route)\n }\n ;(req as Record<symbol, MatchedRoute>)[ROUTE_SLOT] = route\n}\n\nconst matchedRoutes = new WeakMap<RouteEntry, MatchedRoute>()\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\nexport interface MatchedRoute {\n readonly method: RouteMethod\n /** Path as declared on the handler, e.g. `/:id`. */\n readonly path: string\n /**\n * The full route pattern including the mount prefix and version, e.g.\n * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls\n * back to `path` for routes registered without a mount.\n */\n readonly pattern: string\n readonly controller?: Constructor\n readonly handlerName?: string\n /** Enabled flags only — see {@link RouteMeta.flags}. */\n readonly flags: RouteFlags\n /** @internal The app's route names, for `ctx.urlFor()`. */\n readonly urls?: RouteUrls\n}\n\n/** A controller's routes grouped under the module mount prefix. */\nexport type RouteTable = { mountPath: string; routes: RouteEntry[] }[]\n\n/**\n * The response surface {@link RequestContext}'s helpers (`json` / `html` /\n * `sse` / `download` / `render` / `problem`) drive, instead of calling Express\n * `res` methods directly (spec §4.3). Sized so `express.Response` satisfies it\n * structurally — under the Express runtime the driver IS the Express response,\n * so there is no wrapping and no behavior change. Other runtimes (Fastify / h3)\n * provide a thin object implementing this over their native reply.\n *\n * The terminal methods return `RuntimeResponse` for fluent chaining (Express's\n * `Response` is assignable, since it is a superset).\n */\n/** True for the TypeError `JSON.stringify` throws on a bigint. */\nexport function isBigIntJsonError(err: unknown): boolean {\n return err instanceof TypeError && /BigInt/.test(err.message)\n}\n\n/**\n * `JSON.stringify` that writes a bigint as its decimal string instead of\n * throwing — database counts and `bigint` columns reach responses as bigints.\n * Plain `JSON.stringify` runs first, so a body without one costs nothing extra.\n */\nexport function stringifyJson(data: unknown): string {\n try {\n return JSON.stringify(data)\n } catch (err) {\n if (!isBigIntJsonError(err)) throw err\n return JSON.stringify(data, (_key, value) =>\n typeof value === 'bigint' ? value.toString() : value,\n )\n }\n}\n\nexport interface RuntimeResponse {\n status(code: number): RuntimeResponse\n json(data: unknown): RuntimeResponse\n send(data: unknown): RuntimeResponse\n type(contentType: string): RuntimeResponse\n setHeader(name: string, value: string | number | readonly string[]): unknown\n render(view: string, data?: Record<string, unknown>): unknown\n writeHead(statusCode: number, headers?: Record<string, string>): unknown\n flushHeaders(): unknown\n write(chunk: string | Buffer): boolean\n end(data?: unknown): unknown\n once(event: 'close' | 'drain', listener: () => void): unknown\n readonly headersSent: boolean\n}\n\n// ── Runtime-typed escape hatches (spec §4.3b) ─────────────────────────────\n\n/**\n * Per-runtime type map: the engine-native request / response / app types an\n * `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.\n */\nexport interface RuntimeTypeMap {\n request: unknown\n response: unknown\n app: unknown\n}\n\n/**\n * Augmentable runtime registry. Empty by default; the `kick/runtime` typegen\n * plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured\n * runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,\n * `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`\n * — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is\n * uniform with `kick/db` and env typing.\n *\n * @example\n * ```ts\n * // .kickjs/types/kick__runtime.d.ts — generated by typegen\n * declare module '@forinda/kickjs' {\n * interface KickRuntimeRegister {\n * runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes\n * }\n * }\n * ```\n */\n\nexport interface KickRuntimeRegister {}\n\n/**\n * The active runtime's type map — the augmented one, or the connect-style\n * {@link ConnectRuntimeTypes} when nothing is augmented. `kick typegen` augments it from kick.config's\n * `runtime`, Express included.\n */\nexport type ActiveRuntime = KickRuntimeRegister extends { runtime: infer R extends RuntimeTypeMap }\n ? R\n : ConnectRuntimeTypes\n\n/**\n * What the escape hatches are typed as with no augmentation: the connect-style\n * request and response every runtime's middleware sees, and an app of unknown\n * engine.\n */\nexport interface ConnectRuntimeTypes {\n request: ConnectRequest\n response: ConnectResponse\n app: unknown\n}\n\n/** Options passed to {@link HttpRuntime.createApp}. */\nexport interface RuntimeAppOptions {\n /**\n * Express `trust proxy` setting (and the equivalent on other engines). The\n * function form is Express-specific; other runtimes interpret the simpler\n * shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).\n */\n trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean)\n /**\n * When the app is mounted inside another handler (`kick dev`'s Vite server,\n * `app.handle(req, res, next)` in a host server), hand requests no route\n * matched back to it — `true`, the default — or answer them here with the\n * app's not-found handling — `false`. Express always answers.\n */\n notFoundFallthrough?: boolean\n /** Largest request body the engine parses, in bytes — `jsonLimit`, resolved. */\n bodyLimit?: number\n}\n\n/** Where a connect middleware sits and what it scopes to. */\nexport interface UseConnectOptions {\n path?: string | RegExp | ReadonlyArray<string | RegExp>\n}\n\n/**\n * Optional engine capabilities. Absence means the corresponding `ctx` feature\n * raises a clear error on that runtime rather than failing obscurely.\n */\nexport interface RuntimeCapabilities {\n /** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */\n render: boolean\n /** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */\n uploads: boolean\n /** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */\n connectMiddleware: boolean\n /**\n * The engine parses request bodies itself (Fastify, h3). When true, the\n * Application skips its default `express.json()` so the body stream isn't\n * consumed twice (which would deadlock the engine's own parser). Express:\n * false — it relies on the `express.json()` connect middleware.\n */\n nativeBodyParsing: boolean\n /**\n * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2\n * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:\n * true. Express: false — it does not run on that layer. Absent = false, so\n * custom runtimes opt in explicitly.\n */\n http2?: boolean\n}\n\n/**\n * The engine driver. KickJS owns decorators → {@link RouteTable}, the\n * contributor pipeline, the `RequestContext` surface, and error mapping. The\n * runtime owns app/server creation, route materialization, connect-middleware\n * registration, static serving, and the terminal not-found / error handlers.\n *\n * `expressRuntime()` is the default and the M1 reference implementation.\n */\nexport interface HttpRuntime<TApp = unknown> {\n readonly name: 'express' | 'fastify' | 'h3' | (string & {})\n\n /** Create the engine app. Called once per Application (and per HMR rebuild). */\n createApp(options?: RuntimeAppOptions): TApp\n\n /**\n * Node-compatible request listener — the transport contract.\n * `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST\n * invoke `next` (when given) instead of 404-ing if no route matched — the\n * Vite dev chain depends on fall-through.\n */\n nodeHandler(\n app: TApp,\n ): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void\n\n /** Materialize the framework-built route table onto the engine. */\n mountRoutes(app: TApp, table: RouteTable): void\n\n /** Register a connect-style middleware (built-ins + adopter middleware). */\n useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void\n\n /** Serve a static directory (swagger-ui assets, devtools SPA). */\n serveStatic(app: TApp, prefix: string, dir: string): void\n\n /** Terminal not-found handler. */\n setNotFound(app: TApp, mw: ConnectMiddleware): void\n\n /** Terminal error handler. */\n setErrorHandler(app: TApp, mw: ConnectMiddleware): void\n\n /**\n * Load the engine before the first `createApp()` — for a runtime that\n * imports it lazily, as the root `expressRuntime()` does so that\n * `@forinda/kickjs` doesn't need `express` installed. Awaited at setup.\n */\n load?(): Promise<void>\n\n /**\n * Body parsers to mount among the default middleware, for an engine that\n * doesn't parse request bodies itself (`capabilities.nativeBodyParsing:\n * false`). `limit` is `bootstrap({ jsonLimit })`.\n */\n bodyParsers?(options: { limit: string | number }): ConnectMiddleware[]\n\n /** Release the engine app on shutdown (Fastify runs its `onClose` hooks). */\n close?(app: TApp): void | Promise<void>\n\n readonly capabilities: RuntimeCapabilities\n}\n\n/**\n * The supported surface adapters use to add HTTP routes, mounts, static dirs,\n * and middleware — engine-agnostic, in place of reaching for the raw Express\n * `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the\n * Application over the active {@link HttpRuntime}, so an adapter written against\n * this works under any runtime; the raw `app` escape hatch stays available for\n * the rare engine-specific need.\n */\nexport interface AdapterHttp {\n /** Register a single context-handler route (e.g. a docs or transport endpoint). */\n route(method: RouteMethod, path: string, handler: CtxHandler): void\n /** Mount a pre-built route table under a path prefix. */\n mount(prefix: string, routes: RouteEntry[]): void\n /** Serve a static directory under a path prefix. */\n serveStatic(prefix: string, dir: string): void\n /** Register a connect-style middleware (optionally path-scoped). */\n use(mw: ConnectMiddleware, opts?: UseConnectOptions): void\n}\n","import { HttpException } from '../../core/errors'\nimport type { CursorPosition, CursorValue, SortItem } from './types'\n\n/**\n * Cursor wire format: base64url JSON `{ v: <position>, s: <sort signature> }`.\n * Unsigned by design — the position is only ever handed to the fetcher as\n * data, and the sort signature makes a cursor from one ordering answer 400\n * under another instead of silently skipping or repeating rows.\n */\n\n/** `createdAt:desc,id:asc` — what a cursor was issued under. */\nexport function sortSignature(sort: readonly SortItem[]): string {\n return sort.map((s) => `${s.field}:${s.direction}`).join(',')\n}\n\nfunction isPrimitive(value: unknown): value is CursorValue {\n return value === null || ['string', 'number', 'boolean'].includes(typeof value)\n}\n\nexport function encodeCursor(position: Record<string, CursorValue>, signature: string): string {\n const bytes = new TextEncoder().encode(JSON.stringify({ v: position, s: signature }))\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Decode a client cursor. Anything that is not exactly what\n * {@link encodeCursor} produces for this sort (and, when `keys` is given,\n * for exactly these fields) is a 400 — never a guess.\n */\nexport function decodeCursor(\n raw: unknown,\n signature: string,\n keys: readonly string[] | undefined,\n): CursorPosition {\n const invalid = () => HttpException.badRequest('Invalid pagination cursor')\n if (typeof raw !== 'string' || !/^[A-Za-z0-9_-]+$/.test(raw)) throw invalid()\n let parsed: unknown\n try {\n const binary = atob(raw.replace(/-/g, '+').replace(/_/g, '/'))\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0))\n parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n } catch {\n throw invalid()\n }\n if (typeof parsed !== 'object' || parsed === null) throw invalid()\n const { v, s } = parsed as { v?: unknown; s?: unknown }\n if (typeof v !== 'object' || v === null || Array.isArray(v)) throw invalid()\n if (!Object.values(v).every(isPrimitive)) throw invalid()\n if (keys) {\n const got = Object.keys(v)\n if (got.length !== keys.length || !keys.every((k) => Object.hasOwn(v, k))) throw invalid()\n }\n if (s !== signature) {\n throw HttpException.badRequest('Pagination cursor was issued for a different sort')\n }\n return v as CursorPosition\n}\n\n/**\n * The current request's path + query with `key` replaced (or dropped when\n * `value` is null). Relative on purpose: the host comes from the client, so\n * it never goes into a link. The path is re-derived through `URL`, so an\n * absolute-form request target (`GET http://evil/...`), a `//host` path, or\n * a doubled leading slash cannot turn the link into an off-site URL. Other params keep their\n * original encoding.\n */\nexport function pageLink(rawUrl: string, key: string, value: string | number | null): string {\n const url = parseUrl(rawUrl)\n const kept = url.search\n .slice(1)\n .split('&')\n .filter((part) => part !== '' && paramName(part) !== key)\n if (value !== null) kept.push(`${key}=${encodeURIComponent(value)}`)\n return kept.length ? `${url.pathname}?${kept.join('&')}` : url.pathname\n}\n\n/** The current request's path + query, relative — see {@link pageLink}. */\nexport function selfLink(rawUrl: string): string {\n const url = parseUrl(rawUrl)\n return url.pathname + url.search\n}\n\n/** Host-less parse; a leading `//` in the path would read as a host in a link, so collapse it. */\nfunction parseUrl(rawUrl: string): URL {\n const url = new URL(rawUrl, 'http://localhost')\n url.pathname = url.pathname.replace(/^\\/+/, '/')\n return url\n}\n\nfunction paramName(part: string): string {\n const name = part.split('=', 1)[0].replace(/\\+/g, ' ')\n try {\n return decodeURIComponent(name)\n } catch {\n return name\n }\n}\n","/// <reference types=\"multer\" />\nimport { setPendingResponse, viewRendererFor, type ViewRenderOptions } from './view-renderer'\nimport type { RouteName, UrlForArgs } from './url-for'\nimport { evaluatePreconditions, normalizeEtag, type Validators } from './conditional'\nimport type { ConnectRequest as Request, ConnectNext as NextFunction } from './connect'\nimport type { UploadedFile } from './middleware/upload-config'\nimport { ROUTE_SLOT } from '../core/route-flag'\nimport {\n isBigIntJsonError,\n stringifyJson,\n type ActiveRuntime,\n type MatchedRoute,\n type RuntimeResponse,\n} from './runtime'\nimport {\n type ContextMetaKey,\n type ExecutionContext,\n type MetaValue,\n} from '../core/execution-context'\nimport { normalizeProblem, type ProblemDetails, type ValidationError } from '../core/errors'\nimport { MissingContextValueError } from '../core/context-errors'\nimport { requestStore } from './request-store'\nimport { waitUntil } from './background'\nimport { resolveClientIp, type ClientRequestLike } from './client-ip'\nimport type { Session } from './middleware/session'\nimport {\n parseQuery,\n type ParseQueryOptions,\n type QueryFieldConfig,\n type PaginatedResponse,\n type TypedParsedQuery,\n type CursorPaginatedResponse,\n type CursorPaginateOptions,\n type CursorQuery,\n type CursorValue,\n} from './query'\nimport { decodeCursor, encodeCursor, pageLink, selfLink, sortSignature } from './query/cursor'\nimport { isProduction } from '../core/is-production'\n\n/**\n * Input shape for the typed problem-detail convenience methods on\n * {@link ProblemSender} (`ctx.problem.notFound`, `.badRequest`, etc.) —\n * RFC 9457 details minus the `status`, which each method pre-fills.\n */\ntype ProblemInput = Omit<ProblemDetails, 'status'>\n\n/**\n * Callable response helper for RFC 9457 — Problem Details responses.\n * Returned by `ctx.problem`. Invoke directly for a fully-specified\n * payload, or use the named convenience methods to pre-fill `status` +\n * `title` for the common codes.\n *\n * Each call sets `Content-Type: application/problem+json` and serializes\n * the canonical shape (defaulting `type` to `about:blank` and `title` to\n * the IANA reason phrase per RFC 9457 §3.1.1 / §3.1.4).\n *\n * @example\n * ```ts\n * ctx.problem({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30, // extension per §3.2\n * })\n *\n * ctx.problem.notFound({ detail: 'User abc not found' })\n * ctx.problem.validation(zodResult.error.issues)\n * ```\n */\ninterface ProblemSender {\n (input: ProblemDetails): RuntimeResponse\n /** 400 Bad Request — RFC 9457. */\n badRequest(input?: ProblemInput): RuntimeResponse\n /** 401 Unauthorized — RFC 9457. */\n unauthorized(input?: ProblemInput): RuntimeResponse\n /** 403 Forbidden — RFC 9457. */\n forbidden(input?: ProblemInput): RuntimeResponse\n /** 404 Not Found — RFC 9457. */\n notFound(input?: ProblemInput): RuntimeResponse\n /** 409 Conflict — RFC 9457. */\n conflict(input?: ProblemInput): RuntimeResponse\n /** 422 Unprocessable Entity — RFC 9457. */\n unprocessable(input?: ProblemInput): RuntimeResponse\n /** 429 Too Many Requests — RFC 9457. */\n tooManyRequests(input?: ProblemInput): RuntimeResponse\n /** 500 Internal Server Error — RFC 9457. */\n internal(input?: ProblemInput): RuntimeResponse\n /**\n * 422 with Zod issues serialized into the `errors` extension per\n * RFC 9457 §3.2's array convention. Pass `error.issues` from a Zod\n * `safeParse` failure or `error.issues` from a thrown ZodError.\n */\n validation(issues: any[], input?: ProblemInput): RuntimeResponse\n}\n\n/**\n * Recursively marks every property of `T` as `readonly`. Preserves\n * `Function`, `Date`, and `RegExp` unchanged, and converts `Map` / `Set`\n * to `ReadonlyMap` / `ReadonlySet` so their mutating methods (`set`,\n * `delete`, `add`, `clear`) are removed from the public surface.\n * Tuples keep their positional element types — only their per-element\n * mutability is locked.\n *\n * Exposed as a utility for adopters who want to opt into compile-time\n * sealing of their own shapes. **No longer applied to\n * `RequestContext.{body,params,query,headers,file,files}`** — that\n * broke TS narrowing / discriminated-union drilldowns on typed request\n * payloads. Runtime read-only enforcement now lives in\n * {@link makeReadOnlyProxy} (dev-only Proxy that warns on writes,\n * no-op in production).\n *\n * Type-only. No runtime cost. `DeepReadonly<any>` is `any` (TS\n * distributes conditional types over `any`).\n */\nexport type DeepReadonly<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends Date | RegExp\n ? T\n : T extends Map<infer K, infer V>\n ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>\n : T extends Set<infer V>\n ? ReadonlySet<DeepReadonly<V>>\n : T extends readonly (infer U)[]\n ? // Distinguish a regular array from a tuple. A regular `T[]` widens\n // its `length` to `number`; a tuple's `length` is a literal\n // (e.g. `2`). The literal branch maps over `keyof T` so each\n // positional slot keeps its own type — `DeepReadonly<[1, 2]>` →\n // `readonly [1, 2]`, not `readonly (1 | 2)[]`.\n number extends T['length']\n ? ReadonlyArray<DeepReadonly<U>>\n : { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T\n\n/**\n * Re-export the augmentable {@link ContextMeta} registry from core/.\n * Declared in `core/execution-context.ts` so non-HTTP transports\n * (WS/queue/cron, V2) share one declaration site. Apps still augment\n * via the canonical `declare module '@forinda/kickjs'` form.\n */\nexport type { ContextMeta } from '../core/execution-context'\n\n/**\n * Symbol key under which the per-request `AbortController` backing\n * `RequestContext.signal` is cached on the Express `req` object.\n * Shared across every `RequestContext` instance built for the same\n * request (router-builder constructs separate wrappers for\n * middleware, the contributor pipeline, and the main handler — they\n * all need the same signal).\n */\nconst signalControllerKey = Symbol.for('kickjs.requestContext.signalController')\n\n/**\n * Symbol key under which per-target read-only Proxy wrappers are\n * cached on the Express `req` object. Used by {@link makeReadOnlyProxy}\n * so repeat access of `ctx.body` / `ctx.params` / etc. returns the same\n * Proxy instance (cheap, and stable under `===` for adopters comparing\n * values across middleware).\n */\nconst readOnlyProxyCacheKey = Symbol.for('kickjs.requestContext.readOnlyProxyCache')\n\n/**\n * `true` iff `v` is a plain object (`{}` / `Object.create(null)`) or an\n * array — the two shapes JSON.parse / Express body-parser produce and\n * the only ones the read-only Proxy recurses into. Class instances,\n * `Date`, `RegExp`, `Map`, `Set`, `Buffer`, streams, and functions\n * pass through unwrapped so their method dispatch and `instanceof`\n * checks keep working.\n */\nfunction isPlainObjectOrArray(v: unknown): v is object {\n if (v === null || typeof v !== 'object') return false\n if (Array.isArray(v)) return true\n const proto = Object.getPrototypeOf(v)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * In dev, wrap `target` in a `Proxy` whose `set` / `deleteProperty` /\n * `defineProperty` traps log a warning and otherwise leave the\n * underlying object untouched. A `get` trap recursively wraps nested\n * plain objects and arrays on access, so deep mutations\n * (`ctx.body.user.name = 'x'`, `ctx.files[0].fieldname = 'y'`,\n * `ctx.body.tags.push(...)`) all surface a warning — matching the\n * prior `DeepReadonly<T>` contract at runtime instead of at the type\n * level. In production (any `NODE_ENV` but `development` / `test`) the\n * proxy is bypassed entirely and `target` is returned as-is so the\n * hot path stays zero-cost.\n *\n * Why a Proxy instead of `DeepReadonly<T>` at the type level: the\n * recursive conditional type interfered with TS narrowing (notably\n * discriminated unions on `ctx.body`) and slowed type-checking on\n * deeply-nested Zod-inferred shapes. Compile-time sealing is gone;\n * runtime warning catches the same class of bug during dev and tests.\n *\n * Trap returns `true` so strict-mode call sites (which is all of them\n * — ES modules are strict) don't *throw* on assignment — they just\n * get a warning + the underlying value stays untouched. Adopters\n * discover the violation when the subsequent read returns the\n * original value, not the one they \"set\".\n *\n * Targets are cached per-`req` under {@link readOnlyProxyCacheKey} so\n * (1) repeat getter access returns the same proxy (`ctx.body ===\n * ctx.body`, `ctx.body.user === ctx.body.user`); and (2) cyclic refs\n * (`body.self = body`) terminate via the cache hit on the second\n * visit. Primitives, `null`, and non-plain values pass through.\n */\nfunction makeReadOnlyProxy<T>(target: T, req: object, label: string): T {\n if (isProduction()) return target\n if (!isPlainObjectOrArray(target)) return target\n\n type Cache = WeakMap<object, unknown>\n const reqObj = req as Record<symbol, Cache | undefined>\n let cache = reqObj[readOnlyProxyCacheKey]\n if (!cache) {\n cache = new WeakMap()\n reqObj[readOnlyProxyCacheKey] = cache\n }\n const targetObj = target as unknown as object\n const cached = cache.get(targetObj)\n if (cached) return cached as T\n\n const warnWrite = (verb: string, prop: PropertyKey) => {\n console.warn(\n `[kickjs] Attempted to ${verb} \\`ctx.${label}.${String(prop)}\\` — ` +\n `request data is read-only. ` +\n `Stash computed values via \\`ctx.set('key', value)\\` or a Context Contributor, ` +\n `or reach \\`ctx.req.${label}\\` if you genuinely need the raw mutable handle.`,\n )\n }\n\n const proxy = new Proxy(targetObj, {\n get(t, prop, receiver) {\n const value = Reflect.get(t, prop, receiver)\n // Recurse only into plain objects / arrays. Functions (incl.\n // array methods like `.push`) pass through with `receiver` as\n // their `this`, so internal `this[i] = x` writes still hit the\n // `set` trap and warn.\n if (isPlainObjectOrArray(value)) {\n return makeReadOnlyProxy(value, req, `${label}.${String(prop)}`)\n }\n return value\n },\n set(_t, prop) {\n warnWrite('assign', prop)\n return true\n },\n deleteProperty(_t, prop) {\n warnWrite('delete', prop)\n return true\n },\n defineProperty(_t, prop) {\n warnWrite('Object.defineProperty on', prop)\n return true\n },\n })\n cache.set(targetObj, proxy)\n return proxy as T\n}\n\n/**\n * The shape of a single route entry in `KickRoutes`. Generated by\n * `kick typegen` and consumed via the `Ctx<T>` helper. Each field is\n * `unknown` by default and is filled in as the typegen learns more\n * about the route (URL params from the path, body/query from validation\n * schemas, etc.).\n */\nexport interface RouteShape {\n params?: unknown\n body?: unknown\n query?: unknown\n response?: unknown\n /**\n * Union of context keys `kick typegen` proved are populated for this\n * route — the keys of every context contributor applied at method or\n * class level. Drives {@link RequestContext.require} narrowing, so\n * calling `ctx.require()` for a key this route doesn't carry is a\n * compile error instead of a request-time throw.\n *\n * `string` (the default) means \"not proven\", not \"no keys\". Typegen\n * emits `string` whenever it cannot see the full picture — a\n * contributor registered at module / adapter / bootstrap level, or an\n * unrecognised decorator that might bundle contributors of its own.\n * Narrowing an unprovable route would produce compile errors for keys\n * that really are present.\n */\n contextKeys?: string\n}\n\n/**\n * Unified request/response abstraction passed to every controller method.\n * Shields handlers from raw Express objects and provides convenience methods.\n *\n * Implements {@link ExecutionContext} so the transport-agnostic Context\n * Contributor pipeline (#107) can run against this concrete HTTP context\n * the same way it will run against future WS / queue / cron contexts.\n */\nexport class RequestContext<\n TBody = any,\n TParams = any,\n TQuery = any,\n /**\n * Context keys proven present for this route. Defaults to\n * {@link ContextMetaKey} — every key the project has registered — which\n * collapses to `string` when neither registry has been augmented, so a\n * handler typed as plain `RequestContext` keeps today's behaviour. That\n * default is also the deliberate escape hatch when typegen's view of a\n * route is incomplete.\n */\n TKeys extends ContextMetaKey = ContextMetaKey,\n> implements ExecutionContext<TKeys> {\n /**\n * Engine-agnostic response driver the response helpers write through. Under\n * the Express runtime it IS `res` (Express's Response satisfies\n * {@link RuntimeResponse} structurally); other runtimes pass a thin wrapper\n * over their native reply as the optional fourth argument.\n */\n private readonly _response: RuntimeResponse\n\n /**\n * The route this request matched: its method, path, controller, handler name\n * and resolved {@link MatchedRoute.flags}.\n *\n * Available to anything running inside the matched route — route middleware,\n * contributors, guards, the handler. Global middleware runs before route\n * matching, so it sees `undefined` there.\n *\n * ```ts\n * if (ctx.route?.flags.has('auth.public')) return next()\n * ```\n */\n get route(): MatchedRoute | undefined {\n return (this.req as unknown as Record<symbol, MatchedRoute | undefined>)?.[ROUTE_SLOT]\n }\n\n constructor(\n public readonly req: ActiveRuntime['request'],\n public readonly res: ActiveRuntime['response'],\n public readonly next: NextFunction,\n responseDriver?: RuntimeResponse,\n ) {\n // Under the Express runtime `res` IS a RuntimeResponse (structural); other\n // runtimes pass an explicit driver wrapping their native reply.\n this._response = responseDriver ?? (res as unknown as RuntimeResponse)\n }\n\n /**\n * Memo of the most recent {@link qs} call this request. The query\n * object is immutable for a request's lifetime, so a repeat call with\n * the same `(fieldConfig, options)` references returns the cached\n * parse instead of re-walking the filter/sort strings.\n */\n private _qsMemo?: { config: unknown; options: unknown; result: unknown }\n\n /** Memoized {@link problem} sender — built lazily on first access. */\n private _problem?: ProblemSender\n\n /**\n * Read-side accessor for the per-request metadata map.\n *\n * Returns the AsyncLocalStorage map (`requestStore.getStore().values`)\n * shared with the Context Contributor pipeline when an ALS frame is\n * active. Returns `null` outside any frame — read-side callers\n * (`ctx.get`, `ctx.user`, `ctx.tenantId`, `ctx.roles`) treat that as\n * \"no metadata\" and fall through to their `req.*` defaults. Reads\n * never throw because outside an ALS frame nobody could have written\n * via `ctx.set` anyway, so an empty answer is the truthful one.\n */\n private metadataReadOnly(): Map<string, any> | null {\n return (requestStore.getStore()?.values as Map<string, any> | undefined) ?? null\n }\n\n /**\n * Write-side accessor for the per-request metadata map.\n *\n * Returns the same map as {@link metadataReadOnly} when an ALS frame\n * is active. Throws otherwise — writing to a fallback map outside\n * the ALS frame would silently lose data because other call sites\n * (downstream contributors, request-logger, etc.) read from the\n * canonical store and would never see it. Mount\n * `requestScopeMiddleware()` (Application does this for you in\n * `'auto'` mode) or wrap your test setup in\n * `requestStore.run({...}, () => …)` to fix.\n */\n private metadataForWrite(): Map<string, any> {\n const store = requestStore.getStore()\n if (store) return store.values as Map<string, any>\n throw new Error(\n 'RequestContext.set called outside an AsyncLocalStorage frame. ' +\n 'Mount requestScopeMiddleware() before constructing RequestContext, ' +\n 'or wrap test setup in requestStore.run({ requestId, instances: new Map(), values: new Map() }, () => ...).',\n )\n }\n\n // ── Request Data ────────────────────────────────────────────────────\n\n /**\n * Parsed request body. Wrapped in a dev-only Proxy that warns when\n * adopters try to mutate Zod-validated payloads in place — compute\n * new values and stash them via `ctx.set('key', value)` or a Context\n * Contributor instead. Reach for `ctx.req.body` if you genuinely\n * need the raw, mutable Express handle (rare).\n *\n * In production the Proxy is bypassed and `this.req.body` is\n * returned as-is — no runtime cost on the hot path.\n */\n get body(): TBody {\n return makeReadOnlyProxy<TBody>(this.req.body, this.req, 'body')\n }\n\n /** Path parameters parsed from the route — read-only, see {@link body}. */\n get params(): TParams {\n return makeReadOnlyProxy<TParams>(this.req.params as TParams, this.req, 'params')\n }\n\n /** Parsed query string — read-only, see {@link body}. */\n get query(): TQuery {\n return makeReadOnlyProxy<TQuery>(this.req.query as TQuery, this.req, 'query')\n }\n\n /** Inbound HTTP headers — read-only, see {@link body}. */\n get headers(): Request['headers'] {\n return makeReadOnlyProxy<Request['headers']>(this.req.headers, this.req, 'headers')\n }\n\n get requestId(): string | undefined {\n return (this.req as any).requestId ?? (this.req.headers['x-request-id'] as string | undefined)\n }\n\n /**\n * `AbortSignal` that fires when the underlying HTTP request is\n * closed — either because the client disconnected before the\n * response was sent, or because Node's socket-close event ran\n * after a normal response. Multiple `RequestContext` wrappers for\n * the same request (router-builder constructs one per\n * middleware/contributor pipeline / main handler) share a single\n * `AbortController` cached on the underlying `req` object, so the\n * signal is stable across the request lifecycle.\n *\n * Thread it through anything that takes an `AbortSignal` so the\n * work cancels as soon as the client gives up — e.g. a kickjs-db\n * relational query:\n *\n * ```ts\n * @Get('/:id/full')\n * async show(ctx: RequestContext) {\n * const row = await this.repo.findFullById(ctx.params.id, ctx.signal)\n * if (!row) return ctx.notFound()\n * ctx.json(row)\n * }\n * ```\n *\n * The repo passes `signal` to `db.query.<table>.findUnique({ signal })`;\n * if the client disconnects mid-flight, the in-flight query rejects\n * with `RelationalQueryCancelledError` instead of consuming the\n * connection until completion.\n *\n * Implementation note — both `req.on('close')` and `res.on('close')`\n * are wired so the signal aborts regardless of whether the close\n * event lands on the request stream or the response stream first.\n * Subsequent fires are no-ops (`AbortController.abort()` is\n * idempotent).\n */\n get signal(): AbortSignal {\n const req = this.req as Request & { [signalControllerKey]?: AbortController }\n const cached = req[signalControllerKey]\n if (cached) return cached.signal\n\n const ctrl = new AbortController()\n req[signalControllerKey] = ctrl\n const abort = () => ctrl.abort('request closed')\n this.req.once('close', abort)\n this._response.once('close', abort)\n return ctrl.signal\n }\n\n /**\n * The request's session — set by the `session()` middleware, which must be\n * installed. Type your keys once by augmenting `SessionData`:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface SessionData { userId?: string }\n * }\n * ```\n */\n get session(): Session {\n return (this.req as { session?: Session }).session as Session\n }\n\n /**\n * The authenticated user set by AuthAdapter.\n * Reads from the per-request metadata store first (`ctx.set('user', ...)`),\n * then falls back to `req.user` (set directly by AuthAdapter middleware).\n *\n * Extend the `AuthUser` interface via module augmentation in your own auth\n * module — see the BYO Auth recipe in the docs\n * to get full typing.\n *\n * @example\n * ```ts\n * @Get('/me')\n * @Authenticated()\n * getProfile(ctx: RequestContext) {\n * const user = ctx.user\n * if (!user) return ctx.notFound()\n * return ctx.json({ user })\n * }\n * ```\n */\n get user(): MetaValue<'user', Record<string, any>> | undefined {\n return this.metadataReadOnly()?.get('user') ?? (this.req as any).user\n }\n\n /**\n * Tenant identifier for multi-tenant apps. Reads `user.tenantId` —\n * populated either by `AuthAdapter.testMode({ tenantId })`, a tenant\n * resolver middleware, or manually on the strategy's `mapPayload`.\n *\n * Augment `AuthUser` (or `ContextMeta['user']`) to widen the return\n * type if your user shape guarantees a non-`string | undefined` id.\n */\n get tenantId(): string | undefined {\n const u = this.user as Record<string, any> | undefined\n return u?.tenantId\n }\n\n /**\n * Effective role list for the current user. Prefers `user.tenantRoles`\n * (populated by `AuthAdapterOptions.roleResolver` under a tenant) and\n * falls back to `user.roles`. Returns an empty array when the user is\n * absent or the shape has neither field.\n */\n get roles(): string[] {\n const u = this.user as Record<string, any> | undefined\n return u?.tenantRoles ?? u?.roles ?? []\n }\n\n // ── Query String Parsing ───────────────────────────────────────────\n\n /**\n * Parse the request query string into structured filters, sort, pagination, and search.\n * Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).\n *\n * Generic over the field config: when passed an inline literal (or\n * `as const`), `filters[].field` and `sort[].field` are narrowed to\n * the exact whitelisted field names. Pass nothing or a non-literal\n * config and you get the loose `string` fallback.\n *\n * @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields\n * @param options - Limits (`maxLimit`, `defaultLimit`, `maxSearchLength`) and an\n * `onReject` hook. By default a rejected/over-broad field is logged via\n * `console.warn` with the request id; pass an explicit `onReject` to override\n * (e.g. throw to return a 400), or `onReject: () => {}` to silence.\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * } as const)\n * parsed.filters[0].field // typed as 'status' | 'priority'\n * parsed.sort[0].field // typed as 'createdAt' | 'title'\n * }\n * ```\n */\n qs<TConfig extends QueryFieldConfig | undefined = undefined>(\n fieldConfig?: TConfig,\n options?: ParseQueryOptions,\n ): TypedParsedQuery<TConfig> {\n // Cheap per-request memo — repeat calls with the same args (the\n // common controller pattern) skip re-parsing. `req.query` is fixed\n // for the request's lifetime, so caching is always sound.\n const memo = this._qsMemo\n if (memo && memo.config === fieldConfig && memo.options === options) {\n return memo.result as TypedParsedQuery<TConfig>\n }\n const effective: ParseQueryOptions = {\n ...options,\n onReject:\n options?.onReject ??\n ((rejection) => {\n const id = this.requestId ? `[${this.requestId}] ` : ''\n console.warn(\n `${id}query ${rejection.kind} '${rejection.field}' rejected (${rejection.reason})`,\n )\n }),\n }\n const result = parseQuery<TConfig>(\n this.req.query as Record<string, any>,\n fieldConfig,\n effective,\n )\n this._qsMemo = { config: fieldConfig, options, result }\n return result\n }\n\n // ── File Uploads ────────────────────────────────────────────────────\n\n /**\n * Single uploaded file (requires `@FileUpload({ mode: 'single' })`).\n * Wrapped in a dev-only Proxy that warns on mutation — see {@link body}.\n * File metadata is set by the upload middleware and shouldn't be\n * mutated downstream.\n */\n get file(): UploadedFile | undefined {\n const f = this.req.file\n return f ? makeReadOnlyProxy<UploadedFile>(f, this.req, 'file') : undefined\n }\n\n /**\n * Array of uploaded files (requires `@FileUpload({ mode: 'array' })`).\n * The array (and each entry in dev) is wrapped in a read-only Proxy\n * that warns on `push`/`pop` and per-file mutation. Use\n * `ctx.req.files` if you genuinely need the mutable Express handle.\n */\n get files(): UploadedFile[] | undefined {\n // multer's `Request['files']` is a union — array (mode: 'array' /\n // 'any') or `{ [fieldname]: File[] }` (mode: 'fields'). The\n // `@FileUpload({ mode: 'array' })` decorator only sets the array\n // shape, but `Request['files']` is the broad union. Narrow back to\n // `File[]` here for the common-case getter; adopters using\n // `mode: 'fields'` can read `ctx.req.files` directly for the\n // dictionary shape.\n const f = this.req.files\n if (!Array.isArray(f)) return undefined\n return makeReadOnlyProxy<UploadedFile[]>(f, this.req, 'files')\n }\n\n // ── Metadata Store ──────────────────────────────────────────────────\n\n /**\n * Read a value from the per-request metadata store.\n *\n * The key is constrained to {@link ContextMetaKey} — the keys registered in\n * `ContextMeta` / `ContextKeys` — so a typo is a compile error rather than a\n * permanent `undefined`. Projects that have augmented neither registry get\n * `string`, exactly as before.\n *\n * Constrained by `ContextMetaKey` and deliberately NOT by `TKeys`: \"does this\n * key exist in the app\" is a different question from \"does this route carry\n * it\", and narrowing by the latter would turn an incomplete typegen view into\n * false errors for keys written by middleware. Presence is `require`'s job;\n * this always returns `| undefined`.\n *\n * When `ContextMeta` has a matching key the return type is inferred\n * automatically. For ad-hoc keys, pass a generic: `ctx.get<MyType>('custom')`.\n */\n get<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return this.metadataReadOnly()?.get(key) as MetaValue<K> | undefined\n }\n\n /**\n * Read a value that a contributor is expected to have produced, and\n * throw {@link MissingContextValueError} when it hasn't.\n *\n * Use this instead of `ctx.get(key)!` anywhere the value is a\n * precondition rather than an optional extra — permissions, tenants,\n * the resolved subject of the route. The non-null assertion compiles\n * whether or not the producing contributor is actually applied to the\n * route, so a dropped `@LoadTenant` turns into `undefined` flowing\n * silently into an auth check. `require()` fails loudly at that point\n * instead, naming the key.\n *\n * ```ts\n * // before — compiles even if @OperatorPerm was never applied\n * const perm = ctx.get('operatorPerm')!\n *\n * // after — throws MissingContextValueError naming the key + route\n * const perm = ctx.require('operatorPerm')\n * ```\n *\n * When `TKeys` is narrowed — which it is for a handler typed as\n * `Ctx<KickRoutes…>`, from typegen's per-route `contextKeys` — asking\n * for a key the route doesn't carry is a compile error, so a dropped\n * decorator fails the build. `TKeys` stays `string` (no narrowing) for\n * a plain `RequestContext` and for any route typegen couldn't prove\n * complete; there this is a runtime guarantee only.\n * See `architecture.md` §20.14.\n *\n * `null` counts as present; only `undefined` (or a missing entry)\n * throws. A contributor that deliberately resolves to `null` is\n * expressing \"looked, found nothing\", which is a real value — which\n * is why the return type is `Exclude<…, undefined>` and NOT\n * `NonNullable<…>`. The latter would strip `null` from the type while\n * the runtime still hands it back, so a caller would be told a value\n * is non-null and then get `null`.\n */\n require<K extends TKeys>(key: K): Exclude<MetaValue<K>, undefined> {\n const value = this.metadataReadOnly()?.get(key)\n if (value === undefined) {\n throw new MissingContextValueError(key, this.routeLabel())\n }\n return value as Exclude<MetaValue<K>, undefined>\n }\n\n /**\n * Best-effort `\"GET /path\"` label for error messages. Runtime-agnostic:\n * express/fastify requests and web-standard `Request` all expose\n * `method` + `url`, but none of them are guaranteed here, so every\n * access is defensive and the whole thing is optional.\n */\n private routeLabel(): string | undefined {\n const req = this.req as { method?: unknown; url?: unknown } | undefined\n const method = typeof req?.method === 'string' ? req.method : undefined\n const url = typeof req?.url === 'string' ? req.url : undefined\n if (method && url) return `${method} ${url}`\n return method ?? url\n }\n\n /**\n * Write a value to the per-request metadata store. Throws when no\n * AsyncLocalStorage frame is active — see {@link metadataForWrite}\n * for why a silent fallback is the wrong default.\n */\n set<K extends ContextMetaKey>(key: K, value: MetaValue<K>): void {\n this.metadataForWrite().set(key, value)\n }\n\n // ── Response Helpers ────────────────────────────────────────────────\n\n /**\n * Set a response header. Runtime-neutral — works on every engine and on\n * the web/edge entry. No-op guards are the runtime's job (headers set\n * after the response settles are ignored or throw per engine).\n */\n setHeader(name: string, value: string | number | readonly string[]): this {\n this._response.setHeader(name, value)\n return this\n }\n\n json(data: any, status = 200) {\n return this.sendJson(status, data)\n }\n\n created(data: any) {\n return this.sendJson(201, data)\n }\n\n private sendJson(status: number, data: unknown): RuntimeResponse {\n try {\n return this._response.status(status).json(data)\n } catch (err) {\n // Express serialises inside `res.json` and throws on a bigint before\n // anything is written; the other runtimes' drivers use stringifyJson.\n if (!isBigIntJsonError(err) || this._response.headersSent) throw err\n return this._response.status(status).json(JSON.parse(stringifyJson(data)))\n }\n }\n\n noContent() {\n return this._response.status(204).end()\n }\n\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string. Names and params are typed\n * once `kick typegen` has run; an unknown name or a missing param throws.\n *\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const user = await this.users.create(ctx.body)\n * ctx.setHeader('Location', ctx.urlFor('UsersController.show', { id: user.id }))\n * ctx.created(user)\n * }\n * ```\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const urls = this.route?.urls\n if (!urls) throw new Error('ctx.urlFor() is only available inside a matched route')\n const [params, query] = args\n return urls.build(name, params as Record<string, unknown> | undefined, query)\n }\n\n /**\n * Answer a conditional request from the resource's validators, before doing\n * the expensive part. Sets `ETag` / `Last-Modified`, then — per RFC 9110 —\n * answers `304 Not Modified` when the client's copy is current, or `412`\n * when an `If-Match` / `If-Unmodified-Since` write is based on a stale one.\n * Returns `true` when it answered; respond as usual when it returns `false`.\n *\n * ```ts\n * @Get('/:id')\n * async show(ctx: RequestContext) {\n * const { version, updatedAt } = await posts.meta(ctx.params.id) // cheap\n * if (ctx.conditional({ etag: `v${version}`, lastModified: updatedAt })) return\n * ctx.json(await posts.full(ctx.params.id)) // only when it changed\n * }\n * ```\n */\n conditional(validators: Validators): boolean {\n if (validators.etag !== undefined) this.setHeader('ETag', normalizeEtag(validators.etag))\n if (validators.lastModified) {\n this.setHeader('Last-Modified', validators.lastModified.toUTCString())\n }\n const method = String((this.req as { method?: string }).method ?? 'GET').toUpperCase()\n const outcome = evaluatePreconditions(\n method,\n this.headers as Record<string, string | string[] | undefined>,\n validators,\n )\n if (outcome === 304) {\n this._response.status(304).end()\n return true\n }\n if (outcome === 412) {\n this.sendProblem({\n status: 412,\n detail: 'The resource changed since the version this request is based on.',\n })\n return true\n }\n return false\n }\n\n /**\n * @deprecated Prefer {@link ProblemSender.notFound | ctx.problem.notFound()},\n * which emits an RFC 9457 — Problem Details response. This helper stays\n * for backward compatibility and will not be removed.\n */\n notFound(message = 'Not Found') {\n return this._response.status(404).json({ message })\n }\n\n /**\n * @deprecated Prefer {@link ProblemSender.badRequest | ctx.problem.badRequest()},\n * which emits an RFC 9457 — Problem Details response. This helper stays\n * for backward compatibility and will not be removed.\n */\n badRequest(message: string) {\n return this._response.status(400).json({ message })\n }\n\n // ── RFC 9457 Problem Details ───────────────────────────────────────\n\n /**\n * RFC 9457 — Problem Details for HTTP APIs response helper.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * `ctx.problem(...)` sends a canonical problem-detail response with\n * `Content-Type: application/problem+json`. The convenience methods\n * (`ctx.problem.notFound`, `.badRequest`, etc.) pre-fill `status` +\n * `title` for the common codes.\n *\n * `type` defaults to `about:blank` (§3.1.1); `title` defaults to the\n * IANA reason phrase for `status` (§3.1.4). Extension members per §3.2\n * pass through unchanged.\n *\n * @example\n * ```ts\n * ctx.problem({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: `/account/${ctx.user.id}/messages/${ctx.params.id}`,\n * balance: 30,\n * })\n *\n * ctx.problem.notFound({ detail: 'User abc not found' })\n * ctx.problem.validation(zodResult.error.issues)\n * ```\n *\n * @see {@link ProblemException} for the exception-throwing equivalent\n * (use it from services where `ctx` isn't in scope).\n */\n get problem(): ProblemSender {\n // Memoized — building the sender allocates ~10 closures, so pay that only\n // on the first access per context instead of per `ctx.problem.*` call.\n if (this._problem) return this._problem\n const send = (input: ProblemDetails): RuntimeResponse => this.sendProblem(input)\n send.badRequest = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 400, ...input })\n send.unauthorized = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 401, ...input })\n send.forbidden = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 403, ...input })\n send.notFound = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 404, ...input })\n send.conflict = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 409, ...input })\n send.unprocessable = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 422, ...input })\n send.tooManyRequests = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 429, ...input })\n send.internal = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 500, ...input })\n send.validation = (issues: any[], input: ProblemInput = {}): RuntimeResponse => {\n const errors: ValidationError[] = (issues || []).map((issue: any) => ({\n field: issue.path?.join?.('.') ?? '',\n message: issue.message ?? '',\n code: issue.code,\n }))\n return this.sendProblem({\n status: 422,\n detail: issues?.[0]?.message,\n ...input,\n errors,\n })\n }\n this._problem = send as ProblemSender\n return this._problem\n }\n\n private sendProblem(input: ProblemDetails): RuntimeResponse {\n const body = normalizeProblem(input)\n this._response.setHeader('Content-Type', 'application/problem+json')\n return this._response.status(body.status).json(body)\n }\n\n /**\n * Send an HTML response.\n *\n * Passes the full MIME type rather than the `'html'` shorthand. The\n * shorthand is an Express affordance — `res.type()` runs it through a MIME\n * lookup — but the Fastify and h3 drivers forward the string to their own\n * `type()` / `setHeader()` verbatim, so `'html'` reached the wire as a\n * malformed `Content-Type: html` on those engines. Fastify 5.10 started\n * normalising that invalid value to `text/plain`, which is what surfaced it.\n *\n * Express produces `text/html; charset=utf-8` for `.type('html')`, so\n * spelling it out here is byte-identical there and correct everywhere else.\n */\n /**\n * The client's IP address, or `undefined` when it cannot be determined.\n *\n * Prefers the value the runtime computed (Express derives `req.ip` from the\n * app's `trust proxy` setting; Fastify from `trustProxy`), because raw\n * forwarded headers are client-SPOOFABLE on deployments that do not\n * normalize them. The header fallbacks exist for runtimes with no `ip`\n * field at all — notably the web/edge entry.\n *\n * `ctx.req.ip` is Express-only, so reaching for it directly broke on\n * Fastify and h3.\n */\n get ip(): string | undefined {\n return resolveClientIp(this.req as ClientRequestLike)\n }\n\n /**\n * Redirect the client. Works on every runtime.\n *\n * Every engine spells this differently — Express and Fastify have\n * `res.redirect()`, h3 has `sendRedirect(event, location, code)` — and none\n * of them is shared, so this writes the status and `Location` header through\n * the runtime response surface, which all four expose.\n *\n * The response carries no body. Express sends a short text line and h3 an\n * HTML meta-refresh fallback; a bare `Location` with a 3xx is sufficient per\n * RFC 9110, and interpolating the URL into an HTML body would add an\n * injection surface to a value this method already warns is dangerous.\n *\n * ::: warning\n * Never pass an unvalidated user-supplied `url`. An attacker-controlled\n * destination turns this into an open redirect, which is a common phishing\n * primitive. Allow-list the target or keep it relative.\n * :::\n */\n redirect(url: string, status = 302) {\n this._response.status(status).setHeader('location', url)\n return this._response.end()\n }\n\n html(content: string, status = 200) {\n return this._response.status(status).type('text/html; charset=utf-8').send(content)\n }\n\n /**\n * Send a body with its content type — XML, plain text, CSV, an image.\n * Runtime-neutral, like `json()` and `html()`. `type` defaults to\n * `text/plain; charset=utf-8`.\n *\n * @example\n * ```ts\n * ctx.send(sitemapXml, { type: 'application/xml' })\n * ctx.send(csv, { type: 'text/csv; charset=utf-8', status: 200 })\n * ```\n */\n send(body: string | Uint8Array, options: { type?: string; status?: number } = {}) {\n return this._response\n .status(options.status ?? 200)\n .type(options.type ?? 'text/plain; charset=utf-8')\n .send(body)\n }\n\n /**\n * Send `buffer` as a file download named `filename`. The name is written\n * per RFC 6266 — an ASCII fallback plus `filename*` in UTF-8 — so a name\n * from an upload (quotes, line breaks, non-Latin text) can't break the header.\n */\n download(buffer: Buffer, filename: string, contentType = 'application/octet-stream') {\n this._response.setHeader('Content-Disposition', contentDisposition(filename))\n this._response.setHeader('Content-Type', contentType)\n return this._response.send(buffer)\n }\n\n /**\n * Render a template. A view engine bound to the request (`KickView` from\n * `@forinda/kickjs-view`, on every runtime) renders it when it owns the\n * name; otherwise the runtime's engine does (Express + `ViewAdapter`).\n * With a bound engine it returns a promise — await it, or the pipeline\n * waits for it before answering, and a failure reaches the error handler.\n *\n * @param template - Template name (without extension, relative to the views folder)\n * @param data - Data to pass to the template\n * @param opts - `status`, `headers`, `layout: false` for a partial, `locale`, `timeZone`\n *\n * @example\n * ```ts\n * await ctx.render('dashboard', { user, title: 'Dashboard' })\n * await ctx.render('users/row', { user }, { layout: false })\n * ```\n */\n render(template: string, data: Record<string, any> = {}, opts: ViewRenderOptions = {}) {\n const renderer = viewRendererFor(this.req)\n if (!renderer) return this._response.render(template, data)\n const done = renderer(template, data, opts, this).then((html) => {\n if (html === undefined) {\n this._response.render(template, data)\n return\n }\n for (const [name, value] of Object.entries(opts.headers ?? {})) this.setHeader(name, value)\n this.html(html, opts.status ?? 200)\n })\n setPendingResponse(this, done)\n // Handled here so an unawaited render isn't an unhandled rejection; the\n // pipeline (or the caller's await) still sees the failure.\n done.catch(() => {})\n return done\n }\n\n /**\n * Parse query params and return a standardized paginated response.\n * Calls `ctx.qs()` internally, then wraps your data with pagination meta.\n *\n * @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`\n * @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * return ctx.paginate(\n * async (parsed) => {\n * const data = await db.select().from(users)\n * .where(query.where).limit(parsed.pagination.limit)\n * .offset(parsed.pagination.offset).all()\n * const total = await db.select({ count: count() }).from(users).get()\n * return { data, total: total?.count ?? 0 }\n * },\n * { filterable: ['name', 'role'], sortable: ['createdAt'] },\n * )\n * }\n * ```\n */\n async paginate<T, TConfig extends QueryFieldConfig | undefined = undefined>(\n fetcher: (parsed: TypedParsedQuery<TConfig>) => Promise<{ data: T[]; total: number }>,\n fieldConfig?: TConfig,\n ): Promise<PaginatedResponse<T>> {\n const parsed = this.qs<TConfig>(fieldConfig)\n const { data, total } = await fetcher(parsed)\n const { page, limit } = parsed.pagination\n const totalPages = Math.ceil(total / limit) || 1\n\n const response: PaginatedResponse<T> = {\n data,\n meta: {\n page,\n limit,\n total,\n totalPages,\n hasNext: page < totalPages,\n hasPrev: page > 1,\n },\n links: {\n self: selfLink(this.requestUrl()),\n next: page < totalPages ? pageLink(this.requestUrl(), 'page', page + 1) : null,\n prev: page > 1 ? pageLink(this.requestUrl(), 'page', page - 1) : null,\n },\n }\n\n this.json(response)\n // Sends AND returns the payload. Returning `this.json(...)` handed back\n // the engine's `RuntimeResponse`, so the documented usage —\n // `return ctx.paginate(...)` — emitted `response: RuntimeResponse` into\n // `KickRoutes`, and the typed client offered `.status()` / `.setHeader()`\n // where the caller expected `data` and `meta`.\n //\n // Returning the payload rather than tagging the response reuses the\n // existing return-value inference (the same path `return user` and\n // `return reply(201, user)` take) instead of adding a second mechanism\n // beside `reply`. Sending here is kept for handlers that call `paginate`\n // without returning it; the runtimes only auto-send a returned value when\n // nothing was written (`if (!res.headersSent)`), so there is no double\n // send.\n return response\n }\n\n /**\n * Cursor (keyset) pagination: parse `?cursor=&limit=` plus the usual\n * filter / sort / `q`, call the fetcher, and send\n * `{ data, meta: { limit, hasNext, nextCursor }, links: { self, next } }`.\n *\n * The fetcher gets `{ filters, sort, search, cursor, limit }` and returns up\n * to `limit + 1` rows ordered by the sort fields then `idField`, strictly\n * after `cursor` (`null` on the first page). The extra row only sets\n * `hasNext`; it is trimmed off. The next cursor encodes the last returned\n * row's sort-field values + id, and the active sort — a cursor replayed\n * under a different `sort`, or one that does not decode, is a 400.\n *\n * Cursors are not signed. The decoded position is plain data: bind it as\n * query parameters, and keep filters and authorization scoping in the\n * fetcher so a forged cursor can never widen what the caller sees.\n *\n * @example\n * ```ts\n * @Get('/')\n * list(ctx: RequestContext) {\n * return ctx.paginateCursor(\n * (q) => this.repo.findAfter({ ...q, limit: q.limit + 1 }),\n * { sortable: ['createdAt'] },\n * )\n * }\n * ```\n */\n async paginateCursor<T, TConfig extends QueryFieldConfig | undefined = undefined>(\n fetcher: (query: CursorQuery<TConfig>) => Promise<T[]>,\n fieldConfig?: TConfig,\n options?: CursorPaginateOptions<T>,\n ): Promise<CursorPaginatedResponse<T>> {\n const { pagination, ...parsed } = this.qs<TConfig>(fieldConfig)\n const { limit } = pagination\n const idField = options?.idField ?? 'id'\n const signature = sortSignature(parsed.sort)\n // Exact key set to expect back — unknown when the app builds the key itself.\n const keys = options?.cursorKey\n ? undefined\n : [...new Set([...parsed.sort.map((s) => s.field), idField])]\n\n const raw = (this.req.query as Record<string, unknown>)?.cursor\n const cursor = raw === undefined || raw === '' ? null : decodeCursor(raw, signature, keys)\n\n const rows = await fetcher({ ...parsed, cursor, limit })\n const hasNext = rows.length > limit\n const data = hasNext ? rows.slice(0, limit) : rows\n const last = data.at(-1)\n let nextCursor: string | null = null\n if (hasNext && last !== undefined) {\n nextCursor = encodeCursor(cursorValues(last, keys ?? [], options?.cursorKey), signature)\n }\n\n const url = this.requestUrl()\n const response: CursorPaginatedResponse<T> = {\n data,\n meta: { limit, hasNext, nextCursor },\n links: { self: selfLink(url), next: nextCursor ? pageLink(url, 'cursor', nextCursor) : null },\n }\n // Sends AND returns — same reasoning as `paginate` above.\n this.json(response)\n return response\n }\n\n /** Path + query as the client sent it, before any router mount stripped it. */\n private requestUrl(): string {\n const req = this.req as { originalUrl?: unknown; url?: unknown }\n if (typeof req.originalUrl === 'string') return req.originalUrl\n return typeof req.url === 'string' ? req.url : '/'\n }\n\n // ── Server-Sent Events ──────────────────────────────────────────────\n\n /**\n * Start an SSE (Server-Sent Events) stream.\n * Sets the correct headers and returns helpers to send events.\n *\n * Pass a payload type to get typed sends — and `return sse` from the\n * handler so `kick typegen` carries the event type into\n * `KickRoutes.Api`, where `@forinda/kickjs-client`'s `api.stream()`\n * picks it up (the returned handler is ignored at runtime — the\n * response is already streaming).\n *\n * @example\n * ```ts\n * interface Tick { time: string }\n *\n * @Get('/events')\n * async stream(ctx: RequestContext) {\n * const sse = ctx.sse<Tick>()\n *\n * const interval = setInterval(() => {\n * sse.send({ time: new Date().toISOString() }, 'tick')\n * }, 1000)\n *\n * sse.onClose(() => clearInterval(interval))\n * return sse // typed as SseHandler<Tick> → response inference\n * }\n * ```\n */\n /**\n * Send a web-standard `Response` — status, headers (every `Set-Cookie`\n * kept) and body, streamed chunk by chunk — on any runtime. For handing off\n * to libraries that speak `Request`/`Response`, such as the MCP SDK's\n * web-standard transport.\n *\n * Resolves once the body is fully written. Stops reading the body when the\n * client disconnects.\n *\n * @example\n * ```ts\n * @Post('/mcp')\n * async mcp(ctx: RequestContext) {\n * await ctx.sendResponse(await transport.handleRequest(webRequest))\n * }\n * ```\n */\n async sendResponse(response: Response): Promise<void> {\n const headers: Record<string, string | string[]> = {}\n response.headers.forEach((value, name) => {\n if (name !== 'set-cookie') headers[name] = value\n })\n const cookies = response.headers.getSetCookie()\n if (cookies.length > 0) headers['set-cookie'] = cookies\n\n if (!response.body) {\n // Not writeHead() + end(): on the web driver writeHead switches to a\n // streamed Response, which a 204/304 cannot be, and on Fastify end()\n // bypasses the headers set on the reply. send() is each runtime's own\n // buffered reply path.\n this._response.status(response.status)\n for (const [name, value] of Object.entries(headers)) this._response.setHeader(name, value)\n this._response.send('')\n return\n }\n this._response.writeHead(response.status, headers as Record<string, string>)\n // Send the headers now: a stream whose first chunk comes later (SSE)\n // would otherwise leave the client waiting to see the response open.\n this._response.flushHeaders()\n const reader = response.body.getReader()\n const stop = () => {\n reader.cancel().catch(() => {})\n }\n this.signal.addEventListener('abort', stop, { once: true })\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n // Honour backpressure: on a slow client, wait for the socket to drain\n // (or the client to go away) before reading more of the body.\n if (this._response.write(Buffer.from(value)) === false && !this.signal.aborted) {\n await new Promise<void>((resolve) => {\n const resume = () => {\n this.signal.removeEventListener('abort', resume)\n resolve()\n }\n this._response.once('drain', resume)\n this.signal.addEventListener('abort', resume, { once: true })\n })\n }\n }\n } finally {\n this.signal.removeEventListener('abort', stop)\n this._response.end()\n }\n }\n\n /**\n * Keep `promise` running after the response is sent — an audit log, an\n * email, an analytics call. The Node server's `shutdown()` waits for it;\n * `createHandler()` and the web entry hand it to the platform's\n * `waitUntil` when you pass the platform context in. A rejection is\n * logged, never unhandled. Same as the standalone `waitUntil()` export.\n */\n waitUntil(promise: Promise<unknown>): void {\n waitUntil(promise)\n }\n\n sse<T = unknown>(): SseHandler<T> {\n this._response.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n // no-transform: compression middleware (and proxies) would otherwise\n // buffer the stream in gzip, holding events back from the client.\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n this._response.flushHeaders()\n\n const closeCallbacks: Array<() => void> = []\n\n this.req.on('close', () => {\n for (const cb of closeCallbacks) cb()\n })\n\n return {\n /** Send an SSE event with optional event name and id */\n send: (data: T, event?: string, id?: string) => {\n if (id) this._response.write(`id: ${id}\\n`)\n if (event) this._response.write(`event: ${event}\\n`)\n this._response.write(`data: ${JSON.stringify(data)}\\n\\n`)\n },\n /** Send a comment (keeps connection alive) */\n comment: (text: string) => {\n this._response.write(`: ${text}\\n\\n`)\n },\n /** Register a callback when the client disconnects */\n onClose: (fn: () => void) => {\n closeCallbacks.push(fn)\n },\n /** End the SSE stream */\n close: () => {\n this._response.end()\n },\n }\n }\n}\n\n/**\n * The handle {@link RequestContext.sse} returns. The optional phantom\n * `__sse` property carries the event payload type STRUCTURALLY — never set\n * at runtime — so `kick typegen`'s response inference (handler `return sse`)\n * flows it into `KickRoutes.Api`, and `@forinda/kickjs-client` detects SSE\n * routes without importing any server types.\n */\nexport interface SseHandler<T = unknown> {\n /** Phantom event-payload type marker — never assigned at runtime. */\n readonly __sse?: T\n /** Send an SSE event with optional event name and id. */\n send(data: T, event?: string, id?: string): void\n /** Send a comment line (keeps the connection alive through proxies). */\n comment(text: string): void\n /** Register a callback for client disconnect. */\n onClose(fn: () => void): void\n /** End the SSE stream. */\n close(): void\n}\n\n/**\n * Short alias for `RequestContext` parameterised by a route shape.\n *\n * Use with `kick typegen`'s generated `KickRoutes` namespace for\n * fully-typed `ctx.params`, `ctx.body`, and `ctx.query`. Metadata\n * typing (`ctx.get()`, `ctx.set()`, `ctx.user`) comes from\n * `ContextMeta` augmentation and works on all `RequestContext` instances.\n *\n * @example\n * ```ts\n * @Get('/:id')\n * getUser(ctx: Ctx<KickRoutes.UserController['getUser']>) {\n * ctx.params.id // typed from RouteShape\n * ctx.body // typed from RouteShape\n * ctx.user // typed from ContextMeta\n * ctx.get('tenant') // typed from ContextMeta\n * }\n * ```\n */\nexport type Ctx<TRoute extends RouteShape = RouteShape> = RequestContext<\n TRoute extends { body: infer B } ? B : any,\n TRoute extends { params: infer P } ? P : any,\n TRoute extends { query: infer Q } ? Q : any,\n // Falls back to `string` (no narrowing) whenever typegen couldn't prove\n // the route's full contributor set — see `RouteShape.contextKeys`.\n TRoute extends { contextKeys: infer K }\n ? K extends ContextMetaKey\n ? K\n : ContextMetaKey\n : ContextMetaKey\n>\n\n/**\n * Global ambient registry of typed routes, populated by `kick typegen`.\n *\n * Interfaces inside `KickRoutes` correspond to controller classes (each\n * property one route method, conforming to `RouteShape`) — plus the\n * reserved `KickRoutes.Api`: a flat `'METHOD /mounted/path'` map over the\n * same shapes, consumed by `@forinda/kickjs-client`. Don't name a\n * controller class `Api` — it would declaration-merge into that map.\n *\n * Empty by default — declarations come from `.kickjs/types/kick__routes.ts`\n * generated alongside the rest of the typegen output.\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {}\n}\n\n/** `attachment; filename=\"…\"; filename*=UTF-8''…` for any file name (RFC 6266 / RFC 8187). */\nexport function contentDisposition(filename: string): string {\n const fallback = filename.replace(/[^\\x20-\\x7e]|[\"\\\\]/g, '_')\n const encoded = encodeURIComponent(filename).replace(\n /['()*]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n return `attachment; filename=\"${fallback}\"; filename*=UTF-8''${encoded}`\n}\n\n/**\n * A row's cursor values: the app's `cursorKey`, or the sort fields + id read\n * off the row. Dates become ISO strings and bigints decimal strings (JSON\n * would do the first and throw on the second).\n */\nfunction cursorValues<T>(\n row: T,\n keys: readonly string[],\n cursorKey: ((row: T) => Record<string, CursorValue>) | undefined,\n): Record<string, CursorValue> {\n if (cursorKey) return cursorKey(row)\n const values: Record<string, CursorValue> = {}\n for (const key of keys) {\n const value = (row as Record<string, unknown>)[key]\n if (value === undefined) {\n throw new Error(\n `paginateCursor: row has no '${key}' — return the sort fields and the id ` +\n `field on every row, or pass options.cursorKey / options.idField`,\n )\n }\n values[key] =\n value instanceof Date\n ? value.toISOString()\n : typeof value === 'bigint'\n ? value.toString()\n : (value as CursorValue)\n }\n return values\n}\n"],"mappings":";;;;;;;;;;+dAyBA,SAAS,OAAO,QAAkB,KAAkC,CAClE,IAAM,MAAQ,QAAQ,MACtB,OAAO,MAAM,QAAQ,KAAK,EAAI,MAAM,KAAK,IAAI,EAAI,KACnD,CAGA,SAAgB,cAAc,KAAsB,CAClD,GAAI,eAAe,KAAK,IAAI,EAAG,OAAO,KAGtC,IAAM,KAAO,KAAK,WAAW,IAAI,EAC3B,MAAQ,KAAO,KAAK,MAAM,CAAC,EAAI,KAAA,CAAM,WAAW,IAAK,EAAE,EAC7D,MAAO,GAAG,KAAO,KAAO,GAAG,GAAG,KAAK,EACrC,CAEA,MAAM,OAAU,KAAgB,IAAI,QAAQ,OAAQ,EAAE,EAChD,OAAU,KAAgB,IAAI,WAAW,IAAI,EAGnD,SAAS,OAAO,MAAyB,CACvC,OAAO,MAAM,MAAM,qBAAqB,GAAK,CAAC,CAChD,CAGA,SAAS,OAAO,MAA+C,CAC7D,GAAI,CAAC,MAAO,OACZ,IAAM,GAAK,KAAK,MAAM,KAAK,EAC3B,OAAO,OAAO,MAAM,EAAE,EAAI,IAAA,GAAY,EACxC,CAGA,MAAM,QAAW,MAAe,KAAK,MAAM,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UAAa,CACX,KAAK,UAAU,IAAI,CACrB,CACF,CACF,CACF,EAwEA,SAAgB,mBAAmB,SAA0B,CAM3D,MAAO,yBALU,SAAS,QAAQ,sBAAuB,GAKlB,EAAE,sBAJzB,mBAAmB,QAAQ,CAAC,CAAC,QAC3C,UACC,GAAM,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,GAEe,GACvE,CAOA,SAAS,aACP,IACA,KACA,UAC6B,CAC7B,GAAI,UAAW,OAAO,UAAU,GAAG,EACnC,IAAM,OAAsC,CAAC,EAC7C,IAAK,IAAM,OAAO,KAAM,CACtB,IAAM,MAAS,IAAgC,KAC/C,GAAI,QAAU,IAAA,GACZ,MAAU,MACR,+BAA+B,IAAI,sGAErC,EAEF,OAAO,KACL,iBAAiB,KACb,MAAM,YAAY,EAClB,OAAO,OAAU,SACf,MAAM,SAAS,EACd,KACX,CACA,OAAO,MACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"csrf-w5bc-PGs.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/csrf.ts"],"mappings":";;;;;UAeiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;EAMA;;;;;;;;;;EAUA;;EAEA;;;;;;IAME;IACA;IACA;IACA;;;KAIC,YAAY;;;;;;;iBAuBD,gBAAgB,SAAS,WAAW,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmE7C,KAAK,UAAS,eAAgB,KAyB/BA,gBAAO,KAAOC,iBAAQ,MAAQC;UAyC5B,yBAAyB;;;;;;;;;;;;;;;;;;;;;EAqBxC,aAAa;;;;;;;;;;;;;;;;;;;;;;iBAuBC,UAAU,UAAS,mBAAwB"}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.12.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{t as __exportAll}from"./rolldown-runtime-OjcH9Gd_.mjs";import{r as buildRouteTable}from"./router-builder-abKMvAmP.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,d as rejectUnsupportedBody,t as EXPRESS_JSON_TYPES}from"./body-policy-cWfUReGC.mjs";import{n as applyHandlerResult}from"./reply-Bg1gyBtE.mjs";import{t as EXPRESS_CAPABILITIES}from"./express-lazy-BE10FhlA.mjs";import{r as publishMatchedRoute,t as RequestContext}from"./context-Cc6k0gsM.mjs";import{validate}from"./http/middleware/validate.mjs";import{buildUploadMiddleware}from"./http/middleware/upload.mjs";import{t as withPrecompressed}from"./precompressed-CYkmmoRU.mjs";import express,{Router}from"express";var express_exports=/* @__PURE__ */ __exportAll({buildRoutes:()=>buildRoutes,expressRuntime:()=>expressRuntime,materializeRouter:()=>materializeRouter});function materializeRouter(entries){return expressRouter(entries)}function expressRouter(entries){let router=Router();for(let entry of entries){let method=entry.method.toLowerCase(),handlers=[],refusePrototypeKeys=(req,_res,next)=>next(hasPrototypeKey(req.body)?prototypeKeyError():void 0);handlers.push((req,res,next)=>{publishMatchedRoute(req,entry),refusePrototypeKeys(req,res,next)});let contributorStep=run=>async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{await run(ctx),res.headersSent||next()}catch(err){next(err)}};entry.earlyContributorRunner&&handlers.push(contributorStep(entry.earlyContributorRunner)),entry.meta.validation&&handlers.push(validate(entry.meta.validation,{validationError:entry.validationError})),entry.meta.upload&&handlers.push(buildUploadMiddleware(entry.meta.upload),refusePrototypeKeys);for(let mw of entry.middlewares)handlers.push((req,res,next)=>{let ctx=new RequestContext(req,res,next);Promise.resolve(mw(ctx,next)).catch(next)});entry.contributorRunner&&handlers.push(contributorStep(entry.contributorRunner)),handlers.push(async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{let result=await entry.handler(ctx);res.headersSent||await applyHandlerResult(ctx,result)}catch(err){next(err)}}),router[method](entry.path,...handlers)}return router}function buildRoutes(controllerClass,options={}){return expressRouter(buildRouteTable(controllerClass,options))}function expressRuntime(){return{name:`express`,createApp(options={}){let app=express();return app.disable(`x-powered-by`),app.set(`trust proxy`,options.trustProxy??!1),app},nodeHandler(app){return(req,res,next)=>{next?app(req,res,next):app(req,res)}},mountRoutes(app,table){for(let{mountPath,routes}of table)app.use(mountPath,expressRouter(routes))},useConnect(app,mw,opts={}){opts.path===void 0?app.use(mw):app.use(opts.path,mw)},serveStatic(app,prefix,dir){app.use(prefix,withPrecompressed(dir,express.static(dir)))},setNotFound(app,mw){app.use(mw)},setErrorHandler(app,mw){app.use(mw)},bodyParsers({limit}){return[express.json({limit,type:[...EXPRESS_JSON_TYPES]}),express.urlencoded({extended:!0,limit}),express.text({limit,type:`text/*`}),rejectUnsupportedBody()]},capabilities:EXPRESS_CAPABILITIES}}export{materializeRouter as i,expressRuntime as n,express_exports as r,buildRoutes as t};
|
|
12
|
-
//# sourceMappingURL=express-B6jvEdCZ.mjs.map
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.12.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{HttpException}from"./core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,i as formFields,l as readBodyBytes,o as parseByteSize,p as unsupportedMediaTypeError,r as classifyMediaType,s as parseForm,u as readBodyText}from"./body-policy-cWfUReGC.mjs";import{f as requestStore}from"./view-renderer-CSPD7F-f.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{n as disposeRequestStore,t as createRequestStore}from"./request-scope-R9FuLLnB.mjs";import{n as applyHandlerResult}from"./reply-Bg1gyBtE.mjs";import{i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"./context-Cc6k0gsM.mjs";import{validate}from"./http/middleware/validate.mjs";import{c as tooManyFiles,l as uploadLimits,r as applyUploadConfig}from"./upload-config-TFTYQPaH.mjs";var WebRequestShim=class{method;url;headers;body;params={};query={};requestId;file;files;signal;constructor(request,url){this.method=request.method,this.url=url.pathname+url.search,this.signal=request.signal;let headers={};request.headers.forEach((value,key)=>{headers[key]=value}),this.headers=headers;let query={};for(let key of url.searchParams.keys()){let all=url.searchParams.getAll(key);query[key]=all.length>1?all:all[0]}this.query=query}once(event,listener){return event===`close`&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}on(event,listener){return this.once(event,listener)}};const encoder=new TextEncoder;function toBytes(chunk){return chunk instanceof Uint8Array?chunk:encoder.encode(String(chunk))}const utf8=new TextEncoder;var WebResponseDriver=class{signal;ready;settled=!1;_status=200;headers=new Headers;_headersSent=!1;writer;resolveReady;constructor(signal){this.signal=signal,this.ready=new Promise(resolve=>{this.resolveReady=resolve})}status(code){return this._status=code,this}json(data){return this.headers.has(`content-type`)||this.headers.set(`content-type`,`application/json; charset=utf-8`),this.finish(stringifyJson(data))}send(data){return typeof data==`object`&&data&&!(data instanceof Uint8Array)?this.json(data):this.finish(data)}type(contentType){return this.headers.set(`content-type`,contentType),this}getHeader(name){if(name.toLowerCase()===`set-cookie`){let cookies=this.headers.getSetCookie();return cookies.length>0?cookies:void 0}return this.headers.get(name)??void 0}setHeader(name,value){if(Array.isArray(value)){this.headers.delete(name);for(let v of value)this.headers.append(name,String(v))}else this.headers.set(name,String(value));return this}render(){throw Error(`ctx.render() is not supported on the web runtime (no view engine).`)}writeHead(statusCode,headers){if(this._status=statusCode,headers)for(let[name,value]of Object.entries(headers))this.setHeader(name,value);return this.startStream(),this}flushHeaders(){return this.startStream(),this}write(chunk){return this.startStream(),this.writer.write(toBytes(chunk)).catch(()=>{}),!0}end(data){return this.writer?(data!==void 0&&this.write(data),this.writer.close().catch(()=>{}),this.writer=void 0,this):this.finish(data)}once(event,listener){return event===`close`&&this.signal&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}get headersSent(){return this._headersSent}finish(body){if(this.settled)return this;this.settled=!0,this._headersSent=!0;let bodyAllowed=this._status!==204&&this._status!==304;if(bodyAllowed&&body!=null&&!this.headers.has(`content-length`)){let length=typeof body==`string`?utf8.encode(body).byteLength:body.byteLength;this.headers.set(`content-length`,String(length))}return this.resolveReady(new Response(bodyAllowed?body??null:null,{status:this._status,headers:this.headers})),this}startStream(){if(this.writer||this.settled)return;let{readable,writable}=new TransformStream;this.writer=writable.getWriter(),this.settled=!0,this._headersSent=!0,this.signal?.addEventListener(`abort`,()=>{this.writer?.abort().catch(()=>{}),this.writer=void 0},{once:!0}),this.resolveReady(new Response(readable,{status:this._status,headers:this.headers}))}};const NOOP_NEXT=()=>{},BODY_METHODS=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]),builtInError=errorHandler(),builtInNotFound=notFoundHandler();function decodeParams(params){let decoded={};for(let key in params){let value=params[key];decoded[key]=value.includes(`%`)?decodeURIComponent(value):value}return decoded}function readThrough(shim,carry){return new Proxy(shim,{get(target,prop,receiver){let own=Reflect.get(target,prop,receiver);return own===void 0?Reflect.get(carry,prop,carry):own},has(target,prop){return Reflect.has(target,prop)||Reflect.has(carry,prop)}})}function compileWebRoute(entry,hooks,options={}){let bodyLimit=options.bodyLimit??parseByteSize(`1mb`),validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0,upload=entry.meta.upload&&entry.meta.upload.mode!==`none`?entry.meta.upload:null;return async({request,url,params,carry})=>{let shim=new WebRequestShim(request,url),req=carry?readThrough(shim,carry):shim,bodyError;try{req.params=decodeParams(params)}catch{req.params=params,bodyError=HttpException.badRequest(`Malformed URL parameter`)}if(upload){let limits=uploadLimits(upload),form;try{let bytes=await readBodyBytes(request,limits.total),type=request.headers.get(`content-type`)??``;form=await new Response(bytes,{headers:{"content-type":type}}).formData().catch(()=>void 0)}catch(err){err instanceof HttpException&&(bodyError=err)}if(form){let rawParts=[],fields=[];for(let[name,value]of form.entries())typeof value==`string`?fields.push([name,value]):rawParts.push({fieldname:name,filename:value.name??``,mimetype:value.type||`application/octet-stream`,buffer:typeof Buffer==`function`?Buffer.from(await value.arrayBuffer()):new Uint8Array(await value.arrayBuffer())});if(req.body=formFields(fields),rawParts.length>limits.files)bodyError=tooManyFiles(limits.files);else try{let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);req.file=file,req.files=files}catch(err){bodyError=err}}}else if(BODY_METHODS.has(request.method)){let raw=``;try{raw=await readBodyText(request,bodyLimit)}catch(err){err instanceof HttpException&&(bodyError=err)}let kind=classifyMediaType(req.headers[`content-type`]);if(raw!==``&&kind===`unsupported`)bodyError=unsupportedMediaTypeError(req.headers[`content-type`]);else if(raw!==``&&kind!==`multipart`){if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){bodyError=HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`)}else req.body=kind===`urlencoded`?parseForm(raw):raw}}!bodyError&&hasPrototypeKey(req.body)&&(bodyError=prototypeKeyError());let store=createRequestStore(req.requestId||req.headers[`x-request-id`]);req.requestId=store.requestId;let driver=new WebResponseDriver(request.signal);driver.setHeader(`x-request-id`,store.requestId),publishMatchedRoute(req,entry),carry&&publishMatchedRoute(carry,entry);let pipeline=requestStore.run(store,async()=>{if(bodyError)throw bodyError;let ctx=new RequestContext(req,driver,NOOP_NEXT,driver);if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),driver.settled))return;validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||driver.settled)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),driver.settled)return;let result=await entry.handler(ctx);driver.settled||await applyHandlerResult(ctx,result)});try{try{await Promise.race([pipeline,driver.ready])}catch(err){driver.settled||await requestStore.run(store,async()=>{hooks?.onError&&await hooks.onError(err,req,driver),driver.settled||await builtInError(err,req,driver,NOOP_NEXT)})}return driver.settled||builtInNotFound(req,driver,NOOP_NEXT),await driver.ready}finally{Promise.resolve(pipeline).catch(()=>{}).then(()=>disposeRequestStore(store))}}}async function headFromGet(response){let res=await response;return res.body?.cancel().catch(()=>{}),new Response(null,{status:res.status,statusText:res.statusText,headers:res.headers})}export{WebResponseDriver as a,WebRequestShim as i,headFromGet as n,readThrough as r,compileWebRoute as t};
|
|
12
|
-
//# sourceMappingURL=handler-BpMOjmfq.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"handler-BpMOjmfq.mjs","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts"],"sourcesContent":["// Web-standard driver pair — the request/response bridge between web\n// primitives (WHATWG Request/Response) and the KickJS RequestContext surface.\n//\n// Deliberately imports NOTHING from node: this module is the edge-safe core\n// shared by the h3 v2 runtime (`runtimes/h3.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport { stringifyJson, type RuntimeResponse } from '../runtime'\n\n/**\n * Presents a web `Request` as the express-shaped `req` object that\n * `RequestContext` (and route validation) reads: plain-object `headers`,\n * assignable `body`/`params`/`query`, and `on/once('close')` bridged from\n * the request's `AbortSignal` — the only EventEmitter surface the context\n * layer uses (`ctx.signal`, SSE close).\n */\nexport class WebRequestShim {\n readonly method: string\n readonly url: string\n /** Lower-cased plain header object (RequestContext indexes it directly). */\n readonly headers: Record<string, string>\n body: unknown\n params: Record<string, string> = {}\n query: Record<string, unknown> = {}\n requestId?: string\n file?: unknown\n files?: unknown;\n // Ad-hoc props middleware may set (session, user, ...) — index signature\n // keeps assignment open like a node req object.\n [key: string]: unknown\n\n private readonly signal: AbortSignal\n\n constructor(request: Request, url: URL) {\n this.method = request.method\n // Express-shaped `req.url` is path + search, not the absolute URL.\n this.url = url.pathname + url.search\n this.signal = request.signal\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n this.headers = headers\n const query: Record<string, unknown> = {}\n for (const key of url.searchParams.keys()) {\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : all[0]\n }\n this.query = query\n }\n\n /** `req.once('close')` — abort of the underlying request signal. */\n once(event: string, listener: () => void): this {\n if (event === 'close') this.signal.addEventListener('abort', listener, { once: true })\n return this\n }\n\n /** `req.on('close')` — same bridge; signals only abort once anyway. */\n on(event: string, listener: () => void): this {\n return this.once(event, listener)\n }\n}\n\nconst encoder = new TextEncoder()\n\nfunction toBytes(chunk: unknown): Uint8Array {\n if (chunk instanceof Uint8Array) return chunk\n return encoder.encode(String(chunk))\n}\n\n/**\n * `RuntimeResponse` over a web `Response`.\n *\n * Two modes:\n * - **Buffered** (default): `status/json/send/type/setHeader` record state;\n * the terminal call resolves {@link ready} with a complete `Response`.\n * - **Streaming**: the first `writeHead`/`flushHeaders`/`write` call switches\n * to a `TransformStream` and resolves {@link ready} IMMEDIATELY with a\n * streamed `Response` — SSE works on edge this way; `write` feeds the\n * writer, `end` closes it.\n *\n * A class so the method table lives on a shared prototype (one allocation\n * per request — same rationale as the Fastify/h3 driver classes).\n */\n/** Edge-safe byte length — no `Buffer` on Workers. */\nconst utf8 = new TextEncoder()\n\nexport class WebResponseDriver implements RuntimeResponse {\n /** Resolves with the final (or streamed) Response. */\n readonly ready: Promise<Response>\n /** True once a terminal/streaming action produced the Response. */\n settled = false\n\n private _status = 200\n private readonly headers = new Headers()\n private _headersSent = false\n private writer?: WritableStreamDefaultWriter<Uint8Array>\n private resolveReady!: (response: Response) => void\n\n constructor(private readonly signal?: AbortSignal) {\n this.ready = new Promise<Response>((resolve) => {\n this.resolveReady = resolve\n })\n }\n\n status(code: number): this {\n this._status = code\n return this\n }\n\n json(data: unknown): this {\n if (!this.headers.has('content-type'))\n this.headers.set('content-type', 'application/json; charset=utf-8')\n return this.finish(stringifyJson(data))\n }\n\n send(data: unknown): this {\n if (\n data !== undefined &&\n data !== null &&\n typeof data === 'object' &&\n !(data instanceof Uint8Array)\n ) {\n return this.json(data)\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n type(contentType: string): this {\n this.headers.set('content-type', contentType)\n return this\n }\n\n /** What `setHeader` recorded — `Set-Cookie` as its list, like node's `res.getHeader`. */\n getHeader(name: string): string | string[] | undefined {\n if (name.toLowerCase() === 'set-cookie') {\n const cookies = this.headers.getSetCookie()\n return cookies.length > 0 ? cookies : undefined\n }\n return this.headers.get(name) ?? undefined\n }\n\n setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.headers.delete(name)\n for (const v of value) this.headers.append(name, String(v))\n } else {\n this.headers.set(name, String(value))\n }\n return this\n }\n\n render(): never {\n throw new Error('ctx.render() is not supported on the web runtime (no view engine).')\n }\n\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this._status = statusCode\n if (headers) {\n for (const [name, value] of Object.entries(headers)) this.setHeader(name, value)\n }\n this.startStream()\n return this\n }\n\n flushHeaders(): this {\n this.startStream()\n return this\n }\n\n write(chunk: unknown): boolean {\n this.startStream()\n // Fire-and-forget: backpressure is absorbed by the stream's queue. Write\n // failures (client gone) surface via the abort listener, not here.\n void this.writer!.write(toBytes(chunk)).catch(() => {})\n return true\n }\n\n end(data?: unknown): this {\n if (this.writer) {\n if (data !== undefined) this.write(data)\n void this.writer.close().catch(() => {})\n this.writer = undefined\n return this\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n once(event: string, listener: (...args: unknown[]) => void): this {\n if (event === 'close' && this.signal)\n this.signal.addEventListener('abort', listener as () => void, { once: true })\n return this\n }\n\n get headersSent(): boolean {\n return this._headersSent\n }\n\n /** Buffered terminal: build the final Response exactly once. */\n private finish(body?: string | Uint8Array | null): this {\n if (this.settled) return this\n this.settled = true\n this._headersSent = true\n // 204/304 must not carry a body per the Response constructor contract.\n const bodyAllowed = this._status !== 204 && this._status !== 304\n // A buffered body has a known length: say so, as the node runtimes do —\n // no chunked encoding for a small reply, and middleware that decides by\n // size (compression's threshold) can see it.\n if (bodyAllowed && body != null && !this.headers.has('content-length')) {\n const length = typeof body === 'string' ? utf8.encode(body).byteLength : body.byteLength\n this.headers.set('content-length', String(length))\n }\n this.resolveReady(\n new Response(bodyAllowed ? (body ?? null) : null, {\n status: this._status,\n headers: this.headers,\n }),\n )\n return this\n }\n\n /** Switch to streaming mode and resolve `ready` with the streamed Response. */\n private startStream(): void {\n if (this.writer || this.settled) return\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n this.writer = writable.getWriter()\n this.settled = true\n this._headersSent = true\n // Abort from the client tears the stream down so the writer stops queueing.\n this.signal?.addEventListener(\n 'abort',\n () => {\n void this.writer?.abort().catch(() => {})\n this.writer = undefined\n },\n { once: true },\n )\n this.resolveReady(new Response(readable, { status: this._status, headers: this.headers }))\n }\n}\n","// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport {\n DEFAULT_BODY_LIMIT,\n classifyMediaType,\n parseByteSize,\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n readBodyBytes,\n readBodyText,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport {\n applyUploadConfig,\n tooManyFiles,\n uploadLimits,\n type RawUploadPart,\n} from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n /**\n * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n// The same handlers Express and Fastify answer with, so an error or a request\n// nothing answered has one shape on every engine: RFC 9457 problem details,\n// the error's own headers, `requestId` on a 500.\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\n\nfunction decodeParams(params: Record<string, string>): Record<string, string> {\n const decoded: Record<string, string> = {}\n for (const key in params) {\n const value = params[key]\n decoded[key] = value.includes('%') ? decodeURIComponent(value) : value\n }\n return decoded\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n options: { bodyLimit?: number } = {},\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const bodyLimit = options.bodyLimit ?? parseByteSize(DEFAULT_BODY_LIMIT)\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n let bodyError: unknown\n // h3 hands params over still percent-encoded; Express and Fastify decode\n // them, so `/users/a%20b` must reach the handler as `'a b'` here too.\n try {\n req.params = decodeParams(params)\n } catch {\n req.params = params\n bodyError = HttpException.badRequest('Malformed URL parameter')\n }\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n // Bounded before anything is parsed: the route's file budget plus room\n // for fields. Past it is a 413, held like a parse failure below.\n const limits = uploadLimits(upload)\n let form: FormData | undefined\n try {\n const bytes = await readBodyBytes(request, limits.total)\n const type = request.headers.get('content-type') ?? ''\n form = await new Response(bytes as unknown as ConstructorParameters<typeof Response>[0], {\n headers: { 'content-type': type },\n })\n .formData()\n .catch(() => undefined)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields.push([name, value])\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n req.body = formFields(fields)\n // A refused type (415), an oversized file or too many (413) is held like\n // a parse failure — thrown before the driver exists, it would escape the\n // route and reach the client as the host's bare error, not kick's.\n if (rawParts.length > limits.files) {\n bodyError = tooManyFiles(limits.files)\n } else {\n try {\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n } catch (err) {\n bodyError = err\n }\n }\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n // Past the limit is a 413, held like a parse failure below.\n let raw = ''\n try {\n raw = await readBodyText(request, bodyLimit)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = parseForm(raw)\n } else {\n req.body = raw\n }\n }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (!bodyError && hasPrototypeKey(req.body)) bodyError = prototypeKeyError()\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId || req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) await applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n // Inside the request's store: an error page renders with the same\n // context and REQUEST-scoped services the route had.\n if (!driver.settled) {\n await requestStore.run(store, async () => {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n })\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — the catch-all's 404.\n builtInNotFound(req, driver, NOOP_NEXT)\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n\n/**\n * HEAD for a GET route: run the route and answer with its status and\n * headers, without the body — what Express and Fastify do for every GET.\n */\nexport async function headFromGet(response: Promise<Response> | Response): Promise<Response> {\n const res = await response\n // A streamed GET (SSE) would otherwise keep producing for nobody.\n res.body?.cancel().catch(() => {})\n return new Response(null, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n })\n}\n"],"mappings":";;;;;;;;;;2yBAgBA,IAAa,eAAb,KAA4B,CAC1B,OACA,IAEA,QACA,KACA,OAAiC,CAAC,EAClC,MAAiC,CAAC,EAClC,UACA,KACA,MAKA,OAEA,YAAY,QAAkB,IAAU,CACtC,KAAK,OAAS,QAAQ,OAEtB,KAAK,IAAM,IAAI,SAAW,IAAI,OAC9B,KAAK,OAAS,QAAQ,OACtB,IAAM,QAAkC,CAAC,EACzC,QAAQ,QAAQ,SAAS,MAAO,MAAQ,CACtC,QAAQ,KAAO,KACjB,CAAC,EACD,KAAK,QAAU,QACf,IAAM,MAAiC,CAAC,EACxC,IAAK,IAAM,OAAO,IAAI,aAAa,KAAK,EAAG,CACzC,IAAM,IAAM,IAAI,aAAa,OAAO,GAAG,EACvC,MAAM,KAAO,IAAI,OAAS,EAAI,IAAM,IAAI,EAC1C,CACA,KAAK,MAAQ,KACf,CAGA,KAAK,MAAe,SAA4B,CAE9C,OADI,QAAU,SAAS,KAAK,OAAO,iBAAiB,QAAS,SAAU,CAAE,KAAM,EAAK,CAAC,EAC9E,IACT,CAGA,GAAG,MAAe,SAA4B,CAC5C,OAAO,KAAK,KAAK,MAAO,QAAQ,CAClC,CACF,EAEA,MAAM,QAAU,IAAI,YAEpB,SAAS,QAAQ,MAA4B,CAE3C,OADI,iBAAiB,WAAmB,MACjC,QAAQ,OAAO,OAAO,KAAK,CAAC,CACrC,CAiBA,MAAM,KAAO,IAAI,YAEjB,IAAa,kBAAb,KAA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