@forinda/kickjs 10.10.0 → 10.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/dist/{adapter-DLjn8q0c.d.mts → adapter-DiJfCKXU.d.mts} +27 -8
  2. package/dist/adapter-DiJfCKXU.d.mts.map +1 -0
  3. package/dist/{application-DLRHEOeg.mjs → application-BCXdtJd1.mjs} +3 -3
  4. package/dist/{application-DLRHEOeg.mjs.map → application-BCXdtJd1.mjs.map} +1 -1
  5. package/dist/{application-CdUI5E_3.d.mts → application-EinAcKLu.d.mts} +6 -6
  6. package/dist/{application-CdUI5E_3.d.mts.map → application-EinAcKLu.d.mts.map} +1 -1
  7. package/dist/{body-policy-DIgqprai.mjs → body-policy-DccDxmmR.mjs} +2 -2
  8. package/dist/{body-policy-DIgqprai.mjs.map → body-policy-DccDxmmR.mjs.map} +1 -1
  9. package/dist/bootstrap-C5op763j.mjs +12 -0
  10. package/dist/{bootstrap-6ltjueRe.mjs.map → bootstrap-C5op763j.mjs.map} +1 -1
  11. package/dist/{bounded-counters-Dxi2jekd.mjs → bounded-counters-CmmPOr2v.mjs} +2 -2
  12. package/dist/{bounded-counters-Dxi2jekd.mjs.map → bounded-counters-CmmPOr2v.mjs.map} +1 -1
  13. package/dist/{client-ip-dLKJKDZL.mjs → client-ip-STshfERA.mjs} +2 -2
  14. package/dist/{client-ip-dLKJKDZL.mjs.map → client-ip-STshfERA.mjs.map} +1 -1
  15. package/dist/config/index.mjs +2 -2
  16. package/dist/{config-BEoFtveu.mjs → config-DZd8tqGC.mjs} +3 -3
  17. package/dist/{config-BEoFtveu.mjs.map → config-DZd8tqGC.mjs.map} +1 -1
  18. package/dist/context-BJ6HVq4W.mjs +12 -0
  19. package/dist/context-BJ6HVq4W.mjs.map +1 -0
  20. package/dist/{context-errors-B2uJdmkX.mjs → context-errors-s1zG7eax.mjs} +2 -2
  21. package/dist/{context-errors-B2uJdmkX.mjs.map → context-errors-s1zG7eax.mjs.map} +1 -1
  22. package/dist/{contributor-runner-CaZkoZOK.mjs → contributor-runner-B5pv7_R-.mjs} +3 -3
  23. package/dist/{contributor-runner-CaZkoZOK.mjs.map → contributor-runner-B5pv7_R-.mjs.map} +1 -1
  24. package/dist/core/adapter.d.mts +1 -1
  25. package/dist/core/adapter.mjs +1 -1
  26. package/dist/core/app-module.mjs +1 -1
  27. package/dist/core/cache.mjs +1 -1
  28. package/dist/core/container.mjs +2 -2
  29. package/dist/core/cron.mjs +2 -2
  30. package/dist/core/decorators.mjs +2 -2
  31. package/dist/core/errors.mjs +1 -1
  32. package/dist/core/interfaces.mjs +1 -1
  33. package/dist/core/logger.mjs +1 -1
  34. package/dist/core/path.mjs +1 -1
  35. package/dist/core/plugin.d.mts +1 -1
  36. package/dist/core/plugin.mjs +1 -1
  37. package/dist/core/reactivity.mjs +2 -2
  38. package/dist/{core-MyOlkejk.mjs → core-Cf6gPv9R.mjs} +3 -3
  39. package/dist/{core-MyOlkejk.mjs.map → core-Cf6gPv9R.mjs.map} +1 -1
  40. package/dist/{decorate-CU19-7Fw.mjs → decorate-BQA6M9jq.mjs} +3 -3
  41. package/dist/{decorate-CU19-7Fw.mjs.map → decorate-BQA6M9jq.mjs.map} +1 -1
  42. package/dist/{define-adapter-1FfgX1AQ.mjs → define-adapter-B9DcBJKt.mjs} +2 -2
  43. package/dist/{define-adapter-1FfgX1AQ.mjs.map → define-adapter-B9DcBJKt.mjs.map} +1 -1
  44. package/dist/{di-hooks-DX9rJX_0.mjs → di-hooks-DGmtRWDI.mjs} +2 -2
  45. package/dist/{di-hooks-DX9rJX_0.mjs.map → di-hooks-DGmtRWDI.mjs.map} +1 -1
  46. package/dist/{disposables-Bq6gIO7N.mjs → disposables-C1xhXyD6.mjs} +1 -1
  47. package/dist/{error-handler-BrihKETE.d.mts → error-handler-OfxVJX3s.d.mts} +2 -2
  48. package/dist/{error-handler-BrihKETE.d.mts.map → error-handler-OfxVJX3s.d.mts.map} +1 -1
  49. package/dist/{express-BBhisCna.mjs → express-DqWsJylQ.mjs} +3 -3
  50. package/dist/{express-BBhisCna.mjs.map → express-DqWsJylQ.mjs.map} +1 -1
  51. package/dist/{express-lazy-Pua2eR0n.mjs → express-lazy-CdPN1krb.mjs} +3 -3
  52. package/dist/{express-lazy-Pua2eR0n.mjs.map → express-lazy-CdPN1krb.mjs.map} +1 -1
  53. package/dist/handler-Ce16qhGr.mjs +12 -0
  54. package/dist/{handler-C_mWEafU.mjs.map → handler-Ce16qhGr.mjs.map} +1 -1
  55. package/dist/{host-d9X0p13s.mjs → host-BZcjkJ-A.mjs} +2 -2
  56. package/dist/{host-d9X0p13s.mjs.map → host-BZcjkJ-A.mjs.map} +1 -1
  57. package/dist/http/application.d.mts +1 -1
  58. package/dist/http/application.mjs +2 -2
  59. package/dist/http/bootstrap.d.mts +1 -1
  60. package/dist/http/bootstrap.mjs +2 -2
  61. package/dist/http/context.d.mts +1 -1
  62. package/dist/http/context.mjs +2 -2
  63. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  64. package/dist/http/middleware/breach-padding.mjs +1 -1
  65. package/dist/http/middleware/cors.mjs +1 -1
  66. package/dist/http/middleware/csrf.mjs +2 -2
  67. package/dist/http/middleware/error-handler.d.mts +1 -1
  68. package/dist/http/middleware/error-handler.mjs +2 -2
  69. package/dist/http/middleware/helmet.mjs +1 -1
  70. package/dist/http/middleware/rate-limit.mjs +2 -2
  71. package/dist/http/middleware/request-id.mjs +1 -1
  72. package/dist/http/middleware/request-logger.mjs +2 -2
  73. package/dist/http/middleware/session.mjs +2 -2
  74. package/dist/http/middleware/spa.d.mts +1 -1
  75. package/dist/http/middleware/spa.mjs +2 -2
  76. package/dist/http/middleware/upload.d.mts +2 -2
  77. package/dist/http/middleware/upload.mjs +2 -2
  78. package/dist/http/middleware/validate.mjs +1 -1
  79. package/dist/http/middleware/views.d.mts +1 -1
  80. package/dist/http/middleware/views.mjs +2 -2
  81. package/dist/http/query/index.mjs +2 -2
  82. package/dist/http/router-builder.d.mts +1 -1
  83. package/dist/http/router-builder.mjs +2 -2
  84. package/dist/http/runtimes/express.d.mts +2 -2
  85. package/dist/http/runtimes/express.mjs +2 -2
  86. package/dist/http/runtimes/fastify.d.mts +1 -1
  87. package/dist/http/runtimes/fastify.mjs +2 -2
  88. package/dist/http/runtimes/fastify.mjs.map +1 -1
  89. package/dist/http/runtimes/h3-web.mjs +1 -1
  90. package/dist/http/runtimes/h3.d.mts +1 -1
  91. package/dist/http/runtimes/h3.d.mts.map +1 -1
  92. package/dist/http/runtimes/h3.mjs +2 -2
  93. package/dist/http/runtimes/h3.mjs.map +1 -1
  94. package/dist/index.d.mts +7 -7
  95. package/dist/index.mjs +3 -3
  96. package/dist/index.mjs.map +1 -1
  97. package/dist/{is-production-BYwEumHI.mjs → is-production-et6gyyxF.mjs} +2 -2
  98. package/dist/{is-production-BYwEumHI.mjs.map → is-production-et6gyyxF.mjs.map} +1 -1
  99. package/dist/{jobs-bGtYcSgo.mjs → jobs-B4wle0iS.mjs} +3 -3
  100. package/dist/{jobs-bGtYcSgo.mjs.map → jobs-B4wle0iS.mjs.map} +1 -1
  101. package/dist/{kv-stores-DJBnGQsJ.d.mts → kv-stores-BN7c9bt9.d.mts} +2 -2
  102. package/dist/{kv-stores-DJBnGQsJ.d.mts.map → kv-stores-BN7c9bt9.d.mts.map} +1 -1
  103. package/dist/{kv-stores-DbM-V83V.mjs → kv-stores-CLR0N5im.mjs} +3 -3
  104. package/dist/{kv-stores-DbM-V83V.mjs.map → kv-stores-CLR0N5im.mjs.map} +1 -1
  105. package/dist/{lazy-serve-static-Dp3lqSlT.mjs → lazy-serve-static-CKaL8clq.mjs} +3 -3
  106. package/dist/{lazy-serve-static-Dp3lqSlT.mjs.map → lazy-serve-static-CKaL8clq.mjs.map} +1 -1
  107. package/dist/{metadata-BvNkZphr.mjs → metadata-CsfVw6pp.mjs} +1 -1
  108. package/dist/{observers-Bjs-1F1Z.mjs → observers-BbNYzGfC.mjs} +2 -2
  109. package/dist/{observers-Bjs-1F1Z.mjs.map → observers-BbNYzGfC.mjs.map} +1 -1
  110. package/dist/{precompressed-Cydk_Bpr.mjs → precompressed-BTEVCjT_.mjs} +2 -2
  111. package/dist/{precompressed-Cydk_Bpr.mjs.map → precompressed-BTEVCjT_.mjs.map} +1 -1
  112. package/dist/{query-BEnIVY7Q.mjs → query-EQM3lEr_.mjs} +2 -2
  113. package/dist/{query-BEnIVY7Q.mjs.map → query-EQM3lEr_.mjs.map} +1 -1
  114. package/dist/reply-Detphot1.mjs +12 -0
  115. package/dist/reply-Detphot1.mjs.map +1 -0
  116. package/dist/request-scope-D5ggZdvq.mjs +12 -0
  117. package/dist/{request-scope-u_VhYe4-.mjs.map → request-scope-D5ggZdvq.mjs.map} +1 -1
  118. package/dist/{respond-C0NoT3br.mjs → respond-B_5BPAJp.mjs} +2 -2
  119. package/dist/{respond-C0NoT3br.mjs.map → respond-B_5BPAJp.mjs.map} +1 -1
  120. package/dist/{rolldown-runtime-D2dh8WuU.mjs → rolldown-runtime-BgeRdaSa.mjs} +1 -1
  121. package/dist/{route-flag-xPz2wbyz.mjs → route-flag-CO7wkxhn.mjs} +3 -3
  122. package/dist/{route-flag-xPz2wbyz.mjs.map → route-flag-CO7wkxhn.mjs.map} +1 -1
  123. package/dist/{route-policy-weZwvZYs.mjs → route-policy-DJd0iddt.mjs} +2 -2
  124. package/dist/{route-policy-weZwvZYs.mjs.map → route-policy-DJd0iddt.mjs.map} +1 -1
  125. package/dist/{router-builder-CPJHwoL1.d.mts → router-builder-DtGrng_X.d.mts} +2 -2
  126. package/dist/{router-builder-CPJHwoL1.d.mts.map → router-builder-DtGrng_X.d.mts.map} +1 -1
  127. package/dist/{router-builder-CnCNsI87.mjs → router-builder-DtjsnD0b.mjs} +3 -3
  128. package/dist/{router-builder-CnCNsI87.mjs.map → router-builder-DtjsnD0b.mjs.map} +1 -1
  129. package/dist/{settings-Ciut2k76.mjs → settings-CJWJPERr.mjs} +3 -3
  130. package/dist/{settings-Ciut2k76.mjs.map → settings-CJWJPERr.mjs.map} +1 -1
  131. package/dist/{token-CBe6OMQK.mjs → token-kfP7I0D6.mjs} +1 -1
  132. package/dist/{upload-DtQ1pdQw.d.mts → upload-C9IfY1aQ.d.mts} +2 -2
  133. package/dist/{upload-DtQ1pdQw.d.mts.map → upload-C9IfY1aQ.d.mts.map} +1 -1
  134. package/dist/{upload-config-d_LW2u9b.mjs → upload-config-DldXNOHe.mjs} +2 -2
  135. package/dist/{upload-config-d_LW2u9b.mjs.map → upload-config-DldXNOHe.mjs.map} +1 -1
  136. package/dist/{url-for-Df_ts-iM.mjs → url-for-O-DQnRvH.mjs} +3 -3
  137. package/dist/{url-for-Df_ts-iM.mjs.map → url-for-O-DQnRvH.mjs.map} +1 -1
  138. package/dist/{background-CiKEgaD2.mjs → view-renderer-NbkTobFF.mjs} +3 -3
  139. package/dist/view-renderer-NbkTobFF.mjs.map +1 -0
  140. package/dist/{web-crypto-BNF60ZAh.mjs → web-crypto-BNP8o7BF.mjs} +2 -2
  141. package/dist/{web-crypto-BNF60ZAh.mjs.map → web-crypto-BNP8o7BF.mjs.map} +1 -1
  142. package/dist/web.d.mts +2 -2
  143. package/dist/web.d.mts.map +1 -1
  144. package/dist/web.mjs +2 -2
  145. package/dist/web.mjs.map +1 -1
  146. package/package.json +1 -1
  147. package/dist/adapter-DLjn8q0c.d.mts.map +0 -1
  148. package/dist/background-CiKEgaD2.mjs.map +0 -1
  149. package/dist/bootstrap-6ltjueRe.mjs +0 -12
  150. package/dist/context-BPszif4a.mjs +0 -12
  151. package/dist/context-BPszif4a.mjs.map +0 -1
  152. package/dist/handler-C_mWEafU.mjs +0 -12
  153. package/dist/reply-CGn9BmYj.mjs +0 -12
  154. package/dist/reply-CGn9BmYj.mjs.map +0 -1
  155. package/dist/request-scope-u_VhYe4-.mjs +0 -12
@@ -1 +1 @@
1
- {"version":3,"file":"settings-Ciut2k76.mjs","names":[],"sources":["../src/config/settings.ts"],"sourcesContent":["/**\n * Typed configuration sections: one schema per concern (`DB`, `MAIL`,\n * `STORAGE`), each read from its own prefix of the environment and injected\n * where it's needed — instead of one flat env every service reaches into.\n * Spring's `@ConfigurationProperties`, for any schema `@forinda/kickjs-schema`\n * reads — Zod, Valibot, Yup.\n *\n * @module @forinda/kickjs/config/settings\n */\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { INJECTION_TOKEN, type InjectionToken } from '../core/token'\nimport { Container } from '../core/container'\n\n/**\n * Reads `<NAME>_FILE` secrets. Registered by `./env` (Node only) when it\n * loads — this module imports nothing node-only, so the web entry can use it;\n * there, `_FILE` variables are simply not read.\n */\ntype SecretFileReader = (\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n) => Record<string, string | undefined>\nlet readSecretFiles: SecretFileReader | undefined\n\n/** @internal */\nexport function _useSecretFileReader(reader: SecretFileReader): void {\n readSecretFiles = reader\n}\n\n/** A section: an injection token that also knows how to load itself. */\nexport interface Settings<T> extends InjectionToken<T> {\n /** The env prefix, e.g. `'DB'`. */\n readonly prefix: string\n /** Every env name the section reads, e.g. `['DB_URL', 'DB_POOL_MAX']`. */\n readonly envNames: readonly string[]\n /**\n * The section's value — validated at startup, then cached. Before startup\n * (a script, a CLI command) the first call loads and validates it.\n */\n get(): T\n /** Parse the section from `env` (default `process.env`) afresh; throws listing every problem. */\n load(env?: NodeJS.ProcessEnv): T\n /** Each variable the section reads — required or not, default, description. Reads no env. */\n describe(): ConfigVar[]\n /** Validate a value you supply against the schema — defaults applied — instead of reading env. */\n parse(value: unknown): T\n /**\n * Declare the section with a value you supply instead of the environment —\n * a test's container, a service you started, a secret manager's answer.\n * Validated against the schema like env values; bound under this section's\n * token, so everything injecting it gets the provided value.\n *\n * ```ts\n * const pg = await startService('postgres')\n * await createTestApp({ modules, settings: [DbSettings.provide({ url: pg.url })] })\n * ```\n */\n provide(value: unknown): ProvidedSettings<T>\n /**\n * The same schema under another prefix, for a second instance:\n * `DbSettings.scoped('ANALYTICS')` reads `ANALYTICS_DB_*` beside `DB_*`.\n * Returns the same token for the same name.\n */\n scoped(name: string): Settings<T>\n}\n\nconst PROVIDED = Symbol.for('kickjs.settings.provided')\n\n/** A section declared with a supplied value — see {@link Settings.provide}. */\nexport interface ProvidedSettings<T> {\n readonly [PROVIDED]: true\n readonly section: Settings<T>\n readonly value: unknown\n}\n\n/** What a `settings` list accepts: a section (read from env) or a provided one. */\nexport type SettingsDeclaration = Settings<unknown> | ProvidedSettings<unknown>\n\nfunction isProvided(decl: SettingsDeclaration): decl is ProvidedSettings<unknown> {\n return (decl as Partial<ProvidedSettings<unknown>>)[PROVIDED] === true\n}\n\n/** The value type of a section: `SettingsOf<typeof DbSettings>`. */\nexport type SettingsOf<S> = S extends Settings<infer T> ? T : never\n\ninterface Leaf {\n path: string[]\n env: string\n list: boolean\n required: boolean\n default?: unknown\n description?: string\n}\n\n/** One variable, as `describe()` and `app.describeConfig()` report it. */\nexport interface ConfigVar {\n name: string\n /** Startup fails without it: required by the schema, with no default. */\n required: boolean\n /** The schema's default, when it has one. */\n default?: unknown\n /** The schema's description (`.describe('…')` in Zod). */\n description?: string\n /** Read as a comma-separated list. */\n list: boolean\n}\n\n/** The part of a JSON schema the env mapping reads. */\ninterface JsonShape {\n type?: string | string[]\n properties?: Record<string, JsonShape>\n required?: string[]\n default?: unknown\n description?: string\n}\n\n/** `maxConnections` → `MAX_CONNECTIONS`. */\nconst envSegment = (key: string) => key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()\n\n/**\n * The variables a JSON-schema shape reads. A leaf is required when every\n * object on its path is required by its parent and none of them (nor the leaf)\n * has a default — a defaulted parent object supplies its children.\n */\nfunction leavesOf(shape: JsonShape, prefix: string, path: string[] = [], required = true): Leaf[] {\n if (shape.properties) {\n const own = new Set(shape.required ?? [])\n const parentRequired = required && shape.default === undefined\n return Object.entries(shape.properties).flatMap(([key, child]) =>\n leavesOf(child, prefix, [...path, key], parentRequired && own.has(key)),\n )\n }\n const types = Array.isArray(shape.type) ? shape.type : [shape.type]\n return [\n {\n path,\n env: [prefix, ...path.map(envSegment)].join('_'),\n list: types.includes('array'),\n required: required && shape.default === undefined,\n ...(shape.default !== undefined ? { default: shape.default } : {}),\n ...(shape.description ? { description: shape.description } : {}),\n },\n ]\n}\n\nconst toConfigVar = (leaf: Leaf): ConfigVar => ({\n name: leaf.env,\n required: leaf.required,\n list: leaf.list,\n ...(leaf.default !== undefined ? { default: leaf.default } : {}),\n ...(leaf.description ? { description: leaf.description } : {}),\n})\n\n/**\n * The variables of a flat schema (the app's env schema), described the same\n * way — no prefix, top-level keys only.\n */\nexport function describeSchemaVars(schema: unknown): ConfigVar[] {\n const shape = detectSchema(schema).toJsonSchema() as JsonShape\n const required = new Set(shape.required ?? [])\n // The keys of an env schema are the variable names themselves.\n return Object.entries(shape.properties ?? {}).map(([key, child]) => {\n // A fresh object from toConfigVar — safe to set the name on directly.\n const described = toConfigVar(leavesOf(child, '', [key], required.has(key))[0])\n described.name = key\n return described\n })\n}\n\n/** Where a variable's value comes from. */\nexport type ValueOrigin = 'env' | 'file' | 'provided' | 'default' | 'unset'\n\n/** A variable and where its value comes from — never the value itself. */\nexport interface VarOrigin {\n name: string\n origin: ValueOrigin\n}\n\n/**\n * Where each variable's value comes from in `env`: set directly, read from\n * `<NAME>_FILE`, the schema's default, or not set at all. Names only — safe\n * to show where the values themselves must not appear.\n */\nexport function originsOf(\n vars: readonly ConfigVar[],\n env: NodeJS.ProcessEnv = process.env,\n): VarOrigin[] {\n // Empty counts as unset, as the secret-file reader treats it.\n const has = (name: string) => env[name] !== undefined && env[name] !== ''\n return vars.map((v) => {\n let origin: ValueOrigin = 'unset'\n if (has(v.name)) origin = 'env'\n // `_FILE` is only read where a reader is registered (Node, not the web entry).\n else if (readSecretFiles && has(`${v.name}_FILE`)) origin = 'file'\n else if (v.default !== undefined) origin = 'default'\n return { name: v.name, origin }\n })\n}\n\n/** Values validated at startup (or on first `get()`), by prefix. */\nconst cached = new WeakMap<Settings<unknown>, unknown>()\n\n/**\n * Define a typed configuration section read from env variables with a prefix.\n * Each key path becomes one variable: `pool.max` under `'DB'` is `DB_POOL_MAX`,\n * `maxConnections` is `DB_MAX_CONNECTIONS`. A list reads a comma-separated\n * value. `<NAME>_FILE` secrets work for every variable.\n *\n * ```ts\n * export const DbSettings = defineSettings('DB', z.object({\n * url: z.string().url(),\n * pool: z.object({ max: z.coerce.number().default(10) }).default({ max: 10 }),\n * }))\n *\n * @Service()\n * class Database {\n * constructor(@Inject(DbSettings) private readonly db: SettingsOf<typeof DbSettings>) {}\n * }\n * ```\n *\n * Declare it where it's used — `bootstrap({ settings })`, a module's, adapter's\n * or plugin's `settings()` — and it is validated when the app starts (a\n * missing or invalid value fails startup, naming the variable) and injectable\n * by its token. Undeclared, `get()` validates it on first use. Values\n * come from the schema's coercion: use `z.coerce.number()`, and\n * `z.stringbool()` for booleans (`z.coerce.boolean()` reads `'false'` as true).\n */\nexport function defineSettings<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n return createSection(prefix, schema)\n}\n\nfunction createSection<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n type T = InferSchemaOutput<S>\n if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) {\n throw new Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`)\n }\n const wrapped = detectSchema(schema)\n // The env names come from the schema's shape, read through its JSON schema —\n // the one view every adapter (Zod, Valibot, Yup) provides.\n const shape = wrapped.toJsonSchema() as JsonShape\n if (!shape.properties) {\n throw new Error(\n `defineSettings('${prefix}'): the schema must be an object whose keys can be read ` +\n '(Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.',\n )\n }\n const leaves = leavesOf(shape, prefix)\n // `fooBar` and `foo_bar` would both read `DB_FOO_BAR` — one variable for two\n // settings that could never differ. Refuse it here, naming both paths.\n const seenEnv = new Map<string, string>()\n for (const leaf of leaves) {\n const path = leaf.path.join('.')\n const other = seenEnv.get(leaf.env)\n if (other !== undefined) {\n throw new Error(\n `defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`,\n )\n }\n seenEnv.set(leaf.env, path)\n }\n const envNames = leaves.map((leaf) => leaf.env)\n const byPath = new Map(leaves.map((leaf) => [leaf.path.join('.'), leaf.env]))\n\n const load = (env: NodeJS.ProcessEnv = process.env): T => {\n const source = readSecretFiles ? readSecretFiles(env, envNames) : env\n const input: Record<string, unknown> = {}\n for (const leaf of leaves) {\n const raw = source[leaf.env]\n if (raw === undefined) continue\n let target = input\n for (const key of leaf.path.slice(0, -1)) {\n target = (target[key] ??= {}) as Record<string, unknown>\n }\n target[leaf.path.at(-1)!] = leaf.list\n ? raw\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean)\n : raw\n }\n return validate(input)\n }\n\n const validate = (input: unknown): T => {\n const result = wrapped.safeParse(input)\n if (result.success) return result.data as T\n const problems = result.issues.map((issue) => {\n const key = issue.path.join('.')\n // The variable to fix, not the schema path; a nested object that is\n // missing entirely names its prefix.\n const name =\n byPath.get(key) ?? [prefix, ...issue.path.map((p) => envSegment(String(p)))].join('_')\n return ` ${name}: ${issue.message}`\n })\n throw new Error(`Settings '${prefix}' are invalid:\\n${problems.join('\\n')}`)\n }\n\n const scopes = new Map<string, Settings<T>>()\n const settings: Settings<T> = Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name: `Settings(${prefix})`,\n prefix,\n envNames,\n load,\n parse: (value: unknown): T => validate(value),\n provide: (value: unknown): ProvidedSettings<T> =>\n Object.freeze({ [PROVIDED]: true as const, section: settings, value }),\n describe: () => leaves.map(toConfigVar),\n get: (): T => {\n // What injected code sees: the container's binding, which a module or a\n // test may have replaced. Before the app binds it, the validated env.\n const container = Container.getInstance()\n if (container.has(settings)) return container.resolve(settings) as T\n // Keyed by the section, not its prefix: two sections sharing a prefix\n // each parse their own schema.\n if (!cached.has(settings)) cached.set(settings, load())\n return cached.get(settings) as T\n },\n scoped: (name: string): Settings<T> => {\n const scopePrefix = `${name}_${prefix}`\n let scoped = scopes.get(scopePrefix)\n if (!scoped) {\n scoped = createSection(scopePrefix, schema) as Settings<T>\n scopes.set(scopePrefix, scoped)\n }\n return scoped\n },\n }) as Settings<T>\n return settings\n}\n\n/**\n * Validate the given sections — the ones the app declared — throwing once\n * with every problem, so a misconfigured deploy fails at startup with the\n * whole list. A section declared twice is loaded once; two different sections\n * with one prefix would read the same variables, and are refused.\n */\nexport function loadSettings(\n declarations: Iterable<SettingsDeclaration>,\n env: NodeJS.ProcessEnv = process.env,\n /**\n * Prefixes already taken, across calls — an app binds in two phases (app\n * sections, then modules') and a clash between them must still be refused.\n */\n byPrefix: Map<string, Settings<unknown>> = new Map(),\n /** Values passed to `provide()`, across calls — same reason as `byPrefix`. */\n providedBefore: Map<Settings<unknown>, unknown> = new Map(),\n): Map<Settings<unknown>, unknown> {\n const values = new Map<Settings<unknown>, unknown>()\n const failures: string[] = []\n // A provided value wins over the same section read from env, wherever each\n // was declared — a test's provide() must not lose to a module's section.\n const provided = new Map<Settings<unknown>, unknown>()\n const sections: Settings<unknown>[] = []\n for (const decl of declarations) {\n if (isProvided(decl)) {\n // Two provides of one section would silently keep whichever came last.\n const earlier = provided.has(decl.section) ? provided : providedBefore\n if (earlier.has(decl.section) && earlier.get(decl.section) !== decl.value) {\n failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`)\n continue\n }\n provided.set(decl.section, decl.value)\n sections.push(decl.section)\n } else {\n sections.push(decl)\n }\n }\n for (const section of sections) {\n if (values.has(section)) continue\n const other = byPrefix.get(section.prefix)\n // Already bound in an earlier phase: nothing to do — unless that read env\n // and this phase provides a value, which wins.\n if (other === section && !(provided.has(section) && !providedBefore.has(section))) continue\n if (other && other !== section) {\n failures.push(`Two different settings sections use the prefix '${section.prefix}'.`)\n continue\n }\n byPrefix.set(section.prefix, section)\n try {\n const value = provided.has(section) ? section.parse(provided.get(section)) : section.load(env)\n values.set(section, value)\n if (provided.has(section)) providedBefore.set(section, provided.get(section))\n // `get()` returns what the app started with.\n cached.set(section, value)\n } catch (err) {\n failures.push((err as Error).message)\n }\n }\n if (failures.length > 0) throw new Error(failures.join('\\n'))\n return values\n}\n"],"mappings":";;;;;;;;;;oJAsBA,IAAI,gBAGJ,SAAgB,qBAAqB,OAAgC,CACnE,gBAAkB,MACpB,CAuCA,MAAM,SAAW,OAAO,IAAI,0BAA0B,EAYtD,SAAS,WAAW,KAA8D,CAChF,OAAQ,KAA4C,YAAc,EACpE,CAqCA,MAAM,WAAc,KAAgB,IAAI,QAAQ,qBAAsB,OAAO,CAAC,CAAC,YAAY,EAO3F,SAAS,SAAS,MAAkB,OAAgB,KAAiB,CAAC,EAAG,SAAW,GAAc,CAChG,GAAI,MAAM,WAAY,CACpB,IAAM,IAAM,IAAI,IAAI,MAAM,UAAY,CAAC,CAAC,EAClC,eAAiB,UAAY,MAAM,UAAY,IAAA,GACrD,OAAO,OAAO,QAAQ,MAAM,UAAU,CAAC,CAAC,SAAS,CAAC,IAAK,SACrD,SAAS,MAAO,OAAQ,CAAC,GAAG,KAAM,GAAG,EAAG,gBAAkB,IAAI,IAAI,GAAG,CAAC,CACxE,CACF,CACA,IAAM,MAAQ,MAAM,QAAQ,MAAM,IAAI,EAAI,MAAM,KAAO,CAAC,MAAM,IAAI,EAClE,MAAO,CACL,CACE,KACA,IAAK,CAAC,OAAQ,GAAG,KAAK,IAAI,UAAU,CAAC,CAAC,CAAC,KAAK,GAAG,EAC/C,KAAM,MAAM,SAAS,OAAO,EAC5B,SAAU,UAAY,MAAM,UAAY,IAAA,GACxC,GAAI,MAAM,UAAY,IAAA,GAAyC,CAAC,EAA9B,CAAE,QAAS,MAAM,OAAQ,EAC3D,GAAI,MAAM,YAAc,CAAE,YAAa,MAAM,WAAY,EAAI,CAAC,CAChE,CACF,CACF,CAEA,MAAM,YAAe,OAA2B,CAC9C,KAAM,KAAK,IACX,SAAU,KAAK,SACf,KAAM,KAAK,K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MACE,SAAS,KAAK,IAAI,EAGtB,IAAK,IAAM,WAAW,SAAU,CAC9B,GAAI,OAAO,IAAI,OAAO,EAAG,SACzB,IAAM,MAAQ,SAAS,IAAI,QAAQ,MAAM,EAGzC,GAAI,QAAU,SAAa,SAAS,IAAI,OAAO,GAAM,gBAAe,IAAI,OAAO,EAC/E,IAAI,OAAS,QAAU,QACrB,SAAS,KAAK,mDAAmD,QAAQ,OAAO,GAAG,MAGrF,UAAS,IAAI,QAAQ,OAAQ,OAAO,EACpC,GAAI,CACF,IAAM,MAAQ,SAAS,IAAI,OAAO,EAAI,QAAQ,MAAM,SAAS,IAAI,OAAO,CAAC,EAAI,QAAQ,KAAK,GAAG,EAC7F,OAAO,IAAI,QAAS,KAAK,EACrB,SAAS,IAAI,OAAO,GAAG,eAAe,IAAI,QAAS,SAAS,IAAI,OAAO,CAAC,EAE5E,OAAO,IAAI,QAAS,KAAK,CAC3B,OAAS,IAAK,CACZ,SAAS,KAAM,IAAc,OAAO,CACtC,CAToC,CADpC,CAWF,CACA,GAAI,SAAS,OAAS,EAAG,MAAU,MAAM,SAAS,KAAK;CAAI,CAAC,EAC5D,OAAO,MACT"}
1
+ {"version":3,"file":"settings-CJWJPERr.mjs","names":[],"sources":["../src/config/settings.ts"],"sourcesContent":["/**\n * Typed configuration sections: one schema per concern (`DB`, `MAIL`,\n * `STORAGE`), each read from its own prefix of the environment and injected\n * where it's needed — instead of one flat env every service reaches into.\n * Spring's `@ConfigurationProperties`, for any schema `@forinda/kickjs-schema`\n * reads — Zod, Valibot, Yup.\n *\n * @module @forinda/kickjs/config/settings\n */\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { INJECTION_TOKEN, type InjectionToken } from '../core/token'\nimport { Container } from '../core/container'\n\n/**\n * Reads `<NAME>_FILE` secrets. Registered by `./env` (Node only) when it\n * loads — this module imports nothing node-only, so the web entry can use it;\n * there, `_FILE` variables are simply not read.\n */\ntype SecretFileReader = (\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n) => Record<string, string | undefined>\nlet readSecretFiles: SecretFileReader | undefined\n\n/** @internal */\nexport function _useSecretFileReader(reader: SecretFileReader): void {\n readSecretFiles = reader\n}\n\n/** A section: an injection token that also knows how to load itself. */\nexport interface Settings<T> extends InjectionToken<T> {\n /** The env prefix, e.g. `'DB'`. */\n readonly prefix: string\n /** Every env name the section reads, e.g. `['DB_URL', 'DB_POOL_MAX']`. */\n readonly envNames: readonly string[]\n /**\n * The section's value — validated at startup, then cached. Before startup\n * (a script, a CLI command) the first call loads and validates it.\n */\n get(): T\n /** Parse the section from `env` (default `process.env`) afresh; throws listing every problem. */\n load(env?: NodeJS.ProcessEnv): T\n /** Each variable the section reads — required or not, default, description. Reads no env. */\n describe(): ConfigVar[]\n /** Validate a value you supply against the schema — defaults applied — instead of reading env. */\n parse(value: unknown): T\n /**\n * Declare the section with a value you supply instead of the environment —\n * a test's container, a service you started, a secret manager's answer.\n * Validated against the schema like env values; bound under this section's\n * token, so everything injecting it gets the provided value.\n *\n * ```ts\n * const pg = await startService('postgres')\n * await createTestApp({ modules, settings: [DbSettings.provide({ url: pg.url })] })\n * ```\n */\n provide(value: unknown): ProvidedSettings<T>\n /**\n * The same schema under another prefix, for a second instance:\n * `DbSettings.scoped('ANALYTICS')` reads `ANALYTICS_DB_*` beside `DB_*`.\n * Returns the same token for the same name.\n */\n scoped(name: string): Settings<T>\n}\n\nconst PROVIDED = Symbol.for('kickjs.settings.provided')\n\n/** A section declared with a supplied value — see {@link Settings.provide}. */\nexport interface ProvidedSettings<T> {\n readonly [PROVIDED]: true\n readonly section: Settings<T>\n readonly value: unknown\n}\n\n/** What a `settings` list accepts: a section (read from env) or a provided one. */\nexport type SettingsDeclaration = Settings<unknown> | ProvidedSettings<unknown>\n\nfunction isProvided(decl: SettingsDeclaration): decl is ProvidedSettings<unknown> {\n return (decl as Partial<ProvidedSettings<unknown>>)[PROVIDED] === true\n}\n\n/** The value type of a section: `SettingsOf<typeof DbSettings>`. */\nexport type SettingsOf<S> = S extends Settings<infer T> ? T : never\n\ninterface Leaf {\n path: string[]\n env: string\n list: boolean\n required: boolean\n default?: unknown\n description?: string\n}\n\n/** One variable, as `describe()` and `app.describeConfig()` report it. */\nexport interface ConfigVar {\n name: string\n /** Startup fails without it: required by the schema, with no default. */\n required: boolean\n /** The schema's default, when it has one. */\n default?: unknown\n /** The schema's description (`.describe('…')` in Zod). */\n description?: string\n /** Read as a comma-separated list. */\n list: boolean\n}\n\n/** The part of a JSON schema the env mapping reads. */\ninterface JsonShape {\n type?: string | string[]\n properties?: Record<string, JsonShape>\n required?: string[]\n default?: unknown\n description?: string\n}\n\n/** `maxConnections` → `MAX_CONNECTIONS`. */\nconst envSegment = (key: string) => key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()\n\n/**\n * The variables a JSON-schema shape reads. A leaf is required when every\n * object on its path is required by its parent and none of them (nor the leaf)\n * has a default — a defaulted parent object supplies its children.\n */\nfunction leavesOf(shape: JsonShape, prefix: string, path: string[] = [], required = true): Leaf[] {\n if (shape.properties) {\n const own = new Set(shape.required ?? [])\n const parentRequired = required && shape.default === undefined\n return Object.entries(shape.properties).flatMap(([key, child]) =>\n leavesOf(child, prefix, [...path, key], parentRequired && own.has(key)),\n )\n }\n const types = Array.isArray(shape.type) ? shape.type : [shape.type]\n return [\n {\n path,\n env: [prefix, ...path.map(envSegment)].join('_'),\n list: types.includes('array'),\n required: required && shape.default === undefined,\n ...(shape.default !== undefined ? { default: shape.default } : {}),\n ...(shape.description ? { description: shape.description } : {}),\n },\n ]\n}\n\nconst toConfigVar = (leaf: Leaf): ConfigVar => ({\n name: leaf.env,\n required: leaf.required,\n list: leaf.list,\n ...(leaf.default !== undefined ? { default: leaf.default } : {}),\n ...(leaf.description ? { description: leaf.description } : {}),\n})\n\n/**\n * The variables of a flat schema (the app's env schema), described the same\n * way — no prefix, top-level keys only.\n */\nexport function describeSchemaVars(schema: unknown): ConfigVar[] {\n const shape = detectSchema(schema).toJsonSchema() as JsonShape\n const required = new Set(shape.required ?? [])\n // The keys of an env schema are the variable names themselves.\n return Object.entries(shape.properties ?? {}).map(([key, child]) => {\n // A fresh object from toConfigVar — safe to set the name on directly.\n const described = toConfigVar(leavesOf(child, '', [key], required.has(key))[0])\n described.name = key\n return described\n })\n}\n\n/** Where a variable's value comes from. */\nexport type ValueOrigin = 'env' | 'file' | 'provided' | 'default' | 'unset'\n\n/** A variable and where its value comes from — never the value itself. */\nexport interface VarOrigin {\n name: string\n origin: ValueOrigin\n}\n\n/**\n * Where each variable's value comes from in `env`: set directly, read from\n * `<NAME>_FILE`, the schema's default, or not set at all. Names only — safe\n * to show where the values themselves must not appear.\n */\nexport function originsOf(\n vars: readonly ConfigVar[],\n env: NodeJS.ProcessEnv = process.env,\n): VarOrigin[] {\n // Empty counts as unset, as the secret-file reader treats it.\n const has = (name: string) => env[name] !== undefined && env[name] !== ''\n return vars.map((v) => {\n let origin: ValueOrigin = 'unset'\n if (has(v.name)) origin = 'env'\n // `_FILE` is only read where a reader is registered (Node, not the web entry).\n else if (readSecretFiles && has(`${v.name}_FILE`)) origin = 'file'\n else if (v.default !== undefined) origin = 'default'\n return { name: v.name, origin }\n })\n}\n\n/** Values validated at startup (or on first `get()`), by prefix. */\nconst cached = new WeakMap<Settings<unknown>, unknown>()\n\n/**\n * Define a typed configuration section read from env variables with a prefix.\n * Each key path becomes one variable: `pool.max` under `'DB'` is `DB_POOL_MAX`,\n * `maxConnections` is `DB_MAX_CONNECTIONS`. A list reads a comma-separated\n * value. `<NAME>_FILE` secrets work for every variable.\n *\n * ```ts\n * export const DbSettings = defineSettings('DB', z.object({\n * url: z.string().url(),\n * pool: z.object({ max: z.coerce.number().default(10) }).default({ max: 10 }),\n * }))\n *\n * @Service()\n * class Database {\n * constructor(@Inject(DbSettings) private readonly db: SettingsOf<typeof DbSettings>) {}\n * }\n * ```\n *\n * Declare it where it's used — `bootstrap({ settings })`, a module's, adapter's\n * or plugin's `settings()` — and it is validated when the app starts (a\n * missing or invalid value fails startup, naming the variable) and injectable\n * by its token. Undeclared, `get()` validates it on first use. Values\n * come from the schema's coercion: use `z.coerce.number()`, and\n * `z.stringbool()` for booleans (`z.coerce.boolean()` reads `'false'` as true).\n */\nexport function defineSettings<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n return createSection(prefix, schema)\n}\n\nfunction createSection<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n type T = InferSchemaOutput<S>\n if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) {\n throw new Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`)\n }\n const wrapped = detectSchema(schema)\n // The env names come from the schema's shape, read through its JSON schema —\n // the one view every adapter (Zod, Valibot, Yup) provides.\n const shape = wrapped.toJsonSchema() as JsonShape\n if (!shape.properties) {\n throw new Error(\n `defineSettings('${prefix}'): the schema must be an object whose keys can be read ` +\n '(Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.',\n )\n }\n const leaves = leavesOf(shape, prefix)\n // `fooBar` and `foo_bar` would both read `DB_FOO_BAR` — one variable for two\n // settings that could never differ. Refuse it here, naming both paths.\n const seenEnv = new Map<string, string>()\n for (const leaf of leaves) {\n const path = leaf.path.join('.')\n const other = seenEnv.get(leaf.env)\n if (other !== undefined) {\n throw new Error(\n `defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`,\n )\n }\n seenEnv.set(leaf.env, path)\n }\n const envNames = leaves.map((leaf) => leaf.env)\n const byPath = new Map(leaves.map((leaf) => [leaf.path.join('.'), leaf.env]))\n\n const load = (env: NodeJS.ProcessEnv = process.env): T => {\n const source = readSecretFiles ? readSecretFiles(env, envNames) : env\n const input: Record<string, unknown> = {}\n for (const leaf of leaves) {\n const raw = source[leaf.env]\n if (raw === undefined) continue\n let target = input\n for (const key of leaf.path.slice(0, -1)) {\n target = (target[key] ??= {}) as Record<string, unknown>\n }\n target[leaf.path.at(-1)!] = leaf.list\n ? raw\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean)\n : raw\n }\n return validate(input)\n }\n\n const validate = (input: unknown): T => {\n const result = wrapped.safeParse(input)\n if (result.success) return result.data as T\n const problems = result.issues.map((issue) => {\n const key = issue.path.join('.')\n // The variable to fix, not the schema path; a nested object that is\n // missing entirely names its prefix.\n const name =\n byPath.get(key) ?? [prefix, ...issue.path.map((p) => envSegment(String(p)))].join('_')\n return ` ${name}: ${issue.message}`\n })\n throw new Error(`Settings '${prefix}' are invalid:\\n${problems.join('\\n')}`)\n }\n\n const scopes = new Map<string, Settings<T>>()\n const settings: Settings<T> = Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name: `Settings(${prefix})`,\n prefix,\n envNames,\n load,\n parse: (value: unknown): T => validate(value),\n provide: (value: unknown): ProvidedSettings<T> =>\n Object.freeze({ [PROVIDED]: true as const, section: settings, value }),\n describe: () => leaves.map(toConfigVar),\n get: (): T => {\n // What injected code sees: the container's binding, which a module or a\n // test may have replaced. Before the app binds it, the validated env.\n const container = Container.getInstance()\n if (container.has(settings)) return container.resolve(settings) as T\n // Keyed by the section, not its prefix: two sections sharing a prefix\n // each parse their own schema.\n if (!cached.has(settings)) cached.set(settings, load())\n return cached.get(settings) as T\n },\n scoped: (name: string): Settings<T> => {\n const scopePrefix = `${name}_${prefix}`\n let scoped = scopes.get(scopePrefix)\n if (!scoped) {\n scoped = createSection(scopePrefix, schema) as Settings<T>\n scopes.set(scopePrefix, scoped)\n }\n return scoped\n },\n }) as Settings<T>\n return settings\n}\n\n/**\n * Validate the given sections — the ones the app declared — throwing once\n * with every problem, so a misconfigured deploy fails at startup with the\n * whole list. A section declared twice is loaded once; two different sections\n * with one prefix would read the same variables, and are refused.\n */\nexport function loadSettings(\n declarations: Iterable<SettingsDeclaration>,\n env: NodeJS.ProcessEnv = process.env,\n /**\n * Prefixes already taken, across calls — an app binds in two phases (app\n * sections, then modules') and a clash between them must still be refused.\n */\n byPrefix: Map<string, Settings<unknown>> = new Map(),\n /** Values passed to `provide()`, across calls — same reason as `byPrefix`. */\n providedBefore: Map<Settings<unknown>, unknown> = new Map(),\n): Map<Settings<unknown>, unknown> {\n const values = new Map<Settings<unknown>, unknown>()\n const failures: string[] = []\n // A provided value wins over the same section read from env, wherever each\n // was declared — a test's provide() must not lose to a module's section.\n const provided = new Map<Settings<unknown>, unknown>()\n const sections: Settings<unknown>[] = []\n for (const decl of declarations) {\n if (isProvided(decl)) {\n // Two provides of one section would silently keep whichever came last.\n const earlier = provided.has(decl.section) ? provided : providedBefore\n if (earlier.has(decl.section) && earlier.get(decl.section) !== decl.value) {\n failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`)\n continue\n }\n provided.set(decl.section, decl.value)\n sections.push(decl.section)\n } else {\n sections.push(decl)\n }\n }\n for (const section of sections) {\n if (values.has(section)) continue\n const other = byPrefix.get(section.prefix)\n // Already bound in an earlier phase: nothing to do — unless that read env\n // and this phase provides a value, which wins.\n if (other === section && !(provided.has(section) && !providedBefore.has(section))) continue\n if (other && other !== section) {\n failures.push(`Two different settings sections use the prefix '${section.prefix}'.`)\n continue\n }\n byPrefix.set(section.prefix, section)\n try {\n const value = provided.has(section) ? section.parse(provided.get(section)) : section.load(env)\n values.set(section, value)\n if (provided.has(section)) providedBefore.set(section, provided.get(section))\n // `get()` returns what the app started with.\n cached.set(section, value)\n } catch (err) {\n failures.push((err as Error).message)\n }\n }\n if (failures.length > 0) throw new Error(failures.join('\\n'))\n return values\n}\n"],"mappings":";;;;;;;;;;oJAsBA,IAAI,gBAGJ,SAAgB,qBAAqB,OAAgC,CACnE,gBAAkB,MACpB,CAuCA,MAAM,SAAW,OAAO,IAAI,0BAA0B,EAYtD,SAAS,WAAW,KAA8D,CAChF,OAAQ,KAA4C,YAAc,EACpE,CAqCA,MAAM,WAAc,KAAgB,IAAI,QAAQ,qBAAsB,OAAO,CAAC,CAAC,YAAY,EAO3F,SAAS,SAAS,MAAkB,OAAgB,KAAiB,CA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I,QAAS,KAAK,EACrB,SAAS,IAAI,OAAO,GAAG,eAAe,IAAI,QAAS,SAAS,IAAI,OAAO,CAAC,EAE5E,OAAO,IAAI,QAAS,KAAK,CAC3B,OAAS,IAAK,CACZ,SAAS,KAAM,IAAc,OAAO,CACtC,CAToC,CADpC,CAWF,CACA,GAAI,SAAS,OAAS,EAAG,MAAU,MAAM,SAAS,KAAK;CAAI,CAAC,EAC5D,OAAO,MACT"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.11.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,6 +1,6 @@
1
1
 
2
2
  import { g as FileUploadConfig, o as BaseUploadOptions } from "./decorators-DxNb5mWw.mjs";
3
- import { j as UploadStorageEngine } from "./adapter-DLjn8q0c.mjs";
3
+ import { j as UploadStorageEngine } from "./adapter-DiJfCKXU.mjs";
4
4
  import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse } from "./connect-BlIamapT.mjs";
5
5
  //#region src/http/middleware/upload.d.ts
6
6
  /**
@@ -52,4 +52,4 @@ declare const upload: {
52
52
  };
53
53
  //#endregion
54
54
  export { upload as i, buildUploadMiddleware as n, cleanupFiles as r, UploadOptions as t };
55
- //# sourceMappingURL=upload-DtQ1pdQw.d.mts.map
55
+ //# sourceMappingURL=upload-C9IfY1aQ.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload-DtQ1pdQw.d.mts","names":["RequestHandler","Request","Response","NextFunction"],"sources":["../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;;UA+DiB,sBAAsB;;EAErC,UAAU;;EAEV;;iBAkMO,OAAO,mBAAmB,UAAS,gBAAqBA;;;;iBAcxD,MAAM,mBAAmB,mBAAe,UAAS,gBAAqBA;;;;iBAiBtE,KAAK,UAAS,gBAAqBA;;;;;;;;;;;;;;;iBAoB5B,iBAAY,KACbC,gBAAO,KAAOC,iBAAQ,MAAQC;;;;;;iBA+B7B,sBAAsB,QAAQ,mBAAmBH;;cAoBpD"}
1
+ {"version":3,"file":"upload-C9IfY1aQ.d.mts","names":["RequestHandler","Request","Response","NextFunction"],"sources":["../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;;UA+DiB,sBAAsB;;EAErC,UAAU;;EAEV;;iBAkMO,OAAO,mBAAmB,UAAS,gBAAqBA;;;;iBAcxD,MAAM,mBAAmB,mBAAe,UAAS,gBAAqBA;;;;iBAiBtE,KAAK,UAAS,gBAAqBA;;;;;;;;;;;;;;;iBAoB5B,iBAAY,KACbC,gBAAO,KAAOC,iBAAQ,MAAQC;;;;;;iBA+B7B,sBAAsB,QAAQ,mBAAmBH;;cAoBpD"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.11.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  import{HttpException,HttpStatus}from"./core/errors.mjs";const MIME_MAP={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,bmp:`image/bmp`,ico:`image/x-icon`,tiff:`image/tiff`,tif:`image/tiff`,avif:`image/avif`,pdf:`application/pdf`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,txt:`text/plain`,csv:`text/csv`,zip:`application/zip`,gz:`application/gzip`,tar:`application/x-tar`,rar:`application/vnd.rar`,"7z":`application/x-7z-compressed`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,flac:`audio/flac`,aac:`audio/aac`,mp4:`video/mp4`,webm:`video/webm`,avi:`video/x-msvideo`,mov:`video/quicktime`,mkv:`video/x-matroska`,json:`application/json`,xml:`application/xml`,html:`text/html`};function resolveMimeTypes(types){return types.map(t=>{let lower=t.toLowerCase().replace(/^\./,``);return MIME_MAP[lower]??t})}function buildFileTypeFilter(allowedTypes,customMimeMap){if(!allowedTypes)return()=>!0;if(typeof allowedTypes==`function`)return allowedTypes;let mimeMap=customMimeMap?{...MIME_MAP,...customMimeMap}:MIME_MAP,resolved=allowedTypes.map(t=>mimeMap[t.toLowerCase().replace(/^\./,``)]??t);return mimetype=>resolved.some(type=>type.endsWith(`/*`)?mimetype.startsWith(type.replace(`/*`,`/`)):mimetype===type)}const DEFAULT_MAX_SIZE=5242880;function normalizeOriginalName(name){return(name.normalize(`NFC`).split(/[\\/]/).pop()??``).replace(/[\u0000-\u001f\u007f]/g,``).trim()}function matchingExtension(name,mimetype,customMimeMap){let dot=name.lastIndexOf(`.`);if(dot<=0)return``;let ext=name.slice(dot+1).toLowerCase(),type=mimetype.split(`;`)[0].trim().toLowerCase();return(customMimeMap?.[ext]??MIME_MAP[ext])===type?`.${ext}`:``}function serverFileName(file,options={}){let{rename,customMimeMap}=options;if(!rename){let ext=matchingExtension(file.originalname,file.mimetype,customMimeMap);return`${globalThis.crypto.randomUUID()}${ext}`}let name=rename(file);if(typeof name!=`string`||name===``||name===`.`||name===`..`||name.length>255||/[\\/\0]/.test(name))throw Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`);return name}const UPLOAD_FIELDS_ALLOWANCE=1048576,MAX_UPLOAD_FIELDS=1e3;function uploadLimits(config){let fileSize=config.maxSize??DEFAULT_MAX_SIZE,files=config.mode===`none`?0:config.mode===`single`?1:config.maxCount??10;return{fileSize,files,total:fileSize*files+UPLOAD_FIELDS_ALLOWANCE}}function tooManyFiles(limit){return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`Too many files: at most ${limit}`)}function applyUploadConfig(parts,config){if(config.mode===`none`)return{};let field=config.fieldName??`file`,maxSize=config.maxSize??DEFAULT_MAX_SIZE,typeAllowed=buildFileTypeFilter(config.allowedTypes,config.customMimeMap),files=parts.filter(p=>p.fieldname===field).map(p=>{if(!typeAllowed(p.mimetype,p.filename))throw new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${p.mimetype} is not allowed`);if(p.buffer.length>maxSize)throw new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${p.filename} exceeds the ${maxSize}-byte limit`);let named={fieldname:p.fieldname,originalname:normalizeOriginalName(p.filename),mimetype:p.mimetype,size:p.buffer.length};return{...named,filename:serverFileName(named,config),encoding:`7bit`,buffer:p.buffer}});if(config.mode===`single`)return{file:files[0]};let maxCount=config.maxCount??10;return{files:files.slice(0,maxCount)}}export{normalizeOriginalName as a,tooManyFiles as c,buildFileTypeFilter as i,uploadLimits as l,UPLOAD_FIELDS_ALLOWANCE as n,resolveMimeTypes as o,applyUploadConfig as r,serverFileName as s,MAX_UPLOAD_FIELDS as t};
12
- //# sourceMappingURL=upload-config-d_LW2u9b.mjs.map
12
+ //# sourceMappingURL=upload-config-DldXNOHe.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload-config-d_LW2u9b.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":";;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EAG3E,MADU,MAAM,OAAQ,GAAM,EAAE,YAAc,KACZ,CAAC,CAAC,IAAK,GAAM,CACnD,GAAI,CAAC,YAAY,EAAE,SAAU,EAAE,QAAQ,EACrC,MAAM,IAAI,cACR,WAAW,uBACX,aAAa,EAAE,SAAS,gBAC1B,EAEF,GAAI,EAAE,OAAO,OAAS,QACpB,MAAM,IAAI,cACR,WAAW,kBACX,QAAQ,EAAE,SAAS,eAAe,QAAQ,YAC5C,EAEF,IAAM,MAAQ,CACZ,UAAW,EAAE,UACb,aAAc,sBAAsB,EAAE,QAAQ,EAC9C,SAAU,EAAE,SACZ,KAAM,EAAE,OAAO,MACjB,EACA,MAAO,CACL,GAAG,MACH,SAAU,eAAe,MAAO,MAAM,EACtC,SAAU,OACV,OAAQ,EAAE,MACZ,CACF,CAAC,EAED,GAAI,OAAO,OAAS,SAAU,MAAO,CAAE,KAAM,MAAM,EAAG,EACtD,IAAM,SAAW,OAAO,UAAY,GACpC,MAAO,CAAE,MAAO,MAAM,MAAM,EAAG,QAAQ,CAAE,CAC3C"}
1
+ {"version":3,"file":"upload-config-DldXNOHe.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":";;;;;;;;;;wDAUA,MAAa,SAAmC,CAE9C,IAAK,aACL,KAAM,aACN,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,gBACL,IAAK,YACL,IAAK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Q,EACrC,MAAM,IAAI,cACR,WAAW,uBACX,aAAa,EAAE,SAAS,gBAC1B,EAEF,GAAI,EAAE,OAAO,OAAS,QACpB,MAAM,IAAI,cACR,WAAW,kBACX,QAAQ,EAAE,SAAS,eAAe,QAAQ,YAC5C,EAEF,IAAM,MAAQ,CACZ,UAAW,EAAE,UACb,aAAc,sBAAsB,EAAE,QAAQ,EAC9C,SAAU,EAAE,SACZ,KAAM,EAAE,OAAO,MACjB,EACA,MAAO,CACL,GAAG,MACH,SAAU,eAAe,MAAO,MAAM,EACtC,SAAU,OACV,OAAQ,EAAE,MACZ,CACF,CAAC,EAED,GAAI,OAAO,OAAS,SAAU,MAAO,CAAE,KAAM,MAAM,EAAG,EACtD,IAAM,SAAW,OAAO,UAAY,GACpC,MAAO,CAAE,MAAO,MAAM,MAAM,EAAG,QAAQ,CAAE,CAC3C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.11.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as createToken}from"./token-CBe6OMQK.mjs";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}function moduleName(mod){let{__moduleName,name}=mod;if(typeof __moduleName==`string`&&__moduleName)return __moduleName;if(typeof name==`string`&&name)return name;let ctorName=mod.constructor?.name;return ctorName&&ctorName!==`Object`?ctorName:`module`}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);let path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{moduleName as a,defineModule as i,RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
12
- //# sourceMappingURL=url-for-Df_ts-iM.mjs.map
11
+ import{n as createToken}from"./token-kfP7I0D6.mjs";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}function moduleName(mod){let{__moduleName,name}=mod;if(typeof __moduleName==`string`&&__moduleName)return __moduleName;if(typeof name==`string`&&name)return name;let ctorName=mod.constructor?.name;return ctorName&&ctorName!==`Object`?ctorName:`module`}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);let path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{moduleName as a,defineModule as i,RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
12
+ //# sourceMappingURL=url-for-O-DQnRvH.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"url-for-Df_ts-iM.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/** `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>, query?: UrlQuery]\n : [params: ParamsOf<N>, 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> | undefined, query)\n }\n\n build(name: string, params?: Record<string, unknown>, query?: UrlQuery): 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 const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = params?.[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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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-O-DQnRvH.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/** `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>, query?: UrlQuery]\n : [params: ParamsOf<N>, 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> | undefined, query)\n }\n\n build(name: string, params?: Record<string, unknown>, query?: UrlQuery): 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 const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = params?.[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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,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,OAA+C,KAAK,CAC9E,CAEA,MAAM,KAAc,OAAkC,MAA0B,CAC9E,IAAM,QAAU,KAAK,MAAM,IAAI,IAAI,EACnC,GAAI,UAAY,IAAA,GACd,MAAU,MAAM,2BAA2B,KAAK,iCAAiC,EAEnF,IAAM,KAAO,QAAQ,QAAQ,qBAAsB,EAAG,MAAgB,CACpE,IAAM,MAAQ,SAAS,KACvB,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.10.0
2
+ * @forinda/kickjs v10.11.0
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-Bjs-1F1Z.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())}export{getRequestStore as a,waitUntil as i,pendingBackgroundWork as n,getRequestValue as o,settleBackgroundWork as r,requestStore as s,forwardBackgroundWork as t};
12
- //# sourceMappingURL=background-CiKEgaD2.mjs.map
11
+ import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-BbNYzGfC.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-NbkTobFF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"view-renderer-NbkTobFF.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.10.0
2
+ * @forinda/kickjs v10.11.0
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-BNF60ZAh.mjs.map
12
+ //# sourceMappingURL=web-crypto-BNP8o7BF.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-crypto-BNF60ZAh.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-BNP8o7BF.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.d.mts CHANGED
@@ -1,10 +1,10 @@
1
1
 
2
2
  import { i as SettingsDeclaration } from "./settings-BFQisfqG.mjs";
3
3
  import { x as MiddlewareHandler } from "./decorators-DxNb5mWw.mjs";
4
- import { O as SseHandler, h as RouteEntry, x as RuntimeResponse } from "./adapter-DLjn8q0c.mjs";
4
+ import { O as SseHandler, h as RouteEntry, x as RuntimeResponse } from "./adapter-DiJfCKXU.mjs";
5
5
  import { m as ContributorRegistrations, r as AppModuleEntry } from "./app-module-Bk3glnPP.mjs";
6
6
  import { f as runCronJobs, o as CronRun } from "./cron-BTGytNg-.mjs";
7
- import { E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, S as JOB_CONTEXT_FIELD, a as KvSessionStoreOptions, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, x as reply, y as isReply } from "./kv-stores-DJBnGQsJ.mjs";
7
+ import { E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, S as JOB_CONTEXT_FIELD, a as KvSessionStoreOptions, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, x as reply, y as isReply } from "./kv-stores-BN7c9bt9.mjs";
8
8
  import { t as ValidationErrorFactory } from "./validate-D4Poe2EE.mjs";
9
9
  //#region src/http/web/driver.d.ts
10
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"web.d.mts","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts","../src/web.ts"],"mappings":";;;;;;;;;;;;;;;;qBAgBa;WACF;WACA;;WAEA,SAAS;EAClB;EACA,QAAQ;EACR,OAAO;EACP;EACA;EACA;GAGC;mBAEgB;EAEjB,YAAY,SAAS,SAAS,KAAK;;EAmBnC,KAAK,eAAe;;EAMpB,GAAG,eAAe;;qBA6BP,6BAA6B;mBAYX;;WAVpB,OAAO,QAAQ;;EAExB;UAEQ;mBACS;UACT;UACA;UACA;EAER,YAA6B,SAAS;EAMtC,OAAO;EAKP,KAAK;EAML,KAAK;EAYL,KAAK;;EAML,UAAU;EAQV,UAAU,cAAc;EAUxB;EAIA,UAAU,oBAAoB,UAAU;EASxC;EAKA,MAAM;EAQN,IAAI;EAUJ,KAAK,eAAe,cAAc;MAM9B;;UAKI;;UAuBA;;;;UCzLO;EACf,SAAS;EACT,KAAK;EACL,QAAQ;;;;;;;EAOR;;UAGe;;;;;;;;EAQf,WAAW,cAAc,KAAK,gBAAgB,KAAK,6BAA6B;;wBAwClE,gBACd,OAAO,YACP,QAAQ,eACR;EAAW;KACT,YAAY,uBAAuB,QAAQ;;;iBCT9B;;;;;;;EAOf;;EAEA,SAAS;;EAET;;;;;EAKA;;EAEA,eAAe;;;;;;EAMf,MAAM;;;;;;EAMN,cAAc;;;;;EAKd;;EAEA,WAAW;;EAEX,kBAAkB;;iBAGH;;;;;;EAMf,QAAQ,SAAS,SAAS,WAAW,oBAAoB,QAAQ;;EAEjE;;;;;;;;wBASc,aAAa,SAAS,sBAAsB;;;;;;;;;;;;;;;;;;;;;;wBA0J5C,mBACd,QAAQ,KAAK,uCAAuC;EAEpD,QACE,SAAS,SACT,MAAM,oCACN,MAAM,oBACH,QAAQ;EACb,YACE;IAAS;KACT,MAAM,oCACN,MAAM,oBACH;EACL,QACE,OAAO,YACP,MAAM,oCACN,MAAM,oBACH;;;iBAyCU;WACN;WACA,UAAU;aACR;aACA;IACT;IACA"}
1
+ {"version":3,"file":"web.d.mts","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts","../src/web.ts"],"mappings":";;;;;;;;;;;;;;;;qBAgBa;WACF;WACA;;WAEA,SAAS;EAClB;EACA,QAAQ;EACR,OAAO;EACP;EACA;EACA;GAGC;mBAEgB;EAEjB,YAAY,SAAS,SAAS,KAAK;;EAmBnC,KAAK,eAAe;;EAMpB,GAAG,eAAe;;qBA6BP,6BAA6B;mBAYX;;WAVpB,OAAO,QAAQ;;EAExB;UAEQ;mBACS;UACT;UACA;UACA;EAER,YAA6B,SAAS;EAMtC,OAAO;EAKP,KAAK;EAML,KAAK;EAYL,KAAK;;EAML,UAAU;EAQV,UAAU,cAAc;EAUxB;EAIA,UAAU,oBAAoB,UAAU;EASxC;EAKA,MAAM;EAQN,IAAI;EAUJ,KAAK,eAAe,cAAc;MAM9B;;UAKI;;UAuBA;;;;UCzLO;EACf,SAAS;EACT,KAAK;EACL,QAAQ;;;;;;;EAOR;;UAGe;;;;;;;;EAQf,WAAW,cAAc,KAAK,gBAAgB,KAAK,6BAA6B;;wBAwClE,gBACd,OAAO,YACP,QAAQ,eACR;EAAW;KACT,YAAY,uBAAuB,QAAQ;;;iBCT9B;;;;;;;EAOf;;EAEA,SAAS;;EAET;;;;;EAKA;;EAEA,eAAe;;;;;;EAMf,MAAM;;;;;;EAMN,cAAc;;;;;EAKd;;EAEA,WAAW;;EAEX,kBAAkB;;iBAGH;;;;;;EAMf,QAAQ,SAAS,SAAS,WAAW,oBAAoB,QAAQ;;EAEjE;;;;;;;;wBASc,aAAa,SAAS,sBAAsB;;;;;;;;;;;;;;;;;;;;;;wBAsK5C,mBACd,QAAQ,KAAK,uCAAuC;EAEpD,QACE,SAAS,SACT,MAAM,oCACN,MAAM,oBACH,QAAQ;EACb,YACE;IAAS;KACT,MAAM,oCACN,MAAM,oBACH;EACL,QACE,OAAO,YACP,MAAM,oCACN,MAAM,oBACH;;;iBAyCU;WACN;WACA,UAAU;aACR;aACA;IACT;IACA"}
package/dist/web.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.11.0
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-Df_ts-iM.mjs";import{runCronJobs}from"./core/cron.mjs";import{d as stampJobContext,l as registerJobContext,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-bGtYcSgo.mjs";import{buildMountPath}from"./core/path.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-CnCNsI87.mjs";import{t as matchesBearer}from"./web-crypto-BNF60ZAh.mjs";import{o as parseByteSize}from"./body-policy-DIgqprai.mjs";import{i as waitUntil,s as requestStore,t as forwardBackgroundWork}from"./background-CiKEgaD2.mjs";import{notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as loadSettings}from"./settings-Ciut2k76.mjs";import{a as reply,r as isReply}from"./reply-CGn9BmYj.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-DbM-V83V.mjs";import{i as WebResponseDriver,r as WebRequestShim,t as compileWebRoute}from"./handler-C_mWEafU.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,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(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});app.on(entry.method,url,event=>run({request:event.req,url:event.url,params:event.context.params??{}}))}}}finally{_setExternalContributorSources([])}}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-O-DQnRvH.mjs";import{runCronJobs}from"./core/cron.mjs";import{d as stampJobContext,l as registerJobContext,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-B4wle0iS.mjs";import{buildMountPath}from"./core/path.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-DtjsnD0b.mjs";import{t as matchesBearer}from"./web-crypto-BNP8o7BF.mjs";import{o as parseByteSize}from"./body-policy-DccDxmmR.mjs";import{f as requestStore,l as waitUntil,o as forwardBackgroundWork}from"./view-renderer-NbkTobFF.mjs";import{notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as loadSettings}from"./settings-CJWJPERr.mjs";import{a as reply,r as isReply}from"./reply-Detphot1.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-CLR0N5im.mjs";import{a as WebResponseDriver,i as WebRequestShim,n as headFromGet,t as compileWebRoute}from"./handler-Ce16qhGr.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/dist/web.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"web.mjs","names":[],"sources":["../src/web.ts"],"sourcesContent":["// `@forinda/kickjs/web` — the web-standard fetch entry for edge runtimes\n// (Cloudflare Workers), Bun, and Deno.\n//\n// PURITY CONTRACT: this entry's import graph must stay free of node-only\n// runtime imports — no `node:http`, `node:cluster`, `node:fs`, `node:module`,\n// no `express`, no `Application`/`bootstrap`. The single sanctioned node API\n// is `node:async_hooks` (AsyncLocalStorage — available on Workers with\n// `nodejs_compat`, Deno, and Bun). Enforced by the bundle-graph purity test.\n//\n// ```ts\n// // Cloudflare Workers (wrangler.toml: compatibility_flags = [\"nodejs_compat\"])\n// import { createWebApp } from '@forinda/kickjs/web'\n// import * as h3 from 'h3'\n// import { modules } from './modules'\n//\n// const app = createWebApp({ h3, modules })\n// export default { fetch: (req: Request) => app.fetch(req) }\n//\n// // Bun\n// Bun.serve({ fetch: (req) => app.fetch(req) })\n// ```\n\nimport { Container } from './core/container'\nimport { MutableModuleRegistry } from './core/module-registry'\nimport type { AppModule, AppModuleClass, AppModuleEntry } from './core/app-module'\nimport type { ContributorRegistrations } from './core/context-decorator'\nimport type { MiddlewareHandler } from './core/decorators'\nimport type { SourcedRegistration } from './core/contributor-pipeline'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './http/router-builder'\nimport { requestStore } from './http/request-store'\nimport { forwardBackgroundWork, type PlatformContext } from './http/background'\nimport { runCronJobs } from './core/cron'\nimport { runJob } from './core/jobs'\nimport { compileWebRoute } from './http/web/handler'\nimport { ROUTE_URLS, RouteUrls } from './http/url-for'\nimport { loadSettings, type SettingsDeclaration } from './config/settings'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './http/body-policy'\nimport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nimport { notFoundHandler, type MountedRoute } from './http/middleware/error-handler'\nimport type { ValidationErrorFactory } from './http/middleware/validate'\nimport { buildMountPath } from './core/path'\nimport { moduleName } from './core/define-module'\n\nexport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nexport { compileWebRoute } from './http/web/handler'\n// Return-value handler helpers — edge consumers can't import the main barrel.\nexport {\n reply,\n isReply,\n type Reply,\n type ReplyHeaders,\n type ReplyOptions,\n type InferHandlerResponse,\n} from './http/reply'\nexport type { SseHandler } from './http/context'\nexport { waitUntil, type PlatformContext } from './http/background'\nexport { runCronJobs, type CronRun } from './core/cron'\nexport { matchesBearer } from './core/web-crypto'\nexport {\n runJob,\n registerJobContext,\n stampJobContext,\n JOB_CONTEXT_FIELD,\n type JobLike,\n type JobContextCarrier,\n} from './core/jobs'\n// Edge-safe stores + ctx-style rate limiter (zero runtime imports).\nexport {\n KvRateLimitStore,\n KvSessionStore,\n type KvLike,\n type KvRateLimitStoreOptions,\n type KvSessionStoreOptions,\n} from './http/middleware/kv-stores'\nexport { rateLimitGuard, type RateLimitGuardOptions } from './http/middleware/rate-limit-guard'\n\n// Minimal structural surface of h3 v2 used here (kept local so this entry\n// never imports the node-coupled h3 runtime module).\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request\n url: URL\n context: { params?: Record<string, string> }\n}\n\nexport interface CreateWebAppOptions {\n /**\n * The h3 v2 module, statically imported by the caller:\n * `import * as h3 from 'h3'`. Passed in (rather than loaded here) because\n * edge bundlers have no `createRequire`, and a static `import 'h3'` inside\n * this entry would force the peer on every consumer of the subpath.\n */\n h3: unknown\n /** App modules — same shapes `bootstrap({ modules })` accepts. */\n modules: AppModuleEntry[]\n /** Route prefix (default '/api') — parity with bootstrap. */\n apiPrefix?: string\n /**\n * Default route version (default 1) — parity with bootstrap. `false` opts\n * out of URL versioning; a module's own `version` still overrides it.\n */\n defaultVersion?: number | false\n /** Global Context Contributors — parity with `bootstrap({ contributors })`. */\n contributors?: ContributorRegistrations\n /**\n * Env values for ConfigService/@Value resolution. On Workers, pass the\n * `env` binding from the fetch handler (see `createFetchHandler`); on\n * Bun/Deno, ambient `process.env` already works and this can be omitted.\n */\n env?: Record<string, string | undefined>\n /**\n * Global `(ctx, next)` middlewares, run before route middlewares on every\n * route — the web-entry counterpart of `bootstrap({ middlewares })`. Only\n * ctx-style handlers are accepted (no connect/express middleware here).\n */\n middlewares?: MiddlewareHandler[]\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`)\n * — parity with `bootstrap({ jsonLimit })`. A larger body answers 413.\n */\n jsonLimit?: string | number\n /** App-wide settings sections — parity with `bootstrap({ settings })`. */\n settings?: SettingsDeclaration[]\n /** What a failed route validation throws — parity with `bootstrap({ validationError })`. */\n validationError?: ValidationErrorFactory\n}\n\nexport interface WebApp {\n /**\n * Web-standard entry: `Request` in, `Response` out. Pass the platform\n * context (Workers `ctx`, Netlify `context`) so work handed to\n * `ctx.waitUntil()` finishes after the response.\n */\n fetch: (request: Request, platform?: PlatformContext) => Promise<Response>\n /** The underlying h3 v2 app, for advanced composition. */\n h3: unknown\n}\n\n/**\n * Build a KickJS app as a web-standard fetch handler — no node http server,\n * no Application/bootstrap. Module registration, DI, and the contributor\n * pipeline behave exactly like `bootstrap()`; routes are compiled once here\n * and served through h3 v2's router.\n */\nexport function createWebApp(options: CreateWebAppOptions): WebApp {\n const h3mod = options.h3 as { H3?: new () => H3AppLike }\n if (typeof h3mod?.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs/web: pass the h3 v2 module — `createWebApp({ h3: await import(\"h3\"), ... })`. ' +\n \"The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.\",\n )\n }\n\n const container = Container.getInstance()\n // Route names for ctx.urlFor() / the ROUTE_URLS token — bound before modules\n // register so their services can inject it.\n const routeUrls = new RouteUrls()\n container.registerInstance(ROUTE_URLS, routeUrls)\n // Wire ConfigService/@Value env resolution when the platform has no\n // ambient process.env (Workers). Latest-wins like loadEnv().\n if (options.env) {\n const env = options.env\n Container.setEnvResolver((key: string) => env[key])\n }\n\n // Request-scope provider — same wiring Application.setup() performs.\n Container.setRequestStoreProvider(() => requestStore.getStore() ?? null)\n\n // Module mounting — mirrors Application.setup() steps 1:1 for the module\n // path (plugins/adapters are out of scope for the edge entry at launch).\n const registry = new MutableModuleRegistry()\n for (const m of options.modules) registry.mount(m)\n const modules = registry.entries.map((entry) =>\n typeof entry === 'function' ? new (entry as AppModuleClass)() : (entry as AppModule),\n )\n // Declared settings sections — app-wide and mounted modules' — from the\n // platform env (Workers bindings) when given, bound before modules register.\n const settingsEnv = (options.env ??\n (typeof process !== 'undefined' ? process.env : {})) as NodeJS.ProcessEnv\n for (const [section, value] of loadSettings(\n [...(options.settings ?? []), ...modules.flatMap((mod) => mod.settings?.() ?? [])],\n settingsEnv,\n )) {\n container.registerInstance(section, value)\n }\n for (const mod of modules) mod.register?.(container)\n container.bootstrap()\n\n const app = new h3mod.H3()\n const apiPrefix = options.apiPrefix ?? '/api'\n const defaultVersion = options.defaultVersion ?? 1\n const globalMiddleware = options.middlewares ?? []\n const bodyLimit = parseByteSize(options.jsonLimit ?? DEFAULT_BODY_LIMIT)\n\n const globalSources: SourcedRegistration[] = (options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration: registration as SourcedRegistration['registration'],\n label: 'createWebApp',\n }),\n )\n\n // Duplicate-route guard (KICK006) — same boot-time check as the node path.\n const seenRoutes = new Map<string, string>()\n // For the catch-all: a known path with the wrong verb is a 405, not a 404.\n const mounted: MountedRoute[] = []\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n\n _setExternalContributorSources([...moduleSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue\n const routeSets = Array.isArray(result) ? result : [result]\n for (const route of routeSets) {\n if (!route.controller) {\n throw new Error(\n `@forinda/kickjs/web: module route at '${route.path}' has no controller. ` +\n 'Express-style `router` mounts are not supported on the web entry.',\n )\n }\n const version = route.version ?? defaultVersion\n const mountPath = buildMountPath(apiPrefix, version, route.path)\n for (const entry of buildRouteTable(route.controller, { mountFlags: route.flags })) {\n const url = joinPath(mountPath, entry.path)\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${route.controller.name ?? 'controller'}.${String(entry.meta.handlerName ?? '?')}`\n assertRouteUnique(seenRoutes, entry.method, url, owner)\n mounted.push({ method: entry.method, path: url })\n if (globalMiddleware.length > 0) {\n entry.middlewares = [...globalMiddleware, ...entry.middlewares]\n }\n entry.validationError = options.validationError\n entry.urls = routeUrls\n routeUrls.add(owner, url)\n const run = compileWebRoute(entry, undefined, { bodyLimit })\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n }),\n )\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // Anything no route answered: the same 404 / 405 problem details as the\n // node engines, instead of h3's own 404 body.\n const notFound = notFoundHandler(mounted)\n app.all('/**', (event: H3EventLike) => {\n const driver = new WebResponseDriver(event.req.signal)\n notFound(new WebRequestShim(event.req, event.url), driver, () => {})\n return driver.ready\n })\n\n return {\n fetch: async (request: Request, platform?: PlatformContext) => {\n const response = await app.fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n h3: app,\n }\n}\n\n/**\n * Cloudflare Workers convenience: lazily build the app on the first request\n * so the Workers `env` binding can seed config before any module resolves.\n *\n * The Workers execution context (third argument) is forwarded, so work\n * handed to `ctx.waitUntil()` keeps running after the response.\n *\n * `scheduled` runs the `@Cron` jobs whose expression equals the trigger's\n * `event.cron` — list the same expressions under `[triggers] crons` in\n * wrangler.toml.\n *\n * `queue` consumes Cloudflare Queues: each message goes to the `@Job` class\n * for the batch's queue via `runJob`, and is acked when its handler\n * succeeds or retried when it throws. A message body of `{ name, data }`\n * picks the `@Process(name)` method; any other body goes to the queue's\n * catch-all `@Process()` as `data`.\n *\n * ```ts\n * export default createFetchHandler((env) => ({ h3, modules, env }))\n * ```\n */\nexport function createFetchHandler(\n build: (env: Record<string, string | undefined>) => CreateWebAppOptions,\n): {\n fetch: (\n request: Request,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<Response>\n scheduled: (\n event: { cron: string },\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n queue: (\n batch: QueueBatch,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n} {\n let app: WebApp | undefined\n return {\n fetch: (request, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n return app.fetch(request, ctx)\n },\n scheduled: async (event, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n const run = runCronJobs(Container.getInstance(), { expression: event.cron }, 'workers').then(\n () => {},\n )\n ctx?.waitUntil?.(run)\n await run\n },\n queue: async (batch, env = {}) => {\n app ??= createWebApp(build(env))\n const container = Container.getInstance()\n await Promise.all(\n batch.messages.map(async (message) => {\n const body = message.body as { name?: unknown; data?: unknown } | null\n const named = body !== null && typeof body === 'object' && typeof body.name === 'string'\n try {\n await runJob(container, batch.queue, {\n name: named ? (body!.name as string) : '',\n data: named ? body!.data : message.body,\n id: message.id,\n })\n message.ack()\n } catch {\n // Reported by runJob; Cloudflare redelivers per the queue's retry settings.\n message.retry()\n }\n }),\n )\n },\n }\n}\n\n/** The part of a Cloudflare Queues `MessageBatch` the consumer uses. */\nexport interface QueueBatch {\n readonly queue: string\n readonly messages: ReadonlyArray<{\n readonly id: string\n readonly body: unknown\n ack(): void\n retry(): void\n }>\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;6iCAwJA,SAAgB,aAAa,QAAsC,CACjE,IAAM,MAAQ,QAAQ,GACtB,GAAI,OAAO,OAAO,IAAO,WACvB,MAAU,MACR,0KAEF,EAGF,IAAM,UAAY,UAAU,YAAY,EAGlC,UAAY,IAAI,UAItB,GAHA,UAAU,iBAAiB,WAAY,SAAS,EAG5C,QAAQ,IAAK,CACf,IAAM,IAAM,QAAQ,IACpB,UAAU,eAAgB,KAAgB,IAAI,IAAI,CACpD,CAGA,UAAU,4BAA8B,aAAa,SAAS,GAAK,IAAI,EAIvE,IAAM,SAAW,IAAI,sBACrB,IAAK,IAAM,KAAK,QAAQ,QAAS,SAAS,MAAM,CAAC,EACjD,IAAM,QAAU,SAAS,QAAQ,IAAK,OACpC,OAAO,OAAU,WAAa,IAAK,MAA8B,KACnE,EAGM,YAAe,QAAQ,MAC1B,OAAO,QAAY,IAAc,QAAQ,IAAM,CAAC,GACnD,IAAK,GAAM,CAAC,QAAS,SAAU,aAC7B,CAAC,GAAI,QAAQ,UAAY,CAAC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,MAAM,GACR,EACA,MAAO,MAAO,MAAO,IAAM,CAAC,IAAM,CAChC,MAAQ,aAAa,MAAM,GAAG,CAAC,EAC/B,IAAM,UAAY,UAAU,YAAY,EACxC,MAAM,QAAQ,IACZ,MAAM,SAAS,IAAI,KAAO,UAAY,CACpC,IAAM,KAAO,QAAQ,KACf,MAAyB,OAAO,MAAS,YAAjC,MAA6C,OAAO,KAAK,MAAS,SAChF,GAAI,CACF,MAAM,OAAO,UAAW,MAAM,MAAO,CACnC,KAAM,MAAS,KAAM,KAAkB,GACvC,KAAM,MAAQ,KAAM,KAAO,QAAQ,KACnC,GAAI,QAAQ,EACd,CAAC,EACD,QAAQ,IAAI,CACd,MAAQ,CAEN,QAAQ,MAAM,CAChB,CACF,CAAC,CACH,CACF,CACF,CACF,CAcA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
1
+ {"version":3,"file":"web.mjs","names":[],"sources":["../src/web.ts"],"sourcesContent":["// `@forinda/kickjs/web` — the web-standard fetch entry for edge runtimes\n// (Cloudflare Workers), Bun, and Deno.\n//\n// PURITY CONTRACT: this entry's import graph must stay free of node-only\n// runtime imports — no `node:http`, `node:cluster`, `node:fs`, `node:module`,\n// no `express`, no `Application`/`bootstrap`. The single sanctioned node API\n// is `node:async_hooks` (AsyncLocalStorage — available on Workers with\n// `nodejs_compat`, Deno, and Bun). Enforced by the bundle-graph purity test.\n//\n// ```ts\n// // Cloudflare Workers (wrangler.toml: compatibility_flags = [\"nodejs_compat\"])\n// import { createWebApp } from '@forinda/kickjs/web'\n// import * as h3 from 'h3'\n// import { modules } from './modules'\n//\n// const app = createWebApp({ h3, modules })\n// export default { fetch: (req: Request) => app.fetch(req) }\n//\n// // Bun\n// Bun.serve({ fetch: (req) => app.fetch(req) })\n// ```\n\nimport { Container } from './core/container'\nimport { MutableModuleRegistry } from './core/module-registry'\nimport type { AppModule, AppModuleClass, AppModuleEntry } from './core/app-module'\nimport type { ContributorRegistrations } from './core/context-decorator'\nimport type { MiddlewareHandler } from './core/decorators'\nimport type { SourcedRegistration } from './core/contributor-pipeline'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './http/router-builder'\nimport { requestStore } from './http/request-store'\nimport { forwardBackgroundWork, type PlatformContext } from './http/background'\nimport { runCronJobs } from './core/cron'\nimport { runJob } from './core/jobs'\nimport { compileWebRoute, headFromGet } from './http/web/handler'\nimport { ROUTE_URLS, RouteUrls } from './http/url-for'\nimport { loadSettings, type SettingsDeclaration } from './config/settings'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './http/body-policy'\nimport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nimport { notFoundHandler, type MountedRoute } from './http/middleware/error-handler'\nimport type { ValidationErrorFactory } from './http/middleware/validate'\nimport { buildMountPath } from './core/path'\nimport { moduleName } from './core/define-module'\n\nexport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nexport { compileWebRoute } from './http/web/handler'\n// Return-value handler helpers — edge consumers can't import the main barrel.\nexport {\n reply,\n isReply,\n type Reply,\n type ReplyHeaders,\n type ReplyOptions,\n type InferHandlerResponse,\n} from './http/reply'\nexport type { SseHandler } from './http/context'\nexport { waitUntil, type PlatformContext } from './http/background'\nexport { runCronJobs, type CronRun } from './core/cron'\nexport { matchesBearer } from './core/web-crypto'\nexport {\n runJob,\n registerJobContext,\n stampJobContext,\n JOB_CONTEXT_FIELD,\n type JobLike,\n type JobContextCarrier,\n} from './core/jobs'\n// Edge-safe stores + ctx-style rate limiter (zero runtime imports).\nexport {\n KvRateLimitStore,\n KvSessionStore,\n type KvLike,\n type KvRateLimitStoreOptions,\n type KvSessionStoreOptions,\n} from './http/middleware/kv-stores'\nexport { rateLimitGuard, type RateLimitGuardOptions } from './http/middleware/rate-limit-guard'\n\n// Minimal structural surface of h3 v2 used here (kept local so this entry\n// never imports the node-coupled h3 runtime module).\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request\n url: URL\n context: { params?: Record<string, string> }\n}\n\nexport interface CreateWebAppOptions {\n /**\n * The h3 v2 module, statically imported by the caller:\n * `import * as h3 from 'h3'`. Passed in (rather than loaded here) because\n * edge bundlers have no `createRequire`, and a static `import 'h3'` inside\n * this entry would force the peer on every consumer of the subpath.\n */\n h3: unknown\n /** App modules — same shapes `bootstrap({ modules })` accepts. */\n modules: AppModuleEntry[]\n /** Route prefix (default '/api') — parity with bootstrap. */\n apiPrefix?: string\n /**\n * Default route version (default 1) — parity with bootstrap. `false` opts\n * out of URL versioning; a module's own `version` still overrides it.\n */\n defaultVersion?: number | false\n /** Global Context Contributors — parity with `bootstrap({ contributors })`. */\n contributors?: ContributorRegistrations\n /**\n * Env values for ConfigService/@Value resolution. On Workers, pass the\n * `env` binding from the fetch handler (see `createFetchHandler`); on\n * Bun/Deno, ambient `process.env` already works and this can be omitted.\n */\n env?: Record<string, string | undefined>\n /**\n * Global `(ctx, next)` middlewares, run before route middlewares on every\n * route — the web-entry counterpart of `bootstrap({ middlewares })`. Only\n * ctx-style handlers are accepted (no connect/express middleware here).\n */\n middlewares?: MiddlewareHandler[]\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`)\n * — parity with `bootstrap({ jsonLimit })`. A larger body answers 413.\n */\n jsonLimit?: string | number\n /** App-wide settings sections — parity with `bootstrap({ settings })`. */\n settings?: SettingsDeclaration[]\n /** What a failed route validation throws — parity with `bootstrap({ validationError })`. */\n validationError?: ValidationErrorFactory\n}\n\nexport interface WebApp {\n /**\n * Web-standard entry: `Request` in, `Response` out. Pass the platform\n * context (Workers `ctx`, Netlify `context`) so work handed to\n * `ctx.waitUntil()` finishes after the response.\n */\n fetch: (request: Request, platform?: PlatformContext) => Promise<Response>\n /** The underlying h3 v2 app, for advanced composition. */\n h3: unknown\n}\n\n/**\n * Build a KickJS app as a web-standard fetch handler — no node http server,\n * no Application/bootstrap. Module registration, DI, and the contributor\n * pipeline behave exactly like `bootstrap()`; routes are compiled once here\n * and served through h3 v2's router.\n */\nexport function createWebApp(options: CreateWebAppOptions): WebApp {\n const h3mod = options.h3 as { H3?: new () => H3AppLike }\n if (typeof h3mod?.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs/web: pass the h3 v2 module — `createWebApp({ h3: await import(\"h3\"), ... })`. ' +\n \"The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.\",\n )\n }\n\n const container = Container.getInstance()\n // Route names for ctx.urlFor() / the ROUTE_URLS token — bound before modules\n // register so their services can inject it.\n const routeUrls = new RouteUrls()\n container.registerInstance(ROUTE_URLS, routeUrls)\n // Wire ConfigService/@Value env resolution when the platform has no\n // ambient process.env (Workers). Latest-wins like loadEnv().\n if (options.env) {\n const env = options.env\n Container.setEnvResolver((key: string) => env[key])\n }\n\n // Request-scope provider — same wiring Application.setup() performs.\n Container.setRequestStoreProvider(() => requestStore.getStore() ?? null)\n\n // Module mounting — mirrors Application.setup() steps 1:1 for the module\n // path (plugins/adapters are out of scope for the edge entry at launch).\n const registry = new MutableModuleRegistry()\n for (const m of options.modules) registry.mount(m)\n const modules = registry.entries.map((entry) =>\n typeof entry === 'function' ? new (entry as AppModuleClass)() : (entry as AppModule),\n )\n // Declared settings sections — app-wide and mounted modules' — from the\n // platform env (Workers bindings) when given, bound before modules register.\n const settingsEnv = (options.env ??\n (typeof process !== 'undefined' ? process.env : {})) as NodeJS.ProcessEnv\n for (const [section, value] of loadSettings(\n [...(options.settings ?? []), ...modules.flatMap((mod) => mod.settings?.() ?? [])],\n settingsEnv,\n )) {\n container.registerInstance(section, value)\n }\n for (const mod of modules) mod.register?.(container)\n container.bootstrap()\n\n const app = new h3mod.H3()\n const getUrls: Array<{ url: string; handler: (event: H3EventLike) => unknown }> = []\n const apiPrefix = options.apiPrefix ?? '/api'\n const defaultVersion = options.defaultVersion ?? 1\n const globalMiddleware = options.middlewares ?? []\n const bodyLimit = parseByteSize(options.jsonLimit ?? DEFAULT_BODY_LIMIT)\n\n const globalSources: SourcedRegistration[] = (options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration: registration as SourcedRegistration['registration'],\n label: 'createWebApp',\n }),\n )\n\n // Duplicate-route guard (KICK006) — same boot-time check as the node path.\n const seenRoutes = new Map<string, string>()\n // For the catch-all: a known path with the wrong verb is a 405, not a 404.\n const mounted: MountedRoute[] = []\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n\n _setExternalContributorSources([...moduleSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue\n const routeSets = Array.isArray(result) ? result : [result]\n for (const route of routeSets) {\n if (!route.controller) {\n throw new Error(\n `@forinda/kickjs/web: module route at '${route.path}' has no controller. ` +\n 'Express-style `router` mounts are not supported on the web entry.',\n )\n }\n const version = route.version ?? defaultVersion\n // `prefix: false` mounts at the root — parity with Application.\n const mountPath = buildMountPath(\n route.prefix === false ? '' : apiPrefix,\n version,\n route.path,\n )\n for (const entry of buildRouteTable(route.controller, { mountFlags: route.flags })) {\n const url = joinPath(mountPath, entry.path)\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${route.controller.name ?? 'controller'}.${String(entry.meta.handlerName ?? '?')}`\n assertRouteUnique(seenRoutes, entry.method, url, owner)\n mounted.push({ method: entry.method, path: url })\n if (globalMiddleware.length > 0) {\n entry.middlewares = [...globalMiddleware, ...entry.middlewares]\n }\n entry.validationError = options.validationError\n entry.urls = routeUrls\n routeUrls.add(owner, url)\n const run = compileWebRoute(entry, undefined, { bodyLimit })\n const handler = (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n })\n app.on(entry.method, url, handler)\n if (entry.method === 'GET') getUrls.push({ url, handler })\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // HEAD answers every GET route, as on the node engines.\n for (const { url, handler } of getUrls) {\n app.on('HEAD', url, (event: H3EventLike) => headFromGet(handler(event) as Promise<Response>))\n }\n\n // Anything no route answered: the same 404 / 405 problem details as the\n // node engines, instead of h3's own 404 body.\n const notFound = notFoundHandler(mounted)\n app.all('/**', (event: H3EventLike) => {\n const driver = new WebResponseDriver(event.req.signal)\n notFound(new WebRequestShim(event.req, event.url), driver, () => {})\n return driver.ready\n })\n\n return {\n fetch: async (request: Request, platform?: PlatformContext) => {\n const response = await app.fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n h3: app,\n }\n}\n\n/**\n * Cloudflare Workers convenience: lazily build the app on the first request\n * so the Workers `env` binding can seed config before any module resolves.\n *\n * The Workers execution context (third argument) is forwarded, so work\n * handed to `ctx.waitUntil()` keeps running after the response.\n *\n * `scheduled` runs the `@Cron` jobs whose expression equals the trigger's\n * `event.cron` — list the same expressions under `[triggers] crons` in\n * wrangler.toml.\n *\n * `queue` consumes Cloudflare Queues: each message goes to the `@Job` class\n * for the batch's queue via `runJob`, and is acked when its handler\n * succeeds or retried when it throws. A message body of `{ name, data }`\n * picks the `@Process(name)` method; any other body goes to the queue's\n * catch-all `@Process()` as `data`.\n *\n * ```ts\n * export default createFetchHandler((env) => ({ h3, modules, env }))\n * ```\n */\nexport function createFetchHandler(\n build: (env: Record<string, string | undefined>) => CreateWebAppOptions,\n): {\n fetch: (\n request: Request,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<Response>\n scheduled: (\n event: { cron: string },\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n queue: (\n batch: QueueBatch,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n} {\n let app: WebApp | undefined\n return {\n fetch: (request, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n return app.fetch(request, ctx)\n },\n scheduled: async (event, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n const run = runCronJobs(Container.getInstance(), { expression: event.cron }, 'workers').then(\n () => {},\n )\n ctx?.waitUntil?.(run)\n await run\n },\n queue: async (batch, env = {}) => {\n app ??= createWebApp(build(env))\n const container = Container.getInstance()\n await Promise.all(\n batch.messages.map(async (message) => {\n const body = message.body as { name?: unknown; data?: unknown } | null\n const named = body !== null && typeof body === 'object' && typeof body.name === 'string'\n try {\n await runJob(container, batch.queue, {\n name: named ? (body!.name as string) : '',\n data: named ? body!.data : message.body,\n id: message.id,\n })\n message.ack()\n } catch {\n // Reported by runJob; Cloudflare redelivers per the queue's retry settings.\n message.retry()\n }\n }),\n )\n },\n }\n}\n\n/** The part of a Cloudflare Queues `MessageBatch` the consumer uses. */\nexport interface QueueBatch {\n readonly queue: string\n readonly messages: ReadonlyArray<{\n readonly id: string\n readonly body: unknown\n ack(): void\n retry(): void\n }>\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;ikCAwJA,SAAgB,aAAa,QAAsC,CACjE,IAAM,MAAQ,QAAQ,GACtB,GAAI,OAAO,OAAO,IAAO,WACvB,MAAU,MACR,0KAEF,EAGF,IAAM,UAAY,UAAU,YAAY,EAGlC,UAAY,IAAI,UAItB,GAHA,UAAU,iBAAiB,WAAY,SAAS,EAG5C,QAAQ,IAAK,CACf,IAAM,IAAM,QAAQ,IACpB,UAAU,eAAgB,KAAgB,IAAI,IAAI,CACpD,CAGA,UA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AAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs",
3
- "version": "10.10.0",
3
+ "version": "10.11.0",
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",