@forinda/kickjs 10.13.1 → 10.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/application-1Fzmk_Ku.mjs +14 -0
  2. package/dist/application-1Fzmk_Ku.mjs.map +1 -0
  3. package/dist/{application-r0VMb-A5.d.mts → application-DsHdZoZK.d.mts} +4 -3
  4. package/dist/{application-r0VMb-A5.d.mts.map → application-DsHdZoZK.d.mts.map} +1 -1
  5. package/dist/{body-policy-DpzQ1sXo.mjs → body-policy-BQnyy906.mjs} +2 -2
  6. package/dist/{body-policy-DpzQ1sXo.mjs.map → body-policy-BQnyy906.mjs.map} +1 -1
  7. package/dist/{bootstrap-D8U1b1lN.mjs → bootstrap-Ub6N0nVd.mjs} +3 -3
  8. package/dist/{bootstrap-D8U1b1lN.mjs.map → bootstrap-Ub6N0nVd.mjs.map} +1 -1
  9. package/dist/{bounded-counters-W_iZ-6a-.mjs → bounded-counters-BaQwi0aH.mjs} +2 -2
  10. package/dist/{bounded-counters-W_iZ-6a-.mjs.map → bounded-counters-BaQwi0aH.mjs.map} +1 -1
  11. package/dist/{client-ip-B90_tMPE.mjs → client-ip-DwLXnTke.mjs} +2 -2
  12. package/dist/{client-ip-B90_tMPE.mjs.map → client-ip-DwLXnTke.mjs.map} +1 -1
  13. package/dist/config/index.mjs +2 -2
  14. package/dist/{config-CcwnmXAp.mjs → config-Df8GxPDC.mjs} +3 -3
  15. package/dist/{config-CcwnmXAp.mjs.map → config-Df8GxPDC.mjs.map} +1 -1
  16. package/dist/{context-DJh3UImF.mjs → context-ByBa7pR4.mjs} +3 -3
  17. package/dist/{context-DJh3UImF.mjs.map → context-ByBa7pR4.mjs.map} +1 -1
  18. package/dist/{context-errors-Bjmg2Idn.mjs → context-errors-CWTD0Fln.mjs} +2 -2
  19. package/dist/{context-errors-Bjmg2Idn.mjs.map → context-errors-CWTD0Fln.mjs.map} +1 -1
  20. package/dist/{contributor-runner-BDrfpkvN.mjs → contributor-runner-BlYFb9WU.mjs} +3 -3
  21. package/dist/{contributor-runner-BDrfpkvN.mjs.map → contributor-runner-BlYFb9WU.mjs.map} +1 -1
  22. package/dist/core/adapter.mjs +1 -1
  23. package/dist/core/app-module.mjs +1 -1
  24. package/dist/core/cache.mjs +1 -1
  25. package/dist/core/container.mjs +2 -2
  26. package/dist/core/cron.mjs +2 -2
  27. package/dist/core/decorators.mjs +2 -2
  28. package/dist/core/errors.mjs +1 -1
  29. package/dist/core/interfaces.mjs +1 -1
  30. package/dist/core/logger.mjs +1 -1
  31. package/dist/core/path.mjs +1 -1
  32. package/dist/core/plugin.mjs +1 -1
  33. package/dist/core/reactivity.mjs +2 -2
  34. package/dist/{core-fD81or3K.mjs → core-DBoFrkOu.mjs} +3 -3
  35. package/dist/{core-fD81or3K.mjs.map → core-DBoFrkOu.mjs.map} +1 -1
  36. package/dist/{decorate-xqpvUQBu.mjs → decorate-BFKqRpjy.mjs} +3 -3
  37. package/dist/{decorate-xqpvUQBu.mjs.map → decorate-BFKqRpjy.mjs.map} +1 -1
  38. package/dist/{define-adapter-DV0gX0Zc.mjs → define-adapter-C4ATXXqb.mjs} +2 -2
  39. package/dist/{define-adapter-DV0gX0Zc.mjs.map → define-adapter-C4ATXXqb.mjs.map} +1 -1
  40. package/dist/{di-hooks-BCQxqvPP.mjs → di-hooks-CUVLbOER.mjs} +2 -2
  41. package/dist/{di-hooks-BCQxqvPP.mjs.map → di-hooks-CUVLbOER.mjs.map} +1 -1
  42. package/dist/{disposables-CLELPWB2.mjs → disposables-DzxupKRg.mjs} +1 -1
  43. package/dist/{driver-60Ojtg4A.mjs → driver-CQ7sN3vu.mjs} +3 -3
  44. package/dist/{driver-60Ojtg4A.mjs.map → driver-CQ7sN3vu.mjs.map} +1 -1
  45. package/dist/{express-cGEtQgNP.mjs → express-BVQODWsY.mjs} +3 -3
  46. package/dist/{express-cGEtQgNP.mjs.map → express-BVQODWsY.mjs.map} +1 -1
  47. package/dist/{express-lazy-A39r8_jk.mjs → express-lazy-7Ldw2LAF.mjs} +3 -3
  48. package/dist/{express-lazy-A39r8_jk.mjs.map → express-lazy-7Ldw2LAF.mjs.map} +1 -1
  49. package/dist/{handler-BDivc8AT.mjs → handler-CIIBAVAD.mjs} +3 -3
  50. package/dist/{handler-BDivc8AT.mjs.map → handler-CIIBAVAD.mjs.map} +1 -1
  51. package/dist/{host-DTmYT9lX.mjs → host-BDnmvmwu.mjs} +2 -2
  52. package/dist/{host-DTmYT9lX.mjs.map → host-BDnmvmwu.mjs.map} +1 -1
  53. package/dist/http/application.d.mts +1 -1
  54. package/dist/http/application.mjs +2 -2
  55. package/dist/http/bootstrap.d.mts +1 -1
  56. package/dist/http/bootstrap.mjs +2 -2
  57. package/dist/http/context.mjs +2 -2
  58. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  59. package/dist/http/middleware/breach-padding.mjs +1 -1
  60. package/dist/http/middleware/cors.mjs +1 -1
  61. package/dist/http/middleware/csrf.mjs +2 -2
  62. package/dist/http/middleware/error-handler.mjs +2 -2
  63. package/dist/http/middleware/helmet.mjs +1 -1
  64. package/dist/http/middleware/rate-limit.mjs +2 -2
  65. package/dist/http/middleware/request-id.mjs +1 -1
  66. package/dist/http/middleware/request-logger.mjs +2 -2
  67. package/dist/http/middleware/session.mjs +2 -2
  68. package/dist/http/middleware/spa.d.mts +1 -1
  69. package/dist/http/middleware/spa.mjs +2 -2
  70. package/dist/http/middleware/upload.mjs +2 -2
  71. package/dist/http/middleware/validate.mjs +1 -1
  72. package/dist/http/middleware/views.d.mts +1 -1
  73. package/dist/http/middleware/views.mjs +2 -2
  74. package/dist/http/query/index.mjs +2 -2
  75. package/dist/http/router-builder.mjs +2 -2
  76. package/dist/http/runtimes/express.mjs +2 -2
  77. package/dist/http/runtimes/fastify.mjs +2 -2
  78. package/dist/http/runtimes/h3-web.mjs +1 -1
  79. package/dist/http/runtimes/h3.mjs +2 -2
  80. package/dist/index.d.mts +1 -1
  81. package/dist/index.mjs +2 -2
  82. package/dist/{is-production-CC5VwQUr.mjs → is-production-Bmoi-4LP.mjs} +2 -2
  83. package/dist/{is-production-CC5VwQUr.mjs.map → is-production-Bmoi-4LP.mjs.map} +1 -1
  84. package/dist/{jobs-Cv_MxBmp.mjs → jobs-8qPs4uhb.mjs} +3 -3
  85. package/dist/{jobs-Cv_MxBmp.mjs.map → jobs-8qPs4uhb.mjs.map} +1 -1
  86. package/dist/{kv-stores-IqwuxoUl.mjs → kv-stores-u9frHRUO.mjs} +3 -3
  87. package/dist/{kv-stores-IqwuxoUl.mjs.map → kv-stores-u9frHRUO.mjs.map} +1 -1
  88. package/dist/{lazy-serve-static-DA6yo1u9.mjs → lazy-serve-static-C1iV009Y.mjs} +3 -3
  89. package/dist/{lazy-serve-static-DA6yo1u9.mjs.map → lazy-serve-static-C1iV009Y.mjs.map} +1 -1
  90. package/dist/{metadata-BhcNTK8K.mjs → metadata-__BH2A1m.mjs} +1 -1
  91. package/dist/{observers-ZGFBMx7P.mjs → observers-D3m1iUQw.mjs} +2 -2
  92. package/dist/{observers-ZGFBMx7P.mjs.map → observers-D3m1iUQw.mjs.map} +1 -1
  93. package/dist/{precompressed-D03hwjjz.mjs → precompressed-CLMMwxxl.mjs} +2 -2
  94. package/dist/{precompressed-D03hwjjz.mjs.map → precompressed-CLMMwxxl.mjs.map} +1 -1
  95. package/dist/{query-Bs-87jM-.mjs → query-D8Jbrl5C.mjs} +2 -2
  96. package/dist/{query-Bs-87jM-.mjs.map → query-D8Jbrl5C.mjs.map} +1 -1
  97. package/dist/{reply-GgkLk_oe.mjs → reply-Dr88jBEF.mjs} +3 -3
  98. package/dist/{reply-GgkLk_oe.mjs.map → reply-Dr88jBEF.mjs.map} +1 -1
  99. package/dist/{request-scope-mn1b63mA.mjs → request-scope-CN4JvYti.mjs} +3 -3
  100. package/dist/{request-scope-mn1b63mA.mjs.map → request-scope-CN4JvYti.mjs.map} +1 -1
  101. package/dist/{respond-BBYJsJ-G.mjs → respond--wtqY3VK.mjs} +2 -2
  102. package/dist/{respond-BBYJsJ-G.mjs.map → respond--wtqY3VK.mjs.map} +1 -1
  103. package/dist/{rolldown-runtime-C4ng-APQ.mjs → rolldown-runtime-C5JVZt00.mjs} +1 -1
  104. package/dist/{route-flag-DjDiOO3H.mjs → route-flag-qXRvhsbB.mjs} +3 -3
  105. package/dist/{route-flag-DjDiOO3H.mjs.map → route-flag-qXRvhsbB.mjs.map} +1 -1
  106. package/dist/{route-policy-BSaFqylB.mjs → route-policy-Dd12HOZr.mjs} +2 -2
  107. package/dist/{route-policy-BSaFqylB.mjs.map → route-policy-Dd12HOZr.mjs.map} +1 -1
  108. package/dist/{router-builder-BRmu4LTG.mjs → router-builder-DIBhQIki.mjs} +3 -3
  109. package/dist/{router-builder-BRmu4LTG.mjs.map → router-builder-DIBhQIki.mjs.map} +1 -1
  110. package/dist/{runtime-CeZOPbkB.mjs → runtime-pz_XLMOf.mjs} +3 -3
  111. package/dist/{runtime-CeZOPbkB.mjs.map → runtime-pz_XLMOf.mjs.map} +1 -1
  112. package/dist/{settings-DdExbzhu.mjs → settings-DqVmZr-S.mjs} +3 -3
  113. package/dist/{settings-DdExbzhu.mjs.map → settings-DqVmZr-S.mjs.map} +1 -1
  114. package/dist/{token-SjtN7iMS.mjs → token-CbeBj1AB.mjs} +1 -1
  115. package/dist/{upload-config-D8OMmdY7.mjs → upload-config-tyBCdMVF.mjs} +2 -2
  116. package/dist/{upload-config-D8OMmdY7.mjs.map → upload-config-tyBCdMVF.mjs.map} +1 -1
  117. package/dist/{url-for-YPjjzRlH.mjs → url-for-B3mtX1t0.mjs} +3 -3
  118. package/dist/{url-for-YPjjzRlH.mjs.map → url-for-B3mtX1t0.mjs.map} +1 -1
  119. package/dist/{view-renderer-CA8eJU23.mjs → view-renderer-BLYp4qoe.mjs} +3 -3
  120. package/dist/{view-renderer-CA8eJU23.mjs.map → view-renderer-BLYp4qoe.mjs.map} +1 -1
  121. package/dist/{web-crypto-iLWDbH8H.mjs → web-crypto-Up4UvHoI.mjs} +2 -2
  122. package/dist/{web-crypto-iLWDbH8H.mjs.map → web-crypto-Up4UvHoI.mjs.map} +1 -1
  123. package/dist/web.mjs +2 -2
  124. package/package.json +1 -1
  125. package/dist/application-QBVum-rq.mjs +0 -14
  126. package/dist/application-QBVum-rq.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"url-for-YPjjzRlH.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/module-registry.ts","../src/http/url-for.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n\n/**\n * The name a module is labelled with in diagnostics — `describeConfig()`,\n * `.env.example`'s \"declared by\", the contributors table. `defineModule`\n * stamps it as `__moduleName`; a hand-written module may carry `name`; a\n * class module falls back to its class name. Plain objects say `module`, not\n * `Object`.\n */\nexport function moduleName(mod: AppModule): string {\n const { __moduleName, name } = mod as { __moduleName?: unknown; name?: unknown }\n if (typeof __moduleName === 'string' && __moduleName) return __moduleName\n if (typeof name === 'string' && name) return name\n const ctorName = mod.constructor?.name\n return ctorName && ctorName !== 'Object' ? ctorName : 'module'\n}\n","import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n","/**\n * Build a route's URL from its name — `'UsersController.show'` — instead of\n * spelling the path where you link to it, so a moved route can't leave a\n * redirect, a `Location` header or an email link pointing at the old one.\n *\n * @module @forinda/kickjs/http/url-for\n */\n\nimport { createToken } from '../core/token'\n\n/**\n * Route names `kick typegen` knows: `'Controller.method'` → the route's\n * shape. Falls back to `string` before typegen has run.\n */\nexport type RouteName = [keyof KickRoutes.Named] extends [never]\n ? string\n : Extract<keyof KickRoutes.Named, string>\n\ntype ParamsOf<N> = N extends keyof KickRoutes.Named\n ? KickRoutes.Named[N] extends { params: infer P }\n ? P\n : Record<string, string | number>\n : Record<string, string | number>\n\n/** Path params in the order the path has them: `['42', 'a']` for `/users/:id/posts/:slug`. */\nexport type PositionalParams = ReadonlyArray<string | number>\n\n/** `params` is optional when the route has none, required otherwise. */\nexport type UrlForArgs<N> =\n Record<string, never> extends ParamsOf<N>\n ? [params?: ParamsOf<N> | PositionalParams, query?: UrlQuery]\n : [params: ParamsOf<N> | PositionalParams, query?: UrlQuery]\n\nexport type UrlQuery = Record<string, string | number | boolean | Array<string | number>>\n\n/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */\nexport interface UrlBuilder {\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string.\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string\n}\n\n/**\n * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,\n * a service building a link:\n *\n * ```ts\n * @Service()\n * class Mailer {\n * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}\n * resetLink(token: string) {\n * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`\n * }\n * }\n * ```\n */\nexport const ROUTE_URLS = createToken<UrlBuilder>('kick/Http/routeUrls')\n// One per process, like every DI binding: the container is process-wide, so\n// with two apps in one process this is the one set up last. `ctx.urlFor()`\n// always uses the app that is serving the request.\n\n/** One app's route name → full path pattern (`/api/v1/users/:id`). */\nexport class RouteUrls implements UrlBuilder {\n private readonly paths = new Map<string, string>()\n\n /** First registration wins — a controller mounted twice keeps its first path. */\n add(name: string, path: string): void {\n if (!this.paths.has(name)) this.paths.set(name, path)\n }\n\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.build(name, params as Record<string, unknown> | PositionalParams | undefined, query)\n }\n\n build(\n name: string,\n params?: Record<string, unknown> | PositionalParams,\n query?: UrlQuery,\n ): string {\n const pattern = this.paths.get(name)\n if (pattern === undefined) {\n throw new Error(`urlFor: no route named '${name}' — expected 'Controller.method'`)\n }\n if (Array.isArray(params)) {\n const list = params as PositionalParams\n // Positional (templates can't write objects): in the order the path has them.\n const keys = [...pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]!)\n if (list.length !== keys.length) {\n throw new Error(\n `urlFor('${name}'): takes ${keys.length} param${keys.length === 1 ? '' : 's'}${keys.length ? ` (${keys.join(', ')})` : ''}, got ${list.length}`,\n )\n }\n }\n // A list fills each placeholder by position, so a repeated name keeps both values.\n let at = 0\n const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = Array.isArray(params)\n ? (params as PositionalParams)[at++]\n : (params as Record<string, unknown> | undefined)?.[key]\n if (value === undefined || value === null || value === '') {\n throw new Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`)\n }\n return encodeURIComponent(String(value))\n })\n if (!query) return path\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n for (const v of Array.isArray(value) ? value : [value]) search.append(key, String(v))\n }\n const qs = search.toString()\n return qs ? `${path}?${qs}` : path\n }\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {\n /** `'Controller.method'` → route shape, written by `kick typegen`. */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Named {}\n }\n}\n"],"mappings":";;;;;;;;;;mDAkEA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA4CxE,SAAgB,aACd,QACgC,CAChC,GAAwB,OAAO,SAAY,WAAvC,QACF,MAAU,UACR,8FAEF,EAEF,GAAI,OAAO,QAAQ,MAAS,UAAY,QAAQ,KAAK,SAAW,EAAG,CACjE,IAAM,IAAM,OAAO,QAAQ,MAAS,SAAW,KAAO,OAAO,QAAQ,KACrE,MAAU,UACR,8DAA8D,IAAI,0IAGpE,CACF,CACA,GAAI,OAAO,QAAQ,OAAU,WAC3B,MAAU,UACR,gBAAgB,QAAQ,KAAK,2DACnB,OAAO,QAAQ,MAAM,6HAEjC,EAGF,IAAM,WACJ,aACA,OACA,YACuB,CACvB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAYlE,OANA,OAAO,eAAe,MAAO,eAAgB,CAC3C,MAAO,aACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACM,KACT,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GAYvC,MAVA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,OAAO,eAAe,QAAS,aAAc,CAC3C,MAAO,OAAO,OAAO,CAAE,GAAG,OAAQ,CAAC,EACnC,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EAEM,OACT,CASA,SAAgB,WAAW,IAAwB,CACjD,GAAM,CAAE,aAAc,MAAS,IAC/B,GAAI,OAAO,cAAiB,UAAY,aAAc,OAAO,aAC7D,GAAI,OAAO,MAAS,UAAY,KAAM,OAAO,KAC7C,IAAM,SAAW,IAAI,aAAa,KAClC,OAAO,UAAY,WAAa,SAAW,SAAW,QACxD,CC1IA,IAAa,sBAAb,KAA6D,CAC3D,QAAqC,CAAC,EAEtC,MAAM,OAA8B,CAClC,KAAK,QAAQ,KAAK,MAAM,CAC1B,CACF,ECJA,MAAa,WAAa,YAAwB,qBAAqB,EAMvE,IAAa,UAAb,KAA6C,CAC3C,sBAAyB,IAAI,IAG7B,IAAI,KAAc,KAAoB,CAC/B,KAAK,MAAM,IAAI,IAAI,GAAG,KAAK,MAAM,IAAI,KAAM,IAAI,CACtD,CAEA,OAA4B,KAAS,GAAG,KAA6B,CACnE,GAAM,CAAC,OAAQ,OAAS,KACxB,OAAO,KAAK,MAAM,KAAM,OAAkE,KAAK,CACjG,CAEA,MACE,KACA,OACA,MACQ,CACR,IAAM,QAAU,KAAK,MAAM,IAAI,IAAI,EACnC,GAAI,UAAY,IAAA,GACd,MAAU,MAAM,2BAA2B,KAAK,iCAAiC,EAEnF,GAAI,MAAM,QAAQ,MAAM,EAAG,CACzB,IAAM,KAAO,OAEP,KAAO,CAAC,GAAG,QAAQ,SAAS,mBAAmB,CAAC,CAAC,CAAC,IAAK,GAAM,EAAE,EAAG,EACxE,GAAI,KAAK,SAAW,KAAK,OACvB,MAAU,MACR,WAAW,KAAK,YAAY,KAAK,OAAO,QAAQ,KAAK,SAAW,EAAI,GAAK,MAAM,KAAK,OAAS,KAAK,KAAK,KAAK,IAAI,EAAE,GAAK,GAAG,QAAQ,KAAK,QACzI,CAEJ,CAEA,IAAI,GAAK,EACH,KAAO,QAAQ,QAAQ,qBAAsB,EAAG,MAAgB,CACpE,IAAM,MAAQ,MAAM,QAAQ,MAAM,EAC7B,OAA4B,MAC5B,SAAiD,KACtD,GAAI,OAAiC,MAAQ,QAAU,GACrD,MAAU,MAAM,WAAW,KAAK,qBAAqB,IAAI,SAAS,QAAQ,EAAE,EAE9E,OAAO,mBAAmB,OAAO,KAAK,CAAC,CACzC,CAAC,EACD,GAAI,CAAC,MAAO,OAAO,KACnB,IAAM,OAAS,IAAI,gBACnB,IAAK,GAAM,CAAC,IAAK,SAAU,OAAO,QAAQ,KAAK,EAC7C,IAAK,IAAM,KAAK,MAAM,QAAQ,KAAK,EAAI,MAAQ,CAAC,KAAK,EAAG,OAAO,OAAO,IAAK,OAAO,CAAC,CAAC,EAEtF,IAAM,GAAK,OAAO,SAAS,EAC3B,OAAO,GAAK,GAAG,KAAK,GAAG,KAAO,IAChC,CACF"}
1
+ {"version":3,"file":"url-for-B3mtX1t0.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/module-registry.ts","../src/http/url-for.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n\n/**\n * The name a module is labelled with in diagnostics — `describeConfig()`,\n * `.env.example`'s \"declared by\", the contributors table. `defineModule`\n * stamps it as `__moduleName`; a hand-written module may carry `name`; a\n * class module falls back to its class name. Plain objects say `module`, not\n * `Object`.\n */\nexport function moduleName(mod: AppModule): string {\n const { __moduleName, name } = mod as { __moduleName?: unknown; name?: unknown }\n if (typeof __moduleName === 'string' && __moduleName) return __moduleName\n if (typeof name === 'string' && name) return name\n const ctorName = mod.constructor?.name\n return ctorName && ctorName !== 'Object' ? ctorName : 'module'\n}\n","import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n","/**\n * Build a route's URL from its name — `'UsersController.show'` — instead of\n * spelling the path where you link to it, so a moved route can't leave a\n * redirect, a `Location` header or an email link pointing at the old one.\n *\n * @module @forinda/kickjs/http/url-for\n */\n\nimport { createToken } from '../core/token'\n\n/**\n * Route names `kick typegen` knows: `'Controller.method'` → the route's\n * shape. Falls back to `string` before typegen has run.\n */\nexport type RouteName = [keyof KickRoutes.Named] extends [never]\n ? string\n : Extract<keyof KickRoutes.Named, string>\n\ntype ParamsOf<N> = N extends keyof KickRoutes.Named\n ? KickRoutes.Named[N] extends { params: infer P }\n ? P\n : Record<string, string | number>\n : Record<string, string | number>\n\n/** Path params in the order the path has them: `['42', 'a']` for `/users/:id/posts/:slug`. */\nexport type PositionalParams = ReadonlyArray<string | number>\n\n/** `params` is optional when the route has none, required otherwise. */\nexport type UrlForArgs<N> =\n Record<string, never> extends ParamsOf<N>\n ? [params?: ParamsOf<N> | PositionalParams, query?: UrlQuery]\n : [params: ParamsOf<N> | PositionalParams, query?: UrlQuery]\n\nexport type UrlQuery = Record<string, string | number | boolean | Array<string | number>>\n\n/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */\nexport interface UrlBuilder {\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string.\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string\n}\n\n/**\n * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,\n * a service building a link:\n *\n * ```ts\n * @Service()\n * class Mailer {\n * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}\n * resetLink(token: string) {\n * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`\n * }\n * }\n * ```\n */\nexport const ROUTE_URLS = createToken<UrlBuilder>('kick/Http/routeUrls')\n// One per process, like every DI binding: the container is process-wide, so\n// with two apps in one process this is the one set up last. `ctx.urlFor()`\n// always uses the app that is serving the request.\n\n/** One app's route name → full path pattern (`/api/v1/users/:id`). */\nexport class RouteUrls implements UrlBuilder {\n private readonly paths = new Map<string, string>()\n\n /** First registration wins — a controller mounted twice keeps its first path. */\n add(name: string, path: string): void {\n if (!this.paths.has(name)) this.paths.set(name, path)\n }\n\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.build(name, params as Record<string, unknown> | PositionalParams | undefined, query)\n }\n\n build(\n name: string,\n params?: Record<string, unknown> | PositionalParams,\n query?: UrlQuery,\n ): string {\n const pattern = this.paths.get(name)\n if (pattern === undefined) {\n throw new Error(`urlFor: no route named '${name}' — expected 'Controller.method'`)\n }\n if (Array.isArray(params)) {\n const list = params as PositionalParams\n // Positional (templates can't write objects): in the order the path has them.\n const keys = [...pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]!)\n if (list.length !== keys.length) {\n throw new Error(\n `urlFor('${name}'): takes ${keys.length} param${keys.length === 1 ? '' : 's'}${keys.length ? ` (${keys.join(', ')})` : ''}, got ${list.length}`,\n )\n }\n }\n // A list fills each placeholder by position, so a repeated name keeps both values.\n let at = 0\n const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = Array.isArray(params)\n ? (params as PositionalParams)[at++]\n : (params as Record<string, unknown> | undefined)?.[key]\n if (value === undefined || value === null || value === '') {\n throw new Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`)\n }\n return encodeURIComponent(String(value))\n })\n if (!query) return path\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n for (const v of Array.isArray(value) ? value : [value]) search.append(key, String(v))\n }\n const qs = search.toString()\n return qs ? `${path}?${qs}` : path\n }\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {\n /** `'Controller.method'` → route shape, written by `kick typegen`. */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Named {}\n }\n}\n"],"mappings":";;;;;;;;;;mDAkEA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA4CxE,SAAgB,aACd,QACgC,CAChC,GAAwB,OAAO,SAAY,WAAvC,QACF,MAAU,UACR,8FAEF,EAEF,GAAI,OAAO,QAAQ,MAAS,UAAY,QAAQ,KAAK,SAAW,EAAG,CACjE,IAAM,IAAM,OAAO,QAAQ,MAAS,SAAW,KAAO,OAAO,QAAQ,KACrE,MAAU,UACR,8DAA8D,IAAI,0IAGpE,CACF,CACA,GAAI,OAAO,QAAQ,OAAU,WAC3B,MAAU,UACR,gBAAgB,QAAQ,KAAK,2DACnB,OAAO,QAAQ,MAAM,6HAEjC,EAGF,IAAM,WACJ,aACA,OACA,YACuB,CACvB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAYlE,OANA,OAAO,eAAe,MAAO,eAAgB,CAC3C,MAAO,aACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACM,KACT,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GAYvC,MAVA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,OAAO,eAAe,QAAS,aAAc,CAC3C,MAAO,OAAO,OAAO,CAAE,GAAG,OAAQ,CAAC,EACnC,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EAEM,OACT,CASA,SAAgB,WAAW,IAAwB,CACjD,GAAM,CAAE,aAAc,MAAS,IAC/B,GAAI,OAAO,cAAiB,UAAY,aAAc,OAAO,aAC7D,GAAI,OAAO,MAAS,UAAY,KAAM,OAAO,KAC7C,IAAM,SAAW,IAAI,aAAa,KAClC,OAAO,UAAY,WAAa,SAAW,SAAW,QACxD,CC1IA,IAAa,sBAAb,KAA6D,CAC3D,QAAqC,CAAC,EAEtC,MAAM,OAA8B,CAClC,KAAK,QAAQ,KAAK,MAAM,CAC1B,CACF,ECJA,MAAa,WAAa,YAAwB,qBAAqB,EAMvE,IAAa,UAAb,KAA6C,CAC3C,sBAAyB,IAAI,IAG7B,IAAI,KAAc,KAAoB,CAC/B,KAAK,MAAM,IAAI,IAAI,GAAG,KAAK,MAAM,IAAI,KAAM,IAAI,CACtD,CAEA,OAA4B,KAAS,GAAG,KAA6B,CACnE,GAAM,CAAC,OAAQ,OAAS,KACxB,OAAO,KAAK,MAAM,KAAM,OAAkE,KAAK,CACjG,CAEA,MACE,KACA,OACA,MACQ,CACR,IAAM,QAAU,KAAK,MAAM,IAAI,IAAI,EACnC,GAAI,UAAY,IAAA,GACd,MAAU,MAAM,2BAA2B,KAAK,iCAAiC,EAEnF,GAAI,MAAM,QAAQ,MAAM,EAAG,CACzB,IAAM,KAAO,OAEP,KAAO,CAAC,GAAG,QAAQ,SAAS,mBAAmB,CAAC,CAAC,CAAC,IAAK,GAAM,EAAE,EAAG,EACxE,GAAI,KAAK,SAAW,KAAK,OACvB,MAAU,MACR,WAAW,KAAK,YAAY,KAAK,OAAO,QAAQ,KAAK,SAAW,EAAI,GAAK,MAAM,KAAK,OAAS,KAAK,KAAK,KAAK,IAAI,EAAE,GAAK,GAAG,QAAQ,KAAK,QACzI,CAEJ,CAEA,IAAI,GAAK,EACH,KAAO,QAAQ,QAAQ,qBAAsB,EAAG,MAAgB,CACpE,IAAM,MAAQ,MAAM,QAAQ,MAAM,EAC7B,OAA4B,MAC5B,SAAiD,KACtD,GAAI,OAAiC,MAAQ,QAAU,GACrD,MAAU,MAAM,WAAW,KAAK,qBAAqB,IAAI,SAAS,QAAQ,EAAE,EAE9E,OAAO,mBAAmB,OAAO,KAAK,CAAC,CACzC,CAAC,EACD,GAAI,CAAC,MAAO,OAAO,KACnB,IAAM,OAAS,IAAI,gBACnB,IAAK,GAAM,CAAC,IAAK,SAAU,OAAO,QAAQ,KAAK,EAC7C,IAAK,IAAM,KAAK,MAAM,QAAQ,KAAK,EAAI,MAAQ,CAAC,KAAK,EAAG,OAAO,OAAO,IAAK,OAAO,CAAC,CAAC,EAEtF,IAAM,GAAK,OAAO,SAAS,EAC3B,OAAO,GAAK,GAAG,KAAK,GAAG,KAAO,IAChC,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.13.1
2
+ * @forinda/kickjs v10.13.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-ZGFBMx7P.mjs";import{AsyncLocalStorage}from"node:async_hooks";const requestStore=new AsyncLocalStorage;function getRequestStore(){let store=requestStore.getStore();if(!store)throw Error(`No active request context. REQUEST-scoped services can only be resolved during an HTTP request.`);return store}function getRequestValue(key){return requestStore.getStore()?.values.get(key)}const log=createLogger(`waitUntil`),pending=/* @__PURE__ */ new Set;function waitUntil(promise){let requestId=requestStore.getStore()?.requestId,tracked=Promise.resolve(promise).then(()=>{},err=>{log.error({err,requestId},`Background work passed to waitUntil() failed`),reportError(err,{source:`background`,requestId})});pending.add(tracked),tracked.finally(()=>pending.delete(tracked))}async function settleBackgroundWork(){for(;pending.size>0;)await Promise.all(pending)}function pendingBackgroundWork(){return pending.size}function forwardBackgroundWork(platform){platform?.waitUntil?.(settleBackgroundWork())}const VIEW_RENDERER=Symbol.for(`kickjs.viewRenderer`);function bindViewRenderer(req,renderer){req[VIEW_RENDERER]=renderer}function viewRendererFor(req){return req?.[VIEW_RENDERER]}const PENDING=Symbol(`kickjs.pendingResponse`);function setPendingResponse(ctx,p){ctx[PENDING]=p}function pendingResponse(ctx){return ctx[PENDING]}export{viewRendererFor as a,settleBackgroundWork as c,getRequestValue as d,requestStore as f,setPendingResponse as i,waitUntil as l,bindViewRenderer as n,forwardBackgroundWork as o,pendingResponse as r,pendingBackgroundWork as s,VIEW_RENDERER as t,getRequestStore as u};
12
- //# sourceMappingURL=view-renderer-CA8eJU23.mjs.map
11
+ import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-D3m1iUQw.mjs";import{AsyncLocalStorage}from"node:async_hooks";const requestStore=new AsyncLocalStorage;function getRequestStore(){let store=requestStore.getStore();if(!store)throw Error(`No active request context. REQUEST-scoped services can only be resolved during an HTTP request.`);return store}function getRequestValue(key){return requestStore.getStore()?.values.get(key)}const log=createLogger(`waitUntil`),pending=/* @__PURE__ */ new Set;function waitUntil(promise){let requestId=requestStore.getStore()?.requestId,tracked=Promise.resolve(promise).then(()=>{},err=>{log.error({err,requestId},`Background work passed to waitUntil() failed`),reportError(err,{source:`background`,requestId})});pending.add(tracked),tracked.finally(()=>pending.delete(tracked))}async function settleBackgroundWork(){for(;pending.size>0;)await Promise.all(pending)}function pendingBackgroundWork(){return pending.size}function forwardBackgroundWork(platform){platform?.waitUntil?.(settleBackgroundWork())}const VIEW_RENDERER=Symbol.for(`kickjs.viewRenderer`);function bindViewRenderer(req,renderer){req[VIEW_RENDERER]=renderer}function viewRendererFor(req){return req?.[VIEW_RENDERER]}const PENDING=Symbol(`kickjs.pendingResponse`);function setPendingResponse(ctx,p){ctx[PENDING]=p}function pendingResponse(ctx){return ctx[PENDING]}export{viewRendererFor as a,settleBackgroundWork as c,getRequestValue as d,requestStore as f,setPendingResponse as i,waitUntil as l,bindViewRenderer as n,forwardBackgroundWork as o,pendingResponse as r,pendingBackgroundWork as s,VIEW_RENDERER as t,getRequestStore as u};
12
+ //# sourceMappingURL=view-renderer-BLYp4qoe.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"view-renderer-CA8eJU23.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts","../src/http/view-renderer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n","/**\n * The slot a view engine fills so `ctx.render()` works on every runtime.\n * An adapter binds a renderer onto each request; `ctx.render` asks it first\n * and falls back to the runtime's own engine (Express + ViewAdapter) when it\n * doesn't own the name. `Symbol.for`, so an engine binds it without\n * importing this module.\n */\nimport type { RequestContext } from './context'\n\nexport const VIEW_RENDERER = Symbol.for('kickjs.viewRenderer')\n\nexport interface ViewRenderOptions {\n status?: number\n headers?: Record<string, string>\n /** A layout for this render, or `false` for none — a partial response. */\n layout?: boolean | string\n locale?: string\n timeZone?: string\n}\n\n/** Resolves to the HTML, or to `undefined` when the name isn't this engine's. */\nexport type ViewRenderer = (\n name: string,\n data: Record<string, unknown>,\n opts: ViewRenderOptions,\n ctx: RequestContext,\n) => Promise<string | undefined>\n\nexport function bindViewRenderer(req: object, renderer: ViewRenderer): void {\n ;(req as Record<symbol, unknown>)[VIEW_RENDERER] = renderer\n}\n\nexport function viewRendererFor(req: unknown): ViewRenderer | undefined {\n return (req as Record<symbol, ViewRenderer | undefined> | null)?.[VIEW_RENDERER]\n}\n\nconst PENDING = Symbol('kickjs.pendingResponse')\n\n/** Remember a response still being produced, so the pipeline waits for it. */\nexport function setPendingResponse(ctx: object, p: Promise<void>): void {\n ;(ctx as Record<symbol, unknown>)[PENDING] = p\n}\n\n/** A response `ctx.render()` is still producing, when the handler didn't await it. */\nexport function pendingResponse(ctx: object): Promise<void> | undefined {\n return (ctx as Record<symbol, Promise<void> | undefined>)[PENDING]\n}\n"],"mappings":";;;;;;;;;;mJAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,wBAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,EAAE,UACrC,QAAyB,QAAQ,QAAQ,OAAO,CAAC,CAAC,SAChD,CAAC,EACN,KAAiB,CAChB,IAAI,MAAM,CAAE,IAAK,SAAU,EAAG,8CAA8C,EAC5E,YAAY,IAAK,CAAE,OAAQ,aAAc,SAAU,CAAC,CACtD,CACF,EACA,QAAQ,IAAI,OAAO,EACnB,QAAa,YAAc,QAAQ,OAAO,OAAO,CAAC,CACpD,CAMA,eAAsB,sBAAsC,CAC1D,KAAO,QAAQ,KAAO,GAAG,MAAM,QAAQ,IAAI,OAAO,CACpD,CAGA,SAAgB,uBAAgC,CAC9C,OAAO,QAAQ,IACjB,CAYA,SAAgB,sBAAsB,SAA6C,CACjF,UAAU,YAAY,qBAAqB,CAAC,CAC9C,CCpEA,MAAa,cAAgB,OAAO,IAAI,qBAAqB,EAmB7D,SAAgB,iBAAiB,IAAa,SAA8B,CACzE,IAAiC,eAAiB,QACrD,CAEA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,MAA0D,cACpE,CAEA,MAAM,QAAU,OAAO,wBAAwB,EAG/C,SAAgB,mBAAmB,IAAa,EAAwB,CACrE,IAAiC,SAAW,CAC/C,CAGA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,IAAkD,QAC5D"}
1
+ {"version":3,"file":"view-renderer-BLYp4qoe.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts","../src/http/view-renderer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n","/**\n * The slot a view engine fills so `ctx.render()` works on every runtime.\n * An adapter binds a renderer onto each request; `ctx.render` asks it first\n * and falls back to the runtime's own engine (Express + ViewAdapter) when it\n * doesn't own the name. `Symbol.for`, so an engine binds it without\n * importing this module.\n */\nimport type { RequestContext } from './context'\n\nexport const VIEW_RENDERER = Symbol.for('kickjs.viewRenderer')\n\nexport interface ViewRenderOptions {\n status?: number\n headers?: Record<string, string>\n /** A layout for this render, or `false` for none — a partial response. */\n layout?: boolean | string\n locale?: string\n timeZone?: string\n}\n\n/** Resolves to the HTML, or to `undefined` when the name isn't this engine's. */\nexport type ViewRenderer = (\n name: string,\n data: Record<string, unknown>,\n opts: ViewRenderOptions,\n ctx: RequestContext,\n) => Promise<string | undefined>\n\nexport function bindViewRenderer(req: object, renderer: ViewRenderer): void {\n ;(req as Record<symbol, unknown>)[VIEW_RENDERER] = renderer\n}\n\nexport function viewRendererFor(req: unknown): ViewRenderer | undefined {\n return (req as Record<symbol, ViewRenderer | undefined> | null)?.[VIEW_RENDERER]\n}\n\nconst PENDING = Symbol('kickjs.pendingResponse')\n\n/** Remember a response still being produced, so the pipeline waits for it. */\nexport function setPendingResponse(ctx: object, p: Promise<void>): void {\n ;(ctx as Record<symbol, unknown>)[PENDING] = p\n}\n\n/** A response `ctx.render()` is still producing, when the handler didn't await it. */\nexport function pendingResponse(ctx: object): Promise<void> | undefined {\n return (ctx as Record<symbol, Promise<void> | undefined>)[PENDING]\n}\n"],"mappings":";;;;;;;;;;mJAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,wBAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,EAAE,UACrC,QAAyB,QAAQ,QAAQ,OAAO,CAAC,CAAC,SAChD,CAAC,EACN,KAAiB,CAChB,IAAI,MAAM,CAAE,IAAK,SAAU,EAAG,8CAA8C,EAC5E,YAAY,IAAK,CAAE,OAAQ,aAAc,SAAU,CAAC,CACtD,CACF,EACA,QAAQ,IAAI,OAAO,EACnB,QAAa,YAAc,QAAQ,OAAO,OAAO,CAAC,CACpD,CAMA,eAAsB,sBAAsC,CAC1D,KAAO,QAAQ,KAAO,GAAG,MAAM,QAAQ,IAAI,OAAO,CACpD,CAGA,SAAgB,uBAAgC,CAC9C,OAAO,QAAQ,IACjB,CAYA,SAAgB,sBAAsB,SAA6C,CACjF,UAAU,YAAY,qBAAqB,CAAC,CAC9C,CCpEA,MAAa,cAAgB,OAAO,IAAI,qBAAqB,EAmB7D,SAAgB,iBAAiB,IAAa,SAA8B,CACzE,IAAiC,eAAiB,QACrD,CAEA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,MAA0D,cACpE,CAEA,MAAM,QAAU,OAAO,wBAAwB,EAG/C,SAAgB,mBAAmB,IAAa,EAAwB,CACrE,IAAiC,SAAW,CAC/C,CAGA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,IAAkD,QAC5D"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.13.1
2
+ * @forinda/kickjs v10.13.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  function randomHex(bytes){let buf=crypto.getRandomValues(new Uint8Array(bytes));return Array.from(buf,b=>b.toString(16).padStart(2,`0`)).join(``)}function safeEqual(a,b){let length=Math.max(a.length,b.length),diff=a.length^b.length;for(let i=0;i<length;i++)diff|=a.charCodeAt(i)^b.charCodeAt(i);return diff===0}function matchesBearer(header,secret){return typeof header==`string`&&typeof secret==`string`&&secret.length>0&&safeEqual(header,`Bearer ${secret}`)}export{randomHex as n,safeEqual as r,matchesBearer as t};
12
- //# sourceMappingURL=web-crypto-iLWDbH8H.mjs.map
12
+ //# sourceMappingURL=web-crypto-Up4UvHoI.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-crypto-iLWDbH8H.mjs","names":[],"sources":["../src/core/web-crypto.ts"],"sourcesContent":["/**\n * Web Crypto helpers — portable across node/bun/deno/workers via\n * `globalThis.crypto`. The Web Crypto migration lives here so the request\n * path never imports `node:crypto` (edge-runtime portability).\n */\n\n/** Random hex string — replacement for `randomBytes(n).toString('hex')`. */\nexport function randomHex(bytes: number): string {\n const buf = crypto.getRandomValues(new Uint8Array(bytes))\n return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Constant-time string comparison for secrets and tokens — the portable\n * counterpart of `timingSafeEqual`. Walks the longer input and folds the\n * length difference in, so it doesn't stop at the first wrong character and\n * a guess's contents don't show in the timing. The loop runs over the longer\n * input, so the time can still reveal the expected value's length.\n */\nexport function safeEqual(a: string, b: string): boolean {\n const length = Math.max(a.length, b.length)\n let diff = a.length ^ b.length\n // Past the end, charCodeAt is NaN, which `^` treats as 0.\n for (let i = 0; i < length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/**\n * Constant-time check of an `Authorization: Bearer <secret>` header against a\n * shared secret — a cron trigger, a metrics scrape, a webhook. `false` for a\n * missing or non-string header, and for an empty secret (an unset env var\n * must not let `Authorization: Bearer ` through). Pass\n * `ctx.headers.authorization` as is.\n */\nexport function matchesBearer(header: unknown, secret: string): boolean {\n return (\n typeof header === 'string' &&\n typeof secret === 'string' &&\n secret.length > 0 &&\n safeEqual(header, `Bearer ${secret}`)\n )\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,UAAU,MAAuB,CAC/C,IAAM,IAAM,OAAO,gBAAgB,IAAI,WAAW,KAAK,CAAC,EACxD,OAAO,MAAM,KAAK,IAAM,GAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CACxE,CASA,SAAgB,UAAU,EAAW,EAAoB,CACvD,IAAM,OAAS,KAAK,IAAI,EAAE,OAAQ,EAAE,MAAM,EACtC,KAAO,EAAE,OAAS,EAAE,OAExB,IAAK,IAAI,EAAI,EAAG,EAAI,OAAQ,IAAK,MAAQ,EAAE,WAAW,CAAC,EAAI,EAAE,WAAW,CAAC,EACzE,OAAO,OAAS,CAClB,CASA,SAAgB,cAAc,OAAiB,OAAyB,CACtE,OACE,OAAO,QAAW,UAClB,OAAO,QAAW,UAClB,OAAO,OAAS,GAChB,UAAU,OAAQ,UAAU,QAAQ,CAExC"}
1
+ {"version":3,"file":"web-crypto-Up4UvHoI.mjs","names":[],"sources":["../src/core/web-crypto.ts"],"sourcesContent":["/**\n * Web Crypto helpers — portable across node/bun/deno/workers via\n * `globalThis.crypto`. The Web Crypto migration lives here so the request\n * path never imports `node:crypto` (edge-runtime portability).\n */\n\n/** Random hex string — replacement for `randomBytes(n).toString('hex')`. */\nexport function randomHex(bytes: number): string {\n const buf = crypto.getRandomValues(new Uint8Array(bytes))\n return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Constant-time string comparison for secrets and tokens — the portable\n * counterpart of `timingSafeEqual`. Walks the longer input and folds the\n * length difference in, so it doesn't stop at the first wrong character and\n * a guess's contents don't show in the timing. The loop runs over the longer\n * input, so the time can still reveal the expected value's length.\n */\nexport function safeEqual(a: string, b: string): boolean {\n const length = Math.max(a.length, b.length)\n let diff = a.length ^ b.length\n // Past the end, charCodeAt is NaN, which `^` treats as 0.\n for (let i = 0; i < length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/**\n * Constant-time check of an `Authorization: Bearer <secret>` header against a\n * shared secret — a cron trigger, a metrics scrape, a webhook. `false` for a\n * missing or non-string header, and for an empty secret (an unset env var\n * must not let `Authorization: Bearer ` through). Pass\n * `ctx.headers.authorization` as is.\n */\nexport function matchesBearer(header: unknown, secret: string): boolean {\n return (\n typeof header === 'string' &&\n typeof secret === 'string' &&\n secret.length > 0 &&\n safeEqual(header, `Bearer ${secret}`)\n )\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,UAAU,MAAuB,CAC/C,IAAM,IAAM,OAAO,gBAAgB,IAAI,WAAW,KAAK,CAAC,EACxD,OAAO,MAAM,KAAK,IAAM,GAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CACxE,CASA,SAAgB,UAAU,EAAW,EAAoB,CACvD,IAAM,OAAS,KAAK,IAAI,EAAE,OAAQ,EAAE,MAAM,EACtC,KAAO,EAAE,OAAS,EAAE,OAExB,IAAK,IAAI,EAAI,EAAG,EAAI,OAAQ,IAAK,MAAQ,EAAE,WAAW,CAAC,EAAI,EAAE,WAAW,CAAC,EACzE,OAAO,OAAS,CAClB,CASA,SAAgB,cAAc,OAAiB,OAAyB,CACtE,OACE,OAAO,QAAW,UAClB,OAAO,QAAW,UAClB,OAAO,OAAS,GAChB,UAAU,OAAQ,UAAU,QAAQ,CAExC"}
package/dist/web.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.13.1
2
+ * @forinda/kickjs v10.13.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Container}from"./core/container.mjs";import{a as moduleName,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-YPjjzRlH.mjs";import{runCronJobs}from"./core/cron.mjs";import{d as stampJobContext,l as registerJobContext,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-Cv_MxBmp.mjs";import{buildMountPath}from"./core/path.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-BRmu4LTG.mjs";import{t as matchesBearer}from"./web-crypto-iLWDbH8H.mjs";import{o as parseByteSize}from"./body-policy-DpzQ1sXo.mjs";import{f as requestStore,l as waitUntil,o as forwardBackgroundWork}from"./view-renderer-CA8eJU23.mjs";import{notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as loadSettings}from"./settings-DdExbzhu.mjs";import{a as reply,r as isReply}from"./reply-GgkLk_oe.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-IqwuxoUl.mjs";import{n as WebResponseDriver,t as WebRequestShim}from"./driver-60Ojtg4A.mjs";import{n as headFromGet,t as compileWebRoute}from"./handler-BDivc8AT.mjs";function createWebApp(options){let h3mod=options.h3;if(typeof h3mod?.H3!=`function`)throw Error(`@forinda/kickjs/web: pass the h3 v2 module — \`createWebApp({ h3: await import("h3"), ... })\`. The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.`);let container=Container.getInstance(),routeUrls=new RouteUrls;if(container.registerInstance(ROUTE_URLS,routeUrls),options.env){let env=options.env;Container.setEnvResolver(key=>env[key])}Container.setRequestStoreProvider(()=>requestStore.getStore()??null);let registry=new MutableModuleRegistry;for(let m of options.modules)registry.mount(m);let modules=registry.entries.map(entry=>typeof entry==`function`?new entry:entry),settingsEnv=options.env??(typeof process<`u`?process.env:{});for(let[section,value]of loadSettings([...options.settings??[],...modules.flatMap(mod=>mod.settings?.()??[])],settingsEnv))container.registerInstance(section,value);for(let mod of modules)mod.register?.(container);container.bootstrap();let app=new h3mod.H3,getUrls=[],apiPrefix=options.apiPrefix??`/api`,defaultVersion=options.defaultVersion??1,globalMiddleware=options.middlewares??[],bodyLimit=parseByteSize(options.jsonLimit??`1mb`),globalSources=(options.contributors??[]).map(registration=>({source:`global`,registration,label:`createWebApp`})),seenRoutes=/* @__PURE__ */ new Map,mounted=[];for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));_setExternalContributorSources([...moduleSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){if(!route.controller)throw Error(`@forinda/kickjs/web: module route at '${route.path}' has no controller. Express-style \`router\` mounts are not supported on the web entry.`);let version=route.version??defaultVersion,mountPath=buildMountPath(route.prefix===!1?``:apiPrefix,version,route.path);for(let entry of buildRouteTable(route.controller,{mountFlags:route.flags})){let url=joinPath(mountPath,entry.path),owner=`${route.controller.name??`controller`}.${String(entry.meta.handlerName??`?`)}`;assertRouteUnique(seenRoutes,entry.method,url,owner),mounted.push({method:entry.method,path:url}),globalMiddleware.length>0&&(entry.middlewares=[...globalMiddleware,...entry.middlewares]),entry.validationError=options.validationError,entry.urls=routeUrls,routeUrls.add(owner,url);let run=compileWebRoute(entry,void 0,{bodyLimit}),handler=event=>run({request:event.req,url:event.url,params:event.context.params??{}});app.on(entry.method,url,handler),entry.method===`GET`&&getUrls.push({url,handler})}}}finally{_setExternalContributorSources([])}}for(let{url,handler}of getUrls)app.on(`HEAD`,url,event=>headFromGet(handler(event)));let notFound=notFoundHandler(mounted);return app.all(`/**`,event=>{let driver=new WebResponseDriver(event.req.signal);return notFound(new WebRequestShim(event.req,event.url),driver,()=>{}),driver.ready}),{fetch:async(request,platform)=>{let response=await app.fetch(request);return forwardBackgroundWork(platform),response},h3:app}}function createFetchHandler(build){let app;return{fetch:(request,env={},ctx)=>(app??=createWebApp(build(env)),app.fetch(request,ctx)),scheduled:async(event,env={},ctx)=>{app??=createWebApp(build(env));let run=runCronJobs(Container.getInstance(),{expression:event.cron},`workers`).then(()=>{});ctx?.waitUntil?.(run),await run},queue:async(batch,env={})=>{app??=createWebApp(build(env));let container=Container.getInstance();await Promise.all(batch.messages.map(async message=>{let body=message.body,named=typeof body==`object`&&!!body&&typeof body.name==`string`;try{await runJob(container,batch.queue,{name:named?body.name:``,data:named?body.data:message.body,id:message.id}),message.ack()}catch{message.retry()}}))}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{JOB_CONTEXT_FIELD,KvRateLimitStore,KvSessionStore,WebRequestShim,WebResponseDriver,compileWebRoute,createFetchHandler,createWebApp,isReply,matchesBearer,rateLimitGuard,registerJobContext,reply,runCronJobs,runJob,stampJobContext,waitUntil};
11
+ import{Container}from"./core/container.mjs";import{a as moduleName,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-B3mtX1t0.mjs";import{runCronJobs}from"./core/cron.mjs";import{d as stampJobContext,l as registerJobContext,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-8qPs4uhb.mjs";import{buildMountPath}from"./core/path.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-DIBhQIki.mjs";import{t as matchesBearer}from"./web-crypto-Up4UvHoI.mjs";import{o as parseByteSize}from"./body-policy-BQnyy906.mjs";import{f as requestStore,l as waitUntil,o as forwardBackgroundWork}from"./view-renderer-BLYp4qoe.mjs";import{notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as loadSettings}from"./settings-DqVmZr-S.mjs";import{a as reply,r as isReply}from"./reply-Dr88jBEF.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-u9frHRUO.mjs";import{n as WebResponseDriver,t as WebRequestShim}from"./driver-CQ7sN3vu.mjs";import{n as headFromGet,t as compileWebRoute}from"./handler-CIIBAVAD.mjs";function createWebApp(options){let h3mod=options.h3;if(typeof h3mod?.H3!=`function`)throw Error(`@forinda/kickjs/web: pass the h3 v2 module — \`createWebApp({ h3: await import("h3"), ... })\`. The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.`);let container=Container.getInstance(),routeUrls=new RouteUrls;if(container.registerInstance(ROUTE_URLS,routeUrls),options.env){let env=options.env;Container.setEnvResolver(key=>env[key])}Container.setRequestStoreProvider(()=>requestStore.getStore()??null);let registry=new MutableModuleRegistry;for(let m of options.modules)registry.mount(m);let modules=registry.entries.map(entry=>typeof entry==`function`?new entry:entry),settingsEnv=options.env??(typeof process<`u`?process.env:{});for(let[section,value]of loadSettings([...options.settings??[],...modules.flatMap(mod=>mod.settings?.()??[])],settingsEnv))container.registerInstance(section,value);for(let mod of modules)mod.register?.(container);container.bootstrap();let app=new h3mod.H3,getUrls=[],apiPrefix=options.apiPrefix??`/api`,defaultVersion=options.defaultVersion??1,globalMiddleware=options.middlewares??[],bodyLimit=parseByteSize(options.jsonLimit??`1mb`),globalSources=(options.contributors??[]).map(registration=>({source:`global`,registration,label:`createWebApp`})),seenRoutes=/* @__PURE__ */ new Map,mounted=[];for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));_setExternalContributorSources([...moduleSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){if(!route.controller)throw Error(`@forinda/kickjs/web: module route at '${route.path}' has no controller. Express-style \`router\` mounts are not supported on the web entry.`);let version=route.version??defaultVersion,mountPath=buildMountPath(route.prefix===!1?``:apiPrefix,version,route.path);for(let entry of buildRouteTable(route.controller,{mountFlags:route.flags})){let url=joinPath(mountPath,entry.path),owner=`${route.controller.name??`controller`}.${String(entry.meta.handlerName??`?`)}`;assertRouteUnique(seenRoutes,entry.method,url,owner),mounted.push({method:entry.method,path:url}),globalMiddleware.length>0&&(entry.middlewares=[...globalMiddleware,...entry.middlewares]),entry.validationError=options.validationError,entry.urls=routeUrls,routeUrls.add(owner,url);let run=compileWebRoute(entry,void 0,{bodyLimit}),handler=event=>run({request:event.req,url:event.url,params:event.context.params??{}});app.on(entry.method,url,handler),entry.method===`GET`&&getUrls.push({url,handler})}}}finally{_setExternalContributorSources([])}}for(let{url,handler}of getUrls)app.on(`HEAD`,url,event=>headFromGet(handler(event)));let notFound=notFoundHandler(mounted);return app.all(`/**`,event=>{let driver=new WebResponseDriver(event.req.signal);return notFound(new WebRequestShim(event.req,event.url),driver,()=>{}),driver.ready}),{fetch:async(request,platform)=>{let response=await app.fetch(request);return forwardBackgroundWork(platform),response},h3:app}}function createFetchHandler(build){let app;return{fetch:(request,env={},ctx)=>(app??=createWebApp(build(env)),app.fetch(request,ctx)),scheduled:async(event,env={},ctx)=>{app??=createWebApp(build(env));let run=runCronJobs(Container.getInstance(),{expression:event.cron},`workers`).then(()=>{});ctx?.waitUntil?.(run),await run},queue:async(batch,env={})=>{app??=createWebApp(build(env));let container=Container.getInstance();await Promise.all(batch.messages.map(async message=>{let body=message.body,named=typeof body==`object`&&!!body&&typeof body.name==`string`;try{await runJob(container,batch.queue,{name:named?body.name:``,data:named?body.data:message.body,id:message.id}),message.ack()}catch{message.retry()}}))}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{JOB_CONTEXT_FIELD,KvRateLimitStore,KvSessionStore,WebRequestShim,WebResponseDriver,compileWebRoute,createFetchHandler,createWebApp,isReply,matchesBearer,rateLimitGuard,registerJobContext,reply,runCronJobs,runJob,stampJobContext,waitUntil};
12
12
  //# sourceMappingURL=web.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs",
3
- "version": "10.13.1",
3
+ "version": "10.13.2",
4
4
  "description": "Modern type-safe backend framework, powered by Vite. Built for developer experience, pluggable as you need — runs on Express, Fastify or h3.",
5
5
  "keywords": [
6
6
  "kickjs",
@@ -1,14 +0,0 @@
1
- /**
2
- * @forinda/kickjs v10.13.1
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{a as tlsCredentialsError,i as moduleRouteMissingControllerError,n as http2RequiresTlsError,r as http2UnsupportedRuntimeError}from"./di-hooks-BCQxqvPP.mjs";import{METADATA}from"./core/interfaces.mjs";import{Logger,createLogger}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{n as createToken}from"./token-SjtN7iMS.mjs";import{t as getClassMeta}from"./metadata-BhcNTK8K.mjs";import{Controller,Get}from"./core/decorators.mjs";import{a as moduleName,i as defineModule,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-YPjjzRlH.mjs";import{a as setObserverPublisher,i as reportResponse,n as releaseObservers,o as setObservers,r as reportError,t as hasResponseObservers}from"./observers-ZGFBMx7P.mjs";import{runCronJobs}from"./core/cron.mjs";import{i as runDisposables,n as drainDisposables,r as registerDisposable,t as disposeAll}from"./disposables-CLELPWB2.mjs";import{HttpException}from"./core/errors.mjs";import{buildMountPath,joinPaths}from"./core/path.mjs";import{computed,ref}from"./core/reactivity.mjs";import{t as ROUTE_SLOT}from"./route-flag-DjDiOO3H.mjs";import"./core-fD81or3K.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-BRmu4LTG.mjs";import{t as isProduction}from"./is-production-CC5VwQUr.mjs";import{r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-BSaFqylB.mjs";import{t as matchesBearer}from"./web-crypto-iLWDbH8H.mjs";import{o as parseByteSize}from"./body-policy-DpzQ1sXo.mjs";import{requestId}from"./http/middleware/request-id.mjs";import{c as settleBackgroundWork,f as requestStore,s as pendingBackgroundWork}from"./view-renderer-CA8eJU23.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware,r as isRequestScopeMiddleware}from"./request-scope-mn1b63mA.mjs";import{a as originsOf,i as loadSettings}from"./settings-DdExbzhu.mjs";import{i as describeEnvSchema,t as __decorate}from"./decorate-xqpvUQBu.mjs";import{a as reply}from"./reply-GgkLk_oe.mjs";import{i as expressRuntime,o as settleExpressLoad,r as expressBodyParsers}from"./express-lazy-A39r8_jk.mjs";import{createRequire}from"node:module";import{join}from"node:path";import http from"node:http";import https from"node:https";import http2 from"node:http2";import tls from"node:tls";import diagnostics from"node:diagnostics_channel";import{randomBytes}from"node:crypto";var DuplicateMountNameError=class extends Error{kind;mountName;constructor(kind,mountName){super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`),this.name=`DuplicateMountNameError`,this.kind=kind,this.mountName=mountName}},MissingMountDepError=class extends Error{kind;missing;dependent;constructor(kind,missing,dependent){super(`Missing ${kind} dependency '${missing}' required by '${dependent}' — is the ${kind} installed and named correctly?`),this.name=`MissingMountDepError`,this.kind=kind,this.missing=missing,this.dependent=dependent}},MountCycleError=class extends Error{kind;cycle;constructor(kind,cycle){super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(` → `)}`),this.name=`MountCycleError`,this.kind=kind,this.cycle=Object.freeze([...cycle])}};function mountSort(items,kind){let byName=/* @__PURE__ */ new Map;for(let item of items){if(byName.has(item.name))throw new DuplicateMountNameError(kind,item.name);byName.set(item.name,item)}let indegree=/* @__PURE__ */ new Map,dependents=/* @__PURE__ */ new Map;for(let item of items)indegree.set(item.name,item.dependsOn?.length??0);for(let item of items)for(let dep of item.dependsOn??[]){if(!byName.has(dep))throw new MissingMountDepError(kind,dep,item.name);let list=dependents.get(dep)??[];list.push(item),dependents.set(dep,list)}let queue=[];for(let item of items)indegree.get(item.name)===0&&queue.push(item);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.name)??[]){let next=(indegree.get(dependent.name)??0)-1;indegree.set(dependent.name,next),next===0&&queue.push(dependent)}}if(sorted.length!==items.length)throw new MountCycleError(kind,reconstructCycle(items.filter(it=>(indegree.get(it.name)??0)>0),byName));return sorted}function reconstructCycle(residual,byName){let residualNames=new Set(residual.map(r=>r.name)),start=residual[0].name,path=[start],seen=/* @__PURE__ */ new Set([start]),cursor=start;for(;;){let nextDep=byName.get(cursor).dependsOn?.find(d=>residualNames.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}const HANDLER_CHANNEL=`kickjs:handler`,ERROR_CHANNEL=`kickjs:error`,RESPONSE_CHANNEL=`kickjs:response`,handlerChannel=diagnostics.tracingChannel(HANDLER_CHANNEL),errorChannel=diagnostics.channel(ERROR_CHANNEL),responseChannel=diagnostics.channel(RESPONSE_CHANNEL);function installChannelPublisher(){setObserverPublisher({name:`diagnostics_channel`,onError(error,info){errorChannel.hasSubscribers&&errorChannel.publish({error,...info})},onResponse(info){responseChannel.hasSubscribers&&responseChannel.publish(info)}},()=>responseChannel.hasSubscribers)}function traceHandler(handler,meta){return ctx=>handlerChannel.hasSubscribers?handlerChannel.tracePromise(async()=>handler(ctx),{...meta,requestId:ctx.requestId,ctx}):handler(ctx)}const round=ms=>Math.round(ms*10)/10;var StartupTimeline=class{began=performance.now();last=this.began;steps=[];completedAt;mark(name){let now=performance.now();this.steps.push({name,ms:round(now-this.last)}),this.last=now}async time(name,run){let started=performance.now(),before=this.last;try{return await run()}finally{let now=performance.now();this.steps.push({name,ms:round(now-started)}),this.last=now-(started-before)}}complete(){this.completedAt??=performance.now()}snapshot(){let end=this.completedAt??performance.now();return{totalMs:round(end-this.began),steps:[...this.steps]}}slowest(count){return this.steps.toSorted((a,b)=>b.ms-a.ms).slice(0,count)}};function onEnv(name,value){return()=>{let actual=process.env[name];return value===void 0?actual?!0:`${name} is not set`:actual===value?!0:actual===void 0?`${name} is not set`:`${name} is not '${value}'`}}function onPackage(name){return()=>{let bases=[process.argv[1],join(process.cwd(),`package.json`)].filter(base=>typeof base==`string`&&base.length>0);for(let base of bases)try{return createRequire(base).resolve(name),!0}catch{}return`package '${name}' is not installed`}}function allOf(...conditions){return()=>{for(let condition of conditions){let result=condition();if(result!==!0)return result}return!0}}function evaluateCondition(condition,onError){try{let result=condition();return result===!0?!0:typeof result==`string`&&result.length>0?result:`its condition returned false`}catch(err){return onError?.(err),`its condition threw (see the server log)`}}function findCode(err,codes,depth=0){if(!err||typeof err!=`object`||depth>5)return;let e=err;if(typeof e.code==`string`&&codes.includes(e.code))return e;for(let inner of[e.cause,...Array.isArray(e.errors)?e.errors:[]]){let found=findCode(inner,codes,depth+1);if(found)return found}}function findMessage(err,pattern,depth=0){if(!err||typeof err!=`object`||depth>5)return!1;let e=err;return typeof e.message==`string`&&pattern.test(e.message)?!0:[e.cause,...Array.isArray(e.errors)?e.errors:[]].some(inner=>findMessage(inner,pattern,depth+1))}const CREDENTIALS_REJECTED=/password authentication failed|access denied for user|authentication failed|NOAUTH|WRONGPASS/i,target=e=>typeof e.address==`string`?`${e.address}${typeof e.port==`number`?`:${e.port}`:``}`:typeof e.hostname==`string`?e.hostname:`the service`;function builtInAdvice(err,where){let refused=findCode(err,[`ECONNREFUSED`]);if(refused)return{summary:`${where} could not connect to ${target(refused)}: connection refused`,cause:`Nothing is listening at that address — the service is down, not started yet, or the URL points at the wrong host or port.`,fix:`Start the service, or check the connection URL in your env (localhost inside a container is the container itself).`};let dns=findCode(err,[`ENOTFOUND`,`EAI_AGAIN`]);if(dns)return{summary:`${where} could not resolve the host ${target(dns)}`,cause:`The host name in the connection URL does not resolve from here.`,fix:`Check the host name in your env — a typo, or a name that only resolves inside another network (a compose service name used from the host).`};let timeout=findCode(err,[`ETIMEDOUT`,`ECONNRESET`]);if(timeout)return{summary:`${where} lost the connection to ${target(timeout)} (${String(timeout.code)})`,cause:`The address answered slowly or not at all — a firewall, a security group, or the wrong network.`,fix:`Check that this machine is allowed to reach the service, and that TLS and port settings match it.`};if(findMessage(err,CREDENTIALS_REJECTED))return{summary:`${where} was refused: the credentials were not accepted`,cause:`The server rejected the user name or password.`,fix:`Check the user and password in your connection URL or env, and that the user exists on this server.`}}function formatAdvice(advice){return[advice.summary,...advice.cause?[``,` Cause: ${advice.cause}`]:[],``,` Fix: ${advice.fix}`].join(`
12
- `)}const log$1=createLogger(`Checks`);function defineCheck(check){return check}var StartupCheckError=class extends Error{messages;constructor(messages){super(`Startup checks failed:\n${messages.map(m=>` ${m.id}: ${m.message}${m.fix?`\n fix: ${m.fix}`:``}`).join(`
13
- `)}`),this.messages=messages,this.name=`StartupCheckError`}};const builtInChecks=[defineCheck({name:`allowed hosts`,deploy:!0,run:({options})=>{let configured=options.security?.allowedHosts,hosts=Array.isArray(configured)?configured:configured?.hosts;if(!(Array.isArray(hosts)&&hosts.length>0&&!hosts.includes(`*`)))return{id:`KICK-SEC-W001`,level:`warning`,message:"No allowed hosts in production (or `*`): any Host header is accepted, and absolute URLs built from it (reset links, redirects) can point anywhere.",fix:`bootstrap({ security: { allowedHosts: ['example.com'] } })`}}}),defineCheck({name:`trust proxy`,deploy:!0,run:({options})=>{if(options.trustProxy===!0)return{id:`KICK-SEC-W002`,level:`warning`,message:"`trustProxy: true` trusts every X-Forwarded-For hop, so a client that reaches the app directly can set its own IP (rate limits, logs, ctx.ip).",fix:"Trust the number of proxies in front of the app instead, e.g. `trustProxy: 1`."}}})];function runStartupChecks(checks,ctx,silenced=[]){let production=isProduction(),skip=new Set(silenced),found=[];for(let check of checks){if(check.deploy&&!production)continue;let result;try{result=check.run({...ctx,production})}catch(err){log$1.error(err,`Startup check '${check.name}' threw`);continue}for(let message of[result??[]].flat())skip.has(message.id)||found.push(message)}for(let message of found)message.level===`warning`&&log$1.warn(`${message.id}: ${message.message}${message.fix?` Fix: ${message.fix}`:``}`);let errors=found.filter(m=>m.level===`error`);if(errors.length>0)throw new StartupCheckError(errors);return found}function __decorateMetadata(k,v){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(k,v)}const HEALTH_PROBE=createToken(`kick/Health/probe`);function createHealthChecks(sources,options={}){let timeoutMs=options.timeoutMs??2e3,cached,runOne=async source=>{let name=source.name??`unknown`,started=Date.now(),timer,timedOut=new Promise(resolve=>{timer=setTimeout(()=>resolve({name,status:`down`,reason:`timeout`}),timeoutMs)});try{return await Promise.race([Promise.resolve().then(()=>source.onHealthCheck()).catch(()=>({name,status:`down`,reason:`error`})),timedOut])}finally{clearTimeout(timer);let ms=Date.now()-started;ms>=timeoutMs*.5&&options.onSlow?.(name,ms)}};return()=>{let now=Date.now();if(cached&&now-cached.at<1e3)return cached.result;let result=Promise.all(sources().filter(s=>s.onHealthCheck).map(runOne));return cached={at:now,result},result}}let HealthController=class{probe;constructor(probe){this.probe=probe}live(){return reply(200,{status:this.probe.isDraining()?`draining`:`ok`,uptime:process.uptime()})}async ready(){if(this.probe.isDraining())return reply(503,{status:`draining`,checks:[]});if(this.probe.isStarting?.())return reply(503,{status:`starting`,checks:[]});let checks=await this.probe.checks(),healthy=checks.every(c=>c.status===`up`);return reply(healthy?200:503,{status:healthy?`ready`:`degraded`,checks})}};__decorate([Get(`/live`),__decorateMetadata(`design:type`,Function),__decorateMetadata(`design:paramtypes`,[]),__decorateMetadata(`design:returntype`,void 0)],HealthController.prototype,`live`,null),__decorate([Get(`/ready`),__decorateMetadata(`design:type`,Function),__decorateMetadata(`design:paramtypes`,[]),__decorateMetadata(`design:returntype`,Promise)],HealthController.prototype,`ready`,null),HealthController=__decorate([Controller(),__decorateMetadata(`design:paramtypes`,[Object])],HealthController);const healthModule=defineModule({name:`HealthModule`,build:config=>({register(container){container.registerFactory(HealthController,()=>{let probe=container.resolve(HEALTH_PROBE);return new HealthController(probe)})},routes(){return{path:`/health`,controller:HealthController,version:!1,prefix:!1,flags:config.flags}}})}),HOP_BY_HOP_REQUEST=[`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`host`,`content-length`],HOP_BY_HOP_RESPONSE=[`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`upgrade`,`trailer`,`content-encoding`,`content-length`],LOOPBACK_HOST=`x-kick-loopback-host`,LOOPBACK_SECRET=`x-kick-loopback-secret`;async function streamedBody(request){if(!request.body||request.method===`GET`||request.method===`HEAD`)return;let reader=request.body.getReader(),first=await reader.read();if(!first.done)return new ReadableStream({start(controller){controller.enqueue(first.value)},async pull(controller){let{done,value}=await reader.read();done?controller.close():controller.enqueue(value)},cancel(reason){return reader.cancel(reason)}})}function createLoopback(handle){let started,secret=randomBytes(24).toString(`hex`),server=()=>(started??=new Promise((resolve,reject)=>{let instance=http.createServer((req,res)=>{let host=req.headers[LOOPBACK_HOST];req.headers[LOOPBACK_SECRET]===secret&&typeof host==`string`&&(req.headers.host=host),delete req.headers[LOOPBACK_HOST],delete req.headers[LOOPBACK_SECRET],handle(req,res)});instance.once(`error`,reject),instance.listen(0,`127.0.0.1`,()=>{instance.unref(),resolve({origin:`http://127.0.0.1:${instance.address().port}`,server:instance})})}).catch(err=>{throw started=void 0,err}),started);return{async fetch(request){let{origin}=await server(),url=new URL(request.url),headers=new Headers(request.headers);for(let name of HOP_BY_HOP_REQUEST)headers.delete(name);headers.set(`x-forwarded-host`,url.host),headers.set(`x-forwarded-proto`,url.protocol.slice(0,-1)),headers.set(LOOPBACK_HOST,url.host),headers.set(LOOPBACK_SECRET,secret);let body=await streamedBody(request),upstream=await fetch(origin+url.pathname+url.search,{method:request.method,headers,body,...body?{duplex:`half`}:{},redirect:`manual`,signal:request.signal}),responseHeaders=new Headers(upstream.headers),named=responseHeaders.get(`connection`)?.split(`,`)??[];for(let name of[...HOP_BY_HOP_RESPONSE,...named])responseHeaders.delete(name.trim());return new Response(upstream.body,{status:upstream.status,statusText:upstream.statusText,headers:responseHeaders})},async close(){let running=await started?.catch(()=>void 0);if(started=void 0,!running)return;let closed=new Promise(resolve=>running.server.close(()=>resolve()));running.server.closeAllConnections(),await closed}}}const log=createLogger(`Application`);function assertUsableTls(options){let{key,cert,pfx,SNICallback,pskCallback}=options;if(!pfx&&!SNICallback&&!pskCallback){if(!key&&!cert)throw tlsCredentialsError(`no key/cert, pfx, SNICallback, or pskCallback`);if(!key)throw tlsCredentialsError(`cert is set but key is missing`);if(!cert)throw tlsCredentialsError(`key is set but cert is missing`)}try{tls.createSecureContext(options)}catch(err){throw tlsCredentialsError(err.message)}}function isModuleFactory(entry){return typeof entry==`function`&&`definition`in entry&&typeof entry.scoped==`function`}function isConfigurable(factory){return factory.definition?.defaults!=null}function toAppModule(entry){if(typeof entry!=`function`)return entry;if(isModuleFactory(entry)){if(isConfigurable(entry)){let name=entry.definition?.name||entry.name||`<anonymous>`;throw TypeError(`bootstrap: module \`${name}\` takes configuration, so it must be invoked.\n Write \`${name}()\` for its defaults, or \`${name}({ … })\` to configure it.\n Passing it bare would have silently selected the defaults.`)}return entry()}let name=entry.name||`<anonymous>`;if(!isConstructible(entry))throw TypeError(`bootstrap: module entry \`${name}\` is a function, but not a module class and not a defineModule() factory (no \`definition\`).\n A defineModule() module is passed as \`${name}\` or \`${name}()\`; a class must implement AppModule.`);let mod=new entry;if(typeof mod?.routes!=`function`)throw TypeError(`bootstrap: module entry \`${name}\` constructed, but the result does not implement AppModule — \`routes()\` is missing.\n A module class needs \`routes()\`; a defineModule() module is passed as \`${name}\` or \`${name}()\`.`);return mod}function isConstructible(fn){try{return Reflect.construct(String,[],fn),!0}catch{return!1}}const APPLICATION=createToken(`kick/Http/Application`);var Application=class{options;app;runtime;container;httpServer=null;managementApp=null;managementServer=null;wantsManagement=!1;handlerMode=!1;observers=[];http2Sessions=/* @__PURE__ */ new Set;loopback;timeline=new StartupTimeline;conditionReport=[];mountedRoutes=[];mountedRouteInfo=[];routeUrls=new RouteUrls;settingsPrefixes=/* @__PURE__ */ new Map;settingsProvided=/* @__PURE__ */ new Map;handlerFor;adapters;routePolicy=new RoutePolicyTable;plugins;_moduleContributors=[];_inFlightRequests=0;_status=ref(`idle`);status=computed(()=>this._status.value);_shutdownInitiated=!1;_drainResolvers=[];constructor(options){this.options=options,this.runtime=options.runtime??expressRuntime(),this.container=Container.getInstance(),this.container.registerInstance(APPLICATION,this),this.plugins=mountSort(options.plugins??[],`plugin`);let allAdapters=[...this.plugins.flatMap(p=>p.adapters?.()??[]),...options.adapters??[]],anonAdapterCount=0,namedAdapters=allAdapters.map(adapter=>{if(!adapter.name){let ctorName=adapter.constructor?.name,fallback=ctorName&&ctorName!==`Object`?ctorName:`AnonymousAdapter#${anonAdapterCount++}`;return Object.assign(adapter,{name:fallback})}return adapter});this.adapters=mountSort(this.applyConditions(namedAdapters),`adapter`),this.observers=setObservers([...this.adapters,...this.plugins]),installChannelPublisher(),Container.setRequestStoreProvider(()=>requestStore.getStore()??null)}applyConditions(adapters){let seen=/* @__PURE__ */ new Set;for(let adapter of adapters){if(seen.has(adapter.name))throw new DuplicateMountNameError(`adapter`,adapter.name);seen.add(adapter.name)}let off=/* @__PURE__ */ new Map;for(let adapter of adapters){if(!adapter.when)continue;let result=evaluateCondition(adapter.when,err=>log.warn(`Adapter ${adapter.name}: its \`when\` condition threw — ${String(err)}`));result!==!0&&off.set(adapter.name,result)}let changed=off.size>0;for(;changed;){changed=!1;for(let adapter of adapters){if(off.has(adapter.name))continue;let missing=adapter.dependsOn?.find(dep=>off.has(dep));missing&&(off.set(adapter.name,`depends on ${missing}, which is off`),changed=!0)}}this.conditionReport=adapters.filter(a=>a.when||off.has(a.name)).map(a=>off.has(a.name)?{adapter:a.name,enabled:!1,reason:off.get(a.name)}:{adapter:a.name,enabled:!0});for(let outcome of this.conditionReport)outcome.enabled||log.debug(`Adapter ${outcome.adapter} is off: ${outcome.reason}`);return adapters.filter(a=>!off.has(a.name))}getConditionReport(){return this.conditionReport}get isDraining(){return this._status.value===`draining`||this._status.value===`stopped`}get inFlightRequests(){return this._inFlightRequests}getContainer(){return this.container}fetch(request){if(this.app===void 0)return Promise.reject(/* @__PURE__ */ Error(`kickjs: Application.fetch() before setup — await start() or startWithoutServer() first`));let runtimeApp=this.app;return typeof runtimeApp?.fetch==`function`?Promise.resolve(runtimeApp.fetch(request)):(this.loopback??=createLoopback((req,res)=>this.handle(req,res)),this.loopback.fetch(request))}createEngineApp(){return this.runtime.createApp({trustProxy:this.options.trustProxy,notFoundFallthrough:this.options.notFoundFallthrough,bodyLimit:parseByteSize(this.options.jsonLimit??`1mb`)})}handle(req,res,next){if(this.app===void 0)throw Error(`kickjs: Application.handle() before setup — await start() or startWithoutServer() first`);(!this.handlerFor||this.handlerFor.app!==this.app)&&(this.handlerFor={app:this.app,handler:this.runtime.nodeHandler(this.app)});let handler=this.handlerFor.handler;next?handler(req,res,next):handler(req,res)}adapterCtx(server,owner){let env=process.env.NODE_ENV??`production`,managementApp=this.managementApp;return{http:this.adapterHttp(void 0,owner),app:this.app,fetch:request=>this.fetch(request),container:this.container,server,...managementApp?{management:{http:this.adapterHttp(()=>managementApp,owner),server:this.managementServer??void 0}}:{},env,isProduction:isProduction()}}adapterHttp(target=()=>this.app,owner=`kick`){let record=(method,pattern,handler)=>{this.mountedRouteInfo.push({method,pattern,controller:owner,handler,contributors:[],source:`adapter`,port:target()===this.app?`app`:`management`})};return{route:(method,path,handler)=>{record(method,path,``);let entry={method,path,middlewares:[],contributorRunner:null,handler,meta:{}};this.runtime.mountRoutes(target(),[{mountPath:`/`,routes:[entry]}])},mount:(prefix,routes)=>{for(let entry of routes)record(entry.method,joinPaths(prefix,entry.path),String(entry.meta.handlerName??``));this.runtime.mountRoutes(target(),[{mountPath:prefix,routes}])},serveStatic:(prefix,dir)=>{record(`GET`,`${joinPaths(prefix,`/`).replace(/\/$/,``)}/*`,`static`),this.runtime.serveStatic(target(),prefix,dir)},use:(mw,opts)=>{this.runtime.useConnect(target(),mw,opts)}}}async callHook(hook,ctx,adapterName=`adapter`,hookName){if(!hook)return;let where=`${adapterName}.${hookName}`;try{await this.timeline.time(where,()=>hook(ctx))}catch(err){if(this.adviseOnFailure(err,where,adapterName),hookName!==`afterStart`)throw err;log.error(err,`${adapterName} afterStart hook failed`)}}adviseOnFailure(err,where,adapterName){let adapter=this.adapters.find(a=>a.name===adapterName),advice;try{advice=adapter?.analyzeFailure?.(err)}catch(analyzerErr){log.debug(`${adapterName}.analyzeFailure threw: ${String(analyzerErr)}`)}advice??=builtInAdvice(err,where),advice&&log.error(formatAdvice(advice))}getStartupTimeline(){return this.timeline.snapshot()}urlFor(name,...args){let[params,query]=args;return this.routeUrls.build(name,params,query)}collectModules(){let registry=new MutableModuleRegistry;for(let plugin of this.plugins){for(let m of plugin.modules?.()??[])registry.mount(m);plugin.setup?.(registry)}for(let m of this.options.modules)registry.mount(m);return this.options.setup?.(registry),registry}describeConfig(){let sections=[],seen=/* @__PURE__ */ new Set,add=(declaredBy,list)=>{for(let decl of list??[]){let section=`section`in decl?decl.section:decl;seen.has(section)||(seen.add(section),sections.push({prefix:section.prefix,declaredBy,vars:section.describe()}))}};add(`app`,this.options.settings);for(let plugin of this.plugins)add(`plugin ${plugin.name}`,plugin.settings?.());for(let adapter of this.adapters)add(`adapter ${adapter.name}`,adapter.settings?.());for(let entry of this.collectModules().entries){let mod=toAppModule(entry);add(`module ${moduleName(mod)}`,mod.settings?.())}return{env:describeEnvSchema(),sections}}configOrigins(){return{env:originsOf(describeEnvSchema()),sections:Array.from(this.settingsPrefixes.values(),section=>({prefix:section.prefix,vars:this.settingsProvided.has(section)?section.envNames.map(name=>({name,origin:`provided`})):originsOf(section.describe())}))}}bindSettings(sections){for(let[section,value]of loadSettings(sections,process.env,this.settingsPrefixes,this.settingsProvided))this.container.registerInstance(section,value)}runChecks(){runStartupChecks([...builtInChecks,...this.options.checks??[]],{options:this.options,routes:this.mountedRoutes},this.options.silenceChecks),this.timeline.mark(`checks`)}reportStartup(){let{totalMs}=this.timeline.snapshot();if(totalMs<1e3)return;let slowest=this.timeline.slowest(3).map(step=>`${step.name} ${Math.round(step.ms)}ms`).join(`, `);log.info(`Startup took ${Math.round(totalMs)}ms — slowest: ${slowest}`)}async setup(){log.debug(`Bootstrapping application...`),await this.runtime.load?.(),await settleExpressLoad(),this.app??=this.createEngineApp(),this.wantsManagement&&(this.managementApp??=this.createEngineApp()),this.timeline=new StartupTimeline,this.mountedRouteInfo=[],this.routeUrls=new RouteUrls,this.container.registerInstance(ROUTE_URLS,this.routeUrls),this.container.registerInstance(APPLICATION,this),this.settingsPrefixes=/* @__PURE__ */ new Map,this.settingsProvided=/* @__PURE__ */ new Map,this.bindSettings([...this.options.settings??[],...this.plugins.flatMap(plugin=>plugin.settings?.()??[]),...this.adapters.flatMap(adapter=>adapter.settings?.()??[])]),this._moduleContributors=[];let adapterMw=this.collectAdapterMiddleware();this.app.__kickApp=this;let hostList=this.options.security?.allowedHosts;if(hostList){let hostOptions=Array.isArray(hostList)?{hosts:hostList}:hostList;this.runtime.useConnect(this.app,allowedHosts({...hostOptions,ignorePaths:[...hostOptions.ignorePaths??[],`/health/live`,`/health/ready`]}))}for(let adapter of this.adapters)await this.callHook(adapter.beforeMount?.bind(adapter),this.adapterCtx(void 0,adapter.name),adapter.name,`beforeMount`);this.handlerMode&&this.mountCronTrigger(),this.runtime.useConnect(this.app,this.requestTrackingMiddleware()),this.shouldAutoMountRequestScope()&&this.runtime.useConnect(this.app,requestScopeMiddleware()),this.managementApp&&this.options.contextStore!==`manual`&&this.runtime.useConnect(this.managementApp,requestScopeMiddleware()),this.mountMiddlewareList(adapterMw.beforeGlobal);for(let plugin of this.plugins)plugin.register?.(this.container);for(let plugin of this.plugins)try{let mw=plugin.middleware?.()??[];for(let handler of mw)this.runtime.useConnect(this.app,handler)}catch(err){log.error(err,`Plugin middleware failed: ${plugin.name??`unknown`}`)}let declaredHelmet=(this.options.middlewares??[]).some(entry=>typeof entry==`function`&&Symbol.for(`kick/http/helmet`)in entry);if(this.options.security?.helmet!==!1&&!declaredHelmet)try{let{helmet:helmetFn}=await import(`./http/middleware/helmet.mjs`);this.runtime.useConnect(this.app,helmetFn())}catch{}let userMiddlewares=this.options.middlewares;if(userMiddlewares)for(let entry of userMiddlewares)this.mountMiddlewareEntry(entry);else if(this.runtime.useConnect(this.app,requestId()),!this.runtime.capabilities.nativeBodyParsing){let limit=this.options.jsonLimit??`1mb`,parsers=this.runtime.bodyParsers?this.runtime.bodyParsers({limit}):await expressBodyParsers(limit);for(let parser of parsers)this.runtime.useConnect(this.app,parser)}this.mountMiddlewareList(adapterMw.afterGlobal),this.timeline.mark(`middleware`);let moduleRegistry=this.collectModules();this.options.health!==!1&&(this.container.registerInstance(HEALTH_PROBE,{isDraining:()=>this.isDraining,isStarting:()=>this._status.value===`starting`,checks:createHealthChecks(()=>this.adapters,{timeoutMs:typeof this.options.health==`object`?this.options.health.checkTimeout:void 0,onSlow:(name,ms)=>log.warn(`Health check '${name}' took ${ms}ms`)})}),moduleRegistry.mount(healthModule(this.options.health===!0?{}:this.options.health)));let modules=moduleRegistry.entries.map(toAppModule);this.bindSettings(modules.flatMap(mod=>mod.settings?.()??[]));for(let mod of modules)mod.register?.(this.container);this.container.bootstrap(),this.container.has(Logger)||this.container.registerInstance(Logger,new Logger),this.timeline.mark(`modules`),this.mountMiddlewareList(adapterMw.beforeRoutes);let apiPrefix=this.options.apiPrefix??`/api`,defaultVersion=this.options.defaultVersion??1,shouldLogRoutes=this.options.logRouteTable??this.options.logRoutesTable??!1,mountedRoutes=[],adapterSources=[];for(let adapter of this.adapters){let adapterContribs=adapter.contributors?.()??[],adapterLabel=adapter.name??adapter.constructor.name??`adapter`;for(let registration of adapterContribs)adapterSources.push({source:`adapter`,registration,label:adapterLabel})}for(let plugin of this.plugins){let pluginContribs=plugin.contributors?.()??[],pluginLabel=plugin.name??plugin.constructor?.name??`plugin`;for(let registration of pluginContribs)adapterSources.push({source:`adapter`,registration,label:pluginLabel})}let globalSources=(this.options.contributors??[]).map(registration=>({source:`global`,registration,label:`bootstrap`}));this._moduleContributors=[];let seenRoutes=/* @__PURE__ */ new Map,mountedPaths=[],managementPaths=[];this.mountedRoutes=mountedPaths;for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));for(let src of moduleSources)this._moduleContributors.push({registration:src.registration,label:moduleLabel});_setExternalContributorSources([...moduleSources,...adapterSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){let version=route.version??defaultVersion,mountPath=buildMountPath(route.prefix===!1?``:apiPrefix,version,route.path);if(route.router)this.runtime.useConnect(this.app,route.router,{path:mountPath});else if(route.controller){let target=this.managementApp&&route.controller===HealthController?this.managementApp:this.app,routeTable=buildRouteTable(route.controller,{mountFlags:route.flags}),ctrl=route.controller.name??`controller`;for(let entry of routeTable){let owner=`${ctrl}.${String(entry.meta.handlerName??`?`)}`,fullPath=joinPaths(mountPath,entry.path);assertRouteUnique(seenRoutes,entry.method,fullPath,owner),(target===this.app?mountedPaths:managementPaths).push({method:entry.method,path:fullPath}),this.routeUrls.add(owner,fullPath),this.routePolicy.add(entry.method,fullPath,entry.meta.flags)}let traced=routeTable.map(entry=>{let pattern=joinPaths(mountPath,entry.path);return{...entry,handler:traceHandler(entry.handler,{method:entry.method,route:pattern,controller:route.controller?.name,handler:entry.meta.handlerName}),meta:{...entry.meta,pattern},validationError:this.options.validationError,urls:this.routeUrls}});this.runtime.mountRoutes(target,[{mountPath,routes:traced}]);for(let entry of traced)this.mountedRouteInfo.push({method:entry.method,pattern:entry.meta.pattern??entry.path,controller:route.controller.name,handler:String(entry.meta.handlerName??``),contributors:entry.meta.contributors??[],source:`module`,port:target===this.app?`app`:`management`})}else throw moduleRouteMissingControllerError(mountPath);let onManagement=!!this.managementApp&&route.controller===HealthController;if(route.controller&&!onManagement)for(let adapter of this.adapters)try{adapter.onRouteMount?.(route.controller,mountPath)}catch(err){log.error(err,`adapter.onRouteMount() failed for ${mountPath}`)}route.controller&&shouldLogRoutes&&mountedRoutes.push({controller:route.controller,mountPath,management:onManagement})}}finally{_setExternalContributorSources([])}}if(shouldLogRoutes&&mountedRoutes.length>0){let methodOrder=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`],methodRank=m=>{let i=methodOrder.indexOf(m);return i===-1?99:i},totalRoutes=0;log.info(`Routes:`);for(let{controller,mountPath,management}of mountedRoutes){let defs=getClassMeta(METADATA.ROUTES,controller,[]);if(defs.length===0)continue;let counts={};for(let def of defs){let m=def.method.toUpperCase();counts[m]=(counts[m]||0)+1}totalRoutes+=defs.length;let methods=Object.entries(counts).toSorted(([a],[b])=>methodRank(a)-methodRank(b)).map(([m,n])=>`${n} ${m}`).join(`, `),name=controller.name||`Controller`,port=management?` [management port]`:``;log.info(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})${port}`)}log.info(` Total: ${totalRoutes} routes`)}this.mountMiddlewareList(adapterMw.afterRoutes),this.timeline.mark(`routes`);for(let adapter of this.adapters)await this.callHook(adapter.beforeStart?.bind(adapter),this.adapterCtx(void 0,adapter.name),adapter.name,`beforeStart`);for(let entry of this.options.middlewares??[])offerRoutePolicy(typeof entry==`function`?entry:entry.handler,this.routePolicy);for(let adapter of this.adapters)for(let mw of adapter.middleware?.()??[])offerRoutePolicy(mw.handler,this.routePolicy);let builtInNotFound=notFoundHandler(mountedPaths),customNotFound=this.options.onNotFound;this.runtime.setNotFound(this.app,customNotFound?(req,res,next)=>customNotFound(req,res,err=>err===void 0?builtInNotFound(req,res,next):next(err)):builtInNotFound),this.runtime.setErrorHandler(this.app,observeErrors(this.options.onError??errorHandler())),this.managementApp&&(this.runtime.setNotFound(this.managementApp,notFoundHandler(managementPaths)),this.runtime.setErrorHandler(this.managementApp,observeErrors(errorHandler()))),this.timeline.mark(`error handlers`)}async registerOnly(){await this.setup()}async startWithoutServer(){await this.untilStartedOrStopped(()=>this.startWithoutServerSteps())}async untilStartedOrStopped(run){try{await run()}catch(err){throw this._status.value=`stopped`,err}}async startWithoutServerSteps(){this.handlerMode=!0,this._status.value=`starting`,await this.setup(),this.runChecks();let needServer=this.adapters.filter(adapter=>adapter.afterStart);needServer.length>0&&log.warn(`No HTTP server in handler mode, so afterStart does not run for: ${needServer.map(adapter=>adapter.name).join(`, `)}. Anything they attach to the server (WebSockets, upgrade handlers) is unavailable.`);for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup()}async start(){await this.untilStartedOrStopped(()=>this.startSteps())}async startSteps(){let g=globalThis,serverOptions=this.options.server;if(this._status.value=`starting`,serverOptions&&g.__kickjs_httpServer)log.warn(`server options (tls / http2) are ignored in dev mode — Vite owns the server`);else if(serverOptions){if(serverOptions.http2===!0&&!serverOptions.tls)throw http2RequiresTlsError();if(serverOptions.http2===`h2c`&&serverOptions.tls)throw http2RequiresTlsError(!0);if(serverOptions.http2&&!this.runtime.capabilities.http2)throw http2UnsupportedRuntimeError(this.runtime.name);serverOptions.tls&&assertUsableTls(serverOptions.tls)}let management=this.options.management;if(management&&g.__kickjs_httpServer?log.info(`management port is ignored in dev mode — /health stays on the dev server`):management&&(this.wantsManagement=!0),await this.setup(),this.runChecks(),g.__kickjs_httpServer){this.httpServer=g.__kickjs_httpServer,log.debug(`Attached to Vite dev server`),g.__kickjs_app_shutdown=()=>this.shutdown();for(let adapter of this.adapters){let ctx=this.adapterCtx(this.httpServer,adapter.name);await this.callHook(adapter.afterStart?.bind(adapter),ctx,adapter.name,`afterStart`)}for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup();return}let port=this.options.port??parseInt(process.env.PORT||`3000`,10);this.httpServer=this.createNodeServer(),this.httpServer.on(`error`,err=>{throw err.code===`EADDRINUSE`&&(log.error(`Port ${port} is already in use. Kill the existing process or use a different port:\n PORT=${port+1} kick dev\n lsof -i :${port} # find what's using it\n kill <PID> # stop it`),process.exit(1)),err}),this.managementApp&&management&&await this.listenManagement(management);try{await this.listenAndFinishStartup(port,serverOptions)}catch(err){throw await this.closeManagementServer(),err}}async listenAndFinishStartup(port,serverOptions){await new Promise((resolve,reject)=>{this.httpServer.listen(port,async()=>{try{let scheme=serverOptions?.tls?`https`:`http`,protocol=serverOptions?.http2===`h2c`?` (cleartext HTTP/2)`:serverOptions?.http2?` (HTTP/2)`:``;this.timeline.mark(`listen`),log.info(`Server running on ${scheme}://localhost:${port}${protocol}`);for(let adapter of this.adapters){let afterCtx=this.adapterCtx(this.httpServer,adapter.name);await this.callHook(adapter.afterStart?.bind(adapter),afterCtx,adapter.name,`afterStart`)}for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup(),resolve()}catch(err){reject(err)}})})}async closeManagementServer(){let server=this.managementServer;server&&(this.managementServer=null,await new Promise(resolve=>{server.close(()=>resolve()),server.closeAllConnections()}))}async listenManagement(options){let handler=this.runtime.nodeHandler(this.managementApp);options.tls&&assertUsableTls(options.tls);let server=options.tls?https.createServer(options.tls,handler):http.createServer(handler);await new Promise((resolve,reject)=>{server.once(`error`,reject),server.listen(options.port,options.host,()=>{server.off(`error`,reject),resolve()})}),this.managementServer=server;let scheme=options.tls?`https`:`http`;log.info(`Management server on ${scheme}://${options.host??`localhost`}:${options.port}`);for(let line of describeRoutes(this.mountedRouteInfo.filter(r=>r.port===`management`)))log.info(` ${line}`)}createNodeServer(){let server=this.createBareServer(),options=this.options.server??{},keepAlive=options.keepAliveTimeout??65e3;return`keepAliveTimeout`in server&&(server.keepAliveTimeout=keepAlive,server.headersTimeout=options.headersTimeout??keepAlive+1e3,server.requestTimeout=options.requestTimeout??3e5),server}createBareServer(){let handler=this.runtime.nodeHandler(this.app),{tls,http2:useHttp2}=this.options.server??{};if(useHttp2){let server=useHttp2===`h2c`?http2.createServer(handler):http2.createSecureServer({...tls,allowHTTP1:!0},handler);return server.on(`session`,session=>{this.http2Sessions.add(session),session.once(`close`,()=>this.http2Sessions.delete(session))}),server}return tls?https.createServer(tls,handler):http.createServer(handler)}async rebuild(){let prevApp=this.app,prevContainer=this.container,prevRouteUrls=this.routeUrls,prevSettingsPrefixes=this.settingsPrefixes,prevSettingsProvided=this.settingsProvided,staleDisposables=drainDisposables();try{Container.reset(),this.container=Container.getInstance(),this.app=this.createEngineApp(),await this.setup()}catch(err){log.error(err,`HMR rebuild failed, keeping previous app`),await runDisposables(drainDisposables());for(let d of staleDisposables)registerDisposable(d);this.app=prevApp,this.container=prevContainer,this.routeUrls=prevRouteUrls,this.settingsPrefixes=prevSettingsPrefixes,this.settingsProvided=prevSettingsProvided;return}await runDisposables(staleDisposables),this.httpServer&&(this.httpServer.removeAllListeners(`request`),this.httpServer.on(`request`,this.runtime.nodeHandler(this.app)),log.debug(`HMR: app rebuilt and swapped`))}async shutdown(options={}){let closeServer=options.closeServer??!0;if(this._shutdownInitiated){log.debug(`Shutdown already in progress, skipping duplicate call`);return}this._shutdownInitiated=!0,this._status.value=`draining`;let preStopDelay=this.options.preStopDelay??0;closeServer&&preStopDelay>0&&(log.debug(`Waiting ${preStopDelay}ms for load balancers to stop routing here...`),await new Promise(resolve=>setTimeout(resolve,preStopDelay))),log.debug(`Shutting down — draining in-flight requests...`);let timeoutMs=this.options.shutdownTimeout??3e4,timer,forceExitPromise=timeoutMs>0?new Promise(resolve=>{timer=setTimeout(()=>resolve(`timeout`),timeoutMs),timer.unref()}):new Promise(()=>{});try{if(closeServer&&this.httpServer){this.httpServer.close(()=>{});for(let session of this.http2Sessions)session.close()}if(closeServer&&this._inFlightRequests>0){log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`);let drainPromise=new Promise(resolve=>{this._drainResolvers.push(()=>resolve(`drained`))});if(await Promise.race([drainPromise,forceExitPromise])===`timeout`){log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`);for(let session of this.http2Sessions)session.destroy()}else log.debug(`All in-flight requests completed`)}closeServer&&pendingBackgroundWork()>0&&(log.debug(`Waiting for ${pendingBackgroundWork()} waitUntil() task(s) to settle...`),await Promise.race([settleBackgroundWork().then(()=>`settled`),forceExitPromise])===`timeout`&&log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${pendingBackgroundWork()} waitUntil() task(s) still running`));let hookTimeoutMs=closeServer?timeoutMs:Math.min(timeoutMs,5e3),timeBoxed=(label,run)=>{let hook=(async()=>run())();return hookTimeoutMs<=0?hook:new Promise((resolve,reject)=>{let t=setTimeout(()=>{log.warn(`${label} did not finish shutting down within ${hookTimeoutMs}ms — continuing without it. Its resources may still be held.`),resolve(void 0)},hookTimeoutMs);t.unref(),hook.then(value=>{clearTimeout(t),resolve(value)},err=>{clearTimeout(t),reject(err)})})},wasListening=this.httpServer?.listening===!0,results=await Promise.allSettled([...this.plugins.map(plugin=>timeBoxed(`Plugin '${plugin.name}'`,()=>plugin.shutdown?.())),...this.adapters.map(adapter=>timeBoxed(`Adapter '${adapter.name}'`,()=>adapter.shutdown?.())),timeBoxed(`Runtime '${this.runtime.name}'`,()=>this.runtime.close?.(this.app)),...this.managementApp&&closeServer?[timeBoxed(`Runtime '${this.runtime.name}' (management)`,()=>this.runtime.close?.(this.managementApp))]:[]]);!closeServer&&wasListening&&this.httpServer?.listening===!1&&log.error("An adapter or plugin closed the shared HTTP server during an HMR reload. The dev server is now unreachable and will not rebind until you restart it. Close only what you own: socket.io's `io.close()` closes the HTTP server passed to its constructor — on a reload, disconnect the sockets instead.");for(let result of results)result.status===`rejected`&&log.error({err:result.reason},`Adapter shutdown failed`);await disposeAll(),this.container.flushChanges(),await this.loopback?.close(),this.loopback=void 0,closeServer&&await this.closeManagementServer(),closeServer&&releaseObservers(this.observers)}finally{timer&&clearTimeout(timer),this._status.value=`stopped`}}getRuntimeApp(){return this.app}getActiveRuntime(){return{name:this.runtime.name,capabilities:this.runtime.capabilities}}getExpressApp(){return this.app}getAdapters(){return this.adapters}getPlugins(){return this.plugins}getRoutes(){return this.mountedRouteInfo}getContributors(){let out=[],ingest=(list,source,label)=>{if(list)for(let reg of list){let r=reg;if(r.key===void 0||r.key===null)continue;let key=typeof r.key==`string`?r.key:tokenName(r.key);out.push({key,source,label,dependsOn:Array.isArray(r.dependsOn)?r.dependsOn:[]})}};for(let adapter of this.adapters)ingest(adapter.contributors?.(),`adapter`,adapter.name??`adapter`);for(let plugin of this.plugins)ingest(plugin.contributors?.(),`plugin`,plugin.name??`plugin`);for(let{registration,label}of this._moduleContributors)ingest([registration],`module`,label);ingest(this.options.contributors,`global`,`bootstrap`);let sites=/* @__PURE__ */ new Set;for(let route of this.mountedRouteInfo)for(let c of route.contributors){if(c.source!==`class`&&c.source!==`method`)continue;let site=`${c.source}:${c.label??`${route.controller}.${route.handler}`}`;sites.has(site)||(sites.add(site),out.push({key:c.key,source:c.source,label:c.label??`${route.controller}.${route.handler}`,dependsOn:c.dependsOn}))}return out}getHttpServer(){return this.httpServer}getManagementServer(){return this.managementServer}shouldAutoMountRequestScope(){if(this.options.contextStore===`manual`)return!1;let userEntries=this.options.middlewares??[];for(let entry of userEntries){let handler=typeof entry==`function`?entry:entry.handler;if(isRequestScopeMiddleware(handler))return!1}return!0}collectAdapterMiddleware(){let result={beforeGlobal:[],afterGlobal:[],beforeRoutes:[],afterRoutes:[]};for(let adapter of this.adapters){let entries=adapter.middleware?.()??[];for(let entry of entries)result[entry.phase??`afterGlobal`].push(entry)}return result}mountMiddlewareList(entries){for(let entry of entries)entry.path===void 0?this.runtime.useConnect(this.app,entry.handler):this.runtime.useConnect(this.app,entry.handler,{path:entry.path})}mountMiddlewareEntry(entry){typeof entry==`function`?this.runtime.useConnect(this.app,entry):this.runtime.useConnect(this.app,entry.handler,{path:entry.path})}mountCronTrigger(){let secret=process.env.CRON_SECRET;secret&&this.adapterHttp().route(`GET`,`/_kick/cron/:scheduleId`,async ctx=>{if(!matchesBearer(ctx.headers.authorization,secret))throw new HttpException(401,`Missing or invalid CRON_SECRET bearer token`);let result=await runCronJobs(this.container,{scheduleId:ctx.params.scheduleId},`http`);ctx.json(result,result.failed>0?500:200)})}requestTrackingMiddleware(){return(req,res,next)=>{this._inFlightRequests++;let started=hasResponseObservers()?performance.now():void 0,onFinish=()=>settle(!0),onClose=()=>settle(!1),settle=finished=>{if(res.removeListener(`finish`,onFinish),res.removeListener(`close`,onClose),finished&&started!==void 0){let matched=req[ROUTE_SLOT];reportResponse({method:req.method,path:requestPath(req),route:matched?.pattern,status:res.statusCode,durationMs:performance.now()-started,requestId:requestIdOf(req)})}if(this._inFlightRequests--,this.isDraining&&this._inFlightRequests===0){for(let resolve of this._drainResolvers)resolve();this._drainResolvers=[]}};res.on(`finish`,onFinish),res.on(`close`,onClose),next()}}};function describeRoutes(routes){let byOwner=/* @__PURE__ */ new Map;for(let route of routes)byOwner.set(route.controller,[...byOwner.get(route.controller)??[],route]);let width=Math.max(0,...[...byOwner.keys()].map(owner=>owner.length));return[...byOwner].map(([owner,list])=>{if(list.length<=4)return`${owner.padEnd(width)} ${list.map(r=>`${r.method} ${r.pattern}`).join(`, `)}`;let segments=list.map(r=>r.pattern.split(`/`)),common=[];for(let i=0;segments.every(s=>s[i]!==void 0&&s[i]===segments[0][i]);i++)common.push(segments[0][i]);return`${owner.padEnd(width)} ${list.length} routes under ${common.join(`/`)||`/`}`})}function requestPath(req){return(req.originalUrl??req.url??``).split(`?`)[0]}function requestIdOf(req){let header=req.headers?.[`x-request-id`];return req.requestId??(typeof header==`string`?header:void 0)}function errorStatus(err){return typeof err?.problem?.status==`number`?err.problem.status:typeof err?.status==`number`?err.status:typeof err?.statusCode==`number`?err.statusCode:err?.name===`ZodError`?422:500}function observeErrors(handler){return((err,req,res,next)=>{let matched=req?.[ROUTE_SLOT];return reportError(err,{source:`request`,requestId:requestIdOf(req??{}),method:req?.method,path:requestPath(req??{}),route:matched?.pattern,status:errorStatus(err)}),handler(err,req,res,next)})}export{MountCycleError as _,HealthController as a,defineCheck as c,onPackage as d,ERROR_CHANNEL as f,MissingMountDepError as g,DuplicateMountNameError as h,HEALTH_PROBE as i,allOf as l,RESPONSE_CHANNEL as m,Application as n,healthModule as o,HANDLER_CHANNEL as p,describeRoutes as r,StartupCheckError as s,APPLICATION as t,onEnv as u,mountSort as v};
14
- //# sourceMappingURL=application-QBVum-rq.mjs.map