@forinda/kickjs 10.14.0 → 10.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/dist/{adapter-DL9JPcvC.d.mts → adapter-B64IOivZ.d.mts} +13 -53
  2. package/dist/adapter-B64IOivZ.d.mts.map +1 -0
  3. package/dist/{allowed-hosts-BpKwviq5.d.mts → allowed-hosts-U12_gESr.d.mts} +2 -4
  4. package/dist/allowed-hosts-U12_gESr.d.mts.map +1 -0
  5. package/dist/{app-module-Dk2Wenqx.d.mts → app-module-EmIojM4d.d.mts} +5 -11
  6. package/dist/app-module-EmIojM4d.d.mts.map +1 -0
  7. package/dist/application-BzimU62Q.mjs +14 -0
  8. package/dist/application-BzimU62Q.mjs.map +1 -0
  9. package/dist/{application-D921r4MW.d.mts → application-CGcY8SZZ.d.mts} +22 -74
  10. package/dist/application-CGcY8SZZ.d.mts.map +1 -0
  11. package/dist/{body-policy-CaerQ_lu.mjs → body-policy-Be3Y0hjq.mjs} +2 -2
  12. package/dist/{body-policy-CaerQ_lu.mjs.map → body-policy-Be3Y0hjq.mjs.map} +1 -1
  13. package/dist/{bootstrap-BXLsEeMW.mjs → bootstrap-Bvk3BWJX.mjs} +3 -3
  14. package/dist/{bootstrap-BXLsEeMW.mjs.map → bootstrap-Bvk3BWJX.mjs.map} +1 -1
  15. package/dist/{bounded-counters-DFef_B7d.mjs → bounded-counters-Bh5jeT9I.mjs} +2 -2
  16. package/dist/{bounded-counters-DFef_B7d.mjs.map → bounded-counters-Bh5jeT9I.mjs.map} +1 -1
  17. package/dist/{breach-padding-FBVGmcBb.d.mts → breach-padding-DfT9MXGb.d.mts} +2 -4
  18. package/dist/breach-padding-DfT9MXGb.d.mts.map +1 -0
  19. package/dist/{cache-CdRHSXow.d.mts → cache-DMIt3c6M.d.mts} +1 -3
  20. package/dist/cache-DMIt3c6M.d.mts.map +1 -0
  21. package/dist/{client-ip-DE5vkJWL.mjs → client-ip-CGH_IvnC.mjs} +2 -2
  22. package/dist/{client-ip-DE5vkJWL.mjs.map → client-ip-CGH_IvnC.mjs.map} +1 -1
  23. package/dist/config/index.d.mts +1 -1
  24. package/dist/config/index.mjs +2 -2
  25. package/dist/{config-De3xzaiZ.mjs → config-CjFxvh0v.mjs} +3 -3
  26. package/dist/{config-De3xzaiZ.mjs.map → config-CjFxvh0v.mjs.map} +1 -1
  27. package/dist/{connect-BlIamapT.d.mts → connect-DamOelO8.d.mts} +1 -3
  28. package/dist/connect-DamOelO8.d.mts.map +1 -0
  29. package/dist/{context-DBLyIErA.mjs → context-BvZLaTeE.mjs} +3 -3
  30. package/dist/{context-DBLyIErA.mjs.map → context-BvZLaTeE.mjs.map} +1 -1
  31. package/dist/{context-errors-By-pwipc.mjs → context-errors-BZVS0B1O.mjs} +2 -2
  32. package/dist/{context-errors-By-pwipc.mjs.map → context-errors-BZVS0B1O.mjs.map} +1 -1
  33. package/dist/{contributor-runner-BuMi_eLU.mjs → contributor-runner-fdKy6Tme.mjs} +3 -3
  34. package/dist/{contributor-runner-BuMi_eLU.mjs.map → contributor-runner-fdKy6Tme.mjs.map} +1 -1
  35. package/dist/core/adapter.d.mts +1 -1
  36. package/dist/core/adapter.mjs +1 -1
  37. package/dist/core/app-module.d.mts +1 -1
  38. package/dist/core/app-module.mjs +1 -1
  39. package/dist/core/cache.d.mts +1 -1
  40. package/dist/core/cache.mjs +1 -1
  41. package/dist/core/cache.mjs.map +1 -1
  42. package/dist/core/container.mjs +2 -2
  43. package/dist/core/cron.d.mts +1 -1
  44. package/dist/core/cron.mjs +2 -2
  45. package/dist/core/cron.mjs.map +1 -1
  46. package/dist/core/decorators.d.mts +1 -1
  47. package/dist/core/decorators.mjs +2 -2
  48. package/dist/core/decorators.mjs.map +1 -1
  49. package/dist/core/errors.d.mts +1 -1
  50. package/dist/core/errors.mjs +1 -1
  51. package/dist/core/errors.mjs.map +1 -1
  52. package/dist/core/interfaces.d.mts +1 -1
  53. package/dist/core/interfaces.mjs +1 -1
  54. package/dist/core/interfaces.mjs.map +1 -1
  55. package/dist/core/logger.d.mts +1 -1
  56. package/dist/core/logger.mjs +1 -1
  57. package/dist/core/logger.mjs.map +1 -1
  58. package/dist/core/path.d.mts +1 -1
  59. package/dist/core/path.mjs +1 -1
  60. package/dist/core/path.mjs.map +1 -1
  61. package/dist/core/plugin.d.mts +1 -1
  62. package/dist/core/plugin.mjs +1 -1
  63. package/dist/core/reactivity.d.mts +1 -1
  64. package/dist/core/reactivity.mjs +2 -2
  65. package/dist/core/reactivity.mjs.map +1 -1
  66. package/dist/{core-BziwPF77.mjs → core-CCIpjo6g.mjs} +3 -3
  67. package/dist/{core-BziwPF77.mjs.map → core-CCIpjo6g.mjs.map} +1 -1
  68. package/dist/{cors-BlR_b0Qb.d.mts → cors-J-q6PuSU.d.mts} +2 -4
  69. package/dist/cors-J-q6PuSU.d.mts.map +1 -0
  70. package/dist/{cron-BTGytNg-.d.mts → cron-DGV1AE0R.d.mts} +1 -3
  71. package/dist/cron-DGV1AE0R.d.mts.map +1 -0
  72. package/dist/{csrf-DOAaYozG.d.mts → csrf-DjtJPgA3.d.mts} +4 -6
  73. package/dist/csrf-DjtJPgA3.d.mts.map +1 -0
  74. package/dist/decorate-DRbXCNQz.mjs +13 -0
  75. package/dist/decorate-DRbXCNQz.mjs.map +1 -0
  76. package/dist/{decorators-DxNb5mWw.d.mts → decorators-BAD8qjuq.d.mts} +1 -5
  77. package/dist/decorators-BAD8qjuq.d.mts.map +1 -0
  78. package/dist/{define-adapter-CbVg-Fyh.mjs → define-adapter-DMo6og81.mjs} +2 -2
  79. package/dist/{define-adapter-CbVg-Fyh.mjs.map → define-adapter-DMo6og81.mjs.map} +1 -1
  80. package/dist/{di-hooks-DN_UC8Nc.mjs → di-hooks-DCqt2yJ9.mjs} +2 -2
  81. package/dist/{di-hooks-DN_UC8Nc.mjs.map → di-hooks-DCqt2yJ9.mjs.map} +1 -1
  82. package/dist/{disposables-C4BLa-Pc.mjs → disposables-BsdVu69-.mjs} +1 -1
  83. package/dist/{driver-DyWsGdcD.mjs → driver-oZBQDJZz.mjs} +3 -3
  84. package/dist/{driver-DyWsGdcD.mjs.map → driver-oZBQDJZz.mjs.map} +1 -1
  85. package/dist/{error-handler-D7DLWe1Q.d.mts → error-handler-Dl_gZRNK.d.mts} +2 -4
  86. package/dist/error-handler-Dl_gZRNK.d.mts.map +1 -0
  87. package/dist/{errors-By6UueCm.d.mts → errors-DZGuPLoZ.d.mts} +1 -3
  88. package/dist/errors-DZGuPLoZ.d.mts.map +1 -0
  89. package/dist/{express-FnNSFECr.mjs → express-f9CTA8qO.mjs} +3 -3
  90. package/dist/{express-FnNSFECr.mjs.map → express-f9CTA8qO.mjs.map} +1 -1
  91. package/dist/{express-lazy-B8AFaCA-.mjs → express-lazy-DMxcLBpT.mjs} +3 -3
  92. package/dist/{express-lazy-B8AFaCA-.mjs.map → express-lazy-DMxcLBpT.mjs.map} +1 -1
  93. package/dist/{handler--lTqJdpj.mjs → handler-B66laQY0.mjs} +3 -3
  94. package/dist/{handler--lTqJdpj.mjs.map → handler-B66laQY0.mjs.map} +1 -1
  95. package/dist/{helmet-BVuVBl-D.d.mts → helmet-Rwkbp9IS.d.mts} +2 -4
  96. package/dist/helmet-Rwkbp9IS.d.mts.map +1 -0
  97. package/dist/{host-Dn2rI7s7.mjs → host-DalMsn5Z.mjs} +2 -2
  98. package/dist/{host-Dn2rI7s7.mjs.map → host-DalMsn5Z.mjs.map} +1 -1
  99. package/dist/http/application.d.mts +1 -1
  100. package/dist/http/application.mjs +2 -2
  101. package/dist/http/bootstrap.d.mts +1 -1
  102. package/dist/http/bootstrap.mjs +2 -2
  103. package/dist/http/context.d.mts +2 -2
  104. package/dist/http/context.mjs +2 -2
  105. package/dist/http/middleware/allowed-hosts.d.mts +1 -1
  106. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  107. package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
  108. package/dist/http/middleware/breach-padding.d.mts +1 -1
  109. package/dist/http/middleware/breach-padding.mjs +1 -1
  110. package/dist/http/middleware/breach-padding.mjs.map +1 -1
  111. package/dist/http/middleware/cors.d.mts +1 -1
  112. package/dist/http/middleware/cors.mjs +1 -1
  113. package/dist/http/middleware/cors.mjs.map +1 -1
  114. package/dist/http/middleware/csrf.d.mts +1 -1
  115. package/dist/http/middleware/csrf.mjs +2 -2
  116. package/dist/http/middleware/csrf.mjs.map +1 -1
  117. package/dist/http/middleware/error-handler.d.mts +1 -1
  118. package/dist/http/middleware/error-handler.mjs +2 -2
  119. package/dist/http/middleware/error-handler.mjs.map +1 -1
  120. package/dist/http/middleware/helmet.d.mts +1 -1
  121. package/dist/http/middleware/helmet.mjs +1 -1
  122. package/dist/http/middleware/helmet.mjs.map +1 -1
  123. package/dist/http/middleware/rate-limit.d.mts +1 -1
  124. package/dist/http/middleware/rate-limit.mjs +2 -2
  125. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  126. package/dist/http/middleware/request-id.d.mts +1 -1
  127. package/dist/http/middleware/request-id.mjs +1 -1
  128. package/dist/http/middleware/request-id.mjs.map +1 -1
  129. package/dist/http/middleware/request-logger.d.mts +1 -1
  130. package/dist/http/middleware/request-logger.mjs +2 -2
  131. package/dist/http/middleware/request-logger.mjs.map +1 -1
  132. package/dist/http/middleware/session.d.mts +1 -1
  133. package/dist/http/middleware/session.mjs +2 -2
  134. package/dist/http/middleware/session.mjs.map +1 -1
  135. package/dist/http/middleware/spa.d.mts +1 -1
  136. package/dist/http/middleware/spa.mjs +2 -2
  137. package/dist/http/middleware/spa.mjs.map +1 -1
  138. package/dist/http/middleware/upload.d.mts +2 -2
  139. package/dist/http/middleware/upload.mjs +2 -2
  140. package/dist/http/middleware/upload.mjs.map +1 -1
  141. package/dist/http/middleware/validate.d.mts +1 -1
  142. package/dist/http/middleware/validate.mjs +1 -1
  143. package/dist/http/middleware/validate.mjs.map +1 -1
  144. package/dist/http/middleware/views.d.mts +1 -1
  145. package/dist/http/middleware/views.mjs +2 -2
  146. package/dist/http/middleware/views.mjs.map +1 -1
  147. package/dist/http/query/index.d.mts +1 -1
  148. package/dist/http/query/index.mjs +2 -2
  149. package/dist/http/router-builder.d.mts +1 -1
  150. package/dist/http/router-builder.mjs +2 -2
  151. package/dist/http/runtimes/express.d.mts +3 -7
  152. package/dist/http/runtimes/express.d.mts.map +1 -1
  153. package/dist/http/runtimes/express.mjs +2 -2
  154. package/dist/http/runtimes/fastify.d.mts +1 -3
  155. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  156. package/dist/http/runtimes/fastify.mjs +2 -2
  157. package/dist/http/runtimes/fastify.mjs.map +1 -1
  158. package/dist/http/runtimes/h3-web.mjs +1 -1
  159. package/dist/http/runtimes/h3.d.mts +1 -3
  160. package/dist/http/runtimes/h3.d.mts.map +1 -1
  161. package/dist/http/runtimes/h3.mjs +2 -2
  162. package/dist/http/runtimes/h3.mjs.map +1 -1
  163. package/dist/{index-DP_I4puv.d.mts → index-CFTwnev9.d.mts} +3 -7
  164. package/dist/index-CFTwnev9.d.mts.map +1 -0
  165. package/dist/{index-Blgka75E.d.mts → index-ZbCnCyQx.d.mts} +1 -5
  166. package/dist/index-ZbCnCyQx.d.mts.map +1 -0
  167. package/dist/index.d.mts +30 -30
  168. package/dist/index.mjs +2 -2
  169. package/dist/index.mjs.map +1 -1
  170. package/dist/{interfaces-C6LHcYsg.d.mts → interfaces-BQhYh3lL.d.mts} +1 -3
  171. package/dist/interfaces-BQhYh3lL.d.mts.map +1 -0
  172. package/dist/{is-production-Cx4PGne9.mjs → is-production-9QzMIRuO.mjs} +2 -2
  173. package/dist/{is-production-Cx4PGne9.mjs.map → is-production-9QzMIRuO.mjs.map} +1 -1
  174. package/dist/{jobs-Bgtz3Hlq.mjs → jobs-CuZqVDDG.mjs} +3 -3
  175. package/dist/{jobs-Bgtz3Hlq.mjs.map → jobs-CuZqVDDG.mjs.map} +1 -1
  176. package/dist/{kv-stores-LBIBEueO.mjs → kv-stores-C9CJ3xCB.mjs} +3 -3
  177. package/dist/{kv-stores-LBIBEueO.mjs.map → kv-stores-C9CJ3xCB.mjs.map} +1 -1
  178. package/dist/{kv-stores-CwJdsMln.d.mts → kv-stores-wTD3VDPB.d.mts} +6 -18
  179. package/dist/kv-stores-wTD3VDPB.d.mts.map +1 -0
  180. package/dist/{lazy-serve-static-B9xQ0OE1.mjs → lazy-serve-static-DVWmKM7Z.mjs} +3 -3
  181. package/dist/{lazy-serve-static-B9xQ0OE1.mjs.map → lazy-serve-static-DVWmKM7Z.mjs.map} +1 -1
  182. package/dist/{logger-xE9qI_FS.d.mts → logger-BL8MiSrm.d.mts} +1 -3
  183. package/dist/logger-BL8MiSrm.d.mts.map +1 -0
  184. package/dist/{metadata-DS4TBMoC.mjs → metadata-BZRtQog3.mjs} +1 -1
  185. package/dist/{observers-Dokycjj0.mjs → observers-B4VnKAHK.mjs} +2 -2
  186. package/dist/{observers-Dokycjj0.mjs.map → observers-B4VnKAHK.mjs.map} +1 -1
  187. package/dist/{path-CMwIHsdv.d.mts → path-DsenzqJ7.d.mts} +1 -3
  188. package/dist/path-DsenzqJ7.d.mts.map +1 -0
  189. package/dist/{precompressed-BLYcqIAM.mjs → precompressed-AxF66Ls0.mjs} +2 -2
  190. package/dist/{precompressed-BLYcqIAM.mjs.map → precompressed-AxF66Ls0.mjs.map} +1 -1
  191. package/dist/{query-Cmtgo_-P.mjs → query-BwUR-ssX.mjs} +2 -2
  192. package/dist/{query-Cmtgo_-P.mjs.map → query-BwUR-ssX.mjs.map} +1 -1
  193. package/dist/{rate-limit-DQDk6bAH.d.mts → rate-limit-DMiV6bAq.d.mts} +3 -5
  194. package/dist/rate-limit-DMiV6bAq.d.mts.map +1 -0
  195. package/dist/{reactivity-DZrc3Yhu.d.mts → reactivity-Dski64km.d.mts} +1 -3
  196. package/dist/reactivity-Dski64km.d.mts.map +1 -0
  197. package/dist/{reply-Dcm0NAr0.mjs → reply-B5kZ6VGv.mjs} +3 -3
  198. package/dist/{reply-Dcm0NAr0.mjs.map → reply-B5kZ6VGv.mjs.map} +1 -1
  199. package/dist/{request-id-Dn64nEHK.d.mts → request-id-B_n-3A16.d.mts} +2 -4
  200. package/dist/request-id-B_n-3A16.d.mts.map +1 -0
  201. package/dist/{request-logger-TgcKRNDD.d.mts → request-logger-BV1C5r5q.d.mts} +1 -3
  202. package/dist/request-logger-BV1C5r5q.d.mts.map +1 -0
  203. package/dist/{request-scope-BmhPPGPk.mjs → request-scope-D2WQwatk.mjs} +3 -3
  204. package/dist/{request-scope-BmhPPGPk.mjs.map → request-scope-D2WQwatk.mjs.map} +1 -1
  205. package/dist/{respond-NCvYMEwC.mjs → respond-C6ohI69y.mjs} +2 -2
  206. package/dist/{respond-NCvYMEwC.mjs.map → respond-C6ohI69y.mjs.map} +1 -1
  207. package/dist/{rolldown-runtime-DKvcoND8.mjs → rolldown-runtime-DuhQYUab.mjs} +1 -1
  208. package/dist/{route-flag-DRM2yEZT.mjs → route-flag-CHiMvgar.mjs} +3 -3
  209. package/dist/{route-flag-DRM2yEZT.mjs.map → route-flag-CHiMvgar.mjs.map} +1 -1
  210. package/dist/{route-flag-B1lQht6v.d.mts → route-flag-CjXQl-oX.d.mts} +1 -3
  211. package/dist/route-flag-CjXQl-oX.d.mts.map +1 -0
  212. package/dist/{route-policy-T8RavXEx.mjs → route-policy-ckK7N1eN.mjs} +2 -2
  213. package/dist/{route-policy-T8RavXEx.mjs.map → route-policy-ckK7N1eN.mjs.map} +1 -1
  214. package/dist/{router-builder-iEHiFSZh.mjs → router-builder-D2cly8Wt.mjs} +3 -3
  215. package/dist/{router-builder-iEHiFSZh.mjs.map → router-builder-D2cly8Wt.mjs.map} +1 -1
  216. package/dist/{router-builder-C5EtcFSL.d.mts → router-builder-Dtyya4qP.d.mts} +3 -5
  217. package/dist/router-builder-Dtyya4qP.d.mts.map +1 -0
  218. package/dist/{runtime-D9KW2aLY.mjs → runtime-D9TN6CpL.mjs} +3 -3
  219. package/dist/{runtime-D9KW2aLY.mjs.map → runtime-D9TN6CpL.mjs.map} +1 -1
  220. package/dist/{session-DQG72vCf.d.mts → session-CXWu2rXW.d.mts} +2 -4
  221. package/dist/session-CXWu2rXW.d.mts.map +1 -0
  222. package/dist/{settings-DgZLgcNU.d.mts → settings-CB6lh6_s.d.mts} +1 -3
  223. package/dist/settings-CB6lh6_s.d.mts.map +1 -0
  224. package/dist/{settings-hG4DH8hQ.mjs → settings-v2N3V8Bl.mjs} +4 -4
  225. package/dist/settings-v2N3V8Bl.mjs.map +1 -0
  226. package/dist/{token-i5RynFrd.mjs → token-DtW16tw3.mjs} +1 -1
  227. package/dist/{upload-config-CTwzXhph.mjs → upload-config-BXjBiNjC.mjs} +2 -2
  228. package/dist/{upload-config-CTwzXhph.mjs.map → upload-config-BXjBiNjC.mjs.map} +1 -1
  229. package/dist/{upload-DnwvZQyi.d.mts → upload-eNNueUxR.d.mts} +4 -6
  230. package/dist/upload-eNNueUxR.d.mts.map +1 -0
  231. package/dist/{url-for-CQNJYjRH.mjs → url-for-C4Eomib7.mjs} +3 -3
  232. package/dist/{url-for-CQNJYjRH.mjs.map → url-for-C4Eomib7.mjs.map} +1 -1
  233. package/dist/{validate-D4Poe2EE.d.mts → validate-BbthfLBb.d.mts} +3 -5
  234. package/dist/validate-BbthfLBb.d.mts.map +1 -0
  235. package/dist/{view-renderer-BV2rwEUI.mjs → view-renderer-C4sMEruA.mjs} +3 -3
  236. package/dist/{view-renderer-BV2rwEUI.mjs.map → view-renderer-C4sMEruA.mjs.map} +1 -1
  237. package/dist/{web-crypto-hpIdycSO.mjs → web-crypto-SXVOPDxW.mjs} +2 -2
  238. package/dist/{web-crypto-hpIdycSO.mjs.map → web-crypto-SXVOPDxW.mjs.map} +1 -1
  239. package/dist/web.d.mts +7 -13
  240. package/dist/web.d.mts.map +1 -1
  241. package/dist/web.mjs +2 -2
  242. package/dist/web.mjs.map +1 -1
  243. package/package.json +4 -4
  244. package/dist/adapter-DL9JPcvC.d.mts.map +0 -1
  245. package/dist/allowed-hosts-BpKwviq5.d.mts.map +0 -1
  246. package/dist/app-module-Dk2Wenqx.d.mts.map +0 -1
  247. package/dist/application-CHBdxwF5.mjs +0 -14
  248. package/dist/application-CHBdxwF5.mjs.map +0 -1
  249. package/dist/application-D921r4MW.d.mts.map +0 -1
  250. package/dist/breach-padding-FBVGmcBb.d.mts.map +0 -1
  251. package/dist/cache-CdRHSXow.d.mts.map +0 -1
  252. package/dist/connect-BlIamapT.d.mts.map +0 -1
  253. package/dist/cors-BlR_b0Qb.d.mts.map +0 -1
  254. package/dist/cron-BTGytNg-.d.mts.map +0 -1
  255. package/dist/csrf-DOAaYozG.d.mts.map +0 -1
  256. package/dist/decorate-DgGmrJOP.mjs +0 -13
  257. package/dist/decorate-DgGmrJOP.mjs.map +0 -1
  258. package/dist/decorators-DxNb5mWw.d.mts.map +0 -1
  259. package/dist/error-handler-D7DLWe1Q.d.mts.map +0 -1
  260. package/dist/errors-By6UueCm.d.mts.map +0 -1
  261. package/dist/helmet-BVuVBl-D.d.mts.map +0 -1
  262. package/dist/index-Blgka75E.d.mts.map +0 -1
  263. package/dist/index-DP_I4puv.d.mts.map +0 -1
  264. package/dist/interfaces-C6LHcYsg.d.mts.map +0 -1
  265. package/dist/kv-stores-CwJdsMln.d.mts.map +0 -1
  266. package/dist/logger-xE9qI_FS.d.mts.map +0 -1
  267. package/dist/path-CMwIHsdv.d.mts.map +0 -1
  268. package/dist/rate-limit-DQDk6bAH.d.mts.map +0 -1
  269. package/dist/reactivity-DZrc3Yhu.d.mts.map +0 -1
  270. package/dist/request-id-Dn64nEHK.d.mts.map +0 -1
  271. package/dist/request-logger-TgcKRNDD.d.mts.map +0 -1
  272. package/dist/route-flag-B1lQht6v.d.mts.map +0 -1
  273. package/dist/router-builder-C5EtcFSL.d.mts.map +0 -1
  274. package/dist/session-DQG72vCf.d.mts.map +0 -1
  275. package/dist/settings-DgZLgcNU.d.mts.map +0 -1
  276. package/dist/settings-hG4DH8hQ.mjs.map +0 -1
  277. package/dist/upload-DnwvZQyi.d.mts.map +0 -1
  278. package/dist/validate-D4Poe2EE.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router-builder-Dtyya4qP.d.mts","names":[],"sources":["../src/http/router-builder.ts"],"mappings":";;;;iBA2CgB,+BAA+B,kBAAkB;;;;;;;;;;;iBAcjD,kBACd,UAAU,qBACV,gBACA,kBACA;UAUe;;;;;;;EAOf,2BAA2B;;;;;;EAM3B,aAAa;;;;;;;;;;;;;;;;;;;;;;iBAuBC,gBACd,sBACA,UAAS,qBACR"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as ROUTE_SLOT}from"./route-flag-DRM2yEZT.mjs";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)}}export{publishMatchedRoute as n,stringifyJson as r,isBigIntJsonError as t};
12
- //# sourceMappingURL=runtime-D9KW2aLY.mjs.map
11
+ import{t as ROUTE_SLOT}from"./route-flag-CHiMvgar.mjs";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)}}export{publishMatchedRoute as n,stringifyJson as r,isBigIntJsonError as t};
12
+ //# sourceMappingURL=runtime-D9TN6CpL.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-D9KW2aLY.mjs","names":[],"sources":["../src/http/runtime.ts"],"sourcesContent":["// 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"],"mappings":";;;;;;;;;;uDA0JA,SAAgB,oBAAoB,IAAc,MAAyB,CAGzE,IAAI,MAAQ,cAAc,IAAI,KAAK,EAC9B,QACH,MAAQ,OAAO,OAAO,CACpB,OAAQ,MAAM,OACd,KAAM,MAAM,KACZ,WAAY,MAAM,KAAK,WACvB,YAAa,MAAM,KAAK,YACxB,MAAO,MAAM,KAAK,OAAS,YAC3B,QAAS,MAAM,KAAK,SAAW,MAAM,KACrC,KAAM,MAAM,IACd,CAAC,EACD,cAAc,IAAI,MAAO,KAAK,GAE/B,IAAsC,YAAc,KACvD,CAEA,MAAM,8BAAgB,IAAI,QAEpB,4BAA0B,IAAI,IAmCpC,SAAgB,kBAAkB,IAAuB,CACvD,OAAO,eAAe,WAAa,SAAS,KAAK,IAAI,OAAO,CAC9D,CAOA,SAAgB,cAAc,KAAuB,CACnD,GAAI,CACF,OAAO,KAAK,UAAU,IAAI,CAC5B,OAAS,IAAK,CACZ,GAAI,CAAC,kBAAkB,GAAG,EAAG,MAAM,IACnC,OAAO,KAAK,UAAU,MAAO,KAAM,QACjC,OAAO,OAAU,SAAW,MAAM,SAAS,EAAI,KACjD,CACF,CACF"}
1
+ {"version":3,"file":"runtime-D9TN6CpL.mjs","names":[],"sources":["../src/http/runtime.ts"],"sourcesContent":["// 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"],"mappings":";;;;;;;;;;A,uDA0JA,SAAgB,oBAAoB,IAAc,MAAyB,CAGzE,IAAI,MAAQ,cAAc,IAAI,KAAK,EAC9B,QACH,MAAQ,OAAO,OAAO,CACpB,OAAQ,MAAM,OACd,KAAM,MAAM,KACZ,WAAY,MAAM,KAAK,WACvB,YAAa,MAAM,KAAK,YACxB,MAAO,MAAM,KAAK,OAAS,YAC3B,QAAS,MAAM,KAAK,SAAW,MAAM,KACrC,KAAM,MAAM,IACd,CAAC,EACD,cAAc,IAAI,MAAO,KAAK,GAE/B,IAAsC,YAAc,KACvD,CAEA,MAAM,8BAAgB,IAAI,QAEpB,4BAA0B,IAAI,IAmCpC,SAAgB,kBAAkB,IAAuB,CACvD,OAAO,eAAe,WAAa,SAAS,KAAK,IAAI,OAAO,CAC9D,CAOA,SAAgB,cAAc,KAAuB,CACnD,GAAI,CACF,OAAO,KAAK,UAAU,IAAI,CAC5B,OAAS,IAAK,CACZ,GAAI,CAAC,kBAAkB,GAAG,EAAG,MAAM,IACnC,OAAO,KAAK,UAAU,MAAO,KAAM,QACjC,OAAO,OAAU,SAAW,MAAM,SAAS,EAAI,KACjD,CACF,CACF,C"}
@@ -1,6 +1,5 @@
1
1
 
2
- import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-BlIamapT.mjs";
3
- //#region src/http/middleware/session.d.ts
2
+ import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-DamOelO8.mjs";
4
3
  /**
5
4
  * What a session holds. Augment it to type your keys — undeclared keys stay
6
5
  * readable as `unknown`:
@@ -92,6 +91,5 @@ declare class MemoryStore implements SessionStore {
92
91
  private purge;
93
92
  }
94
93
  declare function session(options: SessionOptions): (req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => void;
95
- //#endregion
96
94
  export { SessionStore as a, SessionOptions as i, Session as n, session as o, SessionData as r, MemoryStore as t };
97
- //# sourceMappingURL=session-DQG72vCf.d.mts.map
95
+ //# sourceMappingURL=session-CXWu2rXW.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-CXWu2rXW.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/session.ts"],"mappings":";;;;;;;;;;;;UA+BiB;GACd;;UAGc;EACf,IAAI,cAAc,QAAQ;EAC1B,IAAI,aAAa,MAAM,aAAa,iBAAiB;EACrD,QAAQ,cAAc;EACtB,OAAO,aAAa,iBAAiB;;UAGtB;EACf;EACA,MAAM;EACN,cAAc;EACd,WAAW;EACX,QAAQ;;UAGO;;;;;;;;;;;;;;EAcf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;EAMA;;EAEA;IACE;IACA;IACA;IACA;IACA;;;;;;;;;;;;EAYF,QAAQ;;;cAUG,uBAAuB;mBACjB;;mBAEA;mBACA;EAEjB;;EAWA;EAMM,IAAI,cAAc,QAAQ;EAW1B,IAAI,aAAa,MAAM,aAAa,iBAAiB;EAkBrD,QAAQ,cAAc;EAKtB,MAAM,aAAa,iBAAiB;UASlC;;iBA6EM,QAAQ,SAAS,kBAAc,KAuPhCA,gBAAO,KAAOC,iBAAQ,MAAQC"}
@@ -1,7 +1,6 @@
1
1
 
2
2
  import { n as InjectionToken } from "./token-0ZP--xsp.mjs";
3
3
  import { InferSchemaOutput } from "@forinda/kickjs-schema";
4
- //#region src/config/settings.d.ts
5
4
  /** A section: an injection token that also knows how to load itself. */
6
5
  interface Settings<T> extends InjectionToken<T> {
7
6
  /** The env prefix, e.g. `'DB'`. */
@@ -135,6 +134,5 @@ declare function loadSettings(declarations: Iterable<SettingsDeclaration>, env?:
135
134
  byPrefix?: Map<string, Settings<unknown>>,
136
135
  /** Values passed to `provide()`, across calls — same reason as `byPrefix`. */
137
136
  providedBefore?: Map<Settings<unknown>, unknown>): Map<Settings<unknown>, unknown>;
138
- //#endregion
139
137
  export { SettingsDeclaration as a, VarOrigin as c, originsOf as d, Settings as i, defineSettings as l, OptionalSettings as n, SettingsOf as o, ProvidedSettings as r, ValueOrigin as s, ConfigVar as t, loadSettings as u };
140
- //# sourceMappingURL=settings-DgZLgcNU.d.mts.map
138
+ //# sourceMappingURL=settings-CB6lh6_s.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settings-CB6lh6_s.d.mts","names":[],"sources":["../src/config/settings.ts"],"mappings":";;;;UA8BiB,SAAS,WAAW,eAAe;;WAEzC;;WAEA;;WAEA;;;;;EAKT,OAAO;;EAEP,KAAK,MAAM,OAAO,aAAa;;EAE/B,YAAY;;EAEZ,MAAM,iBAAiB;;;;;;;;;;;;EAYvB,QAAQ,iBAAiB,iBAAiB;;;;;;;;;;;;;EAa1C,YAAY,iBAAiB;;;;;;EAM7B,OAAO,eAAe,SAAS;;cAG3B;;UAGW,iBAAiB;YACtB;WACD,SAAS,SAAS;WAClB;;cAGL;;UAGW,iBAAiB;YACtB;WACD,SAAS,SAAS;;;KAIjB,sBACR,oBACA,4BACA;;KAYQ,WAAW,KAAK,UAAU,eAAe,KAAK;;UAYzC;EACf;;EAEA;;EAEA;;EAEA;;EAEA;;;KAkEU;;UAGK;EACf;EACA,QAAQ;;;;;;;iBAQM,UACd,eAAe,aACf,MAAK,OAAO,aACX;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyDa,eAAe,GAAG,gBAAgB,QAAQ,IAAI,SAAS,kBAAkB;;;;;;;iBAiHzE,aACd,cAAc,SAAS,sBACvB,MAAK,OAAO;;;;;AAKZ,WAAU,YAAY;;AAEtB,iBAAgB,IAAI,8BACnB,IAAI"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Container}from"./core/container.mjs";import{t as INJECTION_TOKEN}from"./token-i5RynFrd.mjs";import{detectSchema}from"@forinda/kickjs-schema";let readSecretFiles;function _useSecretFileReader(reader){readSecretFiles=reader}const PROVIDED=Symbol.for(`kickjs.settings.provided`),OPTIONAL=Symbol.for(`kickjs.settings.optional`);function isProvided(decl){return decl[PROVIDED]===!0}function isOptionalSettings(decl){return decl[OPTIONAL]===!0}const envSegment=key=>key.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toUpperCase();function leavesOf(shape,prefix,path=[],required=!0){if(shape.properties){let own=new Set(shape.required??[]),parentRequired=required&&shape.default===void 0;return Object.entries(shape.properties).flatMap(([key,child])=>leavesOf(child,prefix,[...path,key],parentRequired&&own.has(key)))}let types=Array.isArray(shape.type)?shape.type:[shape.type];return[{path,env:[prefix,...path.map(envSegment)].join(`_`),list:types.includes(`array`),required:required&&shape.default===void 0,...shape.default===void 0?{}:{default:shape.default},...shape.description?{description:shape.description}:{}}]}const toConfigVar=leaf=>({name:leaf.env,required:leaf.required,list:leaf.list,...leaf.default===void 0?{}:{default:leaf.default},...leaf.description?{description:leaf.description}:{}});function describeSchemaVars(schema){let shape=detectSchema(schema).toJsonSchema(),required=new Set(shape.required??[]);return Object.entries(shape.properties??{}).map(([key,child])=>{let described=toConfigVar(leavesOf(child,``,[key],required.has(key))[0]);return described.name=key,described})}function originsOf(vars,env=process.env){let has=name=>env[name]!==void 0&&env[name]!==``;return vars.map(v=>{let origin=`unset`;return has(v.name)?origin=`env`:readSecretFiles&&has(`${v.name}_FILE`)?origin=`file`:v.default!==void 0&&(origin=`default`),{name:v.name,origin}})}const cached=/* @__PURE__ */ new WeakMap,declaredEnv=/* @__PURE__ */ new WeakMap;function defineSettings(prefix,schema){return createSection(prefix,schema)}function createSection(prefix,schema){if(!/^[A-Z][A-Z0-9_]*$/.test(prefix))throw Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`);let wrapped=detectSchema(schema),shape=wrapped.toJsonSchema();if(!shape.properties)throw Error(`defineSettings('${prefix}'): the schema must be an object whose keys can be read (Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.`);let leaves=leavesOf(shape,prefix),seenEnv=/* @__PURE__ */ new Map;for(let leaf of leaves){let path=leaf.path.join(`.`),other=seenEnv.get(leaf.env);if(other!==void 0)throw Error(`defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`);seenEnv.set(leaf.env,path)}let envNames=leaves.map(leaf=>leaf.env),byPath=new Map(leaves.map(leaf=>[leaf.path.join(`.`),leaf.env])),load=(env=process.env)=>{let source=readSecretFiles?readSecretFiles(env,envNames):env,input={};for(let leaf of leaves){let raw=source[leaf.env];if(raw===void 0)continue;let target=input;for(let key of leaf.path.slice(0,-1))target=target[key]??={};target[leaf.path.at(-1)]=leaf.list?raw.split(`,`).map(item=>item.trim()).filter(Boolean):raw}return validate(input)},validate=input=>{let result=wrapped.safeParse(input);if(result.success)return result.data;let problems=result.issues.map(issue=>{let key=issue.path.join(`.`);return` ${byPath.get(key)??[prefix,...issue.path.map(p=>envSegment(String(p)))].join(`_`)}: ${issue.message}`});throw Error(`Settings '${prefix}' are invalid:\n${problems.join(`
11
+ import{t as INJECTION_TOKEN}from"./token-DtW16tw3.mjs";import{Container}from"./core/container.mjs";import{detectSchema}from"@forinda/kickjs-schema";let readSecretFiles;function _useSecretFileReader(reader){readSecretFiles=reader}const PROVIDED=Symbol.for(`kickjs.settings.provided`),OPTIONAL=Symbol.for(`kickjs.settings.optional`);function isProvided(decl){return decl[PROVIDED]===!0}function isOptionalSettings(decl){return decl[OPTIONAL]===!0}const envSegment=key=>key.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toUpperCase();function leavesOf(shape,prefix,path=[],required=!0){if(shape.properties){let own=new Set(shape.required??[]),parentRequired=required&&shape.default===void 0;return Object.entries(shape.properties).flatMap(([key,child])=>leavesOf(child,prefix,[...path,key],parentRequired&&own.has(key)))}let types=Array.isArray(shape.type)?shape.type:[shape.type];return[{path,env:[prefix,...path.map(envSegment)].join(`_`),list:types.includes(`array`),required:required&&shape.default===void 0,...shape.default===void 0?{}:{default:shape.default},...shape.description?{description:shape.description}:{}}]}const toConfigVar=leaf=>({name:leaf.env,required:leaf.required,list:leaf.list,...leaf.default===void 0?{}:{default:leaf.default},...leaf.description?{description:leaf.description}:{}});function describeSchemaVars(schema){let shape=detectSchema(schema).toJsonSchema(),required=new Set(shape.required??[]);return Object.entries(shape.properties??{}).map(([key,child])=>{let described=toConfigVar(leavesOf(child,``,[key],required.has(key))[0]);return described.name=key,described})}function originsOf(vars,env=process.env){let has=name=>env[name]!==void 0&&env[name]!==``;return vars.map(v=>{let origin=`unset`;return has(v.name)?origin=`env`:readSecretFiles&&has(`${v.name}_FILE`)?origin=`file`:v.default!==void 0&&(origin=`default`),{name:v.name,origin}})}let cached=/* @__PURE__ */ new WeakMap;function _forgetLoadedSettings(){cached=/* @__PURE__ */ new WeakMap}const declaredEnv=/* @__PURE__ */ new WeakMap;function defineSettings(prefix,schema){return createSection(prefix,schema)}function createSection(prefix,schema){if(!/^[A-Z][A-Z0-9_]*$/.test(prefix))throw Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`);let wrapped=detectSchema(schema),shape=wrapped.toJsonSchema();if(!shape.properties)throw Error(`defineSettings('${prefix}'): the schema must be an object whose keys can be read (Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.`);let leaves=leavesOf(shape,prefix),seenEnv=/* @__PURE__ */ new Map;for(let leaf of leaves){let path=leaf.path.join(`.`),other=seenEnv.get(leaf.env);if(other!==void 0)throw Error(`defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`);seenEnv.set(leaf.env,path)}let envNames=leaves.map(leaf=>leaf.env),byPath=new Map(leaves.map(leaf=>[leaf.path.join(`.`),leaf.env])),load=(env=process.env)=>{let source=readSecretFiles?readSecretFiles(env,envNames):env,input={};for(let leaf of leaves){let raw=source[leaf.env];if(raw===void 0)continue;let target=input;for(let key of leaf.path.slice(0,-1))target=target[key]??={};target[leaf.path.at(-1)]=leaf.list?raw.split(`,`).map(item=>item.trim()).filter(Boolean):raw}return validate(input)},validate=input=>{let result=wrapped.safeParse(input);if(result.success)return result.data;let problems=result.issues.map(issue=>{let key=issue.path.join(`.`);return` ${byPath.get(key)??[prefix,...issue.path.map(p=>envSegment(String(p)))].join(`_`)}: ${issue.message}`});throw Error(`Settings '${prefix}' are invalid:\n${problems.join(`
12
12
  `)}`)},scopes=/* @__PURE__ */ new Map,settings=Object.freeze({[INJECTION_TOKEN]:!0,name:`Settings(${prefix})`,prefix,envNames,...shape.description?{description:shape.description}:{},load,parse:value=>validate(value),provide:value=>Object.freeze({[PROVIDED]:!0,section:settings,value}),optional:()=>Object.freeze({[OPTIONAL]:!0,section:settings}),describe:()=>leaves.map(toConfigVar),get:()=>{let container=Container.getInstance();return container.has(settings)?container.resolve(settings):(cached.has(settings)||cached.set(settings,load(declaredEnv.get(settings))),cached.get(settings))},scoped:name=>{let scopePrefix=`${name}_${prefix}`,scoped=scopes.get(scopePrefix);return scoped||(scoped=createSection(scopePrefix,schema),scopes.set(scopePrefix,scoped)),scoped}});return settings}function loadSettings(declarations,env=process.env,byPrefix=/* @__PURE__ */ new Map,providedBefore=/* @__PURE__ */ new Map){let values=/* @__PURE__ */ new Map,failures=[],provided=/* @__PURE__ */ new Map,sections=[];for(let decl of declarations)if(isOptionalSettings(decl))declaredEnv.set(decl.section,env);else if(isProvided(decl)){let earlier=provided.has(decl.section)?provided:providedBefore;if(earlier.has(decl.section)&&earlier.get(decl.section)!==decl.value){failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`);continue}provided.set(decl.section,decl.value),sections.push(decl.section)}else sections.push(decl);for(let section of sections){if(values.has(section))continue;let other=byPrefix.get(section.prefix);if(other!==section||provided.has(section)&&!providedBefore.has(section)){if(other&&other!==section)failures.push(`Two different settings sections use the prefix '${section.prefix}'.`);else{byPrefix.set(section.prefix,section);try{let value=provided.has(section)?section.parse(provided.get(section)):section.load(env);values.set(section,value),provided.has(section)&&providedBefore.set(section,provided.get(section)),cached.set(section,value)}catch(err){failures.push(err.message)}}}}if(failures.length>0)throw Error(failures.join(`
13
- `));return values}export{loadSettings as a,isOptionalSettings as i,defineSettings as n,originsOf as o,describeSchemaVars as r,_useSecretFileReader as t};
14
- //# sourceMappingURL=settings-hG4DH8hQ.mjs.map
13
+ `));return values}export{isOptionalSettings as a,describeSchemaVars as i,_useSecretFileReader as n,loadSettings as o,defineSettings as r,originsOf as s,_forgetLoadedSettings as t};
14
+ //# sourceMappingURL=settings-v2N3V8Bl.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settings-v2N3V8Bl.mjs","names":[],"sources":["../src/config/settings.ts"],"sourcesContent":["/**\n * Typed configuration sections: one schema per concern (`DB`, `MAIL`,\n * `STORAGE`), each read from its own prefix of the environment and injected\n * where it's needed — instead of one flat env every service reaches into.\n * Spring's `@ConfigurationProperties`, for any schema `@forinda/kickjs-schema`\n * reads — Zod, Valibot, Yup.\n *\n * @module @forinda/kickjs/config/settings\n */\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { INJECTION_TOKEN, type InjectionToken } from '../core/token'\nimport { Container } from '../core/container'\n\n/**\n * Reads `<NAME>_FILE` secrets. Registered by `./env` (Node only) when it\n * loads — this module imports nothing node-only, so the web entry can use it;\n * there, `_FILE` variables are simply not read.\n */\ntype SecretFileReader = (\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n) => Record<string, string | undefined>\nlet readSecretFiles: SecretFileReader | undefined\n\n/** @internal */\nexport function _useSecretFileReader(reader: SecretFileReader): void {\n readSecretFiles = reader\n}\n\n/** A section: an injection token that also knows how to load itself. */\nexport interface Settings<T> extends InjectionToken<T> {\n /** The env prefix, e.g. `'DB'`. */\n readonly prefix: string\n /** Every env name the section reads, e.g. `['DB_URL', 'DB_POOL_MAX']`. */\n readonly envNames: readonly string[]\n /** The schema's own description (`.describe('…')` on the object in Zod). */\n readonly description?: string\n /**\n * The section's value — validated at startup, then cached. Before startup\n * (a script, a CLI command) the first call loads and validates it.\n */\n get(): T\n /** Parse the section from `env` (default `process.env`) afresh; throws listing every problem. */\n load(env?: NodeJS.ProcessEnv): T\n /** Each variable the section reads — required or not, default, description. Reads no env. */\n describe(): ConfigVar[]\n /** Validate a value you supply against the schema — defaults applied — instead of reading env. */\n parse(value: unknown): T\n /**\n * Declare the section with a value you supply instead of the environment —\n * a test's container, a service you started, a secret manager's answer.\n * Validated against the schema like env values; bound under this section's\n * token, so everything injecting it gets the provided value.\n *\n * ```ts\n * const pg = await startService('postgres')\n * await createTestApp({ modules, settings: [DbSettings.provide({ url: pg.url })] })\n * ```\n */\n provide(value: unknown): ProvidedSettings<T>\n /**\n * Declare the section without requiring it: it's listed (`kick env example`,\n * `describeConfig()`) but not validated or bound at startup — `get()`\n * validates it when the code that needs it runs. For a section only one\n * driver reads, picked at runtime:\n *\n * ```ts\n * settings: () => [SmtpSettings.optional(), ResendSettings.optional()]\n * ```\n *\n * Declared plainly anywhere else too, it's required.\n */\n optional(): OptionalSettings<T>\n /**\n * The same schema under another prefix, for a second instance:\n * `DbSettings.scoped('ANALYTICS')` reads `ANALYTICS_DB_*` beside `DB_*`.\n * Returns the same token for the same name.\n */\n scoped(name: string): Settings<T>\n}\n\nconst PROVIDED = Symbol.for('kickjs.settings.provided')\n\n/** A section declared with a supplied value — see {@link Settings.provide}. */\nexport interface ProvidedSettings<T> {\n readonly [PROVIDED]: true\n readonly section: Settings<T>\n readonly value: unknown\n}\n\nconst OPTIONAL = Symbol.for('kickjs.settings.optional')\n\n/** A section declared without being required — see {@link Settings.optional}. */\nexport interface OptionalSettings<T> {\n readonly [OPTIONAL]: true\n readonly section: Settings<T>\n}\n\n/** What a `settings` list accepts: a section (read from env), a provided one, or an optional one. */\nexport type SettingsDeclaration =\n | Settings<unknown>\n | ProvidedSettings<unknown>\n | OptionalSettings<unknown>\n\nfunction isProvided(decl: SettingsDeclaration): decl is ProvidedSettings<unknown> {\n return (decl as Partial<ProvidedSettings<unknown>>)[PROVIDED] === true\n}\n\n/** @internal True for a declaration made with {@link Settings.optional}. */\nexport function isOptionalSettings(decl: SettingsDeclaration): decl is OptionalSettings<unknown> {\n return (decl as Partial<OptionalSettings<unknown>>)[OPTIONAL] === true\n}\n\n/** The value type of a section: `SettingsOf<typeof DbSettings>`. */\nexport type SettingsOf<S> = S extends Settings<infer T> ? T : never\n\ninterface Leaf {\n path: string[]\n env: string\n list: boolean\n required: boolean\n default?: unknown\n description?: string\n}\n\n/** One variable, as `describe()` and `app.describeConfig()` report it. */\nexport interface ConfigVar {\n name: string\n /** Startup fails without it: required by the schema, with no default. */\n required: boolean\n /** The schema's default, when it has one. */\n default?: unknown\n /** The schema's description (`.describe('…')` in Zod). */\n description?: string\n /** Read as a comma-separated list. */\n list: boolean\n}\n\n/** The part of a JSON schema the env mapping reads. */\ninterface JsonShape {\n type?: string | string[]\n properties?: Record<string, JsonShape>\n required?: string[]\n default?: unknown\n description?: string\n}\n\n/** `maxConnections` → `MAX_CONNECTIONS`. */\nconst envSegment = (key: string) => key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()\n\n/**\n * The variables a JSON-schema shape reads. A leaf is required when every\n * object on its path is required by its parent and none of them (nor the leaf)\n * has a default — a defaulted parent object supplies its children.\n */\nfunction leavesOf(shape: JsonShape, prefix: string, path: string[] = [], required = true): Leaf[] {\n if (shape.properties) {\n const own = new Set(shape.required ?? [])\n const parentRequired = required && shape.default === undefined\n return Object.entries(shape.properties).flatMap(([key, child]) =>\n leavesOf(child, prefix, [...path, key], parentRequired && own.has(key)),\n )\n }\n const types = Array.isArray(shape.type) ? shape.type : [shape.type]\n return [\n {\n path,\n env: [prefix, ...path.map(envSegment)].join('_'),\n list: types.includes('array'),\n required: required && shape.default === undefined,\n ...(shape.default !== undefined ? { default: shape.default } : {}),\n ...(shape.description ? { description: shape.description } : {}),\n },\n ]\n}\n\nconst toConfigVar = (leaf: Leaf): ConfigVar => ({\n name: leaf.env,\n required: leaf.required,\n list: leaf.list,\n ...(leaf.default !== undefined ? { default: leaf.default } : {}),\n ...(leaf.description ? { description: leaf.description } : {}),\n})\n\n/**\n * The variables of a flat schema (the app's env schema), described the same\n * way — no prefix, top-level keys only.\n */\nexport function describeSchemaVars(schema: unknown): ConfigVar[] {\n const shape = detectSchema(schema).toJsonSchema() as JsonShape\n const required = new Set(shape.required ?? [])\n // The keys of an env schema are the variable names themselves.\n return Object.entries(shape.properties ?? {}).map(([key, child]) => {\n // A fresh object from toConfigVar — safe to set the name on directly.\n const described = toConfigVar(leavesOf(child, '', [key], required.has(key))[0])\n described.name = key\n return described\n })\n}\n\n/** Where a variable's value comes from. */\nexport type ValueOrigin = 'env' | 'file' | 'provided' | 'default' | 'unset'\n\n/** A variable and where its value comes from — never the value itself. */\nexport interface VarOrigin {\n name: string\n origin: ValueOrigin\n}\n\n/**\n * Where each variable's value comes from in `env`: set directly, read from\n * `<NAME>_FILE`, the schema's default, or not set at all. Names only — safe\n * to show where the values themselves must not appear.\n */\nexport function originsOf(\n vars: readonly ConfigVar[],\n env: NodeJS.ProcessEnv = process.env,\n): VarOrigin[] {\n // Empty counts as unset, as the secret-file reader treats it.\n const has = (name: string) => env[name] !== undefined && env[name] !== ''\n return vars.map((v) => {\n let origin: ValueOrigin = 'unset'\n if (has(v.name)) origin = 'env'\n // `_FILE` is only read where a reader is registered (Node, not the web entry).\n else if (readSecretFiles && has(`${v.name}_FILE`)) origin = 'file'\n else if (v.default !== undefined) origin = 'default'\n return { name: v.name, origin }\n })\n}\n\n/** Values validated at startup (or on first `get()`), by prefix. */\nlet cached = new WeakMap<Settings<unknown>, unknown>()\n\n/**\n * @internal Forget values `get()` loaded itself — sections that are optional\n * or undeclared, so never bound — so the next `get()` reads the environment\n * again. Called when an app binds its settings (each start and `kick dev`\n * rebuild) and by `reloadEnv()`; bound sections are re-read by the binding.\n */\nexport function _forgetLoadedSettings(): void {\n cached = new WeakMap()\n}\n\n/**\n * The env an optional section was declared against — the web entry's\n * platform bindings — so `get()` reads that, not `process.env`, when it's used.\n */\nconst declaredEnv = new WeakMap<Settings<unknown>, NodeJS.ProcessEnv>()\n\n/**\n * Define a typed configuration section read from env variables with a prefix.\n * Each key path becomes one variable: `pool.max` under `'DB'` is `DB_POOL_MAX`,\n * `maxConnections` is `DB_MAX_CONNECTIONS`. A list reads a comma-separated\n * value. `<NAME>_FILE` secrets work for every variable.\n *\n * ```ts\n * export const DbSettings = defineSettings('DB', z.object({\n * url: z.string().url(),\n * pool: z.object({ max: z.coerce.number().default(10) }).default({ max: 10 }),\n * }))\n *\n * @Service()\n * class Database {\n * constructor(@Inject(DbSettings) private readonly db: SettingsOf<typeof DbSettings>) {}\n * }\n * ```\n *\n * Declare it where it's used — `bootstrap({ settings })`, a module's, adapter's\n * or plugin's `settings()` — and it is validated when the app starts (a\n * missing or invalid value fails startup, naming the variable) and injectable\n * by its token. Undeclared, `get()` validates it on first use. Values\n * come from the schema's coercion: use `z.coerce.number()`, and\n * `z.stringbool()` for booleans (`z.coerce.boolean()` reads `'false'` as true).\n */\nexport function defineSettings<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n return createSection(prefix, schema)\n}\n\nfunction createSection<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n type T = InferSchemaOutput<S>\n if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) {\n throw new Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`)\n }\n const wrapped = detectSchema(schema)\n // The env names come from the schema's shape, read through its JSON schema —\n // the one view every adapter (Zod, Valibot, Yup) provides.\n const shape = wrapped.toJsonSchema() as JsonShape\n if (!shape.properties) {\n throw new Error(\n `defineSettings('${prefix}'): the schema must be an object whose keys can be read ` +\n '(Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.',\n )\n }\n const leaves = leavesOf(shape, prefix)\n // `fooBar` and `foo_bar` would both read `DB_FOO_BAR` — one variable for two\n // settings that could never differ. Refuse it here, naming both paths.\n const seenEnv = new Map<string, string>()\n for (const leaf of leaves) {\n const path = leaf.path.join('.')\n const other = seenEnv.get(leaf.env)\n if (other !== undefined) {\n throw new Error(\n `defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`,\n )\n }\n seenEnv.set(leaf.env, path)\n }\n const envNames = leaves.map((leaf) => leaf.env)\n const byPath = new Map(leaves.map((leaf) => [leaf.path.join('.'), leaf.env]))\n\n const load = (env: NodeJS.ProcessEnv = process.env): T => {\n const source = readSecretFiles ? readSecretFiles(env, envNames) : env\n const input: Record<string, unknown> = {}\n for (const leaf of leaves) {\n const raw = source[leaf.env]\n if (raw === undefined) continue\n let target = input\n for (const key of leaf.path.slice(0, -1)) {\n target = (target[key] ??= {}) as Record<string, unknown>\n }\n target[leaf.path.at(-1)!] = leaf.list\n ? raw\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean)\n : raw\n }\n return validate(input)\n }\n\n const validate = (input: unknown): T => {\n const result = wrapped.safeParse(input)\n if (result.success) return result.data as T\n const problems = result.issues.map((issue) => {\n const key = issue.path.join('.')\n // The variable to fix, not the schema path; a nested object that is\n // missing entirely names its prefix.\n const name =\n byPath.get(key) ?? [prefix, ...issue.path.map((p) => envSegment(String(p)))].join('_')\n return ` ${name}: ${issue.message}`\n })\n throw new Error(`Settings '${prefix}' are invalid:\\n${problems.join('\\n')}`)\n }\n\n const scopes = new Map<string, Settings<T>>()\n const settings: Settings<T> = Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name: `Settings(${prefix})`,\n prefix,\n envNames,\n ...(shape.description ? { description: shape.description } : {}),\n load,\n parse: (value: unknown): T => validate(value),\n provide: (value: unknown): ProvidedSettings<T> =>\n Object.freeze({ [PROVIDED]: true as const, section: settings, value }),\n optional: (): OptionalSettings<T> =>\n Object.freeze({ [OPTIONAL]: true as const, section: settings }),\n describe: () => leaves.map(toConfigVar),\n get: (): T => {\n // What injected code sees: the container's binding, which a module or a\n // test may have replaced. Before the app binds it, the validated env.\n const container = Container.getInstance()\n if (container.has(settings)) return container.resolve(settings) as T\n // Keyed by the section, not its prefix: two sections sharing a prefix\n // each parse their own schema.\n if (!cached.has(settings)) cached.set(settings, load(declaredEnv.get(settings)))\n return cached.get(settings) as T\n },\n scoped: (name: string): Settings<T> => {\n const scopePrefix = `${name}_${prefix}`\n let scoped = scopes.get(scopePrefix)\n if (!scoped) {\n scoped = createSection(scopePrefix, schema) as Settings<T>\n scopes.set(scopePrefix, scoped)\n }\n return scoped\n },\n }) as Settings<T>\n return settings\n}\n\n/**\n * Validate the given sections — the ones the app declared — throwing once\n * with every problem, so a misconfigured deploy fails at startup with the\n * whole list. A section declared twice is loaded once; two different sections\n * with one prefix would read the same variables, and are refused.\n */\nexport function loadSettings(\n declarations: Iterable<SettingsDeclaration>,\n env: NodeJS.ProcessEnv = process.env,\n /**\n * Prefixes already taken, across calls — an app binds in two phases (app\n * sections, then modules') and a clash between them must still be refused.\n */\n byPrefix: Map<string, Settings<unknown>> = new Map(),\n /** Values passed to `provide()`, across calls — same reason as `byPrefix`. */\n providedBefore: Map<Settings<unknown>, unknown> = new Map(),\n): Map<Settings<unknown>, unknown> {\n const values = new Map<Settings<unknown>, unknown>()\n const failures: string[] = []\n // A provided value wins over the same section read from env, wherever each\n // was declared — a test's provide() must not lose to a module's section.\n const provided = new Map<Settings<unknown>, unknown>()\n const sections: Settings<unknown>[] = []\n for (const decl of declarations) {\n // Listed, not required: `get()` validates it when it's used.\n if (isOptionalSettings(decl)) {\n declaredEnv.set(decl.section, env)\n continue\n }\n if (isProvided(decl)) {\n // Two provides of one section would silently keep whichever came last.\n const earlier = provided.has(decl.section) ? provided : providedBefore\n if (earlier.has(decl.section) && earlier.get(decl.section) !== decl.value) {\n failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`)\n continue\n }\n provided.set(decl.section, decl.value)\n sections.push(decl.section)\n } else {\n sections.push(decl)\n }\n }\n for (const section of sections) {\n if (values.has(section)) continue\n const other = byPrefix.get(section.prefix)\n // Already bound in an earlier phase: nothing to do — unless that read env\n // and this phase provides a value, which wins.\n if (other === section && !(provided.has(section) && !providedBefore.has(section))) continue\n if (other && other !== section) {\n failures.push(`Two different settings sections use the prefix '${section.prefix}'.`)\n continue\n }\n byPrefix.set(section.prefix, section)\n try {\n const value = provided.has(section) ? section.parse(provided.get(section)) : section.load(env)\n values.set(section, value)\n if (provided.has(section)) providedBefore.set(section, provided.get(section))\n // `get()` returns what the app started with.\n cached.set(section, value)\n } catch (err) {\n failures.push((err as Error).message)\n }\n }\n if (failures.length > 0) throw new Error(failures.join('\\n'))\n return values\n}\n"],"mappings":"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"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  import{HttpException,HttpStatus}from"./core/errors.mjs";const MIME_MAP={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,bmp:`image/bmp`,ico:`image/x-icon`,tiff:`image/tiff`,tif:`image/tiff`,avif:`image/avif`,pdf:`application/pdf`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,txt:`text/plain`,csv:`text/csv`,zip:`application/zip`,gz:`application/gzip`,tar:`application/x-tar`,rar:`application/vnd.rar`,"7z":`application/x-7z-compressed`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,flac:`audio/flac`,aac:`audio/aac`,mp4:`video/mp4`,webm:`video/webm`,avi:`video/x-msvideo`,mov:`video/quicktime`,mkv:`video/x-matroska`,json:`application/json`,xml:`application/xml`,html:`text/html`};function resolveMimeTypes(types){return types.map(t=>{let lower=t.toLowerCase().replace(/^\./,``);return MIME_MAP[lower]??t})}function buildFileTypeFilter(allowedTypes,customMimeMap){if(!allowedTypes)return()=>!0;if(typeof allowedTypes==`function`)return allowedTypes;let mimeMap=customMimeMap?{...MIME_MAP,...customMimeMap}:MIME_MAP,resolved=allowedTypes.map(t=>mimeMap[t.toLowerCase().replace(/^\./,``)]??t);return mimetype=>resolved.some(type=>type.endsWith(`/*`)?mimetype.startsWith(type.replace(`/*`,`/`)):mimetype===type)}const DEFAULT_MAX_SIZE=5242880;function normalizeOriginalName(name){return(name.normalize(`NFC`).split(/[\\/]/).pop()??``).replace(/[\u0000-\u001f\u007f]/g,``).trim()}function matchingExtension(name,mimetype,customMimeMap){let dot=name.lastIndexOf(`.`);if(dot<=0)return``;let ext=name.slice(dot+1).toLowerCase(),type=mimetype.split(`;`)[0].trim().toLowerCase();return(customMimeMap?.[ext]??MIME_MAP[ext])===type?`.${ext}`:``}function serverFileName(file,options={}){let{rename,customMimeMap}=options;if(!rename){let ext=matchingExtension(file.originalname,file.mimetype,customMimeMap);return`${globalThis.crypto.randomUUID()}${ext}`}let name=rename(file);if(typeof name!=`string`||name===``||name===`.`||name===`..`||name.length>255||/[\\/\0]/.test(name))throw Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`);return name}const UPLOAD_FIELDS_ALLOWANCE=1048576,MAX_UPLOAD_FIELDS=1e3;function uploadLimits(config){let fileSize=config.maxSize??DEFAULT_MAX_SIZE,files=config.mode===`none`?0:config.mode===`single`?1:config.maxCount??10;return{fileSize,files,total:fileSize*files+UPLOAD_FIELDS_ALLOWANCE}}function tooManyFiles(limit){return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`Too many files: at most ${limit}`)}function applyUploadConfig(parts,config){if(config.mode===`none`)return{};let field=config.fieldName??`file`,maxSize=config.maxSize??DEFAULT_MAX_SIZE,typeAllowed=buildFileTypeFilter(config.allowedTypes,config.customMimeMap),files=parts.filter(p=>p.fieldname===field).map(p=>{if(!typeAllowed(p.mimetype,p.filename))throw new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${p.mimetype} is not allowed`);if(p.buffer.length>maxSize)throw new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${p.filename} exceeds the ${maxSize}-byte limit`);let named={fieldname:p.fieldname,originalname:normalizeOriginalName(p.filename),mimetype:p.mimetype,size:p.buffer.length};return{...named,filename:serverFileName(named,config),encoding:`7bit`,buffer:p.buffer}});if(config.mode===`single`)return{file:files[0]};let maxCount=config.maxCount??10;return{files:files.slice(0,maxCount)}}export{normalizeOriginalName as a,tooManyFiles as c,buildFileTypeFilter as i,uploadLimits as l,UPLOAD_FIELDS_ALLOWANCE as n,resolveMimeTypes as o,applyUploadConfig as r,serverFileName as s,MAX_UPLOAD_FIELDS as t};
12
- //# sourceMappingURL=upload-config-CTwzXhph.mjs.map
12
+ //# sourceMappingURL=upload-config-BXjBiNjC.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload-config-CTwzXhph.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"upload-config-BXjBiNjC.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":"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"}
@@ -1,8 +1,7 @@
1
1
 
2
- import { g as FileUploadConfig, o as BaseUploadOptions } from "./decorators-DxNb5mWw.mjs";
3
- import { j as UploadStorageEngine } from "./adapter-DL9JPcvC.mjs";
4
- import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse } from "./connect-BlIamapT.mjs";
5
- //#region src/http/middleware/upload.d.ts
2
+ import { g as FileUploadConfig, o as BaseUploadOptions } from "./decorators-BAD8qjuq.mjs";
3
+ import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse } from "./connect-DamOelO8.mjs";
4
+ import { j as UploadStorageEngine } from "./adapter-B64IOivZ.mjs";
6
5
  /**
7
6
  * Upload options for the middleware.
8
7
  * Extends BaseUploadOptions from core (shared with @FileUpload decorator)
@@ -50,6 +49,5 @@ declare const upload: {
50
49
  array: typeof array;
51
50
  none: typeof none;
52
51
  };
53
- //#endregion
54
52
  export { upload as i, buildUploadMiddleware as n, cleanupFiles as r, UploadOptions as t };
55
- //# sourceMappingURL=upload-DnwvZQyi.d.mts.map
53
+ //# sourceMappingURL=upload-eNNueUxR.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-eNNueUxR.d.mts","names":["RequestHandler","Request","Response","NextFunction"],"sources":["../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;UA+DiB,sBAAsB;;EAErC,UAAU;;EAEV;;iBAkMO,OAAO,mBAAmB,UAAS,gBAAqBA;;;;iBAcxD,MAAM,mBAAmB,mBAAe,UAAS,gBAAqBA;;;;iBAiBtE,KAAK,UAAS,gBAAqBA;;;;;;;;;;;;;;;iBAoB5B,iBAAY,KACbC,gBAAO,KAAOC,iBAAQ,MAAQC;;;;;;iBA+B7B,sBAAsB,QAAQ,mBAAmBH;;cAoBpD"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as createToken}from"./token-i5RynFrd.mjs";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}function moduleName(mod){let{__moduleName,name}=mod;if(typeof __moduleName==`string`&&__moduleName)return __moduleName;if(typeof name==`string`&&name)return name;let ctorName=mod.constructor?.name;return ctorName&&ctorName!==`Object`?ctorName:`module`}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);if(Array.isArray(params)){let list=params,keys=[...pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map(m=>m[1]);if(list.length!==keys.length)throw Error(`urlFor('${name}'): takes ${keys.length} param${keys.length===1?``:`s`}${keys.length?` (${keys.join(`, `)})`:``}, got ${list.length}`)}let at=0,path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=Array.isArray(params)?params[at++]:params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{moduleName as a,defineModule as i,RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
12
- //# sourceMappingURL=url-for-CQNJYjRH.mjs.map
11
+ import{n as createToken}from"./token-DtW16tw3.mjs";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}function moduleName(mod){let{__moduleName,name}=mod;if(typeof __moduleName==`string`&&__moduleName)return __moduleName;if(typeof name==`string`&&name)return name;let ctorName=mod.constructor?.name;return ctorName&&ctorName!==`Object`?ctorName:`module`}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);if(Array.isArray(params)){let list=params,keys=[...pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map(m=>m[1]);if(list.length!==keys.length)throw Error(`urlFor('${name}'): takes ${keys.length} param${keys.length===1?``:`s`}${keys.length?` (${keys.join(`, `)})`:``}, got ${list.length}`)}let at=0,path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=Array.isArray(params)?params[at++]:params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{moduleName as a,defineModule as i,RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
12
+ //# sourceMappingURL=url-for-C4Eomib7.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"url-for-CQNJYjRH.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/module-registry.ts","../src/http/url-for.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n\n/**\n * The name a module is labelled with in diagnostics — `describeConfig()`,\n * `.env.example`'s \"declared by\", the contributors table. `defineModule`\n * stamps it as `__moduleName`; a hand-written module may carry `name`; a\n * class module falls back to its class name. Plain objects say `module`, not\n * `Object`.\n */\nexport function moduleName(mod: AppModule): string {\n const { __moduleName, name } = mod as { __moduleName?: unknown; name?: unknown }\n if (typeof __moduleName === 'string' && __moduleName) return __moduleName\n if (typeof name === 'string' && name) return name\n const ctorName = mod.constructor?.name\n return ctorName && ctorName !== 'Object' ? ctorName : 'module'\n}\n","import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n","/**\n * Build a route's URL from its name — `'UsersController.show'` — instead of\n * spelling the path where you link to it, so a moved route can't leave a\n * redirect, a `Location` header or an email link pointing at the old one.\n *\n * @module @forinda/kickjs/http/url-for\n */\n\nimport { createToken } from '../core/token'\n\n/**\n * Route names `kick typegen` knows: `'Controller.method'` → the route's\n * shape. Falls back to `string` before typegen has run.\n */\nexport type RouteName = [keyof KickRoutes.Named] extends [never]\n ? string\n : Extract<keyof KickRoutes.Named, string>\n\ntype ParamsOf<N> = N extends keyof KickRoutes.Named\n ? KickRoutes.Named[N] extends { params: infer P }\n ? P\n : Record<string, string | number>\n : Record<string, string | number>\n\n/** Path params in the order the path has them: `['42', 'a']` for `/users/:id/posts/:slug`. */\nexport type PositionalParams = ReadonlyArray<string | number>\n\n/** `params` is optional when the route has none, required otherwise. */\nexport type UrlForArgs<N> =\n Record<string, never> extends ParamsOf<N>\n ? [params?: ParamsOf<N> | PositionalParams, query?: UrlQuery]\n : [params: ParamsOf<N> | PositionalParams, query?: UrlQuery]\n\nexport type UrlQuery = Record<string, string | number | boolean | Array<string | number>>\n\n/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */\nexport interface UrlBuilder {\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string.\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string\n}\n\n/**\n * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,\n * a service building a link:\n *\n * ```ts\n * @Service()\n * class Mailer {\n * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}\n * resetLink(token: string) {\n * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`\n * }\n * }\n * ```\n */\nexport const ROUTE_URLS = createToken<UrlBuilder>('kick/Http/routeUrls')\n// One per process, like every DI binding: the container is process-wide, so\n// with two apps in one process this is the one set up last. `ctx.urlFor()`\n// always uses the app that is serving the request.\n\n/** One app's route name → full path pattern (`/api/v1/users/:id`). */\nexport class RouteUrls implements UrlBuilder {\n private readonly paths = new Map<string, string>()\n\n /** First registration wins — a controller mounted twice keeps its first path. */\n add(name: string, path: string): void {\n if (!this.paths.has(name)) this.paths.set(name, path)\n }\n\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.build(name, params as Record<string, unknown> | PositionalParams | undefined, query)\n }\n\n build(\n name: string,\n params?: Record<string, unknown> | PositionalParams,\n query?: UrlQuery,\n ): string {\n const pattern = this.paths.get(name)\n if (pattern === undefined) {\n throw new Error(`urlFor: no route named '${name}' — expected 'Controller.method'`)\n }\n if (Array.isArray(params)) {\n const list = params as PositionalParams\n // Positional (templates can't write objects): in the order the path has them.\n const keys = [...pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]!)\n if (list.length !== keys.length) {\n throw new Error(\n `urlFor('${name}'): takes ${keys.length} param${keys.length === 1 ? '' : 's'}${keys.length ? ` (${keys.join(', ')})` : ''}, got ${list.length}`,\n )\n }\n }\n // A list fills each placeholder by position, so a repeated name keeps both values.\n let at = 0\n const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = Array.isArray(params)\n ? (params as PositionalParams)[at++]\n : (params as Record<string, unknown> | undefined)?.[key]\n if (value === undefined || value === null || value === '') {\n throw new Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`)\n }\n return encodeURIComponent(String(value))\n })\n if (!query) return path\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n for (const v of Array.isArray(value) ? value : [value]) search.append(key, String(v))\n }\n const qs = search.toString()\n return qs ? `${path}?${qs}` : path\n }\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {\n /** `'Controller.method'` → route shape, written by `kick typegen`. */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Named {}\n }\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"url-for-C4Eomib7.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/module-registry.ts","../src/http/url-for.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n\n/**\n * The name a module is labelled with in diagnostics — `describeConfig()`,\n * `.env.example`'s \"declared by\", the contributors table. `defineModule`\n * stamps it as `__moduleName`; a hand-written module may carry `name`; a\n * class module falls back to its class name. Plain objects say `module`, not\n * `Object`.\n */\nexport function moduleName(mod: AppModule): string {\n const { __moduleName, name } = mod as { __moduleName?: unknown; name?: unknown }\n if (typeof __moduleName === 'string' && __moduleName) return __moduleName\n if (typeof name === 'string' && name) return name\n const ctorName = mod.constructor?.name\n return ctorName && ctorName !== 'Object' ? ctorName : 'module'\n}\n","import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n","/**\n * Build a route's URL from its name — `'UsersController.show'` — instead of\n * spelling the path where you link to it, so a moved route can't leave a\n * redirect, a `Location` header or an email link pointing at the old one.\n *\n * @module @forinda/kickjs/http/url-for\n */\n\nimport { createToken } from '../core/token'\n\n/**\n * Route names `kick typegen` knows: `'Controller.method'` → the route's\n * shape. Falls back to `string` before typegen has run.\n */\nexport type RouteName = [keyof KickRoutes.Named] extends [never]\n ? string\n : Extract<keyof KickRoutes.Named, string>\n\ntype ParamsOf<N> = N extends keyof KickRoutes.Named\n ? KickRoutes.Named[N] extends { params: infer P }\n ? P\n : Record<string, string | number>\n : Record<string, string | number>\n\n/** Path params in the order the path has them: `['42', 'a']` for `/users/:id/posts/:slug`. */\nexport type PositionalParams = ReadonlyArray<string | number>\n\n/** `params` is optional when the route has none, required otherwise. */\nexport type UrlForArgs<N> =\n Record<string, never> extends ParamsOf<N>\n ? [params?: ParamsOf<N> | PositionalParams, query?: UrlQuery]\n : [params: ParamsOf<N> | PositionalParams, query?: UrlQuery]\n\nexport type UrlQuery = Record<string, string | number | boolean | Array<string | number>>\n\n/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */\nexport interface UrlBuilder {\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string.\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string\n}\n\n/**\n * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,\n * a service building a link:\n *\n * ```ts\n * @Service()\n * class Mailer {\n * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}\n * resetLink(token: string) {\n * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`\n * }\n * }\n * ```\n */\nexport const ROUTE_URLS = createToken<UrlBuilder>('kick/Http/routeUrls')\n// One per process, like every DI binding: the container is process-wide, so\n// with two apps in one process this is the one set up last. `ctx.urlFor()`\n// always uses the app that is serving the request.\n\n/** One app's route name → full path pattern (`/api/v1/users/:id`). */\nexport class RouteUrls implements UrlBuilder {\n private readonly paths = new Map<string, string>()\n\n /** First registration wins — a controller mounted twice keeps its first path. */\n add(name: string, path: string): void {\n if (!this.paths.has(name)) this.paths.set(name, path)\n }\n\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.build(name, params as Record<string, unknown> | PositionalParams | undefined, query)\n }\n\n build(\n name: string,\n params?: Record<string, unknown> | PositionalParams,\n query?: UrlQuery,\n ): string {\n const pattern = this.paths.get(name)\n if (pattern === undefined) {\n throw new Error(`urlFor: no route named '${name}' — expected 'Controller.method'`)\n }\n if (Array.isArray(params)) {\n const list = params as PositionalParams\n // Positional (templates can't write objects): in the order the path has them.\n const keys = [...pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]!)\n if (list.length !== keys.length) {\n throw new Error(\n `urlFor('${name}'): takes ${keys.length} param${keys.length === 1 ? '' : 's'}${keys.length ? ` (${keys.join(', ')})` : ''}, got ${list.length}`,\n )\n }\n }\n // A list fills each placeholder by position, so a repeated name keeps both values.\n let at = 0\n const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = Array.isArray(params)\n ? (params as PositionalParams)[at++]\n : (params as Record<string, unknown> | undefined)?.[key]\n if (value === undefined || value === null || value === '') {\n throw new Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`)\n }\n return encodeURIComponent(String(value))\n })\n if (!query) return path\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n for (const v of Array.isArray(value) ? value : [value]) search.append(key, String(v))\n }\n const qs = search.toString()\n return qs ? `${path}?${qs}` : path\n }\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {\n /** `'Controller.method'` → route shape, written by `kick typegen`. */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Named {}\n }\n}\n"],"mappings":"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"}
@@ -1,8 +1,7 @@
1
1
 
2
- import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-BlIamapT.mjs";
3
- import { t as HttpException } from "./errors-By6UueCm.mjs";
2
+ import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-DamOelO8.mjs";
3
+ import { t as HttpException } from "./errors-DZGuPLoZ.mjs";
4
4
  import { SchemaIssue } from "@forinda/kickjs-schema";
5
- //#region src/http/middleware/validate.d.ts
6
5
  interface ValidationSchema {
7
6
  body?: any;
8
7
  query?: any;
@@ -48,6 +47,5 @@ declare function validate(schema: ValidationSchema, options?: {
48
47
  /** What a failure throws — see `bootstrap({ validationError })`. Default: a 422. */
49
48
  validationError?: ValidationErrorFactory;
50
49
  }): (req: ConnectRequest, _res: ConnectResponse, next: ConnectNext) => void;
51
- //#endregion
52
50
  export { validate as a, defaultValidationError as i, ValidationFailure as n, ValidationSchema as r, ValidationErrorFactory as t };
53
- //# sourceMappingURL=validate-D4Poe2EE.d.mts.map
51
+ //# sourceMappingURL=validate-BbthfLBb.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-BbthfLBb.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/validate.ts"],"mappings":";;;;UAUiB;EACf;EACA;EACA;;;UAIe;;EAEf;;EAEA,QAAQ;;EAER;;;;;;;;KASU,0BAA0B,SAAS;;;;;;;iBAQ/B,yBAAyB,QAAQ,UAAU,oBAAoB;;;;;;;;;;;;;;iBA0D/D,SACd,QAAQ,kBACR;;EAEE,kBAAkB;KACd,KAcOA,gBAAO,MAAQC,iBAAQ,MAAQC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-Dokycjj0.mjs";import{AsyncLocalStorage}from"node:async_hooks";const requestStore=new AsyncLocalStorage;function getRequestStore(){let store=requestStore.getStore();if(!store)throw Error(`No active request context. REQUEST-scoped services can only be resolved during an HTTP request.`);return store}function getRequestValue(key){return requestStore.getStore()?.values.get(key)}const log=createLogger(`waitUntil`),pending=/* @__PURE__ */ new Set;function waitUntil(promise){let requestId=requestStore.getStore()?.requestId,tracked=Promise.resolve(promise).then(()=>{},err=>{log.error({err,requestId},`Background work passed to waitUntil() failed`),reportError(err,{source:`background`,requestId})});pending.add(tracked),tracked.finally(()=>pending.delete(tracked))}async function settleBackgroundWork(){for(;pending.size>0;)await Promise.all(pending)}function pendingBackgroundWork(){return pending.size}function forwardBackgroundWork(platform){platform?.waitUntil?.(settleBackgroundWork())}const VIEW_RENDERER=Symbol.for(`kickjs.viewRenderer`);function bindViewRenderer(req,renderer){req[VIEW_RENDERER]=renderer}function viewRendererFor(req){return req?.[VIEW_RENDERER]}const PENDING=Symbol(`kickjs.pendingResponse`);function setPendingResponse(ctx,p){ctx[PENDING]=p}function pendingResponse(ctx){return ctx[PENDING]}export{viewRendererFor as a,settleBackgroundWork as c,getRequestValue as d,requestStore as f,setPendingResponse as i,waitUntil as l,bindViewRenderer as n,forwardBackgroundWork as o,pendingResponse as r,pendingBackgroundWork as s,VIEW_RENDERER as t,getRequestStore as u};
12
- //# sourceMappingURL=view-renderer-BV2rwEUI.mjs.map
11
+ import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-B4VnKAHK.mjs";import{AsyncLocalStorage}from"node:async_hooks";const requestStore=new AsyncLocalStorage;function getRequestStore(){let store=requestStore.getStore();if(!store)throw Error(`No active request context. REQUEST-scoped services can only be resolved during an HTTP request.`);return store}function getRequestValue(key){return requestStore.getStore()?.values.get(key)}const log=createLogger(`waitUntil`),pending=/* @__PURE__ */ new Set;function waitUntil(promise){let requestId=requestStore.getStore()?.requestId,tracked=Promise.resolve(promise).then(()=>{},err=>{log.error({err,requestId},`Background work passed to waitUntil() failed`),reportError(err,{source:`background`,requestId})});pending.add(tracked),tracked.finally(()=>pending.delete(tracked))}async function settleBackgroundWork(){for(;pending.size>0;)await Promise.all(pending)}function pendingBackgroundWork(){return pending.size}function forwardBackgroundWork(platform){platform?.waitUntil?.(settleBackgroundWork())}const VIEW_RENDERER=Symbol.for(`kickjs.viewRenderer`);function bindViewRenderer(req,renderer){req[VIEW_RENDERER]=renderer}function viewRendererFor(req){return req?.[VIEW_RENDERER]}const PENDING=Symbol(`kickjs.pendingResponse`);function setPendingResponse(ctx,p){ctx[PENDING]=p}function pendingResponse(ctx){return ctx[PENDING]}export{viewRendererFor as a,settleBackgroundWork as c,getRequestValue as d,requestStore as f,setPendingResponse as i,waitUntil as l,bindViewRenderer as n,forwardBackgroundWork as o,pendingResponse as r,pendingBackgroundWork as s,VIEW_RENDERER as t,getRequestStore as u};
12
+ //# sourceMappingURL=view-renderer-C4sMEruA.mjs.map