@forinda/kickjs 10.3.1 → 10.5.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 (157) hide show
  1. package/dist/{adapter-6fjmVVc2.d.mts → adapter-BZ1WzN1z.d.mts} +35 -5
  2. package/dist/{adapter-6fjmVVc2.d.mts.map → adapter-BZ1WzN1z.d.mts.map} +1 -1
  3. package/dist/{application-BuUWvaqp.d.mts → application-D5Iiy7rt.d.mts} +22 -11
  4. package/dist/{application-BuUWvaqp.d.mts.map → application-D5Iiy7rt.d.mts.map} +1 -1
  5. package/dist/{application-CYCvctQx.mjs → application-DtuQSky3.mjs} +4 -4
  6. package/dist/application-DtuQSky3.mjs.map +1 -0
  7. package/dist/{bootstrap-CfaYHbmd.mjs → bootstrap-B_6QfzXV.mjs} +3 -3
  8. package/dist/{bootstrap-CfaYHbmd.mjs.map → bootstrap-B_6QfzXV.mjs.map} +1 -1
  9. package/dist/{bounded-counters-BcA0f0bV.mjs → bounded-counters-C8PHfWEu.mjs} +2 -2
  10. package/dist/{bounded-counters-BcA0f0bV.mjs.map → bounded-counters-C8PHfWEu.mjs.map} +1 -1
  11. package/dist/{client-ip-BpauuVN_.mjs → client-ip-kxT2SHut.mjs} +2 -2
  12. package/dist/{client-ip-BpauuVN_.mjs.map → client-ip-kxT2SHut.mjs.map} +1 -1
  13. package/dist/config/index.d.mts +1 -1
  14. package/dist/config/index.mjs +2 -2
  15. package/dist/{config-DgMxtfcW.mjs → config-Dz-HnO4c.mjs} +3 -3
  16. package/dist/{config-DgMxtfcW.mjs.map → config-Dz-HnO4c.mjs.map} +1 -1
  17. package/dist/{context-errors-BGIOYMV5.mjs → context-errors-gitMJXxZ.mjs} +2 -2
  18. package/dist/{context-errors-BGIOYMV5.mjs.map → context-errors-gitMJXxZ.mjs.map} +1 -1
  19. package/dist/context-p-KpSsLy.mjs +12 -0
  20. package/dist/context-p-KpSsLy.mjs.map +1 -0
  21. package/dist/{contributor-runner-CJn1gZ8h.mjs → contributor-runner-CDlPrzai.mjs} +3 -3
  22. package/dist/{contributor-runner-CJn1gZ8h.mjs.map → contributor-runner-CDlPrzai.mjs.map} +1 -1
  23. package/dist/core/adapter.d.mts +1 -1
  24. package/dist/core/adapter.mjs +1 -1
  25. package/dist/core/app-module.mjs +1 -1
  26. package/dist/core/cache.mjs +1 -1
  27. package/dist/core/container.mjs +2 -2
  28. package/dist/core/cron.mjs +2 -2
  29. package/dist/core/decorators.d.mts +1 -1
  30. package/dist/core/decorators.mjs +2 -2
  31. package/dist/core/decorators.mjs.map +1 -1
  32. package/dist/core/errors.mjs +1 -1
  33. package/dist/core/interfaces.mjs +1 -1
  34. package/dist/core/logger.mjs +1 -1
  35. package/dist/core/path.mjs +1 -1
  36. package/dist/core/plugin.d.mts +1 -1
  37. package/dist/core/plugin.mjs +1 -1
  38. package/dist/core/reactivity.mjs +1 -1
  39. package/dist/{core-YE-k8IrU.mjs → core-CSWR0hHJ.mjs} +3 -3
  40. package/dist/{core-YE-k8IrU.mjs.map → core-CSWR0hHJ.mjs.map} +1 -1
  41. package/dist/{csrf-ahBjt1ay.d.mts → csrf-BDAZK2mm.d.mts} +2 -2
  42. package/dist/{csrf-ahBjt1ay.d.mts.map → csrf-BDAZK2mm.d.mts.map} +1 -1
  43. package/dist/{decorate-CaEYam5J.mjs → decorate-D2oVJls5.mjs} +3 -3
  44. package/dist/{decorate-CaEYam5J.mjs.map → decorate-D2oVJls5.mjs.map} +1 -1
  45. package/dist/{decorators-deGmthGc.d.mts → decorators-Dvy0JZ5L.d.mts} +6 -2
  46. package/dist/{decorators-deGmthGc.d.mts.map → decorators-Dvy0JZ5L.d.mts.map} +1 -1
  47. package/dist/{define-adapter-C6H-I1og.mjs → define-adapter-oANmOi4a.mjs} +2 -2
  48. package/dist/{define-adapter-C6H-I1og.mjs.map → define-adapter-oANmOi4a.mjs.map} +1 -1
  49. package/dist/{di-hooks-BE0IOQk-.mjs → di-hooks-HI14rSja.mjs} +9 -4
  50. package/dist/di-hooks-HI14rSja.mjs.map +1 -0
  51. package/dist/{disposables-Cste73oY.mjs → disposables-CWNNe9HH.mjs} +1 -1
  52. package/dist/{error-handler-C6JJJct_.d.mts → error-handler-CbP7hKdJ.d.mts} +7 -7
  53. package/dist/{error-handler-C6JJJct_.d.mts.map → error-handler-CbP7hKdJ.d.mts.map} +1 -1
  54. package/dist/{handler-DUyRCpPw.mjs → handler-D23bJ6g1.mjs} +3 -3
  55. package/dist/{handler-DUyRCpPw.mjs.map → handler-D23bJ6g1.mjs.map} +1 -1
  56. package/dist/{host-fc-YQZnN.mjs → host-C2_vvcrO.mjs} +2 -2
  57. package/dist/{host-fc-YQZnN.mjs.map → host-C2_vvcrO.mjs.map} +1 -1
  58. package/dist/http/application.d.mts +2 -2
  59. package/dist/http/application.mjs +2 -2
  60. package/dist/http/bootstrap.d.mts +1 -1
  61. package/dist/http/bootstrap.mjs +2 -2
  62. package/dist/http/context.d.mts +1 -1
  63. package/dist/http/context.mjs +2 -2
  64. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  65. package/dist/http/middleware/breach-padding.mjs +1 -1
  66. package/dist/http/middleware/cors.mjs +1 -1
  67. package/dist/http/middleware/csrf.d.mts +1 -1
  68. package/dist/http/middleware/csrf.mjs +3 -2
  69. package/dist/http/middleware/csrf.mjs.map +1 -0
  70. package/dist/http/middleware/error-handler.d.mts +1 -1
  71. package/dist/http/middleware/error-handler.mjs +2 -2
  72. package/dist/http/middleware/error-handler.mjs.map +1 -1
  73. package/dist/http/middleware/helmet.mjs +1 -1
  74. package/dist/http/middleware/rate-limit.mjs +2 -2
  75. package/dist/http/middleware/request-id.mjs +1 -1
  76. package/dist/http/middleware/request-logger.mjs +2 -2
  77. package/dist/http/middleware/session.mjs +2 -2
  78. package/dist/http/middleware/spa.d.mts +1 -1
  79. package/dist/http/middleware/spa.mjs +2 -2
  80. package/dist/http/middleware/upload.d.mts +1 -1
  81. package/dist/http/middleware/upload.mjs +2 -2
  82. package/dist/http/middleware/validate.mjs +1 -1
  83. package/dist/http/middleware/views.d.mts +1 -1
  84. package/dist/http/middleware/views.mjs +2 -2
  85. package/dist/http/query/index.d.mts +2 -2
  86. package/dist/http/query/index.mjs +2 -2
  87. package/dist/http/router-builder.d.mts +1 -1
  88. package/dist/http/router-builder.mjs +2 -2
  89. package/dist/http/runtimes/fastify.d.mts +1 -1
  90. package/dist/http/runtimes/fastify.mjs +2 -2
  91. package/dist/http/runtimes/h3-web.mjs +1 -1
  92. package/dist/http/runtimes/h3.d.mts +1 -1
  93. package/dist/http/runtimes/h3.mjs +2 -2
  94. package/dist/{index-Dms8LzHG.d.mts → index-B4aOLoId.d.mts} +3 -3
  95. package/dist/{index-Dms8LzHG.d.mts.map → index-B4aOLoId.d.mts.map} +1 -1
  96. package/dist/{index-BfT5KZ-M.d.mts → index-Blgka75E.d.mts} +63 -4
  97. package/dist/index-Blgka75E.d.mts.map +1 -0
  98. package/dist/index.d.mts +11 -11
  99. package/dist/index.mjs +4 -4
  100. package/dist/index.mjs.map +1 -1
  101. package/dist/is-production-TSixl400.mjs +12 -0
  102. package/dist/is-production-TSixl400.mjs.map +1 -0
  103. package/dist/{jobs-DWi_Lwbe.mjs → jobs-DIddIoQs.mjs} +3 -3
  104. package/dist/{jobs-DWi_Lwbe.mjs.map → jobs-DIddIoQs.mjs.map} +1 -1
  105. package/dist/{kv-stores-BGXeNEDK.mjs → kv-stores-B9xLP0mg.mjs} +3 -3
  106. package/dist/{kv-stores-BGXeNEDK.mjs.map → kv-stores-B9xLP0mg.mjs.map} +1 -1
  107. package/dist/{kv-stores-BGXPKv15.d.mts → kv-stores-DXFBEYYu.d.mts} +30 -6
  108. package/dist/kv-stores-DXFBEYYu.d.mts.map +1 -0
  109. package/dist/{lazy-serve-static-Barg3__1.mjs → lazy-serve-static-BNM_5G_r.mjs} +2 -2
  110. package/dist/{lazy-serve-static-Barg3__1.mjs.map → lazy-serve-static-BNM_5G_r.mjs.map} +1 -1
  111. package/dist/{metadata-CnL9sQFa.mjs → metadata-CJRJvpAK.mjs} +1 -1
  112. package/dist/{observers-BNMQ7VLb.mjs → observers-DaIAahW4.mjs} +2 -2
  113. package/dist/{observers-BNMQ7VLb.mjs.map → observers-DaIAahW4.mjs.map} +1 -1
  114. package/dist/query-CUvSp-JT.mjs +12 -0
  115. package/dist/query-CUvSp-JT.mjs.map +1 -0
  116. package/dist/{reply-CMRk-Jp3.mjs → reply-C1CoxeQt.mjs} +3 -3
  117. package/dist/{reply-CMRk-Jp3.mjs.map → reply-C1CoxeQt.mjs.map} +1 -1
  118. package/dist/{respond-gPELdOSi.mjs → respond-Ius0bnxZ.mjs} +2 -2
  119. package/dist/{respond-gPELdOSi.mjs.map → respond-Ius0bnxZ.mjs.map} +1 -1
  120. package/dist/{route-flag-8Pi83-uw.mjs → route-flag-BP_jbhNy.mjs} +3 -3
  121. package/dist/{route-flag-8Pi83-uw.mjs.map → route-flag-BP_jbhNy.mjs.map} +1 -1
  122. package/dist/{route-policy-0LAfSzo-.mjs → route-policy-BF1hOoUO.mjs} +2 -2
  123. package/dist/{route-policy-0LAfSzo-.mjs.map → route-policy-BF1hOoUO.mjs.map} +1 -1
  124. package/dist/{router-builder-obSpg-Ub.d.mts → router-builder-BewIsj7V.d.mts} +2 -2
  125. package/dist/{router-builder-obSpg-Ub.d.mts.map → router-builder-BewIsj7V.d.mts.map} +1 -1
  126. package/dist/{router-builder-D0SDqFTr.mjs → router-builder-CBjQNcUy.mjs} +3 -3
  127. package/dist/{router-builder-D0SDqFTr.mjs.map → router-builder-CBjQNcUy.mjs.map} +1 -1
  128. package/dist/{settings-BW5gVm6c.mjs → settings-DlZtVJ3I.mjs} +3 -3
  129. package/dist/{settings-BW5gVm6c.mjs.map → settings-DlZtVJ3I.mjs.map} +1 -1
  130. package/dist/{token-Q2c8xwJE.mjs → token-9VtCdkUp.mjs} +1 -1
  131. package/dist/{upload-CyBSlnH_.d.mts → upload-DkT2p1gd.d.mts} +3 -3
  132. package/dist/{upload-CyBSlnH_.d.mts.map → upload-DkT2p1gd.d.mts.map} +1 -1
  133. package/dist/{upload-config-D22qKth8.mjs → upload-config-DYr3a8LW.mjs} +2 -2
  134. package/dist/{upload-config-D22qKth8.mjs.map → upload-config-DYr3a8LW.mjs.map} +1 -1
  135. package/dist/url-for-Cci2zH9d.mjs +12 -0
  136. package/dist/url-for-Cci2zH9d.mjs.map +1 -0
  137. package/dist/web-crypto-CWrgn2Yq.mjs +12 -0
  138. package/dist/web-crypto-CWrgn2Yq.mjs.map +1 -0
  139. package/dist/web.d.mts +4 -4
  140. package/dist/web.d.mts.map +1 -1
  141. package/dist/web.mjs +2 -2
  142. package/dist/web.mjs.map +1 -1
  143. package/package.json +2 -2
  144. package/dist/application-CYCvctQx.mjs.map +0 -1
  145. package/dist/context-DJvuLfrx.mjs +0 -12
  146. package/dist/context-DJvuLfrx.mjs.map +0 -1
  147. package/dist/csrf-C6Em76kH.mjs +0 -12
  148. package/dist/csrf-C6Em76kH.mjs.map +0 -1
  149. package/dist/di-hooks-BE0IOQk-.mjs.map +0 -1
  150. package/dist/index-BfT5KZ-M.d.mts.map +0 -1
  151. package/dist/is-production-0lB5MU1j.mjs +0 -12
  152. package/dist/is-production-0lB5MU1j.mjs.map +0 -1
  153. package/dist/kv-stores-BGXPKv15.d.mts.map +0 -1
  154. package/dist/query-mXPZYtQw.mjs +0 -12
  155. package/dist/query-mXPZYtQw.mjs.map +0 -1
  156. package/dist/url-for-UZ5kJjsG.mjs +0 -12
  157. package/dist/url-for-UZ5kJjsG.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrap-CfaYHbmd.mjs","names":["log","log","\"KICK_CRON_WORKER\""],"sources":["../src/http/cron-adapter.ts","../src/http/cluster.ts","../src/http/handler.ts","../src/http/bootstrap.ts"],"sourcesContent":["/**\n * `KickCronAdapter()` — runs `@Cron` jobs on the Node server.\n *\n * Named with the `Kick` prefix (adapter name and logger too) so it never\n * collides with an app's own `CronAdapter` — which is also why it is opt-in.\n *\n * Opt-in: `@Cron` only records metadata, and apps that schedule jobs with\n * their own adapter keep doing so — adding this one to such an app would run\n * every job twice. Register it once:\n *\n * ```ts\n * bootstrap({ modules, adapters: [KickCronAdapter()] })\n * ```\n *\n * Timing comes from the optional peer `croner` (`pnpm add croner`), loaded\n * only when there is a job to schedule. Each tick resolves the job's class\n * from the container (the same singletons a request gets) and calls\n * `runCronJob`, which applies `enabled` / `overlap` and reports failures to\n * the error observers.\n *\n * Several processes: in `bootstrap({ cluster })`, only the worker the primary\n * marks with `KICK_CRON_WORKER=1` schedules, so a job runs once per cluster.\n * Several separate instances (replicas behind a load balancer) each schedule\n * every job — turn it off on all but one (`KickCronAdapter({ enabled: false })`),\n * or have the job take a lock.\n *\n * @module @forinda/kickjs/http/cron-adapter\n */\nimport cluster from 'node:cluster'\nimport { createRequire } from 'node:module'\nimport { defineAdapter } from '../core/define-adapter'\nimport { createLogger } from '../core/logger'\nimport { listCronJobs, runCronJob, type CronJob } from '../core/cron'\nimport type { Container } from '../core/container'\n\nconst log = createLogger('KickCronAdapter')\nconst peerRequire = createRequire(import.meta.url)\n\n/** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */\nexport const CRON_WORKER_ENV = 'KICK_CRON_WORKER'\n\nexport interface CronAdapterOptions {\n /** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */\n enabled?: boolean\n}\n\ninterface Schedule {\n stop(): void\n}\n\ntype CronerCtor = new (pattern: string, options: { timezone?: string }, fn: () => void) => Schedule\n\nfunction loadCroner(): CronerCtor | undefined {\n try {\n return (peerRequire('croner') as { Cron: CronerCtor }).Cron\n } catch {\n return undefined\n }\n}\n\n/** Whether this process should schedule jobs — one worker per cluster. */\nfunction isCronProcess(): boolean {\n return !cluster.isWorker || process.env[CRON_WORKER_ENV] === '1'\n}\n\nexport const KickCronAdapter = defineAdapter<CronAdapterOptions>({\n name: 'KickCronAdapter',\n defaults: { enabled: true },\n build(options) {\n const schedules: Schedule[] = []\n const inFlight = new Set<Promise<unknown>>()\n let jobs: CronJob[] = []\n\n return {\n afterStart({ container }) {\n if (options.enabled === false || !isCronProcess()) return\n jobs = listCronJobs(container)\n if (jobs.length === 0) return\n\n const Croner = loadCroner()\n if (!Croner) {\n log.warn(\n `${jobs.length} @Cron job(s) found but \"croner\" is not installed, so none will run. ` +\n 'Install it: pnpm add croner',\n )\n return\n }\n\n const run = (job: CronJob, trigger: 'schedule' | 'init') => {\n // Failures are already logged and reported by runCronJob.\n const p = runCronJob(job, container as Container, trigger).catch(() => {})\n inFlight.add(p)\n void p.finally(() => inFlight.delete(p))\n }\n\n for (const job of jobs) {\n schedules.push(\n new Croner(\n job.expression,\n // No croner `name`: croner keeps names in a process-wide registry\n // and throws on a duplicate.\n job.timezone ? { timezone: job.timezone } : {},\n () => run(job, 'schedule'),\n ),\n )\n if (job.runOnInit) run(job, 'init')\n }\n log.info(`Scheduled ${jobs.length} @Cron job(s): ${jobs.map((j) => j.name).join(', ')}`)\n },\n\n /**\n * Stops the schedules, then waits for running jobs so they don't lose\n * their dependencies mid-run. Also runs on every HMR reload, so a reload\n * never leaves a second copy ticking.\n */\n async shutdown() {\n for (const schedule of schedules.splice(0)) schedule.stop()\n await Promise.all(inFlight)\n },\n\n introspect() {\n return {\n protocolVersion: 1,\n name: 'KickCronAdapter',\n kind: 'adapter',\n state: {\n jobs: jobs.map((j) => ({\n name: j.name,\n expression: j.expression,\n timezone: j.timezone,\n description: j.description,\n })),\n },\n } as never\n },\n }\n },\n})\n","import cluster from 'node:cluster'\nimport { CRON_WORKER_ENV } from './cron-adapter'\nimport os from 'node:os'\nimport { createLogger } from '../core'\nimport { reactive, ref } from '../core/reactivity'\n\nconst log = createLogger('Cluster')\n\nexport interface ClusterOptions {\n /** Number of worker processes (default: os.cpus().length) */\n workers?: number\n /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */\n gracefulShutdownTimeout?: number\n /** Delay between worker restarts (ms), default: 1000 */\n restartDelay?: number\n /** Max failures in restartWindow before refusing to restart, default: 5 */\n maxFailures?: number\n /** Time window for counting failures (ms), default: 30000 */\n restartWindow?: number\n}\n\n/** Returns true if the current process is the cluster primary */\nexport function isClusterPrimary(): boolean {\n return cluster.isPrimary\n}\n\n/**\n * Fork worker processes and manage the cluster lifecycle.\n *\n * The primary process forks `workers` child processes. Each worker\n * shares the same port via Node's built-in `cluster` module (OS\n * round-robin load balancing).\n *\n * Features:\n * - Graceful shutdown with timeout fallback to forceful kill\n * - Auto-restart dead workers (respects voluntary disconnects)\n * - Startup timeout detection (stuck workers)\n * - Crash loop prevention (backoff on rapid failures)\n * - Comprehensive lifecycle logging\n */\nexport function setupClusterPrimary(opts: ClusterOptions): void {\n const numWorkers = opts.workers ?? os.cpus().length\n const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5000\n const restartDelay = opts.restartDelay ?? 1000\n const maxFailures = opts.maxFailures ?? 5\n const restartWindow = opts.restartWindow ?? 30000\n\n const startupTimeouts = new Map<number, NodeJS.Timeout>()\n const state = reactive({\n failureTimestamps: [] as number[],\n shuttingDown: false,\n })\n const activeWorkers = ref(0)\n\n log.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`)\n\n // Exactly one worker runs `KickCronAdapter` jobs, so a job fires once per\n // cluster rather than once per worker. The primary marks it with\n // KICK_CRON_WORKER=1; when it dies, the next fork inherits the role.\n let cronWorkerId: number | undefined\n const forkWorker = (): void => {\n const takesCron = cronWorkerId === undefined\n const worker = cluster.fork(takesCron ? { [CRON_WORKER_ENV]: '1' } : undefined)\n if (takesCron) cronWorkerId = worker.id\n }\n\n // Initial fork\n for (let i = 0; i < numWorkers; i++) {\n forkWorker()\n }\n\n // Detect stuck workers (no 'listening' event within timeout)\n cluster.on('fork', (worker) => {\n const timeout = setTimeout(() => {\n log.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`)\n worker.kill()\n }, 10000)\n\n startupTimeouts.set(worker.id, timeout)\n activeWorkers.value++\n log.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)\n })\n\n // Clear startup timeout when worker is ready\n cluster.on('listening', (worker, address) => {\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n log.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)\n })\n\n // Log when worker comes online\n cluster.on('online', (worker) => {\n log.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)\n })\n\n // Auto-restart dead workers (unless intentionally disconnected)\n cluster.on('exit', (worker, code, signal) => {\n // Clear startup timeout if still pending\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n\n // Don't restart if worker was intentionally disconnected\n activeWorkers.value--\n if (worker.id === cronWorkerId) cronWorkerId = undefined\n\n if (worker.exitedAfterDisconnect) {\n log.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`)\n return\n }\n\n // Track crash history globally (worker IDs change on restart)\n const now = Date.now()\n // Remove timestamps outside the window, then add the current failure\n while (\n state.failureTimestamps.length > 0 &&\n now - state.failureTimestamps[0] >= restartWindow\n ) {\n state.failureTimestamps.shift()\n }\n state.failureTimestamps.push(now)\n\n // Prevent restart loops\n if (state.failureTimestamps.length > maxFailures) {\n log.error(\n `${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`,\n )\n // Optionally exit the primary if too many workers are crashing\n if (activeWorkers.value === 0) {\n log.error('All workers have crashed, exiting primary')\n process.exit(1)\n }\n return\n }\n\n log.warn(\n `Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`,\n )\n\n setTimeout(() => {\n // Only restart if we still need more workers\n if (activeWorkers.value < numWorkers) {\n forkWorker()\n }\n }, restartDelay)\n })\n\n // Log when worker disconnects (can happen before exit)\n cluster.on('disconnect', (worker) => {\n log.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)\n })\n\n // Forward shutdown signals to workers (disconnect so exitedAfterDisconnect is set)\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => {\n if (state.shuttingDown) return\n state.shuttingDown = true\n log.info(`Primary received ${signal}, disconnecting workers...`)\n cluster.disconnect(() => {\n log.info('All workers disconnected, exiting primary')\n process.exit(0)\n })\n // Force kill after graceful timeout\n setTimeout(() => {\n log.warn('Graceful shutdown timed out, forcing exit')\n process.exit(1)\n }, gracefulTimeout).unref()\n })\n }\n}\n","/**\n * The app as a request handler, with no listening server of its own — for\n * platforms that hand you requests instead of a port: Netlify Functions,\n * Vercel Functions, and any other serverless or embedding host.\n *\n * @module @forinda/kickjs/http/handler\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { Application, type ApplicationOptions } from './application'\nimport { forwardBackgroundWork, settleBackgroundWork, type PlatformContext } from './background'\n\n/** A KickJS app exposed as request handlers. See {@link createHandler}. */\nexport interface KickHandler {\n /**\n * Web-standard handler: `fetch(Request) → Response`. Netlify Functions,\n * Vercel's fetch export, and anything else that speaks `Request`.\n *\n * Pass the platform context (Netlify's `context`, `{ waitUntil }` from\n * `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after\n * the response instead of being frozen with the instance.\n */\n fetch(request: Request, platform?: PlatformContext): Promise<Response>\n /** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */\n node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>\n /** Set the app up now instead of on the first request (warm-up). */\n ready(): Promise<Application>\n /** Shut adapters down and stop the internal forwarding server, if one started. */\n close(): Promise<void>\n}\n\n/**\n * Set on `globalThis` while `createHandler(() => import('./index'))` loads the\n * app's entry: `bootstrap()` hands its app here instead of starting it.\n * @internal\n */\nexport const ENTRY_CAPTURE = Symbol.for('kickjs.handler.entryCapture')\n\n/** What `bootstrap()` hands to a loading handler. @internal */\nexport type EntryCapture = (app: Application, options: ApplicationOptions) => void\n\n/**\n * Load the app's own entry and keep the app its `bootstrap()` call builds.\n * Retries after a failed setup reuse the captured options.\n */\nfunction captureEntry(\n load: () => Promise<unknown>,\n): () => Promise<{ first: Application; options: ApplicationOptions }> {\n let pending: Promise<{ first: Application; options: ApplicationOptions }> | undefined\n return () =>\n (pending ??= (async () => {\n let captured: { first: Application; options: ApplicationOptions } | undefined\n const g = globalThis as Record<symbol, unknown>\n const capture: EntryCapture = (first, options) => {\n captured ??= { first, options }\n }\n g[ENTRY_CAPTURE] = capture\n try {\n await load()\n } finally {\n if (g[ENTRY_CAPTURE] === capture) delete g[ENTRY_CAPTURE]\n }\n if (!captured) {\n throw new Error(\n 'createHandler(): the entry finished loading without calling bootstrap(). ' +\n \"Pass the module that calls it — createHandler(() => import('./index')) — or pass the options.\",\n )\n }\n return captured\n })().catch((err) => {\n pending = undefined\n throw err\n }))\n}\n\n/**\n * Build a KickJS app as request handlers instead of a listening server.\n *\n * Takes the same options as `bootstrap()`, or a function that imports the\n * app's entry — the file that calls `bootstrap()`. With the entry, the app\n * is built from that one `bootstrap({ ... })` call, so the server and the\n * function never drift apart:\n *\n * ```ts\n * // src/serverless.ts\n * export const handler = createHandler(() => import('./index'))\n * ```\n *\n * While the entry loads, its `bootstrap()` call builds the app without\n * starting it — no port, no process signal handlers, no cluster. The app is set up once per process\n * (per function instance), lazily on the first request, and reused after that.\n * Nothing listens on a port, `afterStart` does not run, and no process signal\n * handlers are registered — the platform owns the process.\n *\n * `fetch` uses the runtime's own fetch when it has one (the h3 v2 runtime).\n * Runtimes built on Node request/response objects — Express, the default —\n * are served through a server bound to `127.0.0.1` on a random port inside the\n * same process, started on first use: the `Request` is forwarded to it and its\n * response returned. Request bodies are buffered on that path; response bodies\n * stream. Adapters that rewrite the `res` prototype (Express does) make a\n * direct Request→`res` bridge unreliable, which is why this forwards instead.\n *\n * One handler per process: the DI container is process-wide.\n *\n * @example\n * ```ts\n * // server/src/serverless.ts\n * import 'reflect-metadata'\n * import './config'\n * import { createHandler } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const handler = createHandler({ modules })\n *\n * // netlify/functions/api.mjs\n * export default (request, context) => handler.fetch(request, context)\n * export const config = { path: '/api/*' }\n * ```\n */\nexport function createHandler(options: ApplicationOptions | (() => Promise<unknown>)): KickHandler {\n let app: Promise<Application> | undefined\n const entry =\n typeof options === 'function'\n ? captureEntry(options)\n : async () => ({ first: undefined, options })\n // The app the entry's bootstrap() built is used once; a retry builds anew.\n let firstUsed = false\n\n const ready = (): Promise<Application> => {\n app ??= (async () => {\n let loaded: Awaited<ReturnType<typeof entry>>\n try {\n loaded = await entry()\n } catch (err) {\n // The entry failed to load: try again on the next request.\n app = undefined\n throw err\n }\n const instance = loaded.first && !firstUsed ? loaded.first : new Application(loaded.options)\n firstUsed = true\n try {\n await instance.startWithoutServer()\n } catch (err) {\n // A failed setup (a database that was briefly down, say) is retried on\n // the next request. Shut this attempt down first so its adapters don't\n // stay live next to the retry's.\n app = undefined\n await instance.shutdown().catch(() => {})\n throw err\n }\n return instance\n })()\n return app\n }\n\n return {\n ready,\n\n async fetch(request, platform) {\n const response = await (await ready()).fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n\n async node(req, res, platform) {\n const instance = await ready()\n instance.handle(req, res)\n if (platform?.waitUntil) {\n // The response is written asynchronously: start settling only once it\n // has gone out, so work the handler registered along the way is included.\n const sent = new Promise<void>((resolve) => res.once('close', () => resolve()))\n platform.waitUntil(sent.then(settleBackgroundWork))\n }\n },\n\n async close() {\n const current = app\n app = undefined\n if (current) await (await current).shutdown()\n },\n }\n}\n","import cluster from 'node:cluster'\nimport { reportError } from '../core/observers'\nimport { createLogger, Container } from '../core'\nimport { reloadEnv } from '../config/env'\nimport { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\nimport { ENTRY_CAPTURE, type EntryCapture } from './handler'\n\n/** Reload env from .env file (HMR rebuild) — config now lives in-tree. */\nfunction tryReloadEnv(): void {\n try {\n reloadEnv()\n } catch {\n // Best-effort: never crash bootstrap because env reload failed.\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application.\n *\n * Creates the Express app, registers modules and adapters, and starts\n * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages\n * the server and HMR — source changes are picked up instantly without\n * losing database connections or WebSocket state.\n *\n * @returns The {@link Application} instance.\n *\n * @example\n * ```ts\n * // src/index.ts\n * import 'reflect-metadata'\n * import { bootstrap } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const app = await bootstrap({ modules })\n * ```\n */\nexport async function bootstrap(options: ApplicationOptions): Promise<Application> {\n // ── Loaded by createHandler(() => import('./index')) ────────────────\n // The serverless entry reuses this call's options: build the app and hand\n // it over without listening, forking or registering process hooks.\n const capture = (globalThis as Record<symbol, unknown>)[ENTRY_CAPTURE]\n if (typeof capture === 'function') {\n const app = new Application(options)\n ;(capture as EntryCapture)(app, options)\n return app\n }\n\n // ── Cluster mode ─────────────────────────────────────────────────────\n // In cluster mode the primary process forks workers and never runs the\n // Express application itself. Only workers proceed past this block.\n // Cluster is disabled in Vite dev mode — Vite owns the HTTP server and\n // forked workers would each create their own Vite instance on separate ports.\n const isViteDev = !!(globalThis as any).__kickjs_httpServer\n if (options.cluster && isViteDev) {\n log.warn(\n 'Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).',\n )\n }\n if (options.cluster && cluster.isPrimary && !isViteDev) {\n const clusterOpts: ClusterOptions = typeof options.cluster === 'object' ? options.cluster : {}\n setupClusterPrimary(clusterOpts)\n\n // Return a placeholder — the primary never serves HTTP traffic.\n // The Application is created only so callers get a valid reference.\n return new Application(options)\n }\n\n // Internal: globalThis stores the app instance and Vite's HTTP server\n // reference across HMR rebuilds. When __kickjs_httpServer is set, the\n // Vite plugin owns the port and bootstrap() skips server creation.\n // On subsequent calls (HMR), the Express handler is swapped without\n // restarting the server — preserving DB connections and port bindings.\n const g = globalThis as any\n\n // ── Global error handlers + signal hooks ─────────────────────────────\n // `processHooks` controls whether KickJS registers its own\n // process-level handlers. Defaults to `'auto'` — register everything.\n // Adopters that bring their own observability stack (OpenTelemetry SDK,\n // Sentry, custom shutdown choreographer) often register their own\n // SIGINT/SIGTERM handlers and need to opt out of ours so the two don't\n // race to call `process.exit(0)`. Three modes:\n // - 'auto' (default): register uncaughtException/unhandledRejection\n // loggers + SIGINT/SIGTERM → `app.shutdown()` → `process.exit(0)`.\n // - 'errors-only': register the error loggers; skip signal handlers.\n // Use this when you have your own shutdown choreographer that calls\n // `app.shutdown()` itself.\n // - 'manual': skip everything. Adopter is responsible for both error\n // logging and signal-driven shutdown.\n const processHooks = options.processHooks ?? 'auto'\n\n if (!g.__kickBootstrapped) {\n if (processHooks !== 'manual') {\n // A listener here replaces Node's own handling, which exits with code\n // 1. Keep the failure in the exit code: a boot that throws — a top-level\n // `await bootstrap()` rejecting — must not end the process with 0, or a\n // deploy reads the crash as success.\n process.on('uncaughtException', (err) => {\n log.error(err, 'Uncaught exception')\n reportError(err, { source: 'uncaught' })\n process.exitCode = 1\n })\n\n process.on('unhandledRejection', (reason) => {\n log.error(reason as any, 'Unhandled rejection')\n reportError(reason, { source: 'unhandled-rejection' })\n process.exitCode = 1\n })\n }\n\n if (processHooks === 'auto' && !g.__kickjs_httpServer) {\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, async () => {\n log.info(`Received ${signal}, shutting down...`)\n if (g.__app) await g.__app.shutdown()\n process.exit(0)\n })\n }\n }\n\n g.__kickBootstrapped = true\n }\n\n // ── HMR rebuild ──────────────────────────────────────────────────────\n if (g.__app) {\n log.debug('HMR rebuild triggered')\n\n // Tear the PREVIOUS app down before replacing it. Without this the old\n // Application was dropped on the floor still running: its adapters kept\n // their sockets and consumers open, so every save added another set.\n //\n // Observed in the wild as one process holding several consumer-group\n // members — on a single-partition topic only one can hold the assignment,\n // and it was a leaked consumer no longer wired to anything, so jobs\n // stopped being processed. A second socket.io server on the same HTTP\n // server crashed `handleUpgrade()` the same way.\n //\n // `closeServer: false` is load-bearing: the dev HTTP server is shared\n // across rebuilds, so a full shutdown would close the listening socket and\n // kill HMR on the first save.\n //\n // Failures are logged, not thrown — one broken adapter must not leave the\n // dev server wedged with no app at all.\n try {\n await g.__app.shutdown({ closeServer: false })\n } catch (err) {\n log.error(err as Error, 'HMR teardown of the previous app failed')\n }\n\n tryReloadEnv()\n Container.reset()\n\n const freshApp = new Application(options)\n g.__app = freshApp\n g.__kickjs_container = freshApp.getContainer()\n\n await freshApp.start()\n log.debug('HMR rebuild complete')\n return freshApp\n }\n\n // ── First boot ───────────────────────────────────────────────────────\n const app = new Application(options)\n g.__app = app\n g.__kickjs_container = app.getContainer()\n\n if (process.env.KICK_TINKER) {\n await app.registerOnly()\n return app\n }\n\n await app.start()\n\n return app\n}\n"],"mappings":";;;;;;;;;;qnBAmCA,MAAMA,MAAM,aAAa,iBAAiB,EACpC,YAAc,cAAc,YAAY,GAAG,EAGpC,gBAAkB,mBAa/B,SAAS,YAAqC,CAC5C,GAAI,CACF,OAAQ,YAAY,QAAQ,CAAC,CAA0B,IACzD,MAAQ,CACN,MACF,CACF,CAGA,SAAS,eAAyB,CAChC,MAAO,CAAC,QAAQ,UAAY,QAAQ,IAAAE,mBAAyB,GAC/D,CAEA,MAAa,gBAAkB,cAAkC,CAC/D,KAAM,kBACN,SAAU,CAAE,QAAS,EAAK,EAC1B,MAAM,QAAS,CACb,IAAM,UAAwB,CAAC,EACzB,yBAAW,IAAI,IACjB,KAAkB,CAAC,EAEvB,MAAO,CACL,WAAW,CAAE,WAAa,CAGxB,GAFI,QAAQ,UAAY,IAAS,CAAC,cAAc,IAChD,KAAO,aAAa,SAAS,EACzB,KAAK,SAAW,GAAG,OAEvB,IAAM,OAAS,WAAW,EAC1B,GAAI,CAAC,OAAQ,CACX,MAAI,KACF,GAAG,KAAK,OAAO,iGAEjB,EACA,MACF,CAEA,IAAM,KAAO,IAAc,UAAiC,CAE1D,IAAM,EAAI,WAAW,IAAK,UAAwB,OAAO,CAAC,CAA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,MAAM,SAAS,MAAM,EACrB,IAAI,MAAM,sBAAsB,EACzB,QACT,CAGA,IAAM,IAAM,IAAI,YAAY,OAAO,EAWnC,MAVA,GAAE,MAAQ,IACV,EAAE,mBAAqB,IAAI,aAAa,EAEpC,QAAQ,IAAI,aACd,MAAM,IAAI,aAAa,EAChB,MAGT,MAAM,IAAI,MAAM,EAET,IACT"}
1
+ {"version":3,"file":"bootstrap-B_6QfzXV.mjs","names":["log","log","\"KICK_CRON_WORKER\""],"sources":["../src/http/cron-adapter.ts","../src/http/cluster.ts","../src/http/handler.ts","../src/http/bootstrap.ts"],"sourcesContent":["/**\n * `KickCronAdapter()` — runs `@Cron` jobs on the Node server.\n *\n * Named with the `Kick` prefix (adapter name and logger too) so it never\n * collides with an app's own `CronAdapter` — which is also why it is opt-in.\n *\n * Opt-in: `@Cron` only records metadata, and apps that schedule jobs with\n * their own adapter keep doing so — adding this one to such an app would run\n * every job twice. Register it once:\n *\n * ```ts\n * bootstrap({ modules, adapters: [KickCronAdapter()] })\n * ```\n *\n * Timing comes from the optional peer `croner` (`pnpm add croner`), loaded\n * only when there is a job to schedule. Each tick resolves the job's class\n * from the container (the same singletons a request gets) and calls\n * `runCronJob`, which applies `enabled` / `overlap` and reports failures to\n * the error observers.\n *\n * Several processes: in `bootstrap({ cluster })`, only the worker the primary\n * marks with `KICK_CRON_WORKER=1` schedules, so a job runs once per cluster.\n * Several separate instances (replicas behind a load balancer) each schedule\n * every job — turn it off on all but one (`KickCronAdapter({ enabled: false })`),\n * or have the job take a lock.\n *\n * @module @forinda/kickjs/http/cron-adapter\n */\nimport cluster from 'node:cluster'\nimport { createRequire } from 'node:module'\nimport { defineAdapter } from '../core/define-adapter'\nimport { createLogger } from '../core/logger'\nimport { listCronJobs, runCronJob, type CronJob } from '../core/cron'\nimport type { Container } from '../core/container'\n\nconst log = createLogger('KickCronAdapter')\nconst peerRequire = createRequire(import.meta.url)\n\n/** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */\nexport const CRON_WORKER_ENV = 'KICK_CRON_WORKER'\n\nexport interface CronAdapterOptions {\n /** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */\n enabled?: boolean\n}\n\ninterface Schedule {\n stop(): void\n}\n\ntype CronerCtor = new (pattern: string, options: { timezone?: string }, fn: () => void) => Schedule\n\nfunction loadCroner(): CronerCtor | undefined {\n try {\n return (peerRequire('croner') as { Cron: CronerCtor }).Cron\n } catch {\n return undefined\n }\n}\n\n/** Whether this process should schedule jobs — one worker per cluster. */\nfunction isCronProcess(): boolean {\n return !cluster.isWorker || process.env[CRON_WORKER_ENV] === '1'\n}\n\nexport const KickCronAdapter = defineAdapter<CronAdapterOptions>({\n name: 'KickCronAdapter',\n defaults: { enabled: true },\n build(options) {\n const schedules: Schedule[] = []\n const inFlight = new Set<Promise<unknown>>()\n let jobs: CronJob[] = []\n\n return {\n afterStart({ container }) {\n if (options.enabled === false || !isCronProcess()) return\n jobs = listCronJobs(container)\n if (jobs.length === 0) return\n\n const Croner = loadCroner()\n if (!Croner) {\n log.warn(\n `${jobs.length} @Cron job(s) found but \"croner\" is not installed, so none will run. ` +\n 'Install it: pnpm add croner',\n )\n return\n }\n\n const run = (job: CronJob, trigger: 'schedule' | 'init') => {\n // Failures are already logged and reported by runCronJob.\n const p = runCronJob(job, container as Container, trigger).catch(() => {})\n inFlight.add(p)\n void p.finally(() => inFlight.delete(p))\n }\n\n for (const job of jobs) {\n schedules.push(\n new Croner(\n job.expression,\n // No croner `name`: croner keeps names in a process-wide registry\n // and throws on a duplicate.\n job.timezone ? { timezone: job.timezone } : {},\n () => run(job, 'schedule'),\n ),\n )\n if (job.runOnInit) run(job, 'init')\n }\n log.info(`Scheduled ${jobs.length} @Cron job(s): ${jobs.map((j) => j.name).join(', ')}`)\n },\n\n /**\n * Stops the schedules, then waits for running jobs so they don't lose\n * their dependencies mid-run. Also runs on every HMR reload, so a reload\n * never leaves a second copy ticking.\n */\n async shutdown() {\n for (const schedule of schedules.splice(0)) schedule.stop()\n await Promise.all(inFlight)\n },\n\n introspect() {\n return {\n protocolVersion: 1,\n name: 'KickCronAdapter',\n kind: 'adapter',\n state: {\n jobs: jobs.map((j) => ({\n name: j.name,\n expression: j.expression,\n timezone: j.timezone,\n description: j.description,\n })),\n },\n } as never\n },\n }\n },\n})\n","import cluster from 'node:cluster'\nimport { CRON_WORKER_ENV } from './cron-adapter'\nimport os from 'node:os'\nimport { createLogger } from '../core'\nimport { reactive, ref } from '../core/reactivity'\n\nconst log = createLogger('Cluster')\n\nexport interface ClusterOptions {\n /** Number of worker processes (default: os.cpus().length) */\n workers?: number\n /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */\n gracefulShutdownTimeout?: number\n /** Delay between worker restarts (ms), default: 1000 */\n restartDelay?: number\n /** Max failures in restartWindow before refusing to restart, default: 5 */\n maxFailures?: number\n /** Time window for counting failures (ms), default: 30000 */\n restartWindow?: number\n}\n\n/** Returns true if the current process is the cluster primary */\nexport function isClusterPrimary(): boolean {\n return cluster.isPrimary\n}\n\n/**\n * Fork worker processes and manage the cluster lifecycle.\n *\n * The primary process forks `workers` child processes. Each worker\n * shares the same port via Node's built-in `cluster` module (OS\n * round-robin load balancing).\n *\n * Features:\n * - Graceful shutdown with timeout fallback to forceful kill\n * - Auto-restart dead workers (respects voluntary disconnects)\n * - Startup timeout detection (stuck workers)\n * - Crash loop prevention (backoff on rapid failures)\n * - Comprehensive lifecycle logging\n */\nexport function setupClusterPrimary(opts: ClusterOptions): void {\n const numWorkers = opts.workers ?? os.cpus().length\n const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5000\n const restartDelay = opts.restartDelay ?? 1000\n const maxFailures = opts.maxFailures ?? 5\n const restartWindow = opts.restartWindow ?? 30000\n\n const startupTimeouts = new Map<number, NodeJS.Timeout>()\n const state = reactive({\n failureTimestamps: [] as number[],\n shuttingDown: false,\n })\n const activeWorkers = ref(0)\n\n log.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`)\n\n // Exactly one worker runs `KickCronAdapter` jobs, so a job fires once per\n // cluster rather than once per worker. The primary marks it with\n // KICK_CRON_WORKER=1; when it dies, the next fork inherits the role.\n let cronWorkerId: number | undefined\n const forkWorker = (): void => {\n const takesCron = cronWorkerId === undefined\n const worker = cluster.fork(takesCron ? { [CRON_WORKER_ENV]: '1' } : undefined)\n if (takesCron) cronWorkerId = worker.id\n }\n\n // Initial fork\n for (let i = 0; i < numWorkers; i++) {\n forkWorker()\n }\n\n // Detect stuck workers (no 'listening' event within timeout)\n cluster.on('fork', (worker) => {\n const timeout = setTimeout(() => {\n log.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`)\n worker.kill()\n }, 10000)\n\n startupTimeouts.set(worker.id, timeout)\n activeWorkers.value++\n log.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)\n })\n\n // Clear startup timeout when worker is ready\n cluster.on('listening', (worker, address) => {\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n log.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)\n })\n\n // Log when worker comes online\n cluster.on('online', (worker) => {\n log.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)\n })\n\n // Auto-restart dead workers (unless intentionally disconnected)\n cluster.on('exit', (worker, code, signal) => {\n // Clear startup timeout if still pending\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n\n // Don't restart if worker was intentionally disconnected\n activeWorkers.value--\n if (worker.id === cronWorkerId) cronWorkerId = undefined\n\n if (worker.exitedAfterDisconnect) {\n log.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`)\n return\n }\n\n // Track crash history globally (worker IDs change on restart)\n const now = Date.now()\n // Remove timestamps outside the window, then add the current failure\n while (\n state.failureTimestamps.length > 0 &&\n now - state.failureTimestamps[0] >= restartWindow\n ) {\n state.failureTimestamps.shift()\n }\n state.failureTimestamps.push(now)\n\n // Prevent restart loops\n if (state.failureTimestamps.length > maxFailures) {\n log.error(\n `${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`,\n )\n // Optionally exit the primary if too many workers are crashing\n if (activeWorkers.value === 0) {\n log.error('All workers have crashed, exiting primary')\n process.exit(1)\n }\n return\n }\n\n log.warn(\n `Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`,\n )\n\n setTimeout(() => {\n // Only restart if we still need more workers\n if (activeWorkers.value < numWorkers) {\n forkWorker()\n }\n }, restartDelay)\n })\n\n // Log when worker disconnects (can happen before exit)\n cluster.on('disconnect', (worker) => {\n log.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)\n })\n\n // Forward shutdown signals to workers (disconnect so exitedAfterDisconnect is set)\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => {\n if (state.shuttingDown) return\n state.shuttingDown = true\n log.info(`Primary received ${signal}, disconnecting workers...`)\n cluster.disconnect(() => {\n log.info('All workers disconnected, exiting primary')\n process.exit(0)\n })\n // Force kill after graceful timeout\n setTimeout(() => {\n log.warn('Graceful shutdown timed out, forcing exit')\n process.exit(1)\n }, gracefulTimeout).unref()\n })\n }\n}\n","/**\n * The app as a request handler, with no listening server of its own — for\n * platforms that hand you requests instead of a port: Netlify Functions,\n * Vercel Functions, and any other serverless or embedding host.\n *\n * @module @forinda/kickjs/http/handler\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { Application, type ApplicationOptions } from './application'\nimport { forwardBackgroundWork, settleBackgroundWork, type PlatformContext } from './background'\n\n/** A KickJS app exposed as request handlers. See {@link createHandler}. */\nexport interface KickHandler {\n /**\n * Web-standard handler: `fetch(Request) → Response`. Netlify Functions,\n * Vercel's fetch export, and anything else that speaks `Request`.\n *\n * Pass the platform context (Netlify's `context`, `{ waitUntil }` from\n * `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after\n * the response instead of being frozen with the instance.\n */\n fetch(request: Request, platform?: PlatformContext): Promise<Response>\n /** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */\n node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>\n /** Set the app up now instead of on the first request (warm-up). */\n ready(): Promise<Application>\n /** Shut adapters down and stop the internal forwarding server, if one started. */\n close(): Promise<void>\n}\n\n/**\n * Set on `globalThis` while `createHandler(() => import('./index'))` loads the\n * app's entry: `bootstrap()` hands its app here instead of starting it.\n * @internal\n */\nexport const ENTRY_CAPTURE = Symbol.for('kickjs.handler.entryCapture')\n\n/** What `bootstrap()` hands to a loading handler. @internal */\nexport type EntryCapture = (app: Application, options: ApplicationOptions) => void\n\n/**\n * Load the app's own entry and keep the app its `bootstrap()` call builds.\n * Retries after a failed setup reuse the captured options.\n */\nfunction captureEntry(\n load: () => Promise<unknown>,\n): () => Promise<{ first: Application; options: ApplicationOptions }> {\n let pending: Promise<{ first: Application; options: ApplicationOptions }> | undefined\n return () =>\n (pending ??= (async () => {\n let captured: { first: Application; options: ApplicationOptions } | undefined\n const g = globalThis as Record<symbol, unknown>\n const capture: EntryCapture = (first, options) => {\n captured ??= { first, options }\n }\n g[ENTRY_CAPTURE] = capture\n try {\n await load()\n } finally {\n if (g[ENTRY_CAPTURE] === capture) delete g[ENTRY_CAPTURE]\n }\n if (!captured) {\n throw new Error(\n 'createHandler(): the entry finished loading without calling bootstrap(). ' +\n \"Pass the module that calls it — createHandler(() => import('./index')) — or pass the options.\",\n )\n }\n return captured\n })().catch((err) => {\n pending = undefined\n throw err\n }))\n}\n\n/**\n * Build a KickJS app as request handlers instead of a listening server.\n *\n * Takes the same options as `bootstrap()`, or a function that imports the\n * app's entry — the file that calls `bootstrap()`. With the entry, the app\n * is built from that one `bootstrap({ ... })` call, so the server and the\n * function never drift apart:\n *\n * ```ts\n * // src/serverless.ts\n * export const handler = createHandler(() => import('./index'))\n * ```\n *\n * While the entry loads, its `bootstrap()` call builds the app without\n * starting it — no port, no process signal handlers, no cluster. The app is set up once per process\n * (per function instance), lazily on the first request, and reused after that.\n * Nothing listens on a port, `afterStart` does not run, and no process signal\n * handlers are registered — the platform owns the process.\n *\n * `fetch` uses the runtime's own fetch when it has one (the h3 v2 runtime).\n * Runtimes built on Node request/response objects — Express, the default —\n * are served through a server bound to `127.0.0.1` on a random port inside the\n * same process, started on first use: the `Request` is forwarded to it and its\n * response returned. Request bodies are buffered on that path; response bodies\n * stream. Adapters that rewrite the `res` prototype (Express does) make a\n * direct Request→`res` bridge unreliable, which is why this forwards instead.\n *\n * One handler per process: the DI container is process-wide.\n *\n * @example\n * ```ts\n * // server/src/serverless.ts\n * import 'reflect-metadata'\n * import './config'\n * import { createHandler } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const handler = createHandler({ modules })\n *\n * // netlify/functions/api.mjs\n * export default (request, context) => handler.fetch(request, context)\n * export const config = { path: '/api/*' }\n * ```\n */\nexport function createHandler(options: ApplicationOptions | (() => Promise<unknown>)): KickHandler {\n let app: Promise<Application> | undefined\n const entry =\n typeof options === 'function'\n ? captureEntry(options)\n : async () => ({ first: undefined, options })\n // The app the entry's bootstrap() built is used once; a retry builds anew.\n let firstUsed = false\n\n const ready = (): Promise<Application> => {\n app ??= (async () => {\n let loaded: Awaited<ReturnType<typeof entry>>\n try {\n loaded = await entry()\n } catch (err) {\n // The entry failed to load: try again on the next request.\n app = undefined\n throw err\n }\n const instance = loaded.first && !firstUsed ? loaded.first : new Application(loaded.options)\n firstUsed = true\n try {\n await instance.startWithoutServer()\n } catch (err) {\n // A failed setup (a database that was briefly down, say) is retried on\n // the next request. Shut this attempt down first so its adapters don't\n // stay live next to the retry's.\n app = undefined\n await instance.shutdown().catch(() => {})\n throw err\n }\n return instance\n })()\n return app\n }\n\n return {\n ready,\n\n async fetch(request, platform) {\n const response = await (await ready()).fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n\n async node(req, res, platform) {\n const instance = await ready()\n instance.handle(req, res)\n if (platform?.waitUntil) {\n // The response is written asynchronously: start settling only once it\n // has gone out, so work the handler registered along the way is included.\n const sent = new Promise<void>((resolve) => res.once('close', () => resolve()))\n platform.waitUntil(sent.then(settleBackgroundWork))\n }\n },\n\n async close() {\n const current = app\n app = undefined\n if (current) await (await current).shutdown()\n },\n }\n}\n","import cluster from 'node:cluster'\nimport { reportError } from '../core/observers'\nimport { createLogger, Container } from '../core'\nimport { reloadEnv } from '../config/env'\nimport { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\nimport { ENTRY_CAPTURE, type EntryCapture } from './handler'\n\n/** Reload env from .env file (HMR rebuild) — config now lives in-tree. */\nfunction tryReloadEnv(): void {\n try {\n reloadEnv()\n } catch {\n // Best-effort: never crash bootstrap because env reload failed.\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application.\n *\n * Creates the Express app, registers modules and adapters, and starts\n * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages\n * the server and HMR — source changes are picked up instantly without\n * losing database connections or WebSocket state.\n *\n * @returns The {@link Application} instance.\n *\n * @example\n * ```ts\n * // src/index.ts\n * import 'reflect-metadata'\n * import { bootstrap } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const app = await bootstrap({ modules })\n * ```\n */\nexport async function bootstrap(options: ApplicationOptions): Promise<Application> {\n // ── Loaded by createHandler(() => import('./index')) ────────────────\n // The serverless entry reuses this call's options: build the app and hand\n // it over without listening, forking or registering process hooks.\n const capture = (globalThis as Record<symbol, unknown>)[ENTRY_CAPTURE]\n if (typeof capture === 'function') {\n const app = new Application(options)\n ;(capture as EntryCapture)(app, options)\n return app\n }\n\n // ── Cluster mode ─────────────────────────────────────────────────────\n // In cluster mode the primary process forks workers and never runs the\n // Express application itself. Only workers proceed past this block.\n // Cluster is disabled in Vite dev mode — Vite owns the HTTP server and\n // forked workers would each create their own Vite instance on separate ports.\n const isViteDev = !!(globalThis as any).__kickjs_httpServer\n if (options.cluster && isViteDev) {\n log.warn(\n 'Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).',\n )\n }\n if (options.cluster && cluster.isPrimary && !isViteDev) {\n const clusterOpts: ClusterOptions = typeof options.cluster === 'object' ? options.cluster : {}\n setupClusterPrimary(clusterOpts)\n\n // Return a placeholder — the primary never serves HTTP traffic.\n // The Application is created only so callers get a valid reference.\n return new Application(options)\n }\n\n // Internal: globalThis stores the app instance and Vite's HTTP server\n // reference across HMR rebuilds. When __kickjs_httpServer is set, the\n // Vite plugin owns the port and bootstrap() skips server creation.\n // On subsequent calls (HMR), the Express handler is swapped without\n // restarting the server — preserving DB connections and port bindings.\n const g = globalThis as any\n\n // ── Global error handlers + signal hooks ─────────────────────────────\n // `processHooks` controls whether KickJS registers its own\n // process-level handlers. Defaults to `'auto'` — register everything.\n // Adopters that bring their own observability stack (OpenTelemetry SDK,\n // Sentry, custom shutdown choreographer) often register their own\n // SIGINT/SIGTERM handlers and need to opt out of ours so the two don't\n // race to call `process.exit(0)`. Three modes:\n // - 'auto' (default): register uncaughtException/unhandledRejection\n // loggers + SIGINT/SIGTERM → `app.shutdown()` → `process.exit(0)`.\n // - 'errors-only': register the error loggers; skip signal handlers.\n // Use this when you have your own shutdown choreographer that calls\n // `app.shutdown()` itself.\n // - 'manual': skip everything. Adopter is responsible for both error\n // logging and signal-driven shutdown.\n const processHooks = options.processHooks ?? 'auto'\n\n if (!g.__kickBootstrapped) {\n if (processHooks !== 'manual') {\n // A listener here replaces Node's own handling, which exits with code\n // 1. Keep the failure in the exit code: a boot that throws — a top-level\n // `await bootstrap()` rejecting — must not end the process with 0, or a\n // deploy reads the crash as success.\n process.on('uncaughtException', (err) => {\n log.error(err, 'Uncaught exception')\n reportError(err, { source: 'uncaught' })\n process.exitCode = 1\n })\n\n process.on('unhandledRejection', (reason) => {\n log.error(reason as any, 'Unhandled rejection')\n reportError(reason, { source: 'unhandled-rejection' })\n process.exitCode = 1\n })\n }\n\n if (processHooks === 'auto' && !g.__kickjs_httpServer) {\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, async () => {\n log.info(`Received ${signal}, shutting down...`)\n if (g.__app) await g.__app.shutdown()\n process.exit(0)\n })\n }\n }\n\n g.__kickBootstrapped = true\n }\n\n // ── HMR rebuild ──────────────────────────────────────────────────────\n if (g.__app) {\n log.debug('HMR rebuild triggered')\n\n // Tear the PREVIOUS app down before replacing it. Without this the old\n // Application was dropped on the floor still running: its adapters kept\n // their sockets and consumers open, so every save added another set.\n //\n // Observed in the wild as one process holding several consumer-group\n // members — on a single-partition topic only one can hold the assignment,\n // and it was a leaked consumer no longer wired to anything, so jobs\n // stopped being processed. A second socket.io server on the same HTTP\n // server crashed `handleUpgrade()` the same way.\n //\n // `closeServer: false` is load-bearing: the dev HTTP server is shared\n // across rebuilds, so a full shutdown would close the listening socket and\n // kill HMR on the first save.\n //\n // Failures are logged, not thrown — one broken adapter must not leave the\n // dev server wedged with no app at all.\n try {\n await g.__app.shutdown({ closeServer: false })\n } catch (err) {\n log.error(err as Error, 'HMR teardown of the previous app failed')\n }\n\n tryReloadEnv()\n Container.reset()\n\n const freshApp = new Application(options)\n g.__app = freshApp\n g.__kickjs_container = freshApp.getContainer()\n\n await freshApp.start()\n log.debug('HMR rebuild complete')\n return freshApp\n }\n\n // ── First boot ───────────────────────────────────────────────────────\n const app = new Application(options)\n g.__app = app\n g.__kickjs_container = app.getContainer()\n\n if (process.env.KICK_TINKER) {\n await app.registerOnly()\n return app\n }\n\n await app.start()\n\n return app\n}\n"],"mappings":";;;;;;;;;;qnBAmCA,MAAMA,MAAM,aAAa,iBAAiB,EACpC,YAAc,cAAc,YAAY,GAAG,EAGpC,gBAAkB,mBAa/B,SAAS,YAAqC,CAC5C,GAAI,CACF,OAAQ,YAAY,QAAQ,CAAC,CAA0B,IACzD,MAAQ,CACN,MACF,CACF,CAGA,SAAS,eAAyB,CAChC,MAAO,CAAC,QAAQ,UAAY,QAAQ,IAAAE,mBAAy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vC,QAAQ,GAAG,OAAQ,SAAY,CAC7B,IAAI,KAAK,YAAY,OAAO,mBAAmB,EAC3C,EAAE,OAAO,MAAM,EAAE,MAAM,SAAS,EACpC,QAAQ,KAAK,CAAC,CAChB,CAAC,EAIL,EAAE,mBAAqB,EACzB,CAGA,GAAI,EAAE,MAAO,CACX,IAAI,MAAM,uBAAuB,EAkBjC,GAAI,CACF,MAAM,EAAE,MAAM,SAAS,CAAE,YAAa,EAAM,CAAC,CAC/C,OAAS,IAAK,CACZ,IAAI,MAAM,IAAc,yCAAyC,CACnE,CAEA,aAAa,EACb,UAAU,MAAM,EAEhB,IAAM,SAAW,IAAI,YAAY,OAAO,EAMxC,MALA,GAAE,MAAQ,SACV,EAAE,mBAAqB,SAAS,aAAa,EAE7C,MAAM,SAAS,MAAM,EACrB,IAAI,MAAM,sBAAsB,EACzB,QACT,CAGA,IAAM,IAAM,IAAI,YAAY,OAAO,EAWnC,MAVA,GAAE,MAAQ,IACV,EAAE,mBAAqB,IAAI,aAAa,EAEpC,QAAQ,IAAI,aACd,MAAM,IAAI,aAAa,EAChB,MAGT,MAAM,IAAI,MAAM,EAET,IACT"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.3.1
2
+ * @forinda/kickjs v10.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  var BoundedCounters=class{windowMs;limit;max;hits=/* @__PURE__ */ new Map;singles=/* @__PURE__ */ new Set;constructor(windowMs,limit=1/0,max=1e5){this.windowMs=windowMs,this.limit=limit,this.max=max}get size(){return this.hits.size}increment(key){let now=Date.now(),entry=this.hits.get(key);if(entry&&entry.reset>now)return entry.hits++,entry.hits>1&&this.singles.delete(key),{totalHits:entry.hits,resetTime:new Date(entry.reset)};if(this.remove(key),this.sweep(now),this.hits.size>=this.max){let single=this.limit>1?this.singles.values().next().value:void 0;if(single===void 0){let oldest=this.hits.values().next().value;return{totalHits:1/0,resetTime:new Date(oldest.reset)}}this.remove(single)}let fresh={hits:1,reset:now+this.windowMs};return this.hits.set(key,fresh),this.singles.add(key),{totalHits:1,resetTime:new Date(fresh.reset)}}decrement(key){let entry=this.hits.get(key);entry&&entry.hits!==0&&(entry.hits--,entry.hits<=1&&this.singles.add(key))}reset(key){this.remove(key)}sweep(now=Date.now()){for(let[key,entry]of this.hits){if(entry.reset>now)break;this.remove(key)}}clear(){this.hits.clear(),this.singles.clear()}remove(key){this.hits.delete(key),this.singles.delete(key)}};export{BoundedCounters as t};
12
- //# sourceMappingURL=bounded-counters-BcA0f0bV.mjs.map
12
+ //# sourceMappingURL=bounded-counters-C8PHfWEu.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"bounded-counters-BcA0f0bV.mjs","names":[],"sources":["../src/http/middleware/bounded-counters.ts"],"sourcesContent":["/**\n * Per-key hit counters for a fixed window, in memory, bounded — the core of\n * the in-memory rate-limit stores. Keys come from clients (an IP, a header\n * behind a proxy, a username from a custom key), so the map is capped, and\n * what happens at the cap decides who a flood of new keys can hurt:\n *\n * - Expired windows go first. The map is kept in window order (a key starting\n * a new window moves to the back), so they are always at the front, and a\n * sweep stops at the first live one — no full scan.\n * - Then a counter still at one hit, oldest first — when the limit is above\n * one, so a single hit is below it. A flood of single requests from made-up\n * keys just recycles itself; a counter a client has hit twice (a username\n * with failed logins) is never pushed out, so flooding can't reset it. At\n * most it costs a key one hit, while that key is at one. With a limit of\n * one, a single hit is already the limit, so nothing live is evicted.\n * - Only when every counter is at two or more is a new key refused, counted\n * as over any limit until the oldest window ends. Reaching that takes two\n * requests per key across the whole cap within one window.\n *\n * @internal\n */\nexport class BoundedCounters {\n private readonly hits = new Map<string, { hits: number; reset: number }>()\n /** Keys at one hit (or fewer), oldest first: the only ones evicted. */\n private readonly singles = new Set<string>()\n\n /**\n * @param limit The rate limit these counters enforce (`max`): one-hit\n * counters are only evictable while that's below it.\n */\n constructor(\n private readonly windowMs: number,\n private readonly limit = Number.POSITIVE_INFINITY,\n // ponytail: fixed cap; a store shared between instances (Redis) has its own limits.\n private readonly max = 100_000,\n ) {}\n\n get size(): number {\n return this.hits.size\n }\n\n increment(key: string): { totalHits: number; resetTime: Date } {\n const now = Date.now()\n const entry = this.hits.get(key)\n if (entry && entry.reset > now) {\n entry.hits++\n if (entry.hits > 1) this.singles.delete(key)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n this.remove(key)\n this.sweep(now)\n if (this.hits.size >= this.max) {\n const single = this.limit > 1 ? this.singles.values().next().value : undefined\n if (single === undefined) {\n const oldest = this.hits.values().next().value!\n return { totalHits: Number.POSITIVE_INFINITY, resetTime: new Date(oldest.reset) }\n }\n this.remove(single)\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n this.hits.set(key, fresh)\n this.singles.add(key)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n decrement(key: string): void {\n const entry = this.hits.get(key)\n if (!entry || entry.hits === 0) return\n entry.hits--\n if (entry.hits <= 1) this.singles.add(key)\n }\n\n reset(key: string): void {\n this.remove(key)\n }\n\n /** Drop expired windows, from the front. */\n sweep(now = Date.now()): void {\n for (const [key, entry] of this.hits) {\n if (entry.reset > now) break\n this.remove(key)\n }\n }\n\n clear(): void {\n this.hits.clear()\n this.singles.clear()\n }\n\n private remove(key: string): void {\n this.hits.delete(key)\n this.singles.delete(key)\n }\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,gBAAb,KAA6B,CAUR,SACA,MAEA,IAZnB,qBAAwB,IAAI,IAE5B,wBAA2B,IAAI,IAM/B,YACE,SACA,MAAyB,IAEzB,IAAuB,IACvB,CAJiB,KAAA,SAAA,SACA,KAAA,MAAA,MAEA,KAAA,IAAA,GAChB,CAEH,IAAI,MAAe,CACjB,OAAO,KAAK,KAAK,IACnB,CAEA,UAAU,IAAqD,CAC7D,IAAM,IAAM,KAAK,IAAI,EACf,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC/B,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AAK,QAAQ,OAAO,GAAG,CACzB,CACF"}
1
+ {"version":3,"file":"bounded-counters-C8PHfWEu.mjs","names":[],"sources":["../src/http/middleware/bounded-counters.ts"],"sourcesContent":["/**\n * Per-key hit counters for a fixed window, in memory, bounded — the core of\n * the in-memory rate-limit stores. Keys come from clients (an IP, a header\n * behind a proxy, a username from a custom key), so the map is capped, and\n * what happens at the cap decides who a flood of new keys can hurt:\n *\n * - Expired windows go first. The map is kept in window order (a key starting\n * a new window moves to the back), so they are always at the front, and a\n * sweep stops at the first live one — no full scan.\n * - Then a counter still at one hit, oldest first — when the limit is above\n * one, so a single hit is below it. A flood of single requests from made-up\n * keys just recycles itself; a counter a client has hit twice (a username\n * with failed logins) is never pushed out, so flooding can't reset it. At\n * most it costs a key one hit, while that key is at one. With a limit of\n * one, a single hit is already the limit, so nothing live is evicted.\n * - Only when every counter is at two or more is a new key refused, counted\n * as over any limit until the oldest window ends. Reaching that takes two\n * requests per key across the whole cap within one window.\n *\n * @internal\n */\nexport class BoundedCounters {\n private readonly hits = new Map<string, { hits: number; reset: number }>()\n /** Keys at one hit (or fewer), oldest first: the only ones evicted. */\n private readonly singles = new Set<string>()\n\n /**\n * @param limit The rate limit these counters enforce (`max`): one-hit\n * counters are only evictable while that's below it.\n */\n constructor(\n private readonly windowMs: number,\n private readonly limit = Number.POSITIVE_INFINITY,\n // ponytail: fixed cap; a store shared between instances (Redis) has its own limits.\n private readonly max = 100_000,\n ) {}\n\n get size(): number {\n return this.hits.size\n }\n\n increment(key: string): { totalHits: number; resetTime: Date } {\n const now = Date.now()\n const entry = this.hits.get(key)\n if (entry && entry.reset > now) {\n entry.hits++\n if (entry.hits > 1) this.singles.delete(key)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n this.remove(key)\n this.sweep(now)\n if (this.hits.size >= this.max) {\n const single = this.limit > 1 ? this.singles.values().next().value : undefined\n if (single === undefined) {\n const oldest = this.hits.values().next().value!\n return { totalHits: Number.POSITIVE_INFINITY, resetTime: new Date(oldest.reset) }\n }\n this.remove(single)\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n this.hits.set(key, fresh)\n this.singles.add(key)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n decrement(key: string): void {\n const entry = this.hits.get(key)\n if (!entry || entry.hits === 0) return\n entry.hits--\n if (entry.hits <= 1) this.singles.add(key)\n }\n\n reset(key: string): void {\n this.remove(key)\n }\n\n /** Drop expired windows, from the front. */\n sweep(now = Date.now()): void {\n for (const [key, entry] of this.hits) {\n if (entry.reset > now) break\n this.remove(key)\n }\n }\n\n clear(): void {\n this.hits.clear()\n this.singles.clear()\n }\n\n private remove(key: string): void {\n this.hits.delete(key)\n this.singles.delete(key)\n }\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,gBAAb,KAA6B,CAUR,SACA,MAEA,IAZnB,qBAAwB,IAAI,IAE5B,wBAA2B,IAAI,IAM/B,YACE,SACA,MAAyB,IAEzB,IAAuB,IACvB,CAJiB,KAAA,SAAA,SACA,KAAA,MAAA,MAEA,KAAA,IAAA,GAChB,CAEH,IAAI,MAAe,CACjB,OAAO,KAAK,KAAK,IACnB,CAEA,UAAU,IAAqD,CAC7D,IAAM,IAAM,KAAK,IAAI,EACf,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC/B,GAAI,OAAS,MAAM,MAAQ,IAGzB,MAFA,OAAM,OACF,MAAM,KAAO,GAAG,KAAK,QAAQ,OAAO,GAAG,EACpC,CAAE,UAAW,MAAM,KAAM,UAAW,IAAI,KAAK,MAAM,KAAK,CAAE,EAInE,GAFA,KAAK,OAAO,GAAG,EACf,KAAK,MAAM,GAAG,EACV,KAAK,KAAK,MAAQ,KAAK,IAAK,CAC9B,IAAM,OAAS,KAAK,MAAQ,EAAI,KAAK,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,MAAQ,IAAA,GACrE,GAAI,SAAW,IAAA,GAAW,CACxB,IAAM,OAAS,KAAK,KAAK,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,MACzC,MAAO,CAAE,UAAW,IAA0B,UAAW,IAAI,KAAK,OAAO,KAAK,CAAE,CAClF,CACA,KAAK,OAAO,MAAM,CACpB,CACA,IAAM,MAAQ,CAAE,KAAM,EAAG,MAAO,IAAM,KAAK,QAAS,EAGpD,OAFA,KAAK,KAAK,IAAI,IAAK,KAAK,EACxB,KAAK,QAAQ,IAAI,GAAG,EACb,CAAE,UAAW,EAAG,UAAW,IAAI,KAAK,MAAM,KAAK,CAAE,CAC1D,CAEA,UAAU,IAAmB,CAC3B,IAAM,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC1B,OAAS,MAAM,OAAS,IAC7B,MAAM,OACF,MAAM,MAAQ,GAAG,KAAK,QAAQ,IAAI,GAAG,EAC3C,CAEA,MAAM,IAAmB,CACvB,KAAK,OAAO,GAAG,CACjB,CAGA,MAAM,IAAM,KAAK,IAAI,EAAS,CAC5B,IAAK,GAAM,CAAC,IAAK,SAAU,KAAK,KAAM,CACpC,GAAI,MAAM,MAAQ,IAAK,MACvB,KAAK,OAAO,GAAG,CACjB,CACF,CAEA,OAAc,CACZ,KAAK,KAAK,MAAM,EAChB,KAAK,QAAQ,MAAM,CACrB,CAEA,OAAe,IAAmB,CAChC,KAAK,KAAK,OAAO,GAAG,EACpB,KAAK,QAAQ,OAAO,GAAG,CACzB,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.3.1
2
+ * @forinda/kickjs v10.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  function firstHop(value){return typeof value==`string`&&value.length>0?value.split(`,`)[0].trim():void 0}function headerValue(headers,name){if(headers)return typeof headers.get==`function`?headers.get(name):headers[name]}function resolveClientIp(req){if(typeof req.ip==`string`&&req.ip.length>0)return req.ip;let socketAddress=req.socket?.remoteAddress;if(socketAddress)return socketAddress;let h=req.headers;return firstHop(headerValue(h,`cf-connecting-ip`))??firstHop(headerValue(h,`x-forwarded-for`))??firstHop(headerValue(h,`x-real-ip`))}function resolvePathname(req){if(typeof req.path==`string`&&req.path.length>0)return req.path;let url=req.url;if(!url)return`/`;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(url))try{return new URL(url).pathname||`/`}catch{return`/`}let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}export{resolvePathname as n,resolveClientIp as t};
12
- //# sourceMappingURL=client-ip-BpauuVN_.mjs.map
12
+ //# sourceMappingURL=client-ip-kxT2SHut.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-ip-BpauuVN_.mjs","names":[],"sources":["../src/http/client-ip.ts"],"sourcesContent":["/**\n * Client address + pathname resolution shared by everything that runs as\n * connect-style middleware.\n *\n * Fastify and h3 hand middleware the RAW node request, so the Express\n * conveniences (`req.ip`, `req.path`, `req.originalUrl`) are `undefined`\n * there. Reading them directly produced two live bugs:\n *\n * rate-limit → every caller keyed as the `'127.0.0.1'` fallback, i.e. ONE\n * shared bucket, so a single client could exhaust the limit\n * for everyone\n * csrf → `ignorePaths` never matched, so configured exemptions were\n * silently dead\n *\n * Edge-safe: no node imports.\n */\n\n/** The request members these helpers read, from node's shape rather than Express's. */\nexport interface ClientRequestLike {\n url?: string\n /** Express-only convenience. */\n path?: string\n /** Express-only; the full path before router mounting rewrote `url`. */\n originalUrl?: string\n /** Express and Fastify compute this from their trust-proxy settings. */\n ip?: unknown\n /**\n * A plain object on every path the framework currently takes — `WebRequestShim`\n * normalizes a WHATWG `Headers` before the context is built. A `Headers`\n * instance is accepted defensively: it is not index-accessible, so if one ever\n * did arrive, every lookup would return `undefined` SILENTLY and drop each\n * caller into one shared rate-limit bucket.\n */\n headers?: Record<string, string | string[] | undefined> | Headers\n socket?: { remoteAddress?: string }\n}\n\n/** First entry of a possibly comma-separated header value. */\nfunction firstHop(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value.split(',')[0]!.trim() : undefined\n}\n\n/** Read one header from either a plain object or a WHATWG `Headers`. */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined> | Headers | undefined,\n name: string,\n): unknown {\n if (!headers) return undefined\n // `Headers` has no index access, so `headers[name]` silently yields\n // `undefined` rather than the value.\n if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name)\n return (headers as Record<string, string | string[] | undefined>)[name]\n}\n\n/**\n * The client's IP address, or `undefined` when it cannot be determined.\n *\n * Prefers the address the runtime computed — Express derives `req.ip` from\n * `trust proxy`, Fastify from `trustProxy` — because raw forwarded headers are\n * client-SPOOFABLE wherever nothing normalizes them. h3 takes the same stance:\n * its `getRequestIP` only consults `x-forwarded-for` when explicitly opted in.\n *\n * Order is `req.ip` → `socket.remoteAddress` → forwarded headers. The socket\n * comes BEFORE the headers deliberately: it cannot be spoofed, whereas a direct\n * client can vary `x-forwarded-for` per request to get a fresh rate-limit\n * bucket each time. Headers are consulted only where there is no socket — the\n * web/edge entry, where the platform terminates the connection.\n */\nexport function resolveClientIp(req: ClientRequestLike): string | undefined {\n // 1. What the runtime computed. Express derives `req.ip` from `trust proxy`,\n // Fastify from `trustProxy` — a value vetted against a CONFIGURED proxy,\n // which is the only reason to believe a forwarded header at all.\n if (typeof req.ip === 'string' && req.ip.length > 0) return req.ip\n\n // 2. The socket. Unspoofable, and present on every node runtime.\n //\n // This MUST precede the headers. A raw Fastify / h3 request has no\n // `req.ip`, so consulting `x-forwarded-for` first let a DIRECT client send\n // a different value per request and land in a fresh rate-limit bucket each\n // time — evading the limit entirely. Behind a real proxy the socket is the\n // proxy's address, which buckets clients together; the fix for that is to\n // configure the runtime's trust-proxy setting so step 1 answers, not to\n // trust an unverified header here.\n const socketAddress = req.socket?.remoteAddress\n if (socketAddress) return socketAddress\n\n // 3. Headers, only where there is no socket at all — the web/edge entry,\n // where the platform terminates the connection and these are the only\n // signal available.\n const h = req.headers\n return (\n firstHop(headerValue(h, 'cf-connecting-ip')) ??\n firstHop(headerValue(h, 'x-forwarded-for')) ??\n firstHop(headerValue(h, 'x-real-ip'))\n )\n}\n\n/** Pathname only — `req.url` carries the query string, and `req.path` is Express-only. */\nexport function resolvePathname(req: ClientRequestLike): string {\n if (typeof req.path === 'string' && req.path.length > 0) return req.path\n const url = req.url\n if (!url) return '/'\n // `WebRequestShim` already reduces the WHATWG `Request.url` to path+search,\n // but an ABSOLUTE url would otherwise be returned whole — so a skip prefix\n // like `/health` would never match `https://host/health`.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(url)) {\n try {\n return new URL(url).pathname || '/'\n } catch {\n return '/'\n }\n }\n const q = url.indexOf('?')\n return (q === -1 ? url : url.slice(0, q)) || '/'\n}\n"],"mappings":";;;;;;;;;;AAsCA,SAAS,SAAS,MAAoC,CACpD,OAAO,OAAO,OAAU,UAAY,MAAM,OAAS,EAAI,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,KAAK,EAAI,IAAA,EACvF,CAGA,SAAS,YACP,QACA,KACS,CACT,GAAK,QAIL,OADI,OAAQ,QAAoB,KAAQ,WAAoB,QAAoB,IAAI,IAAI,EAChF,QAA0D,KACpE,CAgBA,SAAgB,gBAAgB,IAA4C,CAI1E,GAAI,OAAO,IAAI,IAAO,UAAY,IAAI,GAAG,OAAS,EAAG,OAAO,IAAI,GAWhE,IAAM,cAAgB,IAAI,QAAQ,cAClC,GAAI,cAAe,OAAO,cAK1B,IAAM,EAAI,IAAI,QACd,OACE,SAAS,YAAY,EAAG,kBAAkB,CAAC,GAC3C,SAAS,YAAY,EAAG,iBAAiB,CAAC,GAC1C,SAAS,YAAY,EAAG,WAAW,CAAC,CAExC,CAGA,SAAgB,gBAAgB,IAAgC,CAC9D,GAAI,OAAO,IAAI,MAAS,UAAY,IAAI,KAAK,OAAS,EAAG,OAAO,IAAI,KACpE,IAAM,IAAM,IAAI,IAChB,GAAI,CAAC,IAAK,MAAO,IAIjB,GAAI,2BAA2B,KAAK,GAAG,EACrC,GAAI,CACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC,UAAY,GAClC,MAAQ,CACN,MAAO,GACT,CAEF,IAAM,EAAI,IAAI,QAAQ,GAAG,EACzB,OAAQ,IAAM,GAAK,IAAM,IAAI,MAAM,EAAG,CAAC,IAAM,GAC/C"}
1
+ {"version":3,"file":"client-ip-kxT2SHut.mjs","names":[],"sources":["../src/http/client-ip.ts"],"sourcesContent":["/**\n * Client address + pathname resolution shared by everything that runs as\n * connect-style middleware.\n *\n * Fastify and h3 hand middleware the RAW node request, so the Express\n * conveniences (`req.ip`, `req.path`, `req.originalUrl`) are `undefined`\n * there. Reading them directly produced two live bugs:\n *\n * rate-limit → every caller keyed as the `'127.0.0.1'` fallback, i.e. ONE\n * shared bucket, so a single client could exhaust the limit\n * for everyone\n * csrf → `ignorePaths` never matched, so configured exemptions were\n * silently dead\n *\n * Edge-safe: no node imports.\n */\n\n/** The request members these helpers read, from node's shape rather than Express's. */\nexport interface ClientRequestLike {\n url?: string\n /** Express-only convenience. */\n path?: string\n /** Express-only; the full path before router mounting rewrote `url`. */\n originalUrl?: string\n /** Express and Fastify compute this from their trust-proxy settings. */\n ip?: unknown\n /**\n * A plain object on every path the framework currently takes — `WebRequestShim`\n * normalizes a WHATWG `Headers` before the context is built. A `Headers`\n * instance is accepted defensively: it is not index-accessible, so if one ever\n * did arrive, every lookup would return `undefined` SILENTLY and drop each\n * caller into one shared rate-limit bucket.\n */\n headers?: Record<string, string | string[] | undefined> | Headers\n socket?: { remoteAddress?: string }\n}\n\n/** First entry of a possibly comma-separated header value. */\nfunction firstHop(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value.split(',')[0]!.trim() : undefined\n}\n\n/** Read one header from either a plain object or a WHATWG `Headers`. */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined> | Headers | undefined,\n name: string,\n): unknown {\n if (!headers) return undefined\n // `Headers` has no index access, so `headers[name]` silently yields\n // `undefined` rather than the value.\n if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name)\n return (headers as Record<string, string | string[] | undefined>)[name]\n}\n\n/**\n * The client's IP address, or `undefined` when it cannot be determined.\n *\n * Prefers the address the runtime computed — Express derives `req.ip` from\n * `trust proxy`, Fastify from `trustProxy` — because raw forwarded headers are\n * client-SPOOFABLE wherever nothing normalizes them. h3 takes the same stance:\n * its `getRequestIP` only consults `x-forwarded-for` when explicitly opted in.\n *\n * Order is `req.ip` → `socket.remoteAddress` → forwarded headers. The socket\n * comes BEFORE the headers deliberately: it cannot be spoofed, whereas a direct\n * client can vary `x-forwarded-for` per request to get a fresh rate-limit\n * bucket each time. Headers are consulted only where there is no socket — the\n * web/edge entry, where the platform terminates the connection.\n */\nexport function resolveClientIp(req: ClientRequestLike): string | undefined {\n // 1. What the runtime computed. Express derives `req.ip` from `trust proxy`,\n // Fastify from `trustProxy` — a value vetted against a CONFIGURED proxy,\n // which is the only reason to believe a forwarded header at all.\n if (typeof req.ip === 'string' && req.ip.length > 0) return req.ip\n\n // 2. The socket. Unspoofable, and present on every node runtime.\n //\n // This MUST precede the headers. A raw Fastify / h3 request has no\n // `req.ip`, so consulting `x-forwarded-for` first let a DIRECT client send\n // a different value per request and land in a fresh rate-limit bucket each\n // time — evading the limit entirely. Behind a real proxy the socket is the\n // proxy's address, which buckets clients together; the fix for that is to\n // configure the runtime's trust-proxy setting so step 1 answers, not to\n // trust an unverified header here.\n const socketAddress = req.socket?.remoteAddress\n if (socketAddress) return socketAddress\n\n // 3. Headers, only where there is no socket at all — the web/edge entry,\n // where the platform terminates the connection and these are the only\n // signal available.\n const h = req.headers\n return (\n firstHop(headerValue(h, 'cf-connecting-ip')) ??\n firstHop(headerValue(h, 'x-forwarded-for')) ??\n firstHop(headerValue(h, 'x-real-ip'))\n )\n}\n\n/** Pathname only — `req.url` carries the query string, and `req.path` is Express-only. */\nexport function resolvePathname(req: ClientRequestLike): string {\n if (typeof req.path === 'string' && req.path.length > 0) return req.path\n const url = req.url\n if (!url) return '/'\n // `WebRequestShim` already reduces the WHATWG `Request.url` to path+search,\n // but an ABSOLUTE url would otherwise be returned whole — so a skip prefix\n // like `/health` would never match `https://host/health`.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(url)) {\n try {\n return new URL(url).pathname || '/'\n } catch {\n return '/'\n }\n }\n const q = url.indexOf('?')\n return (q === -1 ? url : url.slice(0, q)) || '/'\n}\n"],"mappings":";;;;;;;;;;AAsCA,SAAS,SAAS,MAAoC,CACpD,OAAO,OAAO,OAAU,UAAY,MAAM,OAAS,EAAI,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,KAAK,EAAI,IAAA,EACvF,CAGA,SAAS,YACP,QACA,KACS,CACT,GAAK,QAIL,OADI,OAAQ,QAAoB,KAAQ,WAAoB,QAAoB,IAAI,IAAI,EAChF,QAA0D,KACpE,CAgBA,SAAgB,gBAAgB,IAA4C,CAI1E,GAAI,OAAO,IAAI,IAAO,UAAY,IAAI,GAAG,OAAS,EAAG,OAAO,IAAI,GAWhE,IAAM,cAAgB,IAAI,QAAQ,cAClC,GAAI,cAAe,OAAO,cAK1B,IAAM,EAAI,IAAI,QACd,OACE,SAAS,YAAY,EAAG,kBAAkB,CAAC,GAC3C,SAAS,YAAY,EAAG,iBAAiB,CAAC,GAC1C,SAAS,YAAY,EAAG,WAAW,CAAC,CAExC,CAGA,SAAgB,gBAAgB,IAAgC,CAC9D,GAAI,OAAO,IAAI,MAAS,UAAY,IAAI,KAAK,OAAS,EAAG,OAAO,IAAI,KACpE,IAAM,IAAM,IAAI,IAChB,GAAI,CAAC,IAAK,MAAO,IAIjB,GAAI,2BAA2B,KAAK,GAAG,EACrC,GAAI,CACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC,UAAY,GAClC,MAAQ,CACN,MAAO,GACT,CAEF,IAAM,EAAI,IAAI,QAAQ,GAAG,EACzB,OAAQ,IAAM,GAAK,IAAM,IAAI,MAAM,EAAG,CAAC,IAAM,GAC/C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, f as withEnv, i as Env, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "../index-Dms8LzHG.mjs";
2
+ import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, f as withEnv, i as Env, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "../index-B4aOLoId.mjs";
3
3
  export { ConfigService, type Env, type TypedConfigService, baseEnvSchema, createConfigService, defineEnv, getEnv, loadEnv, loadEnvFromSchema, reloadEnv, resetEnvCache, withEnv };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.3.1
2
+ * @forinda/kickjs v10.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"../decorate-CaEYam5J.mjs";import{n as createConfigService,t as ConfigService}from"../config-DgMxtfcW.mjs";export{ConfigService,baseEnvSchema,createConfigService,defineEnv,getEnv,loadEnv,loadEnvFromSchema,reloadEnv,resetEnvCache,withEnv};
11
+ import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"../decorate-D2oVJls5.mjs";import{n as createConfigService,t as ConfigService}from"../config-Dz-HnO4c.mjs";export{ConfigService,baseEnvSchema,createConfigService,defineEnv,getEnv,loadEnv,loadEnvFromSchema,reloadEnv,resetEnvCache,withEnv};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.3.1
2
+ * @forinda/kickjs v10.5.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{c as reloadEnv,o as loadEnv,t as __decorate}from"./decorate-CaEYam5J.mjs";import{Service}from"./core/decorators.mjs";let ConfigService=class{get env(){return loadEnv()}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv()}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};ConfigService=__decorate([Service()],ConfigService);function createConfigService(schema){let SchemaConfigService=class{get env(){return loadEnv(schema)}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv(schema)}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};return SchemaConfigService=__decorate([Service()],SchemaConfigService),SchemaConfigService}export{createConfigService as n,ConfigService as t};
12
- //# sourceMappingURL=config-DgMxtfcW.mjs.map
11
+ import{c as reloadEnv,o as loadEnv,t as __decorate}from"./decorate-D2oVJls5.mjs";import{Service}from"./core/decorators.mjs";let ConfigService=class{get env(){return loadEnv()}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv()}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};ConfigService=__decorate([Service()],ConfigService);function createConfigService(schema){let SchemaConfigService=class{get env(){return loadEnv(schema)}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv(schema)}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};return SchemaConfigService=__decorate([Service()],SchemaConfigService),SchemaConfigService}export{createConfigService as n,ConfigService as t};
12
+ //# sourceMappingURL=config-Dz-HnO4c.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-DgMxtfcW.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container._envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T>\n /** With a fallback, returned when the value is unset (`undefined` or `null`). */\n get<K extends string, T = any>(\n key: ConfigKey<K>,\n fallback: NonNullable<ConfigValue<K, T>>,\n ): NonNullable<ConfigValue<K, T>>\n get(key: string, fallback?: unknown): unknown {\n return this.env[key] ?? fallback\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller()\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n get(key: string, fallback?: unknown): unknown {\n return (this.env as Record<string, unknown>)[key] ?? fallback\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;4HA+CO,IAAM,cAAN,KAAoB,CAczB,IAAY,KAA2B,CACrC,OAAO,QAAQ,CACjB,CAiBA,IAAI,IAAa,SAA6B,CAC5C,OAAO,KAAK,IAAI,MAAQ,QAC1B,CAOA,QAAuF,CACrF,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAGA,QAAe,CACb,UAAU,EAEV,QAAQ,CACV,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAjEC,cAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,aAAA,EA6GT,SAAgB,oBAAgD,OAAW,CAGzE,IACM,oBADN,KAC8D,CAE5D,IAAY,KAAY,CACtB,OAAO,QAAQ,MAAM,CACvB,CAIA,IAAI,IAAa,SAA6B,CAC5C,OAAQ,KAAK,IAAgC,MAAQ,QACvD,CAEA,QAAyB,CACvB,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAEA,QAAe,CACb,UAAU,EACV,QAAQ,MAAM,CAChB,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAEA,MAnCC,qBAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,mBAAA,EAmCF,mBAGT"}
1
+ {"version":3,"file":"config-Dz-HnO4c.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container._envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T>\n /** With a fallback, returned when the value is unset (`undefined` or `null`). */\n get<K extends string, T = any>(\n key: ConfigKey<K>,\n fallback: NonNullable<ConfigValue<K, T>>,\n ): NonNullable<ConfigValue<K, T>>\n get(key: string, fallback?: unknown): unknown {\n return this.env[key] ?? fallback\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller()\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n get(key: string, fallback?: unknown): unknown {\n return (this.env as Record<string, unknown>)[key] ?? fallback\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;4HA+CO,IAAM,cAAN,KAAoB,CAczB,IAAY,KAA2B,CACrC,OAAO,QAAQ,CACjB,CAiBA,IAAI,IAAa,SAA6B,CAC5C,OAAO,KAAK,IAAI,MAAQ,QAC1B,CAOA,QAAuF,CACrF,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAGA,QAAe,CACb,UAAU,EAEV,QAAQ,CACV,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAjEC,cAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,aAAA,EA6GT,SAAgB,oBAAgD,OAAW,CAGzE,IACM,oBADN,KAC8D,CAE5D,IAAY,KAAY,CACtB,OAAO,QAAQ,MAAM,CACvB,CAIA,IAAI,IAAa,SAA6B,CAC5C,OAAQ,KAAK,IAAgC,MAAQ,QACvD,CAEA,QAAyB,CACvB,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAEA,QAAe,CACb,UAAU,EACV,QAAQ,MAAM,CAChB,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAEA,MAnCC,qBAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,mBAAA,EAmCF,mBAGT"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.3.1
2
+ * @forinda/kickjs v10.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -10,4 +10,4 @@
10
10
  */
11
11
  var MissingContributorError=class extends Error{key;dependent;route;dependentDefinedAt;constructor(key,dependent,route,dependentDefinedAt){let where=route?` on route ${route}`:``,declaredAt=formatDeclaredAt(dependentDefinedAt);super(`Missing context contributor '${key}' required by '${dependent}'${where}${declaredAt}`),this.name=`MissingContributorError`,this.key=key,this.dependent=dependent,this.route=route,this.dependentDefinedAt=dependentDefinedAt}},MissingContextValueError=class extends Error{key;route;constructor(key,route){let where=route?` on ${route}`:``;super(`No context value for '${key}'${where}\n Nothing wrote this key before the handler ran. Either the contributor\n that produces it isn't applied to this route, or it ran and resolved\n to undefined (check \`optional: true\` contributors).`),this.name=`MissingContextValueError`,this.key=key,this.route=route}};function formatDeclaredAt(stack){if(!stack)return``;let lines=stack.split(`
12
12
  `);for(let line of lines){let trimmed=line.trim();if(trimmed.startsWith(`at `)&&!trimmed.includes(`context-decorator.`)&&!trimmed.includes(`context-errors.`))return`\n declared at ${trimmed.replace(/^at /,``)}`}return``}var ContributorCycleError=class extends Error{cycle;route;constructor(cycle,route){let where=route?` on route ${route}`:``;super(`Cycle in context contributors${where}: ${cycle.join(` → `)}`),this.name=`ContributorCycleError`,this.cycle=Object.freeze([...cycle]),this.route=route}},DuplicateContributorError=class extends Error{key;sources;constructor(key,sources){super(`Duplicate context contributor for key '${key}' at the same precedence level. Sources: ${sources.join(`, `)}`),this.name=`DuplicateContributorError`,this.key=key,this.sources=Object.freeze([...sources])}};export{MissingContributorError as i,DuplicateContributorError as n,MissingContextValueError as r,ContributorCycleError as t};
13
- //# sourceMappingURL=context-errors-BGIOYMV5.mjs.map
13
+ //# sourceMappingURL=context-errors-gitMJXxZ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-errors-BGIOYMV5.mjs","names":[],"sources":["../src/core/context-errors.ts"],"sourcesContent":["/**\n * Errors thrown by the Context Contributor pipeline.\n *\n * `MissingContributorError`, `ContributorCycleError`, and\n * `DuplicateContributorError` are startup-time errors raised during\n * pipeline build (topo-sort + validation), not per-request — a\n * misconfigured app fails to boot rather than fails a request. Per the\n * locked design in `architecture.md` §20.4, the pipeline is validated\n * once when each route is mounted and the resolved order is cached on\n * the route.\n *\n * `MissingContextValueError` is the one request-time error here: it is\n * raised by `ctx.require(key)` when a value a handler declared it needs\n * is absent. See its doc comment for why that case can't be caught at\n * startup today.\n */\n\n/**\n * A contributor declared `dependsOn: ['<key>']` but no other contributor\n * (at any precedence level) produces that key for the same route.\n *\n * @example\n * ```text\n * MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id\n * declared at src/contributors/load-project.ts:42:18\n * ```\n */\nexport class MissingContributorError extends Error {\n readonly key: string\n readonly dependent: string\n readonly route?: string\n readonly dependentDefinedAt?: string\n\n constructor(key: string, dependent: string, route?: string, dependentDefinedAt?: string) {\n const where = route ? ` on route ${route}` : ''\n const declaredAt = formatDeclaredAt(dependentDefinedAt)\n super(`Missing context contributor '${key}' required by '${dependent}'${where}${declaredAt}`)\n this.name = 'MissingContributorError'\n this.key = key\n this.dependent = dependent\n this.route = route\n this.dependentDefinedAt = dependentDefinedAt\n }\n}\n\n/**\n * `ctx.require(key)` found no value under `key` in the per-request\n * metadata store.\n *\n * Thrown at request time, by design. `ctx.get(key)` returns\n * `T | undefined` for every key, so the usual workaround is a\n * non-null assertion — `ctx.get('tenant')!` — which compiles whether or\n * not the route actually carries the contributor that produces it. On\n * an authorization value that is the worst possible thing to leave\n * untypeable: dropping the decorator produces no diagnostic anywhere,\n * and the handler reads `undefined` as though it were a real value.\n *\n * `ctx.require()` converts that silent hole into a loud, named failure\n * that points at the missing contributor.\n *\n * A handler typed with a generated route type (`Ctx<KickRoutes…>`) also\n * gets compile-time narrowing, so a dropped decorator fails `tsc` rather\n * than reaching this error at all. This error remains the backstop for\n * routes typegen couldn't prove (module/adapter/bootstrap registrations),\n * handlers typed as plain `RequestContext`, and contributors that ran but\n * resolved to `undefined`. See `architecture.md` §20.14.\n *\n * @example\n * ```text\n * MissingContextValueError: No context value for 'tenantPerm' on GET /projects/:id\n * Nothing wrote this key before the handler ran. Either the contributor\n * that produces it isn't applied to this route, or it ran and resolved\n * to undefined (check `optional: true` contributors).\n * ```\n */\nexport class MissingContextValueError extends Error {\n readonly key: string\n readonly route?: string\n\n constructor(key: string, route?: string) {\n const where = route ? ` on ${route}` : ''\n super(\n `No context value for '${key}'${where}\\n` +\n ` Nothing wrote this key before the handler ran. Either the contributor\\n` +\n ` that produces it isn't applied to this route, or it ran and resolved\\n` +\n ` to undefined (check \\`optional: true\\` contributors).`,\n )\n this.name = 'MissingContextValueError'\n this.key = key\n this.route = route\n }\n}\n\n/**\n * Slice the first non-framework frame off a captured `Error.stack`\n * and format it as `\\n declared at <frame>` for inclusion in\n * boot-time error messages. Returns `''` when no useful frame is\n * available (hand-rolled registrations, missing stacks).\n */\nfunction formatDeclaredAt(stack: string | undefined): string {\n if (!stack) return ''\n const lines = stack.split('\\n')\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('at ')) continue\n // Skip frames inside this file or the decorator factory — the\n // adopter's call site is the next frame after those.\n if (trimmed.includes('context-decorator.')) continue\n if (trimmed.includes('context-errors.')) continue\n return `\\n declared at ${trimmed.replace(/^at /, '')}`\n }\n return ''\n}\n\n/**\n * Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field\n * lists the keys in the order they form the loop, with the first key\n * repeated at the end so the path reads naturally.\n *\n * @example\n * ```text\n * ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant\n * ```\n */\nexport class ContributorCycleError extends Error {\n readonly cycle: readonly string[]\n readonly route?: string\n\n constructor(cycle: readonly string[], route?: string) {\n const where = route ? ` on route ${route}` : ''\n super(`Cycle in context contributors${where}: ${cycle.join(' → ')}`)\n this.name = 'ContributorCycleError'\n this.cycle = Object.freeze([...cycle])\n this.route = route\n }\n}\n\n/**\n * Two contributors at the same precedence level both produce the same key\n * for the same route. Precedence resolution (method > class > module >\n * adapter > global, per architecture.md §20.4) silently drops\n * lower-precedence duplicates; this error fires only when ties occur\n * within a single level — e.g., two method-level decorators declaring\n * `key: 'tenant'`.\n *\n * `sources` is best-effort identifying labels for each conflicting\n * registration (typically the decorator's call site or registering\n * module/adapter name).\n *\n * @example\n * ```text\n * DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain\n * ```\n */\nexport class DuplicateContributorError extends Error {\n readonly key: string\n readonly sources: readonly string[]\n\n constructor(key: string, sources: readonly string[]) {\n super(\n `Duplicate context contributor for key '${key}' at the same precedence level. ` +\n `Sources: ${sources.join(', ')}`,\n )\n this.name = 'DuplicateContributorError'\n this.key = key\n this.sources = Object.freeze([...sources])\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,IAAa,wBAAb,cAA6C,KAAM,CACjD,IACA,UACA,MACA,mBAEA,YAAY,IAAa,UAAmB,MAAgB,mBAA6B,CACvF,IAAM,MAAQ,MAAQ,aAAa,QAAU,GACvC,WAAa,iBAAiB,kBAAkB,EACtD,MAAM,gCAAgC,IAAI,iBAAiB,UAAU,GAAG,QAAQ,YAAY,EAC5F,KAAK,KAAO,0BACZ,KAAK,IAAM,IACX,KAAK,UAAY,UACjB,KAAK,MAAQ,MACb,KAAK,mBAAqB,kBAC5B,CACF,EAgCa,yBAAb,cAA8C,KAAM,CAClD,IACA,MAEA,YAAY,IAAa,MAAgB,CACvC,IAAM,MAAQ,MAAQ,OAAO,QAAU,GACvC,MACE,yBAAyB,IAAI,GAAG,MAAM,iNAIxC,EACA,KAAK,KAAO,2BACZ,KAAK,IAAM,IACX,KAAK,MAAQ,KACf,CACF,EAQA,SAAS,iBAAiB,MAAmC,CAC3D,GAAI,CAAC,MAAO,MAAO,GACnB,IAAM,MAAQ,MAAM,MAAM;CAAI,EAC9B,IAAK,IAAM,QAAQ,MAAO,CACxB,IAAM,QAAU,KAAK,KAAK,EAC1B,GAAK,QAAQ,WAAW,KAAK,GAGzB,SAAQ,SAAS,oBAAoB,GACrC,SAAQ,SAAS,iBAAiB,EACtC,MAAO,qBAAqB,QAAQ,QAAQ,OAAQ,EAAE,GACxD,CACA,MAAO,EACT,CAYA,IAAa,sBAAb,cAA2C,KAAM,CAC/C,MACA,MAEA,YAAY,MAA0B,MAAgB,CACpD,IAAM,MAAQ,MAAQ,aAAa,QAAU,GAC7C,MAAM,gCAAgC,MAAM,IAAI,MAAM,KAAK,KAAK,GAAG,EACnE,KAAK,KAAO,wBACZ,KAAK,MAAQ,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC,EACrC,KAAK,MAAQ,KACf,CACF,EAmBa,0BAAb,cAA+C,KAAM,CACnD,IACA,QAEA,YAAY,IAAa,QAA4B,CACnD,MACE,0CAA0C,IAAI,2CAChC,QAAQ,KAAK,IAAI,GACjC,EACA,KAAK,KAAO,4BACZ,KAAK,IAAM,IACX,KAAK,QAAU,OAAO,OAAO,CAAC,GAAG,OAAO,CAAC,CAC3C,CACF"}
1
+ {"version":3,"file":"context-errors-gitMJXxZ.mjs","names":[],"sources":["../src/core/context-errors.ts"],"sourcesContent":["/**\n * Errors thrown by the Context Contributor pipeline.\n *\n * `MissingContributorError`, `ContributorCycleError`, and\n * `DuplicateContributorError` are startup-time errors raised during\n * pipeline build (topo-sort + validation), not per-request — a\n * misconfigured app fails to boot rather than fails a request. Per the\n * locked design in `architecture.md` §20.4, the pipeline is validated\n * once when each route is mounted and the resolved order is cached on\n * the route.\n *\n * `MissingContextValueError` is the one request-time error here: it is\n * raised by `ctx.require(key)` when a value a handler declared it needs\n * is absent. See its doc comment for why that case can't be caught at\n * startup today.\n */\n\n/**\n * A contributor declared `dependsOn: ['<key>']` but no other contributor\n * (at any precedence level) produces that key for the same route.\n *\n * @example\n * ```text\n * MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id\n * declared at src/contributors/load-project.ts:42:18\n * ```\n */\nexport class MissingContributorError extends Error {\n readonly key: string\n readonly dependent: string\n readonly route?: string\n readonly dependentDefinedAt?: string\n\n constructor(key: string, dependent: string, route?: string, dependentDefinedAt?: string) {\n const where = route ? ` on route ${route}` : ''\n const declaredAt = formatDeclaredAt(dependentDefinedAt)\n super(`Missing context contributor '${key}' required by '${dependent}'${where}${declaredAt}`)\n this.name = 'MissingContributorError'\n this.key = key\n this.dependent = dependent\n this.route = route\n this.dependentDefinedAt = dependentDefinedAt\n }\n}\n\n/**\n * `ctx.require(key)` found no value under `key` in the per-request\n * metadata store.\n *\n * Thrown at request time, by design. `ctx.get(key)` returns\n * `T | undefined` for every key, so the usual workaround is a\n * non-null assertion — `ctx.get('tenant')!` — which compiles whether or\n * not the route actually carries the contributor that produces it. On\n * an authorization value that is the worst possible thing to leave\n * untypeable: dropping the decorator produces no diagnostic anywhere,\n * and the handler reads `undefined` as though it were a real value.\n *\n * `ctx.require()` converts that silent hole into a loud, named failure\n * that points at the missing contributor.\n *\n * A handler typed with a generated route type (`Ctx<KickRoutes…>`) also\n * gets compile-time narrowing, so a dropped decorator fails `tsc` rather\n * than reaching this error at all. This error remains the backstop for\n * routes typegen couldn't prove (module/adapter/bootstrap registrations),\n * handlers typed as plain `RequestContext`, and contributors that ran but\n * resolved to `undefined`. See `architecture.md` §20.14.\n *\n * @example\n * ```text\n * MissingContextValueError: No context value for 'tenantPerm' on GET /projects/:id\n * Nothing wrote this key before the handler ran. Either the contributor\n * that produces it isn't applied to this route, or it ran and resolved\n * to undefined (check `optional: true` contributors).\n * ```\n */\nexport class MissingContextValueError extends Error {\n readonly key: string\n readonly route?: string\n\n constructor(key: string, route?: string) {\n const where = route ? ` on ${route}` : ''\n super(\n `No context value for '${key}'${where}\\n` +\n ` Nothing wrote this key before the handler ran. Either the contributor\\n` +\n ` that produces it isn't applied to this route, or it ran and resolved\\n` +\n ` to undefined (check \\`optional: true\\` contributors).`,\n )\n this.name = 'MissingContextValueError'\n this.key = key\n this.route = route\n }\n}\n\n/**\n * Slice the first non-framework frame off a captured `Error.stack`\n * and format it as `\\n declared at <frame>` for inclusion in\n * boot-time error messages. Returns `''` when no useful frame is\n * available (hand-rolled registrations, missing stacks).\n */\nfunction formatDeclaredAt(stack: string | undefined): string {\n if (!stack) return ''\n const lines = stack.split('\\n')\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('at ')) continue\n // Skip frames inside this file or the decorator factory — the\n // adopter's call site is the next frame after those.\n if (trimmed.includes('context-decorator.')) continue\n if (trimmed.includes('context-errors.')) continue\n return `\\n declared at ${trimmed.replace(/^at /, '')}`\n }\n return ''\n}\n\n/**\n * Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field\n * lists the keys in the order they form the loop, with the first key\n * repeated at the end so the path reads naturally.\n *\n * @example\n * ```text\n * ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant\n * ```\n */\nexport class ContributorCycleError extends Error {\n readonly cycle: readonly string[]\n readonly route?: string\n\n constructor(cycle: readonly string[], route?: string) {\n const where = route ? ` on route ${route}` : ''\n super(`Cycle in context contributors${where}: ${cycle.join(' → ')}`)\n this.name = 'ContributorCycleError'\n this.cycle = Object.freeze([...cycle])\n this.route = route\n }\n}\n\n/**\n * Two contributors at the same precedence level both produce the same key\n * for the same route. Precedence resolution (method > class > module >\n * adapter > global, per architecture.md §20.4) silently drops\n * lower-precedence duplicates; this error fires only when ties occur\n * within a single level — e.g., two method-level decorators declaring\n * `key: 'tenant'`.\n *\n * `sources` is best-effort identifying labels for each conflicting\n * registration (typically the decorator's call site or registering\n * module/adapter name).\n *\n * @example\n * ```text\n * DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain\n * ```\n */\nexport class DuplicateContributorError extends Error {\n readonly key: string\n readonly sources: readonly string[]\n\n constructor(key: string, sources: readonly string[]) {\n super(\n `Duplicate context contributor for key '${key}' at the same precedence level. ` +\n `Sources: ${sources.join(', ')}`,\n )\n this.name = 'DuplicateContributorError'\n this.key = key\n this.sources = Object.freeze([...sources])\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,IAAa,wBAAb,cAA6C,KAAM,CACjD,IACA,UACA,MACA,mBAEA,YAAY,IAAa,UAAmB,MAAgB,mBAA6B,CACvF,IAAM,MAAQ,MAAQ,aAAa,QAAU,GACvC,WAAa,iBAAiB,kBAAkB,EACtD,MAAM,gCAAgC,IAAI,iBAAiB,UAAU,GAAG,QAAQ,YAAY,EAC5F,KAAK,KAAO,0BACZ,KAAK,IAAM,IACX,KAAK,UAAY,UACjB,KAAK,MAAQ,MACb,KAAK,mBAAqB,kBAC5B,CACF,EAgCa,yBAAb,cAA8C,KAAM,CAClD,IACA,MAEA,YAAY,IAAa,MAAgB,CACvC,IAAM,MAAQ,MAAQ,OAAO,QAAU,GACvC,MACE,yBAAyB,IAAI,GAAG,MAAM,iNAIxC,EACA,KAAK,KAAO,2BACZ,KAAK,IAAM,IACX,KAAK,MAAQ,KACf,CACF,EAQA,SAAS,iBAAiB,MAAmC,CAC3D,GAAI,CAAC,MAAO,MAAO,GACnB,IAAM,MAAQ,MAAM,MAAM;CAAI,EAC9B,IAAK,IAAM,QAAQ,MAAO,CACxB,IAAM,QAAU,KAAK,KAAK,EAC1B,GAAK,QAAQ,WAAW,KAAK,GAGzB,SAAQ,SAAS,oBAAoB,GACrC,SAAQ,SAAS,iBAAiB,EACtC,MAAO,qBAAqB,QAAQ,QAAQ,OAAQ,EAAE,GACxD,CACA,MAAO,EACT,CAYA,IAAa,sBAAb,cAA2C,KAAM,CAC/C,MACA,MAEA,YAAY,MAA0B,MAAgB,CACpD,IAAM,MAAQ,MAAQ,aAAa,QAAU,GAC7C,MAAM,gCAAgC,MAAM,IAAI,MAAM,KAAK,KAAK,GAAG,EACnE,KAAK,KAAO,wBACZ,KAAK,MAAQ,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC,EACrC,KAAK,MAAQ,KACf,CACF,EAmBa,0BAAb,cAA+C,KAAM,CACnD,IACA,QAEA,YAAY,IAAa,QAA4B,CACnD,MACE,0CAA0C,IAAI,2CAChC,QAAQ,KAAK,IAAI,GACjC,EACA,KAAK,KAAO,4BACZ,KAAK,IAAM,IACX,KAAK,QAAU,OAAO,OAAO,CAAC,GAAG,OAAO,CAAC,CAC3C,CACF"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs v10.5.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-DaIAahW4.mjs";import{HttpException,normalizeProblem}from"./core/errors.mjs";import{t as ROUTE_SLOT}from"./route-flag-BP_jbhNy.mjs";import{r as MissingContextValueError}from"./context-errors-gitMJXxZ.mjs";import{t as isProduction}from"./is-production-TSixl400.mjs";import{t as resolveClientIp}from"./client-ip-kxT2SHut.mjs";import{a as parseQuery}from"./query-CUvSp-JT.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())}function header(headers,name){let value=headers[name];return Array.isArray(value)?value.join(`, `):value}function normalizeEtag(etag){if(/^(W\/)?".*"$/.test(etag))return etag;let weak=etag.startsWith(`W/`),bare=(weak?etag.slice(2):etag).replaceAll(`"`,``);return`${weak?`W/`:``}"${bare}"`}const opaque=tag=>tag.replace(/^W\//,``),isWeak=tag=>tag.startsWith(`W/`);function tagsOf(value){return value.match(/\*|(?:W\/)?"[^"]*"/g)??[]}function dateOf(value){if(!value)return;let ms=Date.parse(value);return Number.isNaN(ms)?void 0:ms}const seconds=date=>Math.floor(date.getTime()/1e3)*1e3;function evaluatePreconditions(method,headers,validators){let etag=validators.etag===void 0?void 0:normalizeEtag(validators.etag),modified=validators.lastModified?seconds(validators.lastModified):void 0,safe=method===`GET`||method===`HEAD`,ifMatch=header(headers,`if-match`);if(ifMatch!==void 0){let tags=tagsOf(ifMatch);if(!(tags.includes(`*`)||etag!==void 0&&!isWeak(etag)&&tags.some(t=>!isWeak(t)&&t===etag)))return 412}else{let since=dateOf(header(headers,`if-unmodified-since`));if(since!==void 0&&modified!==void 0&&modified>since)return 412}let ifNoneMatch=header(headers,`if-none-match`);if(ifNoneMatch!==void 0){let tags=tagsOf(ifNoneMatch);return tags.includes(`*`)||etag!==void 0&&tags.some(t=>opaque(t)===opaque(etag))?safe?304:412:200}if(safe){let since=dateOf(header(headers,`if-modified-since`));if(since!==void 0&&modified!==void 0&&modified<=since)return 304}return 200}function publishMatchedRoute(req,entry){let route=matchedRoutes.get(entry);route||(route=Object.freeze({method:entry.method,path:entry.path,controller:entry.meta.controller,handlerName:entry.meta.handlerName,flags:entry.meta.flags??EMPTY_FLAGS,pattern:entry.meta.pattern??entry.path,urls:entry.urls}),matchedRoutes.set(entry,route)),req[ROUTE_SLOT]=route}const matchedRoutes=/* @__PURE__ */ new WeakMap,EMPTY_FLAGS=/* @__PURE__ */ new Map;function isBigIntJsonError(err){return err instanceof TypeError&&/BigInt/.test(err.message)}function stringifyJson(data){try{return JSON.stringify(data)}catch(err){if(!isBigIntJsonError(err))throw err;return JSON.stringify(data,(_key,value)=>typeof value==`bigint`?value.toString():value)}}function sortSignature(sort){return sort.map(s=>`${s.field}:${s.direction}`).join(`,`)}function isPrimitive(value){return value===null||[`string`,`number`,`boolean`].includes(typeof value)}function encodeCursor(position,signature){let bytes=new TextEncoder().encode(JSON.stringify({v:position,s:signature})),binary=``;for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function decodeCursor(raw,signature,keys){let invalid=()=>HttpException.badRequest(`Invalid pagination cursor`);if(typeof raw!=`string`||!/^[A-Za-z0-9_-]+$/.test(raw))throw invalid();let parsed;try{let binary=atob(raw.replace(/-/g,`+`).replace(/_/g,`/`)),bytes=Uint8Array.from(binary,c=>c.charCodeAt(0));parsed=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(bytes))}catch{throw invalid()}if(typeof parsed!=`object`||!parsed)throw invalid();let{v,s}=parsed;if(typeof v!=`object`||!v||Array.isArray(v)||!Object.values(v).every(isPrimitive)||keys&&(Object.keys(v).length!==keys.length||!keys.every(k=>Object.hasOwn(v,k))))throw invalid();if(s!==signature)throw HttpException.badRequest(`Pagination cursor was issued for a different sort`);return v}function pageLink(rawUrl,key,value){let url=parseUrl(rawUrl),kept=url.search.slice(1).split(`&`).filter(part=>part!==``&&paramName(part)!==key);return value!==null&&kept.push(`${key}=${encodeURIComponent(value)}`),kept.length?`${url.pathname}?${kept.join(`&`)}`:url.pathname}function selfLink(rawUrl){let url=parseUrl(rawUrl);return url.pathname+url.search}function parseUrl(rawUrl){let url=new URL(rawUrl,`http://localhost`);return url.pathname=url.pathname.replace(/^\/+/,`/`),url}function paramName(part){let name=part.split(`=`,1)[0].replace(/\+/g,` `);try{return decodeURIComponent(name)}catch{return name}}const signalControllerKey=Symbol.for(`kickjs.requestContext.signalController`),readOnlyProxyCacheKey=Symbol.for(`kickjs.requestContext.readOnlyProxyCache`);function isPlainObjectOrArray(v){if(typeof v!=`object`||!v)return!1;if(Array.isArray(v))return!0;let proto=Object.getPrototypeOf(v);return proto===Object.prototype||proto===null}function makeReadOnlyProxy(target,req,label){if(isProduction()||!isPlainObjectOrArray(target))return target;let reqObj=req,cache=reqObj[readOnlyProxyCacheKey];cache||(cache=/* @__PURE__ */ new WeakMap,reqObj[readOnlyProxyCacheKey]=cache);let targetObj=target,cached=cache.get(targetObj);if(cached)return cached;let warnWrite=(verb,prop)=>{console.warn(`[kickjs] Attempted to ${verb} \`ctx.${label}.${String(prop)}\` — request data is read-only. Stash computed values via \`ctx.set('key', value)\` or a Context Contributor, or reach \`ctx.req.${label}\` if you genuinely need the raw mutable handle.`)},proxy=new Proxy(targetObj,{get(t,prop,receiver){let value=Reflect.get(t,prop,receiver);return isPlainObjectOrArray(value)?makeReadOnlyProxy(value,req,`${label}.${String(prop)}`):value},set(_t,prop){return warnWrite(`assign`,prop),!0},deleteProperty(_t,prop){return warnWrite(`delete`,prop),!0},defineProperty(_t,prop){return warnWrite(`Object.defineProperty on`,prop),!0}});return cache.set(targetObj,proxy),proxy}var RequestContext=class{req;res;next;_response;get route(){return this.req?.[ROUTE_SLOT]}constructor(req,res,next,responseDriver){this.req=req,this.res=res,this.next=next,this._response=responseDriver??res}_qsMemo;_problem;metadataReadOnly(){return requestStore.getStore()?.values??null}metadataForWrite(){let store=requestStore.getStore();if(store)return store.values;throw Error(`RequestContext.set called outside an AsyncLocalStorage frame. Mount requestScopeMiddleware() before constructing RequestContext, or wrap test setup in requestStore.run({ requestId, instances: new Map(), values: new Map() }, () => ...).`)}get body(){return makeReadOnlyProxy(this.req.body,this.req,`body`)}get params(){return makeReadOnlyProxy(this.req.params,this.req,`params`)}get query(){return makeReadOnlyProxy(this.req.query,this.req,`query`)}get headers(){return makeReadOnlyProxy(this.req.headers,this.req,`headers`)}get requestId(){return this.req.requestId??this.req.headers[`x-request-id`]}get signal(){let req=this.req,cached=req[signalControllerKey];if(cached)return cached.signal;let ctrl=new AbortController;req[signalControllerKey]=ctrl;let abort=()=>ctrl.abort(`request closed`);return this.req.once(`close`,abort),this._response.once(`close`,abort),ctrl.signal}get session(){return this.req.session}get user(){return this.metadataReadOnly()?.get(`user`)??this.req.user}get tenantId(){return this.user?.tenantId}get roles(){let u=this.user;return u?.tenantRoles??u?.roles??[]}qs(fieldConfig,options){let memo=this._qsMemo;if(memo&&memo.config===fieldConfig&&memo.options===options)return memo.result;let effective={...options,onReject:options?.onReject??(rejection=>{let id=this.requestId?`[${this.requestId}] `:``;console.warn(`${id}query ${rejection.kind} '${rejection.field}' rejected (${rejection.reason})`)})},result=parseQuery(this.req.query,fieldConfig,effective);return this._qsMemo={config:fieldConfig,options,result},result}get file(){let f=this.req.file;return f?makeReadOnlyProxy(f,this.req,`file`):void 0}get files(){let f=this.req.files;if(Array.isArray(f))return makeReadOnlyProxy(f,this.req,`files`)}get(key){return this.metadataReadOnly()?.get(key)}require(key){let value=this.metadataReadOnly()?.get(key);if(value===void 0)throw new MissingContextValueError(key,this.routeLabel());return value}routeLabel(){let req=this.req,method=typeof req?.method==`string`?req.method:void 0,url=typeof req?.url==`string`?req.url:void 0;return method&&url?`${method} ${url}`:method??url}set(key,value){this.metadataForWrite().set(key,value)}setHeader(name,value){return this._response.setHeader(name,value),this}json(data,status=200){return this.sendJson(status,data)}created(data){return this.sendJson(201,data)}sendJson(status,data){try{return this._response.status(status).json(data)}catch(err){if(!isBigIntJsonError(err)||this._response.headersSent)throw err;return this._response.status(status).json(JSON.parse(stringifyJson(data)))}}noContent(){return this._response.status(204).end()}urlFor(name,...args){let urls=this.route?.urls;if(!urls)throw Error(`ctx.urlFor() is only available inside a matched route`);let[params,query]=args;return urls.build(name,params,query)}conditional(validators){validators.etag!==void 0&&this.setHeader(`ETag`,normalizeEtag(validators.etag)),validators.lastModified&&this.setHeader(`Last-Modified`,validators.lastModified.toUTCString());let outcome=evaluatePreconditions(String(this.req.method??`GET`).toUpperCase(),this.headers,validators);return outcome===304?(this._response.status(304).end(),!0):outcome===412&&(this.sendProblem({status:412,detail:`The resource changed since the version this request is based on.`}),!0)}notFound(message=`Not Found`){return this._response.status(404).json({message})}badRequest(message){return this._response.status(400).json({message})}get problem(){if(this._problem)return this._problem;let send=input=>this.sendProblem(input);return send.badRequest=(input={})=>this.sendProblem({status:400,...input}),send.unauthorized=(input={})=>this.sendProblem({status:401,...input}),send.forbidden=(input={})=>this.sendProblem({status:403,...input}),send.notFound=(input={})=>this.sendProblem({status:404,...input}),send.conflict=(input={})=>this.sendProblem({status:409,...input}),send.unprocessable=(input={})=>this.sendProblem({status:422,...input}),send.tooManyRequests=(input={})=>this.sendProblem({status:429,...input}),send.internal=(input={})=>this.sendProblem({status:500,...input}),send.validation=(issues,input={})=>{let errors=(issues||[]).map(issue=>({field:issue.path?.join?.(`.`)??``,message:issue.message??``,code:issue.code}));return this.sendProblem({status:422,detail:issues?.[0]?.message,...input,errors})},this._problem=send,this._problem}sendProblem(input){let body=normalizeProblem(input);return this._response.setHeader(`Content-Type`,`application/problem+json`),this._response.status(body.status).json(body)}get ip(){return resolveClientIp(this.req)}redirect(url,status=302){return this._response.status(status).setHeader(`location`,url),this._response.end()}html(content,status=200){return this._response.status(status).type(`text/html; charset=utf-8`).send(content)}send(body,options={}){return this._response.status(options.status??200).type(options.type??`text/plain; charset=utf-8`).send(body)}download(buffer,filename,contentType=`application/octet-stream`){return this._response.setHeader(`Content-Disposition`,contentDisposition(filename)),this._response.setHeader(`Content-Type`,contentType),this._response.send(buffer)}render(template,data={}){return this._response.render(template,data)}async paginate(fetcher,fieldConfig){let parsed=this.qs(fieldConfig),{data,total}=await fetcher(parsed),{page,limit}=parsed.pagination,totalPages=Math.ceil(total/limit)||1,response={data,meta:{page,limit,total,totalPages,hasNext:page<totalPages,hasPrev:page>1},links:{self:selfLink(this.requestUrl()),next:page<totalPages?pageLink(this.requestUrl(),`page`,page+1):null,prev:page>1?pageLink(this.requestUrl(),`page`,page-1):null}};return this.json(response),response}async paginateCursor(fetcher,fieldConfig,options){let{pagination,...parsed}=this.qs(fieldConfig),{limit}=pagination,idField=options?.idField??`id`,signature=sortSignature(parsed.sort),keys=options?.cursorKey?void 0:[.../* @__PURE__ */ new Set([...parsed.sort.map(s=>s.field),idField])],raw=this.req.query?.cursor,cursor=raw===void 0||raw===``?null:decodeCursor(raw,signature,keys),rows=await fetcher({...parsed,cursor,limit}),hasNext=rows.length>limit,data=hasNext?rows.slice(0,limit):rows,last=data.at(-1),nextCursor=null;hasNext&&last!==void 0&&(nextCursor=encodeCursor(cursorValues(last,keys??[],options?.cursorKey),signature));let url=this.requestUrl(),response={data,meta:{limit,hasNext,nextCursor},links:{self:selfLink(url),next:nextCursor?pageLink(url,`cursor`,nextCursor):null}};return this.json(response),response}requestUrl(){let req=this.req;return typeof req.originalUrl==`string`?req.originalUrl:typeof req.url==`string`?req.url:`/`}async sendResponse(response){let headers={};response.headers.forEach((value,name)=>{name!==`set-cookie`&&(headers[name]=value)});let cookies=response.headers.getSetCookie();if(cookies.length>0&&(headers[`set-cookie`]=cookies),!response.body){this._response.status(response.status);for(let[name,value]of Object.entries(headers))this._response.setHeader(name,value);this._response.send(``);return}this._response.writeHead(response.status,headers),this._response.flushHeaders();let reader=response.body.getReader(),stop=()=>{reader.cancel().catch(()=>{})};this.signal.addEventListener(`abort`,stop,{once:!0});try{for(;;){let{done,value}=await reader.read();if(done)break;this._response.write(Buffer.from(value))===!1&&!this.signal.aborted&&await new Promise(resolve=>{let resume=()=>{this.signal.removeEventListener(`abort`,resume),resolve()};this._response.once(`drain`,resume),this.signal.addEventListener(`abort`,resume,{once:!0})})}}finally{this.signal.removeEventListener(`abort`,stop),this._response.end()}}waitUntil(promise){waitUntil(promise)}sse(){this._response.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}),this._response.flushHeaders();let closeCallbacks=[];return this.req.on(`close`,()=>{for(let cb of closeCallbacks)cb()}),{send:(data,event,id)=>{id&&this._response.write(`id: ${id}\n`),event&&this._response.write(`event: ${event}\n`),this._response.write(`data: ${JSON.stringify(data)}\n\n`)},comment:text=>{this._response.write(`: ${text}\n\n`)},onClose:fn=>{closeCallbacks.push(fn)},close:()=>{this._response.end()}}}};function contentDisposition(filename){return`attachment; filename="${filename.replace(/[^\x20-\x7e]|["\\]/g,`_`)}"; filename*=UTF-8''${encodeURIComponent(filename).replace(/['()*]/g,c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`}function cursorValues(row,keys,cursorKey){if(cursorKey)return cursorKey(row);let values={};for(let key of keys){let value=row[key];if(value===void 0)throw Error(`paginateCursor: row has no '${key}' — return the sort fields and the id field on every row, or pass options.cursorKey / options.idField`);values[key]=value instanceof Date?value.toISOString():typeof value==`bigint`?value.toString():value}return values}export{evaluatePreconditions as a,settleBackgroundWork as c,getRequestValue as d,requestStore as f,stringifyJson as i,waitUntil as l,contentDisposition as n,forwardBackgroundWork as o,publishMatchedRoute as r,pendingBackgroundWork as s,RequestContext as t,getRequestStore as u};
12
+ //# sourceMappingURL=context-p-KpSsLy.mjs.map