@forinda/kickjs 10.5.0 → 10.7.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 (208) hide show
  1. package/dist/{adapter-BZ1WzN1z.d.mts → adapter-9sPr_5xt.d.mts} +123 -35
  2. package/dist/adapter-9sPr_5xt.d.mts.map +1 -0
  3. package/dist/{allowed-hosts-D6qcuK5I.d.mts → allowed-hosts-BpKwviq5.d.mts} +3 -3
  4. package/dist/allowed-hosts-BpKwviq5.d.mts.map +1 -0
  5. package/dist/application-BSzwuTQ6.mjs +14 -0
  6. package/dist/application-BSzwuTQ6.mjs.map +1 -0
  7. package/dist/{application-D5Iiy7rt.d.mts → application-BZjDmsWb.d.mts} +118 -45
  8. package/dist/application-BZjDmsWb.d.mts.map +1 -0
  9. package/dist/background-BJjLKrnK.mjs +12 -0
  10. package/dist/background-BJjLKrnK.mjs.map +1 -0
  11. package/dist/bootstrap-Dxax6Mcp.mjs +12 -0
  12. package/dist/{bootstrap-B_6QfzXV.mjs.map → bootstrap-Dxax6Mcp.mjs.map} +1 -1
  13. package/dist/{bounded-counters-C8PHfWEu.mjs → bounded-counters-_6sdDRhT.mjs} +2 -2
  14. package/dist/{bounded-counters-C8PHfWEu.mjs.map → bounded-counters-_6sdDRhT.mjs.map} +1 -1
  15. package/dist/{breach-padding-C-Dnq8CS.d.mts → breach-padding-FBVGmcBb.d.mts} +3 -3
  16. package/dist/breach-padding-FBVGmcBb.d.mts.map +1 -0
  17. package/dist/{client-ip-kxT2SHut.mjs → client-ip-CrO5ktYs.mjs} +2 -2
  18. package/dist/{client-ip-kxT2SHut.mjs.map → client-ip-CrO5ktYs.mjs.map} +1 -1
  19. package/dist/config/index.mjs +2 -2
  20. package/dist/{config-Dz-HnO4c.mjs → config-CWKj0Z66.mjs} +3 -3
  21. package/dist/{config-Dz-HnO4c.mjs.map → config-CWKj0Z66.mjs.map} +1 -1
  22. package/dist/connect-BlIamapT.d.mts +41 -0
  23. package/dist/connect-BlIamapT.d.mts.map +1 -0
  24. package/dist/context-BlJRkMyq.mjs +12 -0
  25. package/dist/context-BlJRkMyq.mjs.map +1 -0
  26. package/dist/{context-errors-gitMJXxZ.mjs → context-errors-ykpXYECS.mjs} +2 -2
  27. package/dist/{context-errors-gitMJXxZ.mjs.map → context-errors-ykpXYECS.mjs.map} +1 -1
  28. package/dist/{contributor-runner-CDlPrzai.mjs → contributor-runner-BM-5Wr19.mjs} +3 -3
  29. package/dist/{contributor-runner-CDlPrzai.mjs.map → contributor-runner-BM-5Wr19.mjs.map} +1 -1
  30. package/dist/core/adapter.d.mts +1 -1
  31. package/dist/core/adapter.mjs +1 -1
  32. package/dist/core/app-module.mjs +1 -1
  33. package/dist/core/cache.mjs +1 -1
  34. package/dist/core/container.mjs +2 -2
  35. package/dist/core/cron.mjs +2 -2
  36. package/dist/core/decorators.mjs +2 -2
  37. package/dist/core/errors.mjs +1 -1
  38. package/dist/core/interfaces.mjs +1 -1
  39. package/dist/core/logger.mjs +1 -1
  40. package/dist/core/path.mjs +1 -1
  41. package/dist/core/plugin.d.mts +1 -1
  42. package/dist/core/plugin.mjs +1 -1
  43. package/dist/core/reactivity.mjs +1 -1
  44. package/dist/core-DlrlhjF4.mjs +12 -0
  45. package/dist/{core-CSWR0hHJ.mjs.map → core-DlrlhjF4.mjs.map} +1 -1
  46. package/dist/{cors-2Bwhyhpt.d.mts → cors-BlR_b0Qb.d.mts} +3 -3
  47. package/dist/cors-BlR_b0Qb.d.mts.map +1 -0
  48. package/dist/{csrf-BDAZK2mm.d.mts → csrf-ZFOrJZhJ.d.mts} +3 -3
  49. package/dist/csrf-ZFOrJZhJ.d.mts.map +1 -0
  50. package/dist/decorate-BHhpOfEF.mjs +13 -0
  51. package/dist/{decorate-D2oVJls5.mjs.map → decorate-BHhpOfEF.mjs.map} +1 -1
  52. package/dist/{define-adapter-oANmOi4a.mjs → define-adapter-CF-DJRq9.mjs} +2 -2
  53. package/dist/{define-adapter-oANmOi4a.mjs.map → define-adapter-CF-DJRq9.mjs.map} +1 -1
  54. package/dist/{di-hooks-HI14rSja.mjs → di-hooks-CCKeiLT-.mjs} +2 -2
  55. package/dist/{di-hooks-HI14rSja.mjs.map → di-hooks-CCKeiLT-.mjs.map} +1 -1
  56. package/dist/{disposables-CWNNe9HH.mjs → disposables-bnkL4rG7.mjs} +1 -1
  57. package/dist/{error-handler-CbP7hKdJ.d.mts → error-handler-CH4PPZCK.d.mts} +2 -2
  58. package/dist/{error-handler-CbP7hKdJ.d.mts.map → error-handler-CH4PPZCK.d.mts.map} +1 -1
  59. package/dist/express-4fvuMB5q.mjs +12 -0
  60. package/dist/express-4fvuMB5q.mjs.map +1 -0
  61. package/dist/express-lazy-D9MZnma8.mjs +12 -0
  62. package/dist/express-lazy-D9MZnma8.mjs.map +1 -0
  63. package/dist/handler-TzaD8jPN.mjs +12 -0
  64. package/dist/{handler-D23bJ6g1.mjs.map → handler-TzaD8jPN.mjs.map} +1 -1
  65. package/dist/{helmet-CEOmo516.d.mts → helmet-BVuVBl-D.d.mts} +3 -3
  66. package/dist/helmet-BVuVBl-D.d.mts.map +1 -0
  67. package/dist/{host-C2_vvcrO.mjs → host-CtpcIKcA.mjs} +2 -2
  68. package/dist/{host-C2_vvcrO.mjs.map → host-CtpcIKcA.mjs.map} +1 -1
  69. package/dist/http/application.d.mts +2 -2
  70. package/dist/http/application.mjs +2 -2
  71. package/dist/http/bootstrap.d.mts +1 -1
  72. package/dist/http/bootstrap.mjs +2 -2
  73. package/dist/http/context.d.mts +1 -1
  74. package/dist/http/context.mjs +2 -2
  75. package/dist/http/middleware/allowed-hosts.d.mts +1 -1
  76. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  77. package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
  78. package/dist/http/middleware/breach-padding.d.mts +1 -1
  79. package/dist/http/middleware/breach-padding.mjs +1 -1
  80. package/dist/http/middleware/breach-padding.mjs.map +1 -1
  81. package/dist/http/middleware/cors.d.mts +1 -1
  82. package/dist/http/middleware/cors.mjs +1 -1
  83. package/dist/http/middleware/cors.mjs.map +1 -1
  84. package/dist/http/middleware/csrf.d.mts +1 -1
  85. package/dist/http/middleware/csrf.mjs +2 -2
  86. package/dist/http/middleware/csrf.mjs.map +1 -1
  87. package/dist/http/middleware/error-handler.d.mts +1 -1
  88. package/dist/http/middleware/error-handler.mjs +2 -2
  89. package/dist/http/middleware/helmet.d.mts +1 -1
  90. package/dist/http/middleware/helmet.mjs +1 -1
  91. package/dist/http/middleware/helmet.mjs.map +1 -1
  92. package/dist/http/middleware/rate-limit.d.mts +1 -1
  93. package/dist/http/middleware/rate-limit.mjs +2 -2
  94. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  95. package/dist/http/middleware/request-id.d.mts +1 -1
  96. package/dist/http/middleware/request-id.mjs +1 -1
  97. package/dist/http/middleware/request-id.mjs.map +1 -1
  98. package/dist/http/middleware/request-logger.mjs +2 -2
  99. package/dist/http/middleware/session.d.mts +1 -1
  100. package/dist/http/middleware/session.mjs +2 -2
  101. package/dist/http/middleware/session.mjs.map +1 -1
  102. package/dist/http/middleware/spa.d.mts +1 -1
  103. package/dist/http/middleware/spa.mjs +2 -2
  104. package/dist/http/middleware/upload.d.mts +3 -2
  105. package/dist/http/middleware/upload.mjs +2 -2
  106. package/dist/http/middleware/upload.mjs.map +1 -1
  107. package/dist/http/middleware/validate.d.mts +1 -1
  108. package/dist/http/middleware/validate.mjs +1 -1
  109. package/dist/http/middleware/validate.mjs.map +1 -1
  110. package/dist/http/middleware/views.d.mts +1 -1
  111. package/dist/http/middleware/views.mjs +2 -2
  112. package/dist/http/middleware/views.mjs.map +1 -1
  113. package/dist/http/query/index.mjs +2 -2
  114. package/dist/http/router-builder.d.mts +1 -1
  115. package/dist/http/router-builder.mjs +2 -2
  116. package/dist/http/runtimes/express.d.mts +47 -0
  117. package/dist/http/runtimes/express.d.mts.map +1 -0
  118. package/dist/http/runtimes/express.mjs +11 -0
  119. package/dist/http/runtimes/fastify.d.mts +1 -1
  120. package/dist/http/runtimes/fastify.mjs +2 -2
  121. package/dist/http/runtimes/fastify.mjs.map +1 -1
  122. package/dist/http/runtimes/h3-web.mjs +1 -1
  123. package/dist/http/runtimes/h3.d.mts +1 -1
  124. package/dist/http/runtimes/h3.mjs +2 -2
  125. package/dist/index.d.mts +17 -16
  126. package/dist/index.mjs +3 -3
  127. package/dist/index.mjs.map +1 -1
  128. package/dist/{is-production-TSixl400.mjs → is-production-BfIKY2Sw.mjs} +2 -2
  129. package/dist/{is-production-TSixl400.mjs.map → is-production-BfIKY2Sw.mjs.map} +1 -1
  130. package/dist/{jobs-DIddIoQs.mjs → jobs-BJfIOWUT.mjs} +3 -3
  131. package/dist/{jobs-DIddIoQs.mjs.map → jobs-BJfIOWUT.mjs.map} +1 -1
  132. package/dist/{kv-stores-B9xLP0mg.mjs → kv-stores-BeDHfiyW.mjs} +3 -3
  133. package/dist/{kv-stores-B9xLP0mg.mjs.map → kv-stores-BeDHfiyW.mjs.map} +1 -1
  134. package/dist/{kv-stores-DXFBEYYu.d.mts → kv-stores-C1sQs2Rb.d.mts} +4 -4
  135. package/dist/{kv-stores-DXFBEYYu.d.mts.map → kv-stores-C1sQs2Rb.d.mts.map} +1 -1
  136. package/dist/lazy-serve-static-BUMcYDMn.mjs +12 -0
  137. package/dist/lazy-serve-static-BUMcYDMn.mjs.map +1 -0
  138. package/dist/{metadata-CJRJvpAK.mjs → metadata-x0eCJRTl.mjs} +1 -1
  139. package/dist/{observers-DaIAahW4.mjs → observers-Ss6-7Si7.mjs} +2 -2
  140. package/dist/{observers-DaIAahW4.mjs.map → observers-Ss6-7Si7.mjs.map} +1 -1
  141. package/dist/precompressed-BBXQUDXp.mjs +12 -0
  142. package/dist/precompressed-BBXQUDXp.mjs.map +1 -0
  143. package/dist/{query-CUvSp-JT.mjs → query-DIS_2QiJ.mjs} +2 -2
  144. package/dist/{query-CUvSp-JT.mjs.map → query-DIS_2QiJ.mjs.map} +1 -1
  145. package/dist/{rate-limit-BgoeahE5.d.mts → rate-limit-DQDk6bAH.d.mts} +5 -5
  146. package/dist/rate-limit-DQDk6bAH.d.mts.map +1 -0
  147. package/dist/reply-BVdki3Z4.mjs +12 -0
  148. package/dist/reply-BVdki3Z4.mjs.map +1 -0
  149. package/dist/{request-id-CVzJ1uHD.d.mts → request-id-Dn64nEHK.d.mts} +3 -3
  150. package/dist/request-id-Dn64nEHK.d.mts.map +1 -0
  151. package/dist/request-scope-BTdpkAqv.mjs +12 -0
  152. package/dist/request-scope-BTdpkAqv.mjs.map +1 -0
  153. package/dist/{respond-Ius0bnxZ.mjs → respond-BUWP_L0Y.mjs} +2 -2
  154. package/dist/{respond-Ius0bnxZ.mjs.map → respond-BUWP_L0Y.mjs.map} +1 -1
  155. package/dist/rolldown-runtime-Dp0gGuQG.mjs +11 -0
  156. package/dist/{route-flag-BP_jbhNy.mjs → route-flag-p89Wzt0D.mjs} +3 -3
  157. package/dist/{route-flag-BP_jbhNy.mjs.map → route-flag-p89Wzt0D.mjs.map} +1 -1
  158. package/dist/{route-policy-BF1hOoUO.mjs → route-policy-DJMiiTrD.mjs} +2 -2
  159. package/dist/{route-policy-BF1hOoUO.mjs.map → route-policy-DJMiiTrD.mjs.map} +1 -1
  160. package/dist/{router-builder-BewIsj7V.d.mts → router-builder-BfbEdxew.d.mts} +2 -2
  161. package/dist/{router-builder-BewIsj7V.d.mts.map → router-builder-BfbEdxew.d.mts.map} +1 -1
  162. package/dist/{router-builder-CBjQNcUy.mjs → router-builder-dCWA4pdK.mjs} +3 -3
  163. package/dist/{router-builder-CBjQNcUy.mjs.map → router-builder-dCWA4pdK.mjs.map} +1 -1
  164. package/dist/{session-ChXx7jG5.d.mts → session-8uNRCplB.d.mts} +3 -3
  165. package/dist/session-8uNRCplB.d.mts.map +1 -0
  166. package/dist/{settings-DlZtVJ3I.mjs → settings-BHYpcj_p.mjs} +3 -3
  167. package/dist/{settings-DlZtVJ3I.mjs.map → settings-BHYpcj_p.mjs.map} +1 -1
  168. package/dist/{token-9VtCdkUp.mjs → token-Cz4YKuL-.mjs} +1 -1
  169. package/dist/upload-Jgs9BFC4.d.mts +55 -0
  170. package/dist/upload-Jgs9BFC4.d.mts.map +1 -0
  171. package/dist/{upload-config-DYr3a8LW.mjs → upload-config-CkMQ5bW5.mjs} +2 -2
  172. package/dist/upload-config-CkMQ5bW5.mjs.map +1 -0
  173. package/dist/{url-for-Cci2zH9d.mjs → url-for-CDxa8ik-.mjs} +3 -3
  174. package/dist/{url-for-Cci2zH9d.mjs.map → url-for-CDxa8ik-.mjs.map} +1 -1
  175. package/dist/{validate-CzjCbRUn.d.mts → validate-D4Poe2EE.d.mts} +3 -3
  176. package/dist/validate-D4Poe2EE.d.mts.map +1 -0
  177. package/dist/{web-crypto-CWrgn2Yq.mjs → web-crypto-Bijc63tB.mjs} +2 -2
  178. package/dist/{web-crypto-CWrgn2Yq.mjs.map → web-crypto-Bijc63tB.mjs.map} +1 -1
  179. package/dist/web.d.mts +3 -3
  180. package/dist/web.mjs +2 -2
  181. package/dist/web.mjs.map +1 -1
  182. package/package.json +8 -1
  183. package/dist/adapter-BZ1WzN1z.d.mts.map +0 -1
  184. package/dist/allowed-hosts-D6qcuK5I.d.mts.map +0 -1
  185. package/dist/application-D5Iiy7rt.d.mts.map +0 -1
  186. package/dist/application-DtuQSky3.mjs +0 -14
  187. package/dist/application-DtuQSky3.mjs.map +0 -1
  188. package/dist/bootstrap-B_6QfzXV.mjs +0 -12
  189. package/dist/breach-padding-C-Dnq8CS.d.mts.map +0 -1
  190. package/dist/context-p-KpSsLy.mjs +0 -12
  191. package/dist/context-p-KpSsLy.mjs.map +0 -1
  192. package/dist/core-CSWR0hHJ.mjs +0 -12
  193. package/dist/cors-2Bwhyhpt.d.mts.map +0 -1
  194. package/dist/csrf-BDAZK2mm.d.mts.map +0 -1
  195. package/dist/decorate-D2oVJls5.mjs +0 -13
  196. package/dist/handler-D23bJ6g1.mjs +0 -12
  197. package/dist/helmet-CEOmo516.d.mts.map +0 -1
  198. package/dist/lazy-serve-static-BNM_5G_r.mjs +0 -12
  199. package/dist/lazy-serve-static-BNM_5G_r.mjs.map +0 -1
  200. package/dist/rate-limit-BgoeahE5.d.mts.map +0 -1
  201. package/dist/reply-C1CoxeQt.mjs +0 -12
  202. package/dist/reply-C1CoxeQt.mjs.map +0 -1
  203. package/dist/request-id-CVzJ1uHD.d.mts.map +0 -1
  204. package/dist/session-ChXx7jG5.d.mts.map +0 -1
  205. package/dist/upload-DkT2p1gd.d.mts +0 -104
  206. package/dist/upload-DkT2p1gd.d.mts.map +0 -1
  207. package/dist/upload-config-DYr3a8LW.mjs.map +0 -1
  208. package/dist/validate-CzjCbRUn.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"breach-padding-FBVGmcBb.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/breach-padding.ts"],"mappings":";;;UAMiB;;;;;EAKf;;;;;;;;;iBAoBc,cAAc,OAAO,YAAY,mBAAmB;;;;;;;;;;;;;;;;;;iBAuCpD,cAAc,UAAS,wBAAyB,KAGjDA,gBAAO,KAAOC,iBAAQ,MAAQC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.5.0
2
+ * @forinda/kickjs v10.7.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-kxT2SHut.mjs.map
12
+ //# sourceMappingURL=client-ip-CrO5ktYs.mjs.map
@@ -1 +1 @@
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
+ {"version":3,"file":"client-ip-CrO5ktYs.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,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.5.0
2
+ * @forinda/kickjs v10.7.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-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};
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-BHhpOfEF.mjs";import{n as createConfigService,t as ConfigService}from"../config-CWKj0Z66.mjs";export{ConfigService,baseEnvSchema,createConfigService,defineEnv,getEnv,loadEnv,loadEnvFromSchema,reloadEnv,resetEnvCache,withEnv};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.5.0
2
+ * @forinda/kickjs v10.7.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-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
11
+ import{Service}from"./core/decorators.mjs";import{c as reloadEnv,o as loadEnv,t as __decorate}from"./decorate-BHhpOfEF.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-CWKj0Z66.mjs.map
@@ -1 +1 @@
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
+ {"version":3,"file":"config-CWKj0Z66.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"}
@@ -0,0 +1,41 @@
1
+
2
+ import { IncomingMessage, ServerResponse } from "node:http";
3
+ //#region src/http/connect.d.ts
4
+ /**
5
+ * The request a connect middleware sees: Node's `IncomingMessage`, plus the
6
+ * members Express adds. Those are optional — under Fastify and h3 a member
7
+ * Express adds may be missing, unless a middleware before it set it.
8
+ */
9
+ interface ConnectRequest extends IncomingMessage {
10
+ /** Always set on a request a server received. */
11
+ method: string;
12
+ url: string;
13
+ body?: any;
14
+ query?: any;
15
+ params?: any;
16
+ path?: string;
17
+ originalUrl?: string;
18
+ ip?: string;
19
+ hostname?: string;
20
+ cookies?: Record<string, string>;
21
+ /** Whatever earlier middleware attached: `file`, `files`, `session`, `user`, … */
22
+ [key: string]: any;
23
+ }
24
+ /** The response a connect middleware sees: Node's `ServerResponse`, plus what an engine adds. */
25
+ interface ConnectResponse extends ServerResponse {
26
+ [key: string]: any;
27
+ }
28
+ /** Call to continue; pass an error to skip to the error handlers. */
29
+ type ConnectNext = (err?: any) => void;
30
+ type Bivariant<F extends (...args: any[]) => unknown> = {
31
+ fn(...args: Parameters<F>): unknown;
32
+ }['fn'];
33
+ /** `(req, res, next)` middleware. */
34
+ type ConnectHandler = Bivariant<(req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => unknown>;
35
+ /** `(err, req, res, next)` error middleware. */
36
+ type ConnectErrorHandler = Bivariant<(err: any, req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => unknown>;
37
+ /** Either kind of connect middleware. */
38
+ type ConnectMiddleware = ConnectHandler | ConnectErrorHandler;
39
+ //#endregion
40
+ export { ConnectRequest as a, ConnectNext as i, ConnectHandler as n, ConnectResponse as o, ConnectMiddleware as r, ConnectErrorHandler as t };
41
+ //# sourceMappingURL=connect-BlIamapT.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect-BlIamapT.d.mts","names":[],"sources":["../src/http/connect.ts"],"mappings":";;;;;;;;UAgBiB,uBAAuB;;EAEtC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU;;GAET;;;UAIc,wBAAwB;GACtC;;;KAIS,eAAe;KAItB,UAAU,cAAc;EAC3B,MAAM,MAAM,WAAW;;;KAIb,iBAAiB,WAC1B,KAAK,gBAAgB,KAAK,iBAAiB,MAAM;;KAIxC,sBAAsB,WAC/B,UAAU,KAAK,gBAAgB,KAAK,iBAAiB,MAAM;;KAIlD,oBAAoB,iBAAiB"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs v10.7.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{HttpException,normalizeProblem}from"./core/errors.mjs";import{t as ROUTE_SLOT}from"./route-flag-p89Wzt0D.mjs";import{r as MissingContextValueError}from"./context-errors-ykpXYECS.mjs";import{t as isProduction}from"./is-production-BfIKY2Sw.mjs";import{i as waitUntil,s as requestStore}from"./background-BJjLKrnK.mjs";import{t as resolveClientIp}from"./client-ip-CrO5ktYs.mjs";import{a as parseQuery}from"./query-DIS_2QiJ.mjs";function header(headers,name){let value=headers[name];return Array.isArray(value)?value.join(`, `):value}function normalizeEtag(etag){if(/^(W\/)?".*"$/.test(etag))return etag;let weak=etag.startsWith(`W/`),bare=(weak?etag.slice(2):etag).replaceAll(`"`,``);return`${weak?`W/`:``}"${bare}"`}const opaque=tag=>tag.replace(/^W\//,``),isWeak=tag=>tag.startsWith(`W/`);function tagsOf(value){return value.match(/\*|(?:W\/)?"[^"]*"/g)??[]}function dateOf(value){if(!value)return;let ms=Date.parse(value);return Number.isNaN(ms)?void 0:ms}const seconds=date=>Math.floor(date.getTime()/1e3)*1e3;function evaluatePreconditions(method,headers,validators){let etag=validators.etag===void 0?void 0:normalizeEtag(validators.etag),modified=validators.lastModified?seconds(validators.lastModified):void 0,safe=method===`GET`||method===`HEAD`,ifMatch=header(headers,`if-match`);if(ifMatch!==void 0){let tags=tagsOf(ifMatch);if(!(tags.includes(`*`)||etag!==void 0&&!isWeak(etag)&&tags.some(t=>!isWeak(t)&&t===etag)))return 412}else{let since=dateOf(header(headers,`if-unmodified-since`));if(since!==void 0&&modified!==void 0&&modified>since)return 412}let ifNoneMatch=header(headers,`if-none-match`);if(ifNoneMatch!==void 0){let tags=tagsOf(ifNoneMatch);return tags.includes(`*`)||etag!==void 0&&tags.some(t=>opaque(t)===opaque(etag))?safe?304:412:200}if(safe){let since=dateOf(header(headers,`if-modified-since`));if(since!==void 0&&modified!==void 0&&modified<=since)return 304}return 200}function publishMatchedRoute(req,entry){let route=matchedRoutes.get(entry);route||(route=Object.freeze({method:entry.method,path:entry.path,controller:entry.meta.controller,handlerName:entry.meta.handlerName,flags:entry.meta.flags??EMPTY_FLAGS,pattern:entry.meta.pattern??entry.path,urls:entry.urls}),matchedRoutes.set(entry,route)),req[ROUTE_SLOT]=route}const matchedRoutes=/* @__PURE__ */ new WeakMap,EMPTY_FLAGS=/* @__PURE__ */ new Map;function isBigIntJsonError(err){return err instanceof TypeError&&/BigInt/.test(err.message)}function stringifyJson(data){try{return JSON.stringify(data)}catch(err){if(!isBigIntJsonError(err))throw err;return JSON.stringify(data,(_key,value)=>typeof value==`bigint`?value.toString():value)}}function sortSignature(sort){return sort.map(s=>`${s.field}:${s.direction}`).join(`,`)}function isPrimitive(value){return value===null||[`string`,`number`,`boolean`].includes(typeof value)}function encodeCursor(position,signature){let bytes=new TextEncoder().encode(JSON.stringify({v:position,s:signature})),binary=``;for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function decodeCursor(raw,signature,keys){let invalid=()=>HttpException.badRequest(`Invalid pagination cursor`);if(typeof raw!=`string`||!/^[A-Za-z0-9_-]+$/.test(raw))throw invalid();let parsed;try{let binary=atob(raw.replace(/-/g,`+`).replace(/_/g,`/`)),bytes=Uint8Array.from(binary,c=>c.charCodeAt(0));parsed=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(bytes))}catch{throw invalid()}if(typeof parsed!=`object`||!parsed)throw invalid();let{v,s}=parsed;if(typeof v!=`object`||!v||Array.isArray(v)||!Object.values(v).every(isPrimitive)||keys&&(Object.keys(v).length!==keys.length||!keys.every(k=>Object.hasOwn(v,k))))throw invalid();if(s!==signature)throw HttpException.badRequest(`Pagination cursor was issued for a different sort`);return v}function pageLink(rawUrl,key,value){let url=parseUrl(rawUrl),kept=url.search.slice(1).split(`&`).filter(part=>part!==``&&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,stringifyJson as i,contentDisposition as n,publishMatchedRoute as r,RequestContext as t};
12
+ //# sourceMappingURL=context-BlJRkMyq.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-BlJRkMyq.mjs","names":[],"sources":["../src/http/conditional.ts","../src/http/runtime.ts","../src/http/query/cursor.ts","../src/http/context.ts"],"sourcesContent":["/**\n * Conditional requests (RFC 9110 §13): answer `304 Not Modified` when the\n * client's copy is current, and `412 Precondition Failed` when a write was\n * based on a stale one. Decided from validators the handler supplies — an\n * ETag, a last-modified time — before it does the expensive part.\n *\n * @module @forinda/kickjs/http/conditional\n */\n\n/** What identifies the current version of a resource. */\nexport interface Validators {\n /**\n * An entity tag. Quoted for you if bare: `'v42'` → `\"v42\"`. Prefix with\n * `W/` for a weak tag (same meaning, not byte-identical).\n */\n etag?: string\n /** When the resource last changed. Compared to the second, as HTTP dates are. */\n lastModified?: Date\n}\n\n/** 200: go on and respond. 304 / 412: answer with that status, no body. */\nexport type ConditionalOutcome = 200 | 304 | 412\n\ntype Headers = Record<string, string | string[] | undefined>\n\nfunction header(headers: Headers, name: string): string | undefined {\n const value = headers[name]\n return Array.isArray(value) ? value.join(', ') : value\n}\n\n/** `\"v1\"` and `W/\"v1\"` stay; bare `v1` becomes `\"v1\"`, bare `W/v1` becomes `W/\"v1\"`. */\nexport function normalizeEtag(etag: string): string {\n if (/^(W\\/)?\".*\"$/.test(etag)) return etag\n // Keep a weak prefix weak: quoting `W/v1` whole would make `\"W/v1\"`, a\n // strong tag, and change how If-Match compares it.\n const weak = etag.startsWith('W/')\n const bare = (weak ? etag.slice(2) : etag).replaceAll('\"', '')\n return `${weak ? 'W/' : ''}\"${bare}\"`\n}\n\nconst opaque = (tag: string) => tag.replace(/^W\\//, '')\nconst isWeak = (tag: string) => tag.startsWith('W/')\n\n/** The tags in an If-Match / If-None-Match list (`*` kept as is). */\nfunction tagsOf(value: string): string[] {\n return value.match(/\\*|(?:W\\/)?\"[^\"]*\"/g) ?? []\n}\n\n/** An HTTP date, or undefined when it doesn't parse — an invalid one is ignored. */\nfunction dateOf(value: string | undefined): number | undefined {\n if (!value) return undefined\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? undefined : ms\n}\n\n/** HTTP dates have one-second resolution. */\nconst seconds = (date: Date) => Math.floor(date.getTime() / 1000) * 1000\n\n/**\n * The outcome of a request's preconditions against the current validators,\n * evaluated in RFC 9110 §13.2.2 order.\n */\nexport function evaluatePreconditions(\n method: string,\n headers: Headers,\n validators: Validators,\n): ConditionalOutcome {\n const etag = validators.etag === undefined ? undefined : normalizeEtag(validators.etag)\n const modified = validators.lastModified ? seconds(validators.lastModified) : undefined\n const safe = method === 'GET' || method === 'HEAD'\n\n // 1. If-Match — strong comparison; `*` matches any current representation.\n const ifMatch = header(headers, 'if-match')\n if (ifMatch !== undefined) {\n const tags = tagsOf(ifMatch)\n const matched =\n tags.includes('*') ||\n (etag !== undefined && !isWeak(etag) && tags.some((t) => !isWeak(t) && t === etag))\n if (!matched) return 412\n } else {\n // 2. If-Unmodified-Since, only without If-Match.\n const since = dateOf(header(headers, 'if-unmodified-since'))\n if (since !== undefined && modified !== undefined && modified > since) return 412\n }\n\n // 3. If-None-Match — weak comparison.\n const ifNoneMatch = header(headers, 'if-none-match')\n if (ifNoneMatch !== undefined) {\n const tags = tagsOf(ifNoneMatch)\n const matched =\n tags.includes('*') || (etag !== undefined && tags.some((t) => opaque(t) === opaque(etag)))\n if (matched) return safe ? 304 : 412\n return 200\n }\n\n // 4. If-Modified-Since, only for GET/HEAD and only without If-None-Match.\n if (safe) {\n const since = dateOf(header(headers, 'if-modified-since'))\n if (since !== undefined && modified !== undefined && modified <= since) return 304\n }\n return 200\n}\n","// The HttpRuntime seam.\n//\n// Decorators no longer emit an `express.Router` directly. `buildRouteTable()`\n// turns controller metadata into a plain-data `RouteEntry[]`; an `HttpRuntime`\n// materializes that table onto whatever engine it owns. Express is the default\n// runtime and the only one shipped in M1 — its materializer reproduces the exact\n// handler chain the old `buildRoutes()` built, so behavior is unchanged.\n//\n// Fastify / h3 runtimes (later milestones) consume the SAME `RouteEntry` data\n// and the SAME `HttpRuntime` contract; the request/response driver abstraction\n// that lets `RequestContext` run engine-agnostically lands with them (M3), since\n// under Express the drivers ARE the Express request/response objects already.\n//\n// Why a seam: running Fastify / h3 behind an Express-compat layer\n// (`@fastify/express`, h3's node bridge) bypasses their router and\n// serialization, and rebuilding `ctx` over web-standard Request/Response\n// would break SSE / streaming, multer uploads and `ctx.res` for every adopter.\n// The seam keeps `ctx` and swaps only the engine underneath it.\n\nimport { ROUTE_SLOT, type RouteFlags } from '../core/route-flag'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { ConnectMiddleware, ConnectRequest, ConnectResponse } from './connect'\n\nimport type { Constructor, FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core'\nimport type { RequestContext } from './context'\nimport type { ValidationErrorFactory } from './middleware/validate'\nimport type { RouteUrls } from './url-for'\nimport type { ContributorSource } from '../core/contributor-pipeline'\n\n/** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */\nexport type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n\n/**\n * A context-based handler: the runtime-neutral unit of the request pipeline.\n * Contributors, route middleware (via {@link MiddlewareHandler}), and the\n * terminal controller call all reduce to this shape. The runtime owns how a\n * `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,\n * next)`; Fastify in its own handler).\n */\nexport type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>\n\n/**\n * Connect-style middleware — the portable middleware format. Built-in\n * middleware and adopter-supplied Express middleware are this shape. The\n * Express runtime hands them straight to `app.use`; the others bridge them\n * (Fastify via `@fastify/middie`, h3 via its node adapter). See `./connect`.\n */\nexport type { ConnectMiddleware }\n\n/**\n * One materialized route, as plain data. Produced by {@link buildRouteTable}\n * from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.\n *\n * The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`\n * keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),\n * `contributorRunner` is a closure over the pre-built pipeline + container (the\n * pipeline is built — and any cycle / missing-dep error thrown — at table-build\n * time, i.e. boot), and `validation` / `upload` stay as metadata the runtime\n * materializes its own way. Faithfully reproducing the legacy Express chain —\n * not collapsing it — is what keeps M1 behavior-neutral.\n */\nexport interface RouteEntry {\n method: RouteMethod\n /** Path with `:param` segments — the portable subset all engines accept. */\n path: string\n /** Class + method middleware, in execution order; each receives `(ctx, next)`. */\n middlewares: MiddlewareHandler[]\n /**\n * Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),\n * or `null` when no contributors apply. Closes over the built pipeline and\n * the DI container so it stays engine-neutral; the runtime advances the\n * chain (Express: call `next()`) once it resolves.\n */\n contributorRunner: CtxHandler | null\n /**\n * Contributors registered with `beforeValidation: true`. Runtimes run this\n * right after publishing the matched route — before validation, upload and\n * middleware — so a rejection (401) lands before a malformed body's 422.\n * Absent or `null` when no contributor asks for it.\n */\n earlyContributorRunner?: CtxHandler | null\n /** The app's `validationError` — what this route's validation failure throws. */\n validationError?: ValidationErrorFactory\n /** The app's route names → paths, for `ctx.urlFor()`. */\n urls?: RouteUrls\n /** Terminal handler: resolves the controller per-request and invokes it. */\n handler: CtxHandler\n /** Introspection + runtime-materialized concerns (swagger/typegen read this). */\n meta: RouteMeta\n}\n\n/** Per-route metadata: introspection refs plus runtime-materialized concerns. */\n/**\n * One context contributor on a route, as introspection sees it: the\n * contributors a request runs, in execution order. Built with the route.\n */\nexport interface RouteContributor {\n /** The key it sets with `ctx.set(...)`. */\n key: string\n /** Where it was registered — `method` / `class` decorators, or a module, adapter or global list. */\n source: ContributorSource\n /** The registering site, e.g. `UsersController.show#0(tenant)` or a module name. */\n label?: string\n dependsOn: readonly string[]\n /** Runs before validation (`beforeValidation: true`). */\n beforeValidation: boolean\n /** Lower-precedence registrations of the same key this one replaced. */\n overrides: ReadonlyArray<{ source: ContributorSource; label?: string }>\n}\n\nexport interface RouteMeta {\n /**\n * Owning controller class — for DI resolution and adapter introspection.\n * Absent for ad-hoc routes registered through {@link AdapterHttp.route},\n * which have no controller class behind them.\n */\n controller?: Constructor\n /** Handler method name on the controller, when there is one. */\n handlerName?: string\n /** The route's context contributors, in execution order — for devtools / introspection. */\n contributors?: readonly RouteContributor[]\n /** Zod/JSON-schema validation config from the route decorator, if any. */\n validation?: RouteDefinition['validation']\n /** `@FileUpload` config, if present — the runtime supplies the backend. */\n upload?: FileUploadConfig\n /**\n * Route flags in force here, resolved at build time (method over class).\n * Enabled flags only: a flag declared `false` at a higher-precedence site is\n * absent rather than present-and-false, so `has()` is always the right\n * question. See `core/route-flag.ts`.\n */\n flags?: RouteFlags\n /**\n * The full mounted pattern (`/api/v1/users/:id`) — set by the Application\n * for controller routes. `path` is relative to the module mount.\n */\n pattern?: string\n}\n\n/**\n * The route a request matched, published on `ctx.route`.\n *\n * Everything that holds a {@link RequestContext} — handlers, `@Middleware()`,\n * guards, contributors — can read it, which is what lets one declaration on a\n * route serve every consumer.\n */\n/**\n * Publish the matched route on the request, for `ctx.route` to read.\n *\n * Called by each runtime once per dispatch, before it builds a RequestContext.\n * It lives on `req` rather than on the ctx because the Express runtime\n * constructs a fresh RequestContext per middleware step — anything written to\n * one ctx would be invisible to the next and to the handler.\n */\nexport function publishMatchedRoute(req: unknown, entry: RouteEntry): void {\n // One object per route, shared by its requests — every field comes from the\n // entry, which is final once mounted. Frozen, since it is shared.\n let route = matchedRoutes.get(entry)\n if (!route) {\n route = Object.freeze({\n method: entry.method,\n path: entry.path,\n controller: entry.meta.controller,\n handlerName: entry.meta.handlerName,\n flags: entry.meta.flags ?? EMPTY_FLAGS,\n pattern: entry.meta.pattern ?? entry.path,\n urls: entry.urls,\n })\n matchedRoutes.set(entry, route)\n }\n ;(req as Record<symbol, MatchedRoute>)[ROUTE_SLOT] = route\n}\n\nconst matchedRoutes = new WeakMap<RouteEntry, MatchedRoute>()\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\nexport interface MatchedRoute {\n readonly method: RouteMethod\n /** Path as declared on the handler, e.g. `/:id`. */\n readonly path: string\n /**\n * The full route pattern including the mount prefix and version, e.g.\n * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls\n * back to `path` for routes registered without a mount.\n */\n readonly pattern: string\n readonly controller?: Constructor\n readonly handlerName?: string\n /** Enabled flags only — see {@link RouteMeta.flags}. */\n readonly flags: RouteFlags\n /** @internal The app's route names, for `ctx.urlFor()`. */\n readonly urls?: RouteUrls\n}\n\n/** A controller's routes grouped under the module mount prefix. */\nexport type RouteTable = { mountPath: string; routes: RouteEntry[] }[]\n\n/**\n * The response surface {@link RequestContext}'s helpers (`json` / `html` /\n * `sse` / `download` / `render` / `problem`) drive, instead of calling Express\n * `res` methods directly (spec §4.3). Sized so `express.Response` satisfies it\n * structurally — under the Express runtime the driver IS the Express response,\n * so there is no wrapping and no behavior change. Other runtimes (Fastify / h3)\n * provide a thin object implementing this over their native reply.\n *\n * The terminal methods return `RuntimeResponse` for fluent chaining (Express's\n * `Response` is assignable, since it is a superset).\n */\n/** True for the TypeError `JSON.stringify` throws on a bigint. */\nexport function isBigIntJsonError(err: unknown): boolean {\n return err instanceof TypeError && /BigInt/.test(err.message)\n}\n\n/**\n * `JSON.stringify` that writes a bigint as its decimal string instead of\n * throwing — database counts and `bigint` columns reach responses as bigints.\n * Plain `JSON.stringify` runs first, so a body without one costs nothing extra.\n */\nexport function stringifyJson(data: unknown): string {\n try {\n return JSON.stringify(data)\n } catch (err) {\n if (!isBigIntJsonError(err)) throw err\n return JSON.stringify(data, (_key, value) =>\n typeof value === 'bigint' ? value.toString() : value,\n )\n }\n}\n\nexport interface RuntimeResponse {\n status(code: number): RuntimeResponse\n json(data: unknown): RuntimeResponse\n send(data: unknown): RuntimeResponse\n type(contentType: string): RuntimeResponse\n setHeader(name: string, value: string | number | readonly string[]): unknown\n render(view: string, data?: Record<string, unknown>): unknown\n writeHead(statusCode: number, headers?: Record<string, string>): unknown\n flushHeaders(): unknown\n write(chunk: string | Buffer): boolean\n end(data?: unknown): unknown\n once(event: 'close' | 'drain', listener: () => void): unknown\n readonly headersSent: boolean\n}\n\n// ── Runtime-typed escape hatches (spec §4.3b) ─────────────────────────────\n\n/**\n * Per-runtime type map: the engine-native request / response / app types an\n * `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.\n */\nexport interface RuntimeTypeMap {\n request: unknown\n response: unknown\n app: unknown\n}\n\n/**\n * Augmentable runtime registry. Empty by default; the `kick/runtime` typegen\n * plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured\n * runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,\n * `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`\n * — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is\n * uniform with `kick/db` and env typing.\n *\n * @example\n * ```ts\n * // .kickjs/types/kick__runtime.d.ts — generated by typegen\n * declare module '@forinda/kickjs' {\n * interface KickRuntimeRegister {\n * runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes\n * }\n * }\n * ```\n */\n\nexport interface KickRuntimeRegister {}\n\n/**\n * The active runtime's type map — the augmented one, or the connect-style\n * {@link ConnectRuntimeTypes} when nothing is augmented. `kick typegen` augments it from kick.config's\n * `runtime`, Express included.\n */\nexport type ActiveRuntime = KickRuntimeRegister extends { runtime: infer R extends RuntimeTypeMap }\n ? R\n : ConnectRuntimeTypes\n\n/**\n * What the escape hatches are typed as with no augmentation: the connect-style\n * request and response every runtime's middleware sees, and an app of unknown\n * engine.\n */\nexport interface ConnectRuntimeTypes {\n request: ConnectRequest\n response: ConnectResponse\n app: unknown\n}\n\n/** Options passed to {@link HttpRuntime.createApp}. */\nexport interface RuntimeAppOptions {\n /**\n * Express `trust proxy` setting (and the equivalent on other engines). The\n * function form is Express-specific; other runtimes interpret the simpler\n * shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).\n */\n trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean)\n /**\n * When the app is mounted inside another handler (`kick dev`'s Vite server,\n * `app.handle(req, res, next)` in a host server), hand requests no route\n * matched back to it — `true`, the default — or answer them here with the\n * app's not-found handling — `false`. Express always answers.\n */\n notFoundFallthrough?: boolean\n /** Largest request body the engine parses, in bytes — `jsonLimit`, resolved. */\n bodyLimit?: number\n}\n\n/** Where a connect middleware sits and what it scopes to. */\nexport interface UseConnectOptions {\n path?: string | RegExp | ReadonlyArray<string | RegExp>\n}\n\n/**\n * Optional engine capabilities. Absence means the corresponding `ctx` feature\n * raises a clear error on that runtime rather than failing obscurely.\n */\nexport interface RuntimeCapabilities {\n /** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */\n render: boolean\n /** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */\n uploads: boolean\n /** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */\n connectMiddleware: boolean\n /**\n * The engine parses request bodies itself (Fastify, h3). When true, the\n * Application skips its default `express.json()` so the body stream isn't\n * consumed twice (which would deadlock the engine's own parser). Express:\n * false — it relies on the `express.json()` connect middleware.\n */\n nativeBodyParsing: boolean\n /**\n * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2\n * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:\n * true. Express: false — it does not run on that layer. Absent = false, so\n * custom runtimes opt in explicitly.\n */\n http2?: boolean\n}\n\n/**\n * The engine driver. KickJS owns decorators → {@link RouteTable}, the\n * contributor pipeline, the `RequestContext` surface, and error mapping. The\n * runtime owns app/server creation, route materialization, connect-middleware\n * registration, static serving, and the terminal not-found / error handlers.\n *\n * `expressRuntime()` is the default and the M1 reference implementation.\n */\nexport interface HttpRuntime<TApp = unknown> {\n readonly name: 'express' | 'fastify' | 'h3' | (string & {})\n\n /** Create the engine app. Called once per Application (and per HMR rebuild). */\n createApp(options?: RuntimeAppOptions): TApp\n\n /**\n * Node-compatible request listener — the transport contract.\n * `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST\n * invoke `next` (when given) instead of 404-ing if no route matched — the\n * Vite dev chain depends on fall-through.\n */\n nodeHandler(\n app: TApp,\n ): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void\n\n /** Materialize the framework-built route table onto the engine. */\n mountRoutes(app: TApp, table: RouteTable): void\n\n /** Register a connect-style middleware (built-ins + adopter middleware). */\n useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void\n\n /** Serve a static directory (swagger-ui assets, devtools SPA). */\n serveStatic(app: TApp, prefix: string, dir: string): void\n\n /** Terminal not-found handler. */\n setNotFound(app: TApp, mw: ConnectMiddleware): void\n\n /** Terminal error handler. */\n setErrorHandler(app: TApp, mw: ConnectMiddleware): void\n\n /**\n * Load the engine before the first `createApp()` — for a runtime that\n * imports it lazily, as the root `expressRuntime()` does so that\n * `@forinda/kickjs` doesn't need `express` installed. Awaited at setup.\n */\n load?(): Promise<void>\n\n /**\n * Body parsers to mount among the default middleware, for an engine that\n * doesn't parse request bodies itself (`capabilities.nativeBodyParsing:\n * false`). `limit` is `bootstrap({ jsonLimit })`.\n */\n bodyParsers?(options: { limit: string | number }): ConnectMiddleware[]\n\n /** Release the engine app on shutdown (Fastify runs its `onClose` hooks). */\n close?(app: TApp): void | Promise<void>\n\n readonly capabilities: RuntimeCapabilities\n}\n\n/**\n * The supported surface adapters use to add HTTP routes, mounts, static dirs,\n * and middleware — engine-agnostic, in place of reaching for the raw Express\n * `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the\n * Application over the active {@link HttpRuntime}, so an adapter written against\n * this works under any runtime; the raw `app` escape hatch stays available for\n * the rare engine-specific need.\n */\nexport interface AdapterHttp {\n /** Register a single context-handler route (e.g. a docs or transport endpoint). */\n route(method: RouteMethod, path: string, handler: CtxHandler): void\n /** Mount a pre-built route table under a path prefix. */\n mount(prefix: string, routes: RouteEntry[]): void\n /** Serve a static directory under a path prefix. */\n serveStatic(prefix: string, dir: string): void\n /** Register a connect-style middleware (optionally path-scoped). */\n use(mw: ConnectMiddleware, opts?: UseConnectOptions): void\n}\n","import { HttpException } from '../../core/errors'\nimport type { CursorPosition, CursorValue, SortItem } from './types'\n\n/**\n * Cursor wire format: base64url JSON `{ v: <position>, s: <sort signature> }`.\n * Unsigned by design — the position is only ever handed to the fetcher as\n * data, and the sort signature makes a cursor from one ordering answer 400\n * under another instead of silently skipping or repeating rows.\n */\n\n/** `createdAt:desc,id:asc` — what a cursor was issued under. */\nexport function sortSignature(sort: readonly SortItem[]): string {\n return sort.map((s) => `${s.field}:${s.direction}`).join(',')\n}\n\nfunction isPrimitive(value: unknown): value is CursorValue {\n return value === null || ['string', 'number', 'boolean'].includes(typeof value)\n}\n\nexport function encodeCursor(position: Record<string, CursorValue>, signature: string): string {\n const bytes = new TextEncoder().encode(JSON.stringify({ v: position, s: signature }))\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Decode a client cursor. Anything that is not exactly what\n * {@link encodeCursor} produces for this sort (and, when `keys` is given,\n * for exactly these fields) is a 400 — never a guess.\n */\nexport function decodeCursor(\n raw: unknown,\n signature: string,\n keys: readonly string[] | undefined,\n): CursorPosition {\n const invalid = () => HttpException.badRequest('Invalid pagination cursor')\n if (typeof raw !== 'string' || !/^[A-Za-z0-9_-]+$/.test(raw)) throw invalid()\n let parsed: unknown\n try {\n const binary = atob(raw.replace(/-/g, '+').replace(/_/g, '/'))\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0))\n parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n } catch {\n throw invalid()\n }\n if (typeof parsed !== 'object' || parsed === null) throw invalid()\n const { v, s } = parsed as { v?: unknown; s?: unknown }\n if (typeof v !== 'object' || v === null || Array.isArray(v)) throw invalid()\n if (!Object.values(v).every(isPrimitive)) throw invalid()\n if (keys) {\n const got = Object.keys(v)\n if (got.length !== keys.length || !keys.every((k) => Object.hasOwn(v, k))) throw invalid()\n }\n if (s !== signature) {\n throw HttpException.badRequest('Pagination cursor was issued for a different sort')\n }\n return v as CursorPosition\n}\n\n/**\n * The current request's path + query with `key` replaced (or dropped when\n * `value` is null). Relative on purpose: the host comes from the client, so\n * it never goes into a link. The path is re-derived through `URL`, so an\n * absolute-form request target (`GET http://evil/...`), a `//host` path, or\n * a doubled leading slash cannot turn the link into an off-site URL. Other params keep their\n * original encoding.\n */\nexport function pageLink(rawUrl: string, key: string, value: string | number | null): string {\n const url = parseUrl(rawUrl)\n const kept = url.search\n .slice(1)\n .split('&')\n .filter((part) => part !== '' && paramName(part) !== key)\n if (value !== null) kept.push(`${key}=${encodeURIComponent(value)}`)\n return kept.length ? `${url.pathname}?${kept.join('&')}` : url.pathname\n}\n\n/** The current request's path + query, relative — see {@link pageLink}. */\nexport function selfLink(rawUrl: string): string {\n const url = parseUrl(rawUrl)\n return url.pathname + url.search\n}\n\n/** Host-less parse; a leading `//` in the path would read as a host in a link, so collapse it. */\nfunction parseUrl(rawUrl: string): URL {\n const url = new URL(rawUrl, 'http://localhost')\n url.pathname = url.pathname.replace(/^\\/+/, '/')\n return url\n}\n\nfunction paramName(part: string): string {\n const name = part.split('=', 1)[0].replace(/\\+/g, ' ')\n try {\n return decodeURIComponent(name)\n } catch {\n return name\n }\n}\n","/// <reference types=\"multer\" />\nimport type { RouteName, UrlForArgs } from './url-for'\nimport { evaluatePreconditions, normalizeEtag, type Validators } from './conditional'\nimport type { ConnectRequest as Request, ConnectNext as NextFunction } from './connect'\nimport type { UploadedFile } from './middleware/upload-config'\nimport { ROUTE_SLOT } from '../core/route-flag'\nimport {\n isBigIntJsonError,\n stringifyJson,\n type ActiveRuntime,\n type MatchedRoute,\n type RuntimeResponse,\n} from './runtime'\nimport {\n type ContextMetaKey,\n type ExecutionContext,\n type MetaValue,\n} from '../core/execution-context'\nimport { normalizeProblem, type ProblemDetails, type ValidationError } from '../core/errors'\nimport { MissingContextValueError } from '../core/context-errors'\nimport { requestStore } from './request-store'\nimport { waitUntil } from './background'\nimport { resolveClientIp, type ClientRequestLike } from './client-ip'\nimport type { Session } from './middleware/session'\nimport {\n parseQuery,\n type ParseQueryOptions,\n type QueryFieldConfig,\n type PaginatedResponse,\n type TypedParsedQuery,\n type CursorPaginatedResponse,\n type CursorPaginateOptions,\n type CursorQuery,\n type CursorValue,\n} from './query'\nimport { decodeCursor, encodeCursor, pageLink, selfLink, sortSignature } from './query/cursor'\nimport { isProduction } from '../core/is-production'\n\n/**\n * Input shape for the typed problem-detail convenience methods on\n * {@link ProblemSender} (`ctx.problem.notFound`, `.badRequest`, etc.) —\n * RFC 9457 details minus the `status`, which each method pre-fills.\n */\ntype ProblemInput = Omit<ProblemDetails, 'status'>\n\n/**\n * Callable response helper for RFC 9457 — Problem Details responses.\n * Returned by `ctx.problem`. Invoke directly for a fully-specified\n * payload, or use the named convenience methods to pre-fill `status` +\n * `title` for the common codes.\n *\n * Each call sets `Content-Type: application/problem+json` and serializes\n * the canonical shape (defaulting `type` to `about:blank` and `title` to\n * the IANA reason phrase per RFC 9457 §3.1.1 / §3.1.4).\n *\n * @example\n * ```ts\n * ctx.problem({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30, // extension per §3.2\n * })\n *\n * ctx.problem.notFound({ detail: 'User abc not found' })\n * ctx.problem.validation(zodResult.error.issues)\n * ```\n */\ninterface ProblemSender {\n (input: ProblemDetails): RuntimeResponse\n /** 400 Bad Request — RFC 9457. */\n badRequest(input?: ProblemInput): RuntimeResponse\n /** 401 Unauthorized — RFC 9457. */\n unauthorized(input?: ProblemInput): RuntimeResponse\n /** 403 Forbidden — RFC 9457. */\n forbidden(input?: ProblemInput): RuntimeResponse\n /** 404 Not Found — RFC 9457. */\n notFound(input?: ProblemInput): RuntimeResponse\n /** 409 Conflict — RFC 9457. */\n conflict(input?: ProblemInput): RuntimeResponse\n /** 422 Unprocessable Entity — RFC 9457. */\n unprocessable(input?: ProblemInput): RuntimeResponse\n /** 429 Too Many Requests — RFC 9457. */\n tooManyRequests(input?: ProblemInput): RuntimeResponse\n /** 500 Internal Server Error — RFC 9457. */\n internal(input?: ProblemInput): RuntimeResponse\n /**\n * 422 with Zod issues serialized into the `errors` extension per\n * RFC 9457 §3.2's array convention. Pass `error.issues` from a Zod\n * `safeParse` failure or `error.issues` from a thrown ZodError.\n */\n validation(issues: any[], input?: ProblemInput): RuntimeResponse\n}\n\n/**\n * Recursively marks every property of `T` as `readonly`. Preserves\n * `Function`, `Date`, and `RegExp` unchanged, and converts `Map` / `Set`\n * to `ReadonlyMap` / `ReadonlySet` so their mutating methods (`set`,\n * `delete`, `add`, `clear`) are removed from the public surface.\n * Tuples keep their positional element types — only their per-element\n * mutability is locked.\n *\n * Exposed as a utility for adopters who want to opt into compile-time\n * sealing of their own shapes. **No longer applied to\n * `RequestContext.{body,params,query,headers,file,files}`** — that\n * broke TS narrowing / discriminated-union drilldowns on typed request\n * payloads. Runtime read-only enforcement now lives in\n * {@link makeReadOnlyProxy} (dev-only Proxy that warns on writes,\n * no-op in production).\n *\n * Type-only. No runtime cost. `DeepReadonly<any>` is `any` (TS\n * distributes conditional types over `any`).\n */\nexport type DeepReadonly<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends Date | RegExp\n ? T\n : T extends Map<infer K, infer V>\n ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>\n : T extends Set<infer V>\n ? ReadonlySet<DeepReadonly<V>>\n : T extends readonly (infer U)[]\n ? // Distinguish a regular array from a tuple. A regular `T[]` widens\n // its `length` to `number`; a tuple's `length` is a literal\n // (e.g. `2`). The literal branch maps over `keyof T` so each\n // positional slot keeps its own type — `DeepReadonly<[1, 2]>` →\n // `readonly [1, 2]`, not `readonly (1 | 2)[]`.\n number extends T['length']\n ? ReadonlyArray<DeepReadonly<U>>\n : { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T\n\n/**\n * Re-export the augmentable {@link ContextMeta} registry from core/.\n * Declared in `core/execution-context.ts` so non-HTTP transports\n * (WS/queue/cron, V2) share one declaration site. Apps still augment\n * via the canonical `declare module '@forinda/kickjs'` form.\n */\nexport type { ContextMeta } from '../core/execution-context'\n\n/**\n * Symbol key under which the per-request `AbortController` backing\n * `RequestContext.signal` is cached on the Express `req` object.\n * Shared across every `RequestContext` instance built for the same\n * request (router-builder constructs separate wrappers for\n * middleware, the contributor pipeline, and the main handler — they\n * all need the same signal).\n */\nconst signalControllerKey = Symbol.for('kickjs.requestContext.signalController')\n\n/**\n * Symbol key under which per-target read-only Proxy wrappers are\n * cached on the Express `req` object. Used by {@link makeReadOnlyProxy}\n * so repeat access of `ctx.body` / `ctx.params` / etc. returns the same\n * Proxy instance (cheap, and stable under `===` for adopters comparing\n * values across middleware).\n */\nconst readOnlyProxyCacheKey = Symbol.for('kickjs.requestContext.readOnlyProxyCache')\n\n/**\n * `true` iff `v` is a plain object (`{}` / `Object.create(null)`) or an\n * array — the two shapes JSON.parse / Express body-parser produce and\n * the only ones the read-only Proxy recurses into. Class instances,\n * `Date`, `RegExp`, `Map`, `Set`, `Buffer`, streams, and functions\n * pass through unwrapped so their method dispatch and `instanceof`\n * checks keep working.\n */\nfunction isPlainObjectOrArray(v: unknown): v is object {\n if (v === null || typeof v !== 'object') return false\n if (Array.isArray(v)) return true\n const proto = Object.getPrototypeOf(v)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * In dev, wrap `target` in a `Proxy` whose `set` / `deleteProperty` /\n * `defineProperty` traps log a warning and otherwise leave the\n * underlying object untouched. A `get` trap recursively wraps nested\n * plain objects and arrays on access, so deep mutations\n * (`ctx.body.user.name = 'x'`, `ctx.files[0].fieldname = 'y'`,\n * `ctx.body.tags.push(...)`) all surface a warning — matching the\n * prior `DeepReadonly<T>` contract at runtime instead of at the type\n * level. In production (any `NODE_ENV` but `development` / `test`) the\n * proxy is bypassed entirely and `target` is returned as-is so the\n * hot path stays zero-cost.\n *\n * Why a Proxy instead of `DeepReadonly<T>` at the type level: the\n * recursive conditional type interfered with TS narrowing (notably\n * discriminated unions on `ctx.body`) and slowed type-checking on\n * deeply-nested Zod-inferred shapes. Compile-time sealing is gone;\n * runtime warning catches the same class of bug during dev and tests.\n *\n * Trap returns `true` so strict-mode call sites (which is all of them\n * — ES modules are strict) don't *throw* on assignment — they just\n * get a warning + the underlying value stays untouched. Adopters\n * discover the violation when the subsequent read returns the\n * original value, not the one they \"set\".\n *\n * Targets are cached per-`req` under {@link readOnlyProxyCacheKey} so\n * (1) repeat getter access returns the same proxy (`ctx.body ===\n * ctx.body`, `ctx.body.user === ctx.body.user`); and (2) cyclic refs\n * (`body.self = body`) terminate via the cache hit on the second\n * visit. Primitives, `null`, and non-plain values pass through.\n */\nfunction makeReadOnlyProxy<T>(target: T, req: object, label: string): T {\n if (isProduction()) return target\n if (!isPlainObjectOrArray(target)) return target\n\n type Cache = WeakMap<object, unknown>\n const reqObj = req as Record<symbol, Cache | undefined>\n let cache = reqObj[readOnlyProxyCacheKey]\n if (!cache) {\n cache = new WeakMap()\n reqObj[readOnlyProxyCacheKey] = cache\n }\n const targetObj = target as unknown as object\n const cached = cache.get(targetObj)\n if (cached) return cached as T\n\n const warnWrite = (verb: string, prop: PropertyKey) => {\n console.warn(\n `[kickjs] Attempted to ${verb} \\`ctx.${label}.${String(prop)}\\` — ` +\n `request data is read-only. ` +\n `Stash computed values via \\`ctx.set('key', value)\\` or a Context Contributor, ` +\n `or reach \\`ctx.req.${label}\\` if you genuinely need the raw mutable handle.`,\n )\n }\n\n const proxy = new Proxy(targetObj, {\n get(t, prop, receiver) {\n const value = Reflect.get(t, prop, receiver)\n // Recurse only into plain objects / arrays. Functions (incl.\n // array methods like `.push`) pass through with `receiver` as\n // their `this`, so internal `this[i] = x` writes still hit the\n // `set` trap and warn.\n if (isPlainObjectOrArray(value)) {\n return makeReadOnlyProxy(value, req, `${label}.${String(prop)}`)\n }\n return value\n },\n set(_t, prop) {\n warnWrite('assign', prop)\n return true\n },\n deleteProperty(_t, prop) {\n warnWrite('delete', prop)\n return true\n },\n defineProperty(_t, prop) {\n warnWrite('Object.defineProperty on', prop)\n return true\n },\n })\n cache.set(targetObj, proxy)\n return proxy as T\n}\n\n/**\n * The shape of a single route entry in `KickRoutes`. Generated by\n * `kick typegen` and consumed via the `Ctx<T>` helper. Each field is\n * `unknown` by default and is filled in as the typegen learns more\n * about the route (URL params from the path, body/query from validation\n * schemas, etc.).\n */\nexport interface RouteShape {\n params?: unknown\n body?: unknown\n query?: unknown\n response?: unknown\n /**\n * Union of context keys `kick typegen` proved are populated for this\n * route — the keys of every context contributor applied at method or\n * class level. Drives {@link RequestContext.require} narrowing, so\n * calling `ctx.require()` for a key this route doesn't carry is a\n * compile error instead of a request-time throw.\n *\n * `string` (the default) means \"not proven\", not \"no keys\". Typegen\n * emits `string` whenever it cannot see the full picture — a\n * contributor registered at module / adapter / bootstrap level, or an\n * unrecognised decorator that might bundle contributors of its own.\n * Narrowing an unprovable route would produce compile errors for keys\n * that really are present.\n */\n contextKeys?: string\n}\n\n/**\n * Unified request/response abstraction passed to every controller method.\n * Shields handlers from raw Express objects and provides convenience methods.\n *\n * Implements {@link ExecutionContext} so the transport-agnostic Context\n * Contributor pipeline (#107) can run against this concrete HTTP context\n * the same way it will run against future WS / queue / cron contexts.\n */\nexport class RequestContext<\n TBody = any,\n TParams = any,\n TQuery = any,\n /**\n * Context keys proven present for this route. Defaults to\n * {@link ContextMetaKey} — every key the project has registered — which\n * collapses to `string` when neither registry has been augmented, so a\n * handler typed as plain `RequestContext` keeps today's behaviour. That\n * default is also the deliberate escape hatch when typegen's view of a\n * route is incomplete.\n */\n TKeys extends ContextMetaKey = ContextMetaKey,\n> implements ExecutionContext<TKeys> {\n /**\n * Engine-agnostic response driver the response helpers write through. Under\n * the Express runtime it IS `res` (Express's Response satisfies\n * {@link RuntimeResponse} structurally); other runtimes pass a thin wrapper\n * over their native reply as the optional fourth argument.\n */\n private readonly _response: RuntimeResponse\n\n /**\n * The route this request matched: its method, path, controller, handler name\n * and resolved {@link MatchedRoute.flags}.\n *\n * Available to anything running inside the matched route — route middleware,\n * contributors, guards, the handler. Global middleware runs before route\n * matching, so it sees `undefined` there.\n *\n * ```ts\n * if (ctx.route?.flags.has('auth.public')) return next()\n * ```\n */\n get route(): MatchedRoute | undefined {\n return (this.req as unknown as Record<symbol, MatchedRoute | undefined>)?.[ROUTE_SLOT]\n }\n\n constructor(\n public readonly req: ActiveRuntime['request'],\n public readonly res: ActiveRuntime['response'],\n public readonly next: NextFunction,\n responseDriver?: RuntimeResponse,\n ) {\n // Under the Express runtime `res` IS a RuntimeResponse (structural); other\n // runtimes pass an explicit driver wrapping their native reply.\n this._response = responseDriver ?? (res as unknown as RuntimeResponse)\n }\n\n /**\n * Memo of the most recent {@link qs} call this request. The query\n * object is immutable for a request's lifetime, so a repeat call with\n * the same `(fieldConfig, options)` references returns the cached\n * parse instead of re-walking the filter/sort strings.\n */\n private _qsMemo?: { config: unknown; options: unknown; result: unknown }\n\n /** Memoized {@link problem} sender — built lazily on first access. */\n private _problem?: ProblemSender\n\n /**\n * Read-side accessor for the per-request metadata map.\n *\n * Returns the AsyncLocalStorage map (`requestStore.getStore().values`)\n * shared with the Context Contributor pipeline when an ALS frame is\n * active. Returns `null` outside any frame — read-side callers\n * (`ctx.get`, `ctx.user`, `ctx.tenantId`, `ctx.roles`) treat that as\n * \"no metadata\" and fall through to their `req.*` defaults. Reads\n * never throw because outside an ALS frame nobody could have written\n * via `ctx.set` anyway, so an empty answer is the truthful one.\n */\n private metadataReadOnly(): Map<string, any> | null {\n return (requestStore.getStore()?.values as Map<string, any> | undefined) ?? null\n }\n\n /**\n * Write-side accessor for the per-request metadata map.\n *\n * Returns the same map as {@link metadataReadOnly} when an ALS frame\n * is active. Throws otherwise — writing to a fallback map outside\n * the ALS frame would silently lose data because other call sites\n * (downstream contributors, request-logger, etc.) read from the\n * canonical store and would never see it. Mount\n * `requestScopeMiddleware()` (Application does this for you in\n * `'auto'` mode) or wrap your test setup in\n * `requestStore.run({...}, () => …)` to fix.\n */\n private metadataForWrite(): Map<string, any> {\n const store = requestStore.getStore()\n if (store) return store.values as Map<string, any>\n throw new Error(\n 'RequestContext.set called outside an AsyncLocalStorage frame. ' +\n 'Mount requestScopeMiddleware() before constructing RequestContext, ' +\n 'or wrap test setup in requestStore.run({ requestId, instances: new Map(), values: new Map() }, () => ...).',\n )\n }\n\n // ── Request Data ────────────────────────────────────────────────────\n\n /**\n * Parsed request body. Wrapped in a dev-only Proxy that warns when\n * adopters try to mutate Zod-validated payloads in place — compute\n * new values and stash them via `ctx.set('key', value)` or a Context\n * Contributor instead. Reach for `ctx.req.body` if you genuinely\n * need the raw, mutable Express handle (rare).\n *\n * In production the Proxy is bypassed and `this.req.body` is\n * returned as-is — no runtime cost on the hot path.\n */\n get body(): TBody {\n return makeReadOnlyProxy<TBody>(this.req.body, this.req, 'body')\n }\n\n /** Path parameters parsed from the route — read-only, see {@link body}. */\n get params(): TParams {\n return makeReadOnlyProxy<TParams>(this.req.params as TParams, this.req, 'params')\n }\n\n /** Parsed query string — read-only, see {@link body}. */\n get query(): TQuery {\n return makeReadOnlyProxy<TQuery>(this.req.query as TQuery, this.req, 'query')\n }\n\n /** Inbound HTTP headers — read-only, see {@link body}. */\n get headers(): Request['headers'] {\n return makeReadOnlyProxy<Request['headers']>(this.req.headers, this.req, 'headers')\n }\n\n get requestId(): string | undefined {\n return (this.req as any).requestId ?? (this.req.headers['x-request-id'] as string | undefined)\n }\n\n /**\n * `AbortSignal` that fires when the underlying HTTP request is\n * closed — either because the client disconnected before the\n * response was sent, or because Node's socket-close event ran\n * after a normal response. Multiple `RequestContext` wrappers for\n * the same request (router-builder constructs one per\n * middleware/contributor pipeline / main handler) share a single\n * `AbortController` cached on the underlying `req` object, so the\n * signal is stable across the request lifecycle.\n *\n * Thread it through anything that takes an `AbortSignal` so the\n * work cancels as soon as the client gives up — e.g. a kickjs-db\n * relational query:\n *\n * ```ts\n * @Get('/:id/full')\n * async show(ctx: RequestContext) {\n * const row = await this.repo.findFullById(ctx.params.id, ctx.signal)\n * if (!row) return ctx.notFound()\n * ctx.json(row)\n * }\n * ```\n *\n * The repo passes `signal` to `db.query.<table>.findUnique({ signal })`;\n * if the client disconnects mid-flight, the in-flight query rejects\n * with `RelationalQueryCancelledError` instead of consuming the\n * connection until completion.\n *\n * Implementation note — both `req.on('close')` and `res.on('close')`\n * are wired so the signal aborts regardless of whether the close\n * event lands on the request stream or the response stream first.\n * Subsequent fires are no-ops (`AbortController.abort()` is\n * idempotent).\n */\n get signal(): AbortSignal {\n const req = this.req as Request & { [signalControllerKey]?: AbortController }\n const cached = req[signalControllerKey]\n if (cached) return cached.signal\n\n const ctrl = new AbortController()\n req[signalControllerKey] = ctrl\n const abort = () => ctrl.abort('request closed')\n this.req.once('close', abort)\n this._response.once('close', abort)\n return ctrl.signal\n }\n\n /**\n * The request's session — set by the `session()` middleware, which must be\n * installed. Type your keys once by augmenting `SessionData`:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface SessionData { userId?: string }\n * }\n * ```\n */\n get session(): Session {\n return (this.req as { session?: Session }).session as Session\n }\n\n /**\n * The authenticated user set by AuthAdapter.\n * Reads from the per-request metadata store first (`ctx.set('user', ...)`),\n * then falls back to `req.user` (set directly by AuthAdapter middleware).\n *\n * Extend the `AuthUser` interface via module augmentation in your own auth\n * module — see the BYO Auth recipe in the docs\n * to get full typing.\n *\n * @example\n * ```ts\n * @Get('/me')\n * @Authenticated()\n * getProfile(ctx: RequestContext) {\n * const user = ctx.user\n * if (!user) return ctx.notFound()\n * return ctx.json({ user })\n * }\n * ```\n */\n get user(): MetaValue<'user', Record<string, any>> | undefined {\n return this.metadataReadOnly()?.get('user') ?? (this.req as any).user\n }\n\n /**\n * Tenant identifier for multi-tenant apps. Reads `user.tenantId` —\n * populated either by `AuthAdapter.testMode({ tenantId })`, a tenant\n * resolver middleware, or manually on the strategy's `mapPayload`.\n *\n * Augment `AuthUser` (or `ContextMeta['user']`) to widen the return\n * type if your user shape guarantees a non-`string | undefined` id.\n */\n get tenantId(): string | undefined {\n const u = this.user as Record<string, any> | undefined\n return u?.tenantId\n }\n\n /**\n * Effective role list for the current user. Prefers `user.tenantRoles`\n * (populated by `AuthAdapterOptions.roleResolver` under a tenant) and\n * falls back to `user.roles`. Returns an empty array when the user is\n * absent or the shape has neither field.\n */\n get roles(): string[] {\n const u = this.user as Record<string, any> | undefined\n return u?.tenantRoles ?? u?.roles ?? []\n }\n\n // ── Query String Parsing ───────────────────────────────────────────\n\n /**\n * Parse the request query string into structured filters, sort, pagination, and search.\n * Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).\n *\n * Generic over the field config: when passed an inline literal (or\n * `as const`), `filters[].field` and `sort[].field` are narrowed to\n * the exact whitelisted field names. Pass nothing or a non-literal\n * config and you get the loose `string` fallback.\n *\n * @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields\n * @param options - Limits (`maxLimit`, `defaultLimit`, `maxSearchLength`) and an\n * `onReject` hook. By default a rejected/over-broad field is logged via\n * `console.warn` with the request id; pass an explicit `onReject` to override\n * (e.g. throw to return a 400), or `onReject: () => {}` to silence.\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * } as const)\n * parsed.filters[0].field // typed as 'status' | 'priority'\n * parsed.sort[0].field // typed as 'createdAt' | 'title'\n * }\n * ```\n */\n qs<TConfig extends QueryFieldConfig | undefined = undefined>(\n fieldConfig?: TConfig,\n options?: ParseQueryOptions,\n ): TypedParsedQuery<TConfig> {\n // Cheap per-request memo — repeat calls with the same args (the\n // common controller pattern) skip re-parsing. `req.query` is fixed\n // for the request's lifetime, so caching is always sound.\n const memo = this._qsMemo\n if (memo && memo.config === fieldConfig && memo.options === options) {\n return memo.result as TypedParsedQuery<TConfig>\n }\n const effective: ParseQueryOptions = {\n ...options,\n onReject:\n options?.onReject ??\n ((rejection) => {\n const id = this.requestId ? `[${this.requestId}] ` : ''\n console.warn(\n `${id}query ${rejection.kind} '${rejection.field}' rejected (${rejection.reason})`,\n )\n }),\n }\n const result = parseQuery<TConfig>(\n this.req.query as Record<string, any>,\n fieldConfig,\n effective,\n )\n this._qsMemo = { config: fieldConfig, options, result }\n return result\n }\n\n // ── File Uploads ────────────────────────────────────────────────────\n\n /**\n * Single uploaded file (requires `@FileUpload({ mode: 'single' })`).\n * Wrapped in a dev-only Proxy that warns on mutation — see {@link body}.\n * File metadata is set by the upload middleware and shouldn't be\n * mutated downstream.\n */\n get file(): UploadedFile | undefined {\n const f = this.req.file\n return f ? makeReadOnlyProxy<UploadedFile>(f, this.req, 'file') : undefined\n }\n\n /**\n * Array of uploaded files (requires `@FileUpload({ mode: 'array' })`).\n * The array (and each entry in dev) is wrapped in a read-only Proxy\n * that warns on `push`/`pop` and per-file mutation. Use\n * `ctx.req.files` if you genuinely need the mutable Express handle.\n */\n get files(): UploadedFile[] | undefined {\n // multer's `Request['files']` is a union — array (mode: 'array' /\n // 'any') or `{ [fieldname]: File[] }` (mode: 'fields'). The\n // `@FileUpload({ mode: 'array' })` decorator only sets the array\n // shape, but `Request['files']` is the broad union. Narrow back to\n // `File[]` here for the common-case getter; adopters using\n // `mode: 'fields'` can read `ctx.req.files` directly for the\n // dictionary shape.\n const f = this.req.files\n if (!Array.isArray(f)) return undefined\n return makeReadOnlyProxy<UploadedFile[]>(f, this.req, 'files')\n }\n\n // ── Metadata Store ──────────────────────────────────────────────────\n\n /**\n * Read a value from the per-request metadata store.\n *\n * The key is constrained to {@link ContextMetaKey} — the keys registered in\n * `ContextMeta` / `ContextKeys` — so a typo is a compile error rather than a\n * permanent `undefined`. Projects that have augmented neither registry get\n * `string`, exactly as before.\n *\n * Constrained by `ContextMetaKey` and deliberately NOT by `TKeys`: \"does this\n * key exist in the app\" is a different question from \"does this route carry\n * it\", and narrowing by the latter would turn an incomplete typegen view into\n * false errors for keys written by middleware. Presence is `require`'s job;\n * this always returns `| undefined`.\n *\n * When `ContextMeta` has a matching key the return type is inferred\n * automatically. For ad-hoc keys, pass a generic: `ctx.get<MyType>('custom')`.\n */\n get<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return this.metadataReadOnly()?.get(key) as MetaValue<K> | undefined\n }\n\n /**\n * Read a value that a contributor is expected to have produced, and\n * throw {@link MissingContextValueError} when it hasn't.\n *\n * Use this instead of `ctx.get(key)!` anywhere the value is a\n * precondition rather than an optional extra — permissions, tenants,\n * the resolved subject of the route. The non-null assertion compiles\n * whether or not the producing contributor is actually applied to the\n * route, so a dropped `@LoadTenant` turns into `undefined` flowing\n * silently into an auth check. `require()` fails loudly at that point\n * instead, naming the key.\n *\n * ```ts\n * // before — compiles even if @OperatorPerm was never applied\n * const perm = ctx.get('operatorPerm')!\n *\n * // after — throws MissingContextValueError naming the key + route\n * const perm = ctx.require('operatorPerm')\n * ```\n *\n * When `TKeys` is narrowed — which it is for a handler typed as\n * `Ctx<KickRoutes…>`, from typegen's per-route `contextKeys` — asking\n * for a key the route doesn't carry is a compile error, so a dropped\n * decorator fails the build. `TKeys` stays `string` (no narrowing) for\n * a plain `RequestContext` and for any route typegen couldn't prove\n * complete; there this is a runtime guarantee only.\n * See `architecture.md` §20.14.\n *\n * `null` counts as present; only `undefined` (or a missing entry)\n * throws. A contributor that deliberately resolves to `null` is\n * expressing \"looked, found nothing\", which is a real value — which\n * is why the return type is `Exclude<…, undefined>` and NOT\n * `NonNullable<…>`. The latter would strip `null` from the type while\n * the runtime still hands it back, so a caller would be told a value\n * is non-null and then get `null`.\n */\n require<K extends TKeys>(key: K): Exclude<MetaValue<K>, undefined> {\n const value = this.metadataReadOnly()?.get(key)\n if (value === undefined) {\n throw new MissingContextValueError(key, this.routeLabel())\n }\n return value as Exclude<MetaValue<K>, undefined>\n }\n\n /**\n * Best-effort `\"GET /path\"` label for error messages. Runtime-agnostic:\n * express/fastify requests and web-standard `Request` all expose\n * `method` + `url`, but none of them are guaranteed here, so every\n * access is defensive and the whole thing is optional.\n */\n private routeLabel(): string | undefined {\n const req = this.req as { method?: unknown; url?: unknown } | undefined\n const method = typeof req?.method === 'string' ? req.method : undefined\n const url = typeof req?.url === 'string' ? req.url : undefined\n if (method && url) return `${method} ${url}`\n return method ?? url\n }\n\n /**\n * Write a value to the per-request metadata store. Throws when no\n * AsyncLocalStorage frame is active — see {@link metadataForWrite}\n * for why a silent fallback is the wrong default.\n */\n set<K extends ContextMetaKey>(key: K, value: MetaValue<K>): void {\n this.metadataForWrite().set(key, value)\n }\n\n // ── Response Helpers ────────────────────────────────────────────────\n\n /**\n * Set a response header. Runtime-neutral — works on every engine and on\n * the web/edge entry. No-op guards are the runtime's job (headers set\n * after the response settles are ignored or throw per engine).\n */\n setHeader(name: string, value: string | number | readonly string[]): this {\n this._response.setHeader(name, value)\n return this\n }\n\n json(data: any, status = 200) {\n return this.sendJson(status, data)\n }\n\n created(data: any) {\n return this.sendJson(201, data)\n }\n\n private sendJson(status: number, data: unknown): RuntimeResponse {\n try {\n return this._response.status(status).json(data)\n } catch (err) {\n // Express serialises inside `res.json` and throws on a bigint before\n // anything is written; the other runtimes' drivers use stringifyJson.\n if (!isBigIntJsonError(err) || this._response.headersSent) throw err\n return this._response.status(status).json(JSON.parse(stringifyJson(data)))\n }\n }\n\n noContent() {\n return this._response.status(204).end()\n }\n\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string. Names and params are typed\n * once `kick typegen` has run; an unknown name or a missing param throws.\n *\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const user = await this.users.create(ctx.body)\n * ctx.setHeader('Location', ctx.urlFor('UsersController.show', { id: user.id }))\n * ctx.created(user)\n * }\n * ```\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const urls = this.route?.urls\n if (!urls) throw new Error('ctx.urlFor() is only available inside a matched route')\n const [params, query] = args\n return urls.build(name, params as Record<string, unknown> | undefined, query)\n }\n\n /**\n * Answer a conditional request from the resource's validators, before doing\n * the expensive part. Sets `ETag` / `Last-Modified`, then — per RFC 9110 —\n * answers `304 Not Modified` when the client's copy is current, or `412`\n * when an `If-Match` / `If-Unmodified-Since` write is based on a stale one.\n * Returns `true` when it answered; respond as usual when it returns `false`.\n *\n * ```ts\n * @Get('/:id')\n * async show(ctx: RequestContext) {\n * const { version, updatedAt } = await posts.meta(ctx.params.id) // cheap\n * if (ctx.conditional({ etag: `v${version}`, lastModified: updatedAt })) return\n * ctx.json(await posts.full(ctx.params.id)) // only when it changed\n * }\n * ```\n */\n conditional(validators: Validators): boolean {\n if (validators.etag !== undefined) this.setHeader('ETag', normalizeEtag(validators.etag))\n if (validators.lastModified) {\n this.setHeader('Last-Modified', validators.lastModified.toUTCString())\n }\n const method = String((this.req as { method?: string }).method ?? 'GET').toUpperCase()\n const outcome = evaluatePreconditions(\n method,\n this.headers as Record<string, string | string[] | undefined>,\n validators,\n )\n if (outcome === 304) {\n this._response.status(304).end()\n return true\n }\n if (outcome === 412) {\n this.sendProblem({\n status: 412,\n detail: 'The resource changed since the version this request is based on.',\n })\n return true\n }\n return false\n }\n\n /**\n * @deprecated Prefer {@link ProblemSender.notFound | ctx.problem.notFound()},\n * which emits an RFC 9457 — Problem Details response. This helper stays\n * for backward compatibility and will not be removed.\n */\n notFound(message = 'Not Found') {\n return this._response.status(404).json({ message })\n }\n\n /**\n * @deprecated Prefer {@link ProblemSender.badRequest | ctx.problem.badRequest()},\n * which emits an RFC 9457 — Problem Details response. This helper stays\n * for backward compatibility and will not be removed.\n */\n badRequest(message: string) {\n return this._response.status(400).json({ message })\n }\n\n // ── RFC 9457 Problem Details ───────────────────────────────────────\n\n /**\n * RFC 9457 — Problem Details for HTTP APIs response helper.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * `ctx.problem(...)` sends a canonical problem-detail response with\n * `Content-Type: application/problem+json`. The convenience methods\n * (`ctx.problem.notFound`, `.badRequest`, etc.) pre-fill `status` +\n * `title` for the common codes.\n *\n * `type` defaults to `about:blank` (§3.1.1); `title` defaults to the\n * IANA reason phrase for `status` (§3.1.4). Extension members per §3.2\n * pass through unchanged.\n *\n * @example\n * ```ts\n * ctx.problem({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: `/account/${ctx.user.id}/messages/${ctx.params.id}`,\n * balance: 30,\n * })\n *\n * ctx.problem.notFound({ detail: 'User abc not found' })\n * ctx.problem.validation(zodResult.error.issues)\n * ```\n *\n * @see {@link ProblemException} for the exception-throwing equivalent\n * (use it from services where `ctx` isn't in scope).\n */\n get problem(): ProblemSender {\n // Memoized — building the sender allocates ~10 closures, so pay that only\n // on the first access per context instead of per `ctx.problem.*` call.\n if (this._problem) return this._problem\n const send = (input: ProblemDetails): RuntimeResponse => this.sendProblem(input)\n send.badRequest = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 400, ...input })\n send.unauthorized = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 401, ...input })\n send.forbidden = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 403, ...input })\n send.notFound = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 404, ...input })\n send.conflict = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 409, ...input })\n send.unprocessable = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 422, ...input })\n send.tooManyRequests = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 429, ...input })\n send.internal = (input: ProblemInput = {}): RuntimeResponse =>\n this.sendProblem({ status: 500, ...input })\n send.validation = (issues: any[], input: ProblemInput = {}): RuntimeResponse => {\n const errors: ValidationError[] = (issues || []).map((issue: any) => ({\n field: issue.path?.join?.('.') ?? '',\n message: issue.message ?? '',\n code: issue.code,\n }))\n return this.sendProblem({\n status: 422,\n detail: issues?.[0]?.message,\n ...input,\n errors,\n })\n }\n this._problem = send as ProblemSender\n return this._problem\n }\n\n private sendProblem(input: ProblemDetails): RuntimeResponse {\n const body = normalizeProblem(input)\n this._response.setHeader('Content-Type', 'application/problem+json')\n return this._response.status(body.status).json(body)\n }\n\n /**\n * Send an HTML response.\n *\n * Passes the full MIME type rather than the `'html'` shorthand. The\n * shorthand is an Express affordance — `res.type()` runs it through a MIME\n * lookup — but the Fastify and h3 drivers forward the string to their own\n * `type()` / `setHeader()` verbatim, so `'html'` reached the wire as a\n * malformed `Content-Type: html` on those engines. Fastify 5.10 started\n * normalising that invalid value to `text/plain`, which is what surfaced it.\n *\n * Express produces `text/html; charset=utf-8` for `.type('html')`, so\n * spelling it out here is byte-identical there and correct everywhere else.\n */\n /**\n * The client's IP address, or `undefined` when it cannot be determined.\n *\n * Prefers the value the runtime computed (Express derives `req.ip` from the\n * app's `trust proxy` setting; Fastify from `trustProxy`), because raw\n * forwarded headers are client-SPOOFABLE on deployments that do not\n * normalize them. The header fallbacks exist for runtimes with no `ip`\n * field at all — notably the web/edge entry.\n *\n * `ctx.req.ip` is Express-only, so reaching for it directly broke on\n * Fastify and h3.\n */\n get ip(): string | undefined {\n return resolveClientIp(this.req as ClientRequestLike)\n }\n\n /**\n * Redirect the client. Works on every runtime.\n *\n * Every engine spells this differently — Express and Fastify have\n * `res.redirect()`, h3 has `sendRedirect(event, location, code)` — and none\n * of them is shared, so this writes the status and `Location` header through\n * the runtime response surface, which all four expose.\n *\n * The response carries no body. Express sends a short text line and h3 an\n * HTML meta-refresh fallback; a bare `Location` with a 3xx is sufficient per\n * RFC 9110, and interpolating the URL into an HTML body would add an\n * injection surface to a value this method already warns is dangerous.\n *\n * ::: warning\n * Never pass an unvalidated user-supplied `url`. An attacker-controlled\n * destination turns this into an open redirect, which is a common phishing\n * primitive. Allow-list the target or keep it relative.\n * :::\n */\n redirect(url: string, status = 302) {\n this._response.status(status).setHeader('location', url)\n return this._response.end()\n }\n\n html(content: string, status = 200) {\n return this._response.status(status).type('text/html; charset=utf-8').send(content)\n }\n\n /**\n * Send a body with its content type — XML, plain text, CSV, an image.\n * Runtime-neutral, like `json()` and `html()`. `type` defaults to\n * `text/plain; charset=utf-8`.\n *\n * @example\n * ```ts\n * ctx.send(sitemapXml, { type: 'application/xml' })\n * ctx.send(csv, { type: 'text/csv; charset=utf-8', status: 200 })\n * ```\n */\n send(body: string | Uint8Array, options: { type?: string; status?: number } = {}) {\n return this._response\n .status(options.status ?? 200)\n .type(options.type ?? 'text/plain; charset=utf-8')\n .send(body)\n }\n\n /**\n * Send `buffer` as a file download named `filename`. The name is written\n * per RFC 6266 — an ASCII fallback plus `filename*` in UTF-8 — so a name\n * from an upload (quotes, line breaks, non-Latin text) can't break the header.\n */\n download(buffer: Buffer, filename: string, contentType = 'application/octet-stream') {\n this._response.setHeader('Content-Disposition', contentDisposition(filename))\n this._response.setHeader('Content-Type', contentType)\n return this._response.send(buffer)\n }\n\n /**\n * Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).\n * Requires a ViewAdapter to be configured in bootstrap().\n *\n * @param template - Template name (without extension, relative to viewsDir)\n * @param data - Data to pass to the template\n *\n * @example\n * ```ts\n * ctx.render('dashboard', { user, title: 'Dashboard' })\n * ctx.render('emails/welcome', { name: 'Alice' })\n * ```\n */\n render(template: string, data: Record<string, any> = {}) {\n return this._response.render(template, data)\n }\n\n /**\n * Parse query params and return a standardized paginated response.\n * Calls `ctx.qs()` internally, then wraps your data with pagination meta.\n *\n * @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`\n * @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * return ctx.paginate(\n * async (parsed) => {\n * const data = await db.select().from(users)\n * .where(query.where).limit(parsed.pagination.limit)\n * .offset(parsed.pagination.offset).all()\n * const total = await db.select({ count: count() }).from(users).get()\n * return { data, total: total?.count ?? 0 }\n * },\n * { filterable: ['name', 'role'], sortable: ['createdAt'] },\n * )\n * }\n * ```\n */\n async paginate<T, TConfig extends QueryFieldConfig | undefined = undefined>(\n fetcher: (parsed: TypedParsedQuery<TConfig>) => Promise<{ data: T[]; total: number }>,\n fieldConfig?: TConfig,\n ): Promise<PaginatedResponse<T>> {\n const parsed = this.qs<TConfig>(fieldConfig)\n const { data, total } = await fetcher(parsed)\n const { page, limit } = parsed.pagination\n const totalPages = Math.ceil(total / limit) || 1\n\n const response: PaginatedResponse<T> = {\n data,\n meta: {\n page,\n limit,\n total,\n totalPages,\n hasNext: page < totalPages,\n hasPrev: page > 1,\n },\n links: {\n self: selfLink(this.requestUrl()),\n next: page < totalPages ? pageLink(this.requestUrl(), 'page', page + 1) : null,\n prev: page > 1 ? pageLink(this.requestUrl(), 'page', page - 1) : null,\n },\n }\n\n this.json(response)\n // Sends AND returns the payload. Returning `this.json(...)` handed back\n // the engine's `RuntimeResponse`, so the documented usage —\n // `return ctx.paginate(...)` — emitted `response: RuntimeResponse` into\n // `KickRoutes`, and the typed client offered `.status()` / `.setHeader()`\n // where the caller expected `data` and `meta`.\n //\n // Returning the payload rather than tagging the response reuses the\n // existing return-value inference (the same path `return user` and\n // `return reply(201, user)` take) instead of adding a second mechanism\n // beside `reply`. Sending here is kept for handlers that call `paginate`\n // without returning it; the runtimes only auto-send a returned value when\n // nothing was written (`if (!res.headersSent)`), so there is no double\n // send.\n return response\n }\n\n /**\n * Cursor (keyset) pagination: parse `?cursor=&limit=` plus the usual\n * filter / sort / `q`, call the fetcher, and send\n * `{ data, meta: { limit, hasNext, nextCursor }, links: { self, next } }`.\n *\n * The fetcher gets `{ filters, sort, search, cursor, limit }` and returns up\n * to `limit + 1` rows ordered by the sort fields then `idField`, strictly\n * after `cursor` (`null` on the first page). The extra row only sets\n * `hasNext`; it is trimmed off. The next cursor encodes the last returned\n * row's sort-field values + id, and the active sort — a cursor replayed\n * under a different `sort`, or one that does not decode, is a 400.\n *\n * Cursors are not signed. The decoded position is plain data: bind it as\n * query parameters, and keep filters and authorization scoping in the\n * fetcher so a forged cursor can never widen what the caller sees.\n *\n * @example\n * ```ts\n * @Get('/')\n * list(ctx: RequestContext) {\n * return ctx.paginateCursor(\n * (q) => this.repo.findAfter({ ...q, limit: q.limit + 1 }),\n * { sortable: ['createdAt'] },\n * )\n * }\n * ```\n */\n async paginateCursor<T, TConfig extends QueryFieldConfig | undefined = undefined>(\n fetcher: (query: CursorQuery<TConfig>) => Promise<T[]>,\n fieldConfig?: TConfig,\n options?: CursorPaginateOptions<T>,\n ): Promise<CursorPaginatedResponse<T>> {\n const { pagination, ...parsed } = this.qs<TConfig>(fieldConfig)\n const { limit } = pagination\n const idField = options?.idField ?? 'id'\n const signature = sortSignature(parsed.sort)\n // Exact key set to expect back — unknown when the app builds the key itself.\n const keys = options?.cursorKey\n ? undefined\n : [...new Set([...parsed.sort.map((s) => s.field), idField])]\n\n const raw = (this.req.query as Record<string, unknown>)?.cursor\n const cursor = raw === undefined || raw === '' ? null : decodeCursor(raw, signature, keys)\n\n const rows = await fetcher({ ...parsed, cursor, limit })\n const hasNext = rows.length > limit\n const data = hasNext ? rows.slice(0, limit) : rows\n const last = data.at(-1)\n let nextCursor: string | null = null\n if (hasNext && last !== undefined) {\n nextCursor = encodeCursor(cursorValues(last, keys ?? [], options?.cursorKey), signature)\n }\n\n const url = this.requestUrl()\n const response: CursorPaginatedResponse<T> = {\n data,\n meta: { limit, hasNext, nextCursor },\n links: { self: selfLink(url), next: nextCursor ? pageLink(url, 'cursor', nextCursor) : null },\n }\n // Sends AND returns — same reasoning as `paginate` above.\n this.json(response)\n return response\n }\n\n /** Path + query as the client sent it, before any router mount stripped it. */\n private requestUrl(): string {\n const req = this.req as { originalUrl?: unknown; url?: unknown }\n if (typeof req.originalUrl === 'string') return req.originalUrl\n return typeof req.url === 'string' ? req.url : '/'\n }\n\n // ── Server-Sent Events ──────────────────────────────────────────────\n\n /**\n * Start an SSE (Server-Sent Events) stream.\n * Sets the correct headers and returns helpers to send events.\n *\n * Pass a payload type to get typed sends — and `return sse` from the\n * handler so `kick typegen` carries the event type into\n * `KickRoutes.Api`, where `@forinda/kickjs-client`'s `api.stream()`\n * picks it up (the returned handler is ignored at runtime — the\n * response is already streaming).\n *\n * @example\n * ```ts\n * interface Tick { time: string }\n *\n * @Get('/events')\n * async stream(ctx: RequestContext) {\n * const sse = ctx.sse<Tick>()\n *\n * const interval = setInterval(() => {\n * sse.send({ time: new Date().toISOString() }, 'tick')\n * }, 1000)\n *\n * sse.onClose(() => clearInterval(interval))\n * return sse // typed as SseHandler<Tick> → response inference\n * }\n * ```\n */\n /**\n * Send a web-standard `Response` — status, headers (every `Set-Cookie`\n * kept) and body, streamed chunk by chunk — on any runtime. For handing off\n * to libraries that speak `Request`/`Response`, such as the MCP SDK's\n * web-standard transport.\n *\n * Resolves once the body is fully written. Stops reading the body when the\n * client disconnects.\n *\n * @example\n * ```ts\n * @Post('/mcp')\n * async mcp(ctx: RequestContext) {\n * await ctx.sendResponse(await transport.handleRequest(webRequest))\n * }\n * ```\n */\n async sendResponse(response: Response): Promise<void> {\n const headers: Record<string, string | string[]> = {}\n response.headers.forEach((value, name) => {\n if (name !== 'set-cookie') headers[name] = value\n })\n const cookies = response.headers.getSetCookie()\n if (cookies.length > 0) headers['set-cookie'] = cookies\n\n if (!response.body) {\n // Not writeHead() + end(): on the web driver writeHead switches to a\n // streamed Response, which a 204/304 cannot be, and on Fastify end()\n // bypasses the headers set on the reply. send() is each runtime's own\n // buffered reply path.\n this._response.status(response.status)\n for (const [name, value] of Object.entries(headers)) this._response.setHeader(name, value)\n this._response.send('')\n return\n }\n this._response.writeHead(response.status, headers as Record<string, string>)\n // Send the headers now: a stream whose first chunk comes later (SSE)\n // would otherwise leave the client waiting to see the response open.\n this._response.flushHeaders()\n const reader = response.body.getReader()\n const stop = () => {\n reader.cancel().catch(() => {})\n }\n this.signal.addEventListener('abort', stop, { once: true })\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n // Honour backpressure: on a slow client, wait for the socket to drain\n // (or the client to go away) before reading more of the body.\n if (this._response.write(Buffer.from(value)) === false && !this.signal.aborted) {\n await new Promise<void>((resolve) => {\n const resume = () => {\n this.signal.removeEventListener('abort', resume)\n resolve()\n }\n this._response.once('drain', resume)\n this.signal.addEventListener('abort', resume, { once: true })\n })\n }\n }\n } finally {\n this.signal.removeEventListener('abort', stop)\n this._response.end()\n }\n }\n\n /**\n * Keep `promise` running after the response is sent — an audit log, an\n * email, an analytics call. The Node server's `shutdown()` waits for it;\n * `createHandler()` and the web entry hand it to the platform's\n * `waitUntil` when you pass the platform context in. A rejection is\n * logged, never unhandled. Same as the standalone `waitUntil()` export.\n */\n waitUntil(promise: Promise<unknown>): void {\n waitUntil(promise)\n }\n\n sse<T = unknown>(): SseHandler<T> {\n this._response.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n // no-transform: compression middleware (and proxies) would otherwise\n // buffer the stream in gzip, holding events back from the client.\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n this._response.flushHeaders()\n\n const closeCallbacks: Array<() => void> = []\n\n this.req.on('close', () => {\n for (const cb of closeCallbacks) cb()\n })\n\n return {\n /** Send an SSE event with optional event name and id */\n send: (data: T, event?: string, id?: string) => {\n if (id) this._response.write(`id: ${id}\\n`)\n if (event) this._response.write(`event: ${event}\\n`)\n this._response.write(`data: ${JSON.stringify(data)}\\n\\n`)\n },\n /** Send a comment (keeps connection alive) */\n comment: (text: string) => {\n this._response.write(`: ${text}\\n\\n`)\n },\n /** Register a callback when the client disconnects */\n onClose: (fn: () => void) => {\n closeCallbacks.push(fn)\n },\n /** End the SSE stream */\n close: () => {\n this._response.end()\n },\n }\n }\n}\n\n/**\n * The handle {@link RequestContext.sse} returns. The optional phantom\n * `__sse` property carries the event payload type STRUCTURALLY — never set\n * at runtime — so `kick typegen`'s response inference (handler `return sse`)\n * flows it into `KickRoutes.Api`, and `@forinda/kickjs-client` detects SSE\n * routes without importing any server types.\n */\nexport interface SseHandler<T = unknown> {\n /** Phantom event-payload type marker — never assigned at runtime. */\n readonly __sse?: T\n /** Send an SSE event with optional event name and id. */\n send(data: T, event?: string, id?: string): void\n /** Send a comment line (keeps the connection alive through proxies). */\n comment(text: string): void\n /** Register a callback for client disconnect. */\n onClose(fn: () => void): void\n /** End the SSE stream. */\n close(): void\n}\n\n/**\n * Short alias for `RequestContext` parameterised by a route shape.\n *\n * Use with `kick typegen`'s generated `KickRoutes` namespace for\n * fully-typed `ctx.params`, `ctx.body`, and `ctx.query`. Metadata\n * typing (`ctx.get()`, `ctx.set()`, `ctx.user`) comes from\n * `ContextMeta` augmentation and works on all `RequestContext` instances.\n *\n * @example\n * ```ts\n * @Get('/:id')\n * getUser(ctx: Ctx<KickRoutes.UserController['getUser']>) {\n * ctx.params.id // typed from RouteShape\n * ctx.body // typed from RouteShape\n * ctx.user // typed from ContextMeta\n * ctx.get('tenant') // typed from ContextMeta\n * }\n * ```\n */\nexport type Ctx<TRoute extends RouteShape = RouteShape> = RequestContext<\n TRoute extends { body: infer B } ? B : any,\n TRoute extends { params: infer P } ? P : any,\n TRoute extends { query: infer Q } ? Q : any,\n // Falls back to `string` (no narrowing) whenever typegen couldn't prove\n // the route's full contributor set — see `RouteShape.contextKeys`.\n TRoute extends { contextKeys: infer K }\n ? K extends ContextMetaKey\n ? K\n : ContextMetaKey\n : ContextMetaKey\n>\n\n/**\n * Global ambient registry of typed routes, populated by `kick typegen`.\n *\n * Interfaces inside `KickRoutes` correspond to controller classes (each\n * property one route method, conforming to `RouteShape`) — plus the\n * reserved `KickRoutes.Api`: a flat `'METHOD /mounted/path'` map over the\n * same shapes, consumed by `@forinda/kickjs-client`. Don't name a\n * controller class `Api` — it would declaration-merge into that map.\n *\n * Empty by default — declarations come from `.kickjs/types/kick__routes.ts`\n * generated alongside the rest of the typegen output.\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {}\n}\n\n/** `attachment; filename=\"…\"; filename*=UTF-8''…` for any file name (RFC 6266 / RFC 8187). */\nexport function contentDisposition(filename: string): string {\n const fallback = filename.replace(/[^\\x20-\\x7e]|[\"\\\\]/g, '_')\n const encoded = encodeURIComponent(filename).replace(\n /['()*]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n return `attachment; filename=\"${fallback}\"; filename*=UTF-8''${encoded}`\n}\n\n/**\n * A row's cursor values: the app's `cursorKey`, or the sort fields + id read\n * off the row. Dates become ISO strings and bigints decimal strings (JSON\n * would do the first and throw on the second).\n */\nfunction cursorValues<T>(\n row: T,\n keys: readonly string[],\n cursorKey: ((row: T) => Record<string, CursorValue>) | undefined,\n): Record<string, CursorValue> {\n if (cursorKey) return cursorKey(row)\n const values: Record<string, CursorValue> = {}\n for (const key of keys) {\n const value = (row as Record<string, unknown>)[key]\n if (value === undefined) {\n throw new Error(\n `paginateCursor: row has no '${key}' — return the sort fields and the id ` +\n `field on every row, or pass options.cursorKey / options.idField`,\n )\n }\n values[key] =\n value instanceof Date\n ? value.toISOString()\n : typeof value === 'bigint'\n ? value.toString()\n : (value as CursorValue)\n }\n return values\n}\n"],"mappings":";;;;;;;;;;+aAyBA,SAAS,OAAO,QAAkB,KAAkC,CAClE,IAAM,MAAQ,QAAQ,MACtB,OAAO,MAAM,QAAQ,KAAK,EAAI,MAAM,KAAK,IAAI,EAAI,KACnD,CAGA,SAAgB,cAAc,KAAsB,CAClD,GAAI,eAAe,KAAK,IAAI,EAAG,OAAO,KAGtC,IAAM,KAAO,KAAK,WAAW,IAAI,EAC3B,MAAQ,KAAO,KAAK,MAAM,CAAC,EAAI,KAAA,CAAM,WAAW,IAAK,EAAE,EAC7D,MAAO,GAAG,KAAO,KAAO,GAAG,GAAG,KAAK,EACrC,CAEA,MAAM,OAAU,KAAgB,IAAI,QAAQ,OAAQ,EAAE,EAChD,OAAU,KAAgB,IAAI,WAAW,IAAI,EAGnD,SAAS,OAAO,MAAyB,CACvC,OAAO,MAAM,MAAM,qBAAqB,GAAK,CAAC,CAChD,CAGA,SAAS,OAAO,MAA+C,CAC7D,GAAI,CAAC,MAAO,OACZ,IAAM,GAAK,KAAK,MAAM,KAAK,EAC3B,OAAO,OAAO,MAAM,EAAE,EAAI,IAAA,GAAY,EACxC,CAGA,MAAM,QAAW,MAAe,KAAK,MAAM,KAAK,QAAQ,EAAI,GA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B,IAAI,sGAErC,EAEF,OAAO,KACL,iBAAiB,KACb,MAAM,YAAY,EAClB,OAAO,OAAU,SACf,MAAM,SAAS,EACd,KACX,CACA,OAAO,MACT"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.5.0
2
+ * @forinda/kickjs v10.7.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-gitMJXxZ.mjs.map
13
+ //# sourceMappingURL=context-errors-ykpXYECS.mjs.map
@@ -1 +1 @@
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"}
1
+ {"version":3,"file":"context-errors-ykpXYECS.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,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.5.0
2
+ * @forinda/kickjs v10.7.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{s as matchesFlagTest}from"./route-flag-BP_jbhNy.mjs";function shouldRun(reg,ctx,flags){if(reg.skipWhen===void 0&&reg.onlyWhen===void 0)return!0;let resolved=flags??EMPTY_FLAGS,route=ctx.route;return!(reg.skipWhen!==void 0&&matchesFlagTest(reg.skipWhen,resolved,route)||reg.onlyWhen!==void 0&&!matchesFlagTest(reg.onlyWhen,resolved,route))}const EMPTY_FLAGS=/* @__PURE__ */ new Map;async function runContributors(options){let{pipeline,ctx,container,flags}=options;for(let reg of pipeline.contributors)shouldRun(reg,ctx,flags)&&await runOne(reg,ctx,container)}async function runOne(reg,ctx,container){let value;try{let deps=resolveDeps(reg,container);value=await reg.resolve(ctx,deps)}catch(err){if(reg.optional)return;if(reg.onError){let replacement=await reg.onError(err,ctx);if(replacement===void 0)return;ctx.set(reg.key,replacement);return}throw err}ctx.set(reg.key,value)}function resolveDeps(reg,container){let deps=depEntries.get(reg);deps||depEntries.set(reg,deps=Object.entries(reg.deps));let out={};for(let[key,token]of deps)out[key]=container.resolve(token);return out}const depEntries=/* @__PURE__ */ new WeakMap;export{runContributors as t};
12
- //# sourceMappingURL=contributor-runner-CDlPrzai.mjs.map
11
+ import{s as matchesFlagTest}from"./route-flag-p89Wzt0D.mjs";function shouldRun(reg,ctx,flags){if(reg.skipWhen===void 0&&reg.onlyWhen===void 0)return!0;let resolved=flags??EMPTY_FLAGS,route=ctx.route;return!(reg.skipWhen!==void 0&&matchesFlagTest(reg.skipWhen,resolved,route)||reg.onlyWhen!==void 0&&!matchesFlagTest(reg.onlyWhen,resolved,route))}const EMPTY_FLAGS=/* @__PURE__ */ new Map;async function runContributors(options){let{pipeline,ctx,container,flags}=options;for(let reg of pipeline.contributors)shouldRun(reg,ctx,flags)&&await runOne(reg,ctx,container)}async function runOne(reg,ctx,container){let value;try{let deps=resolveDeps(reg,container);value=await reg.resolve(ctx,deps)}catch(err){if(reg.optional)return;if(reg.onError){let replacement=await reg.onError(err,ctx);if(replacement===void 0)return;ctx.set(reg.key,replacement);return}throw err}ctx.set(reg.key,value)}function resolveDeps(reg,container){let deps=depEntries.get(reg);deps||depEntries.set(reg,deps=Object.entries(reg.deps));let out={};for(let[key,token]of deps)out[key]=container.resolve(token);return out}const depEntries=/* @__PURE__ */ new WeakMap;export{runContributors as t};
12
+ //# sourceMappingURL=contributor-runner-BM-5Wr19.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"contributor-runner-CDlPrzai.mjs","names":[],"sources":["../src/core/contributor-runner.ts"],"sourcesContent":["import type { Container } from './container'\nimport type { ContributorRegistration } from './context-decorator'\nimport type { ExecutionContext } from './execution-context'\nimport type { ContributorPipeline } from './contributor-pipeline'\nimport { matchesFlagTest, type RouteFlags } from './route-flag'\nimport type { MatchedRoute } from '../http/runtime'\n\nexport interface RunContributorsOptions {\n /** Pre-built, validated, topo-sorted pipeline. */\n pipeline: ContributorPipeline\n /** The execution context contributors read from and write into. */\n ctx: ExecutionContext\n /** DI container used to resolve declared `deps`. */\n container: Container\n /**\n * Route flags in force for the matched route, used to honour a\n * registration's `skipWhen` / `onlyWhen`. Omitted outside a route (the\n * pipeline then runs every contributor, as before).\n */\n flags?: RouteFlags\n}\n\n/**\n * Should this contributor run on a route carrying `flags`?\n *\n * `skipWhen` is what makes exemption composable: today a contributor can only\n * be opted out of by registering a permissive twin under the same key, which\n * requires owning that key. A flag is declared on the route, so an adopter can\n * exempt a contributor shipped by a plugin without forking it.\n */\nfunction shouldRun(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n flags?: RouteFlags,\n): boolean {\n if (reg.skipWhen === undefined && reg.onlyWhen === undefined) return true\n const resolved = flags ?? EMPTY_FLAGS\n const route = (ctx as { route?: MatchedRoute }).route\n if (reg.skipWhen !== undefined && matchesFlagTest(reg.skipWhen, resolved, route)) return false\n if (reg.onlyWhen !== undefined && !matchesFlagTest(reg.onlyWhen, resolved, route)) return false\n return true\n}\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\n/**\n * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.\n *\n * Sequential — one contributor at a time, in the topo order chosen at\n * pipeline-build time. Per `architecture.md` §20.10, V1 does not run\n * contributors in parallel even within the same topo level; that is a\n * V2 follow-up gated on profiling.\n *\n * ## Error matrix (architecture.md §20.9)\n *\n * | resolve outcome | optional | onError defined | runner behaviour |\n * |-----------------|----------|-----------------|--------------------------------------------------|\n * | throws | true | — | skip; `ctx.get(key)` remains undefined |\n * | throws | false | yes | call hook; returned value (if any) stored |\n * | throws | false | no | propagate the original error |\n * | hook throws | — | yes | propagate the new error |\n * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |\n * | resolves | — | — | `ctx.set(key, value)` |\n *\n * Container.resolve() throwing while building `deps` is treated as a\n * resolve-side throw and flows through the same matrix — adopters who\n * need different behaviour for missing-DI vs. data-lookup failures can\n * wrap the container access inside their own `resolve()`.\n */\nexport async function runContributors(options: RunContributorsOptions): Promise<void> {\n const { pipeline, ctx, container, flags } = options\n\n for (const reg of pipeline.contributors) {\n if (!shouldRun(reg, ctx, flags)) continue\n await runOne(reg, ctx, container)\n }\n}\n\nasync function runOne(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n container: Container,\n): Promise<void> {\n let value: unknown\n try {\n const deps = resolveDeps(reg, container)\n value = await reg.resolve(ctx, deps)\n } catch (err) {\n if (reg.optional) return\n if (reg.onError) {\n // Hook throws are unconditionally propagated — there is no\n // second-chance hook. Returning undefined/void from the hook\n // means \"skip\"; returning a value means \"use this instead\".\n const replacement = await reg.onError(err, ctx)\n if (replacement === undefined) return\n ctx.set(reg.key, replacement as never)\n return\n }\n throw err\n }\n ctx.set(reg.key, value as never)\n}\n\n/**\n * Resolve a contributor's declared dependencies through the container,\n * preserving the property names from the spec so `resolve(ctx, deps)`\n * receives exactly the shape the user wrote.\n *\n * Empty `deps` produces an empty object — `resolve()` always sees an\n * object, never `undefined`.\n */\nfunction resolveDeps(reg: ContributorRegistration, container: Container): Record<string, unknown> {\n // The spec is fixed per registration; list its entries once, not per request.\n let deps = depEntries.get(reg)\n if (!deps) depEntries.set(reg, (deps = Object.entries(reg.deps)))\n const out: Record<string, unknown> = {}\n for (const [key, token] of deps) {\n out[key] = container.resolve(token as never)\n }\n return out\n}\n\nconst depEntries = new WeakMap<ContributorRegistration, Array<[string, unknown]>>()\n"],"mappings":";;;;;;;;;;4DA8BA,SAAS,UACP,IACA,IACA,MACS,CACT,GAAI,IAAI,WAAa,IAAA,IAAa,IAAI,WAAa,IAAA,GAAW,MAAO,GACrE,IAAM,SAAW,OAAS,YACpB,MAAS,IAAiC,MAGhD,MADA,EADI,IAAI,WAAa,IAAA,IAAa,gBAAgB,IAAI,SAAU,SAAU,KAAK,GAC3E,IAAI,WAAa,IAAA,IAAa,CAAC,gBAAgB,IAAI,SAAU,SAAU,KAAK,EAElF,CAEA,MAAM,4BAA0B,IAAI,IA0BpC,eAAsB,gBAAgB,QAAgD,CACpF,GAAM,CAAE,SAAU,IAAK,UAAW,OAAU,QAE5C,IAAK,IAAM,OAAO,SAAS,aACpB,UAAU,IAAK,IAAK,KAAK,GAC9B,MAAM,OAAO,IAAK,IAAK,SAAS,CAEpC,CAEA,eAAe,OACb,IACA,IACA,UACe,CACf,IAAI,MACJ,GAAI,CACF,IAAM,KAAO,YAAY,IAAK,SAAS,EACvC,MAAQ,MAAM,IAAI,QAAQ,IAAK,IAAI,CACrC,OAAS,IAAK,CACZ,GAAI,IAAI,SAAU,OAClB,GAAI,IAAI,QAAS,CAIf,IAAM,YAAc,MAAM,IAAI,QAAQ,IAAK,GAAG,EAC9C,GAAI,cAAgB,IAAA,GAAW,OAC/B,IAAI,IAAI,IAAI,IAAK,WAAoB,EACrC,MACF,CACA,MAAM,GACR,CACA,IAAI,IAAI,IAAI,IAAK,KAAc,CACjC,CAUA,SAAS,YAAY,IAA8B,UAA+C,CAEhG,IAAI,KAAO,WAAW,IAAI,GAAG,EACxB,MAAM,WAAW,IAAI,IAAM,KAAO,OAAO,QAAQ,IAAI,IAAI,CAAE,EAChE,IAAM,IAA+B,CAAC,EACtC,IAAK,GAAM,CAAC,IAAK,SAAU,KACzB,IAAI,KAAO,UAAU,QAAQ,KAAc,EAE7C,OAAO,GACT,CAEA,MAAM,2BAAa,IAAI"}
1
+ {"version":3,"file":"contributor-runner-BM-5Wr19.mjs","names":[],"sources":["../src/core/contributor-runner.ts"],"sourcesContent":["import type { Container } from './container'\nimport type { ContributorRegistration } from './context-decorator'\nimport type { ExecutionContext } from './execution-context'\nimport type { ContributorPipeline } from './contributor-pipeline'\nimport { matchesFlagTest, type RouteFlags } from './route-flag'\nimport type { MatchedRoute } from '../http/runtime'\n\nexport interface RunContributorsOptions {\n /** Pre-built, validated, topo-sorted pipeline. */\n pipeline: ContributorPipeline\n /** The execution context contributors read from and write into. */\n ctx: ExecutionContext\n /** DI container used to resolve declared `deps`. */\n container: Container\n /**\n * Route flags in force for the matched route, used to honour a\n * registration's `skipWhen` / `onlyWhen`. Omitted outside a route (the\n * pipeline then runs every contributor, as before).\n */\n flags?: RouteFlags\n}\n\n/**\n * Should this contributor run on a route carrying `flags`?\n *\n * `skipWhen` is what makes exemption composable: today a contributor can only\n * be opted out of by registering a permissive twin under the same key, which\n * requires owning that key. A flag is declared on the route, so an adopter can\n * exempt a contributor shipped by a plugin without forking it.\n */\nfunction shouldRun(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n flags?: RouteFlags,\n): boolean {\n if (reg.skipWhen === undefined && reg.onlyWhen === undefined) return true\n const resolved = flags ?? EMPTY_FLAGS\n const route = (ctx as { route?: MatchedRoute }).route\n if (reg.skipWhen !== undefined && matchesFlagTest(reg.skipWhen, resolved, route)) return false\n if (reg.onlyWhen !== undefined && !matchesFlagTest(reg.onlyWhen, resolved, route)) return false\n return true\n}\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\n/**\n * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.\n *\n * Sequential — one contributor at a time, in the topo order chosen at\n * pipeline-build time. Per `architecture.md` §20.10, V1 does not run\n * contributors in parallel even within the same topo level; that is a\n * V2 follow-up gated on profiling.\n *\n * ## Error matrix (architecture.md §20.9)\n *\n * | resolve outcome | optional | onError defined | runner behaviour |\n * |-----------------|----------|-----------------|--------------------------------------------------|\n * | throws | true | — | skip; `ctx.get(key)` remains undefined |\n * | throws | false | yes | call hook; returned value (if any) stored |\n * | throws | false | no | propagate the original error |\n * | hook throws | — | yes | propagate the new error |\n * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |\n * | resolves | — | — | `ctx.set(key, value)` |\n *\n * Container.resolve() throwing while building `deps` is treated as a\n * resolve-side throw and flows through the same matrix — adopters who\n * need different behaviour for missing-DI vs. data-lookup failures can\n * wrap the container access inside their own `resolve()`.\n */\nexport async function runContributors(options: RunContributorsOptions): Promise<void> {\n const { pipeline, ctx, container, flags } = options\n\n for (const reg of pipeline.contributors) {\n if (!shouldRun(reg, ctx, flags)) continue\n await runOne(reg, ctx, container)\n }\n}\n\nasync function runOne(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n container: Container,\n): Promise<void> {\n let value: unknown\n try {\n const deps = resolveDeps(reg, container)\n value = await reg.resolve(ctx, deps)\n } catch (err) {\n if (reg.optional) return\n if (reg.onError) {\n // Hook throws are unconditionally propagated — there is no\n // second-chance hook. Returning undefined/void from the hook\n // means \"skip\"; returning a value means \"use this instead\".\n const replacement = await reg.onError(err, ctx)\n if (replacement === undefined) return\n ctx.set(reg.key, replacement as never)\n return\n }\n throw err\n }\n ctx.set(reg.key, value as never)\n}\n\n/**\n * Resolve a contributor's declared dependencies through the container,\n * preserving the property names from the spec so `resolve(ctx, deps)`\n * receives exactly the shape the user wrote.\n *\n * Empty `deps` produces an empty object — `resolve()` always sees an\n * object, never `undefined`.\n */\nfunction resolveDeps(reg: ContributorRegistration, container: Container): Record<string, unknown> {\n // The spec is fixed per registration; list its entries once, not per request.\n let deps = depEntries.get(reg)\n if (!deps) depEntries.set(reg, (deps = Object.entries(reg.deps)))\n const out: Record<string, unknown> = {}\n for (const [key, token] of deps) {\n out[key] = container.resolve(token as never)\n }\n return out\n}\n\nconst depEntries = new WeakMap<ContributorRegistration, Array<[string, unknown]>>()\n"],"mappings":";;;;;;;;;;4DA8BA,SAAS,UACP,IACA,IACA,MACS,CACT,GAAI,IAAI,WAAa,IAAA,IAAa,IAAI,WAAa,IAAA,GAAW,MAAO,GACrE,IAAM,SAAW,OAAS,YACpB,MAAS,IAAiC,MAGhD,MADA,EADI,IAAI,WAAa,IAAA,IAAa,gBAAgB,IAAI,SAAU,SAAU,KAAK,GAC3E,IAAI,WAAa,IAAA,IAAa,CAAC,gBAAgB,IAAI,SAAU,SAAU,KAAK,EAElF,CAEA,MAAM,4BAA0B,IAAI,IA0BpC,eAAsB,gBAAgB,QAAgD,CACpF,GAAM,CAAE,SAAU,IAAK,UAAW,OAAU,QAE5C,IAAK,IAAM,OAAO,SAAS,aACpB,UAAU,IAAK,IAAK,KAAK,GAC9B,MAAM,OAAO,IAAK,IAAK,SAAS,CAEpC,CAEA,eAAe,OACb,IACA,IACA,UACe,CACf,IAAI,MACJ,GAAI,CACF,IAAM,KAAO,YAAY,IAAK,SAAS,EACvC,MAAQ,MAAM,IAAI,QAAQ,IAAK,IAAI,CACrC,OAAS,IAAK,CACZ,GAAI,IAAI,SAAU,OAClB,GAAI,IAAI,QAAS,CAIf,IAAM,YAAc,MAAM,IAAI,QAAQ,IAAK,GAAG,EAC9C,GAAI,cAAgB,IAAA,GAAW,OAC/B,IAAI,IAAI,IAAI,IAAK,WAAoB,EACrC,MACF,CACA,MAAM,GACR,CACA,IAAI,IAAI,IAAI,IAAK,KAAc,CACjC,CAUA,SAAS,YAAY,IAA8B,UAA+C,CAEhG,IAAI,KAAO,WAAW,IAAI,GAAG,EACxB,MAAM,WAAW,IAAI,IAAM,KAAO,OAAO,QAAQ,IAAI,IAAI,CAAE,EAChE,IAAM,IAA+B,CAAC,EACtC,IAAK,GAAM,CAAC,IAAK,SAAU,KACzB,IAAI,KAAO,UAAU,QAAQ,KAAc,EAE7C,OAAO,GACT,CAEA,MAAM,2BAAa,IAAI"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as KickServer, i as AppAdapterClass, n as AdapterMiddleware, o as MiddlewarePath, r as AppAdapter, s as MiddlewarePhase, t as AdapterContext } from "../adapter-BZ1WzN1z.mjs";
2
+ import { a as KickServer, i as AppAdapterClass, n as AdapterMiddleware, o as MiddlewarePath, r as AppAdapter, s as MiddlewarePhase, t as AdapterContext } from "../adapter-9sPr_5xt.mjs";
3
3
  export { AdapterContext, AdapterMiddleware, AppAdapter, AppAdapterClass, KickServer, MiddlewarePath, MiddlewarePhase };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.5.0
2
+ * @forinda/kickjs v10.7.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *