@forinda/kickjs 10.14.2 → 10.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. package/dist/{adapter-B64IOivZ.d.mts → adapter-D_nUmKEQ.d.mts} +172 -34
  2. package/dist/adapter-D_nUmKEQ.d.mts.map +1 -0
  3. package/dist/{allowed-hosts-U12_gESr.d.mts → allowed-hosts-BQlQFt-1.d.mts} +6 -1
  4. package/dist/allowed-hosts-BQlQFt-1.d.mts.map +1 -0
  5. package/dist/{app-module-EmIojM4d.d.mts → app-module-BmViGLgj.d.mts} +5 -5
  6. package/dist/{app-module-EmIojM4d.d.mts.map → app-module-BmViGLgj.d.mts.map} +1 -1
  7. package/dist/application-B16ltRnC.mjs +14 -0
  8. package/dist/application-B16ltRnC.mjs.map +1 -0
  9. package/dist/{application-CGcY8SZZ.d.mts → application-ClCq0AgY.d.mts} +190 -53
  10. package/dist/application-ClCq0AgY.d.mts.map +1 -0
  11. package/dist/{body-policy-Be3Y0hjq.mjs → body-policy-D8LveWmO.mjs} +2 -2
  12. package/dist/{body-policy-Be3Y0hjq.mjs.map → body-policy-D8LveWmO.mjs.map} +1 -1
  13. package/dist/{bootstrap-Bvk3BWJX.mjs → bootstrap-C5NvsxHQ.mjs} +3 -3
  14. package/dist/bootstrap-C5NvsxHQ.mjs.map +1 -0
  15. package/dist/{bounded-counters-Bh5jeT9I.mjs → bounded-counters-BtvB2daV.mjs} +2 -2
  16. package/dist/{bounded-counters-Bh5jeT9I.mjs.map → bounded-counters-BtvB2daV.mjs.map} +1 -1
  17. package/dist/{breach-padding-DfT9MXGb.d.mts → breach-padding-BUuc21Eu.d.mts} +6 -1
  18. package/dist/breach-padding-BUuc21Eu.d.mts.map +1 -0
  19. package/dist/{cache-DMIt3c6M.d.mts → cache-ByX5O2Hp.d.mts} +26 -1
  20. package/dist/{cache-DMIt3c6M.d.mts.map → cache-ByX5O2Hp.d.mts.map} +1 -1
  21. package/dist/{client-ip-CGH_IvnC.mjs → client-ip-CWvyHmqt.mjs} +2 -2
  22. package/dist/{client-ip-CGH_IvnC.mjs.map → client-ip-CWvyHmqt.mjs.map} +1 -1
  23. package/dist/config/index.d.mts +6 -1
  24. package/dist/config/index.mjs +2 -2
  25. package/dist/{config-CjFxvh0v.mjs → config-BIQoDNil.mjs} +3 -3
  26. package/dist/{config-CjFxvh0v.mjs.map → config-BIQoDNil.mjs.map} +1 -1
  27. package/dist/container-DtdUiRwr.d.mts +3 -0
  28. package/dist/{context-BvZLaTeE.mjs → context-BzFNflxV.mjs} +3 -3
  29. package/dist/context-BzFNflxV.mjs.map +1 -0
  30. package/dist/{context-errors-BZVS0B1O.mjs → context-errors-BmaG4vwd.mjs} +2 -2
  31. package/dist/context-errors-BmaG4vwd.mjs.map +1 -0
  32. package/dist/{contributor-runner-fdKy6Tme.mjs → contributor-runner-BnJzu2GI.mjs} +3 -3
  33. package/dist/contributor-runner-BnJzu2GI.mjs.map +1 -0
  34. package/dist/core/adapter.d.mts +1 -1
  35. package/dist/core/adapter.mjs +1 -1
  36. package/dist/core/app-module.d.mts +1 -1
  37. package/dist/core/app-module.mjs +1 -1
  38. package/dist/core/cache.d.mts +1 -1
  39. package/dist/core/cache.mjs +1 -1
  40. package/dist/core/cache.mjs.map +1 -1
  41. package/dist/core/container.d.mts +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/logger.d.mts +1 -1
  55. package/dist/core/logger.mjs +1 -1
  56. package/dist/core/logger.mjs.map +1 -1
  57. package/dist/core/path.mjs +1 -1
  58. package/dist/core/plugin.d.mts +1 -1
  59. package/dist/core/plugin.mjs +1 -1
  60. package/dist/core/reactivity.d.mts +1 -1
  61. package/dist/core/reactivity.mjs +2 -2
  62. package/dist/core/reactivity.mjs.map +1 -1
  63. package/dist/core-Dqzah_BX.mjs +12 -0
  64. package/dist/core-Dqzah_BX.mjs.map +1 -0
  65. package/dist/{cors-J-q6PuSU.d.mts → cors-u1OwTxQ8.d.mts} +6 -1
  66. package/dist/cors-u1OwTxQ8.d.mts.map +1 -0
  67. package/dist/{cron-DGV1AE0R.d.mts → cron-Bxm2MY8u.d.mts} +10 -1
  68. package/dist/cron-Bxm2MY8u.d.mts.map +1 -0
  69. package/dist/{csrf-DjtJPgA3.d.mts → csrf-8-Jknvmc.d.mts} +12 -2
  70. package/dist/csrf-8-Jknvmc.d.mts.map +1 -0
  71. package/dist/{decorate-DRbXCNQz.mjs → decorate-C3to8dG-.mjs} +3 -3
  72. package/dist/{decorate-DRbXCNQz.mjs.map → decorate-C3to8dG-.mjs.map} +1 -1
  73. package/dist/{decorators-BAD8qjuq.d.mts → decorators-Bflncyz6.d.mts} +122 -6
  74. package/dist/decorators-Bflncyz6.d.mts.map +1 -0
  75. package/dist/{define-adapter-DMo6og81.mjs → define-adapter-DCjNTP6m.mjs} +2 -2
  76. package/dist/define-adapter-DCjNTP6m.mjs.map +1 -0
  77. package/dist/{di-hooks-DCqt2yJ9.mjs → di-hooks-DTDy7ABs.mjs} +2 -2
  78. package/dist/di-hooks-DTDy7ABs.mjs.map +1 -0
  79. package/dist/{disposables-BsdVu69-.mjs → disposables-BC291ukb.mjs} +1 -1
  80. package/dist/{driver-oZBQDJZz.mjs → driver-D59oWDec.mjs} +3 -3
  81. package/dist/{driver-oZBQDJZz.mjs.map → driver-D59oWDec.mjs.map} +1 -1
  82. package/dist/{error-handler-Dl_gZRNK.d.mts → error-handler-gZLQFHeE.d.mts} +2 -2
  83. package/dist/{error-handler-Dl_gZRNK.d.mts.map → error-handler-gZLQFHeE.d.mts.map} +1 -1
  84. package/dist/{errors-DZGuPLoZ.d.mts → errors-CppqPy0A.d.mts} +2 -1
  85. package/dist/errors-CppqPy0A.d.mts.map +1 -0
  86. package/dist/{express-f9CTA8qO.mjs → express-JAXx9MK0.mjs} +3 -3
  87. package/dist/{express-f9CTA8qO.mjs.map → express-JAXx9MK0.mjs.map} +1 -1
  88. package/dist/{express-lazy-DMxcLBpT.mjs → express-lazy-jIFBeDpY.mjs} +3 -3
  89. package/dist/{express-lazy-DMxcLBpT.mjs.map → express-lazy-jIFBeDpY.mjs.map} +1 -1
  90. package/dist/{handler-B66laQY0.mjs → handler-C8iAD_xz.mjs} +3 -3
  91. package/dist/{handler-B66laQY0.mjs.map → handler-C8iAD_xz.mjs.map} +1 -1
  92. package/dist/{helmet-Rwkbp9IS.d.mts → helmet-1H0LKr6y.d.mts} +6 -1
  93. package/dist/helmet-1H0LKr6y.d.mts.map +1 -0
  94. package/dist/{host-DalMsn5Z.mjs → host-Crxmi91N.mjs} +2 -2
  95. package/dist/{host-DalMsn5Z.mjs.map → host-Crxmi91N.mjs.map} +1 -1
  96. package/dist/http/application.d.mts +1 -1
  97. package/dist/http/application.mjs +2 -2
  98. package/dist/http/bootstrap.d.mts +1 -1
  99. package/dist/http/bootstrap.mjs +2 -2
  100. package/dist/http/context.d.mts +2 -2
  101. package/dist/http/context.mjs +2 -2
  102. package/dist/http/middleware/allowed-hosts.d.mts +1 -1
  103. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  104. package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
  105. package/dist/http/middleware/breach-padding.d.mts +1 -1
  106. package/dist/http/middleware/breach-padding.mjs +1 -1
  107. package/dist/http/middleware/breach-padding.mjs.map +1 -1
  108. package/dist/http/middleware/cors.d.mts +1 -1
  109. package/dist/http/middleware/cors.mjs +1 -1
  110. package/dist/http/middleware/cors.mjs.map +1 -1
  111. package/dist/http/middleware/csrf.d.mts +1 -1
  112. package/dist/http/middleware/csrf.mjs +2 -2
  113. package/dist/http/middleware/csrf.mjs.map +1 -1
  114. package/dist/http/middleware/error-handler.d.mts +1 -1
  115. package/dist/http/middleware/error-handler.mjs +2 -2
  116. package/dist/http/middleware/helmet.d.mts +1 -1
  117. package/dist/http/middleware/helmet.mjs +1 -1
  118. package/dist/http/middleware/helmet.mjs.map +1 -1
  119. package/dist/http/middleware/rate-limit.d.mts +1 -1
  120. package/dist/http/middleware/rate-limit.mjs +2 -2
  121. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  122. package/dist/http/middleware/request-id.d.mts +1 -1
  123. package/dist/http/middleware/request-id.mjs +1 -1
  124. package/dist/http/middleware/request-id.mjs.map +1 -1
  125. package/dist/http/middleware/request-logger.d.mts +1 -1
  126. package/dist/http/middleware/request-logger.mjs +2 -2
  127. package/dist/http/middleware/request-logger.mjs.map +1 -1
  128. package/dist/http/middleware/session.d.mts +1 -1
  129. package/dist/http/middleware/session.mjs +2 -2
  130. package/dist/http/middleware/session.mjs.map +1 -1
  131. package/dist/http/middleware/spa.d.mts +1 -1
  132. package/dist/http/middleware/spa.mjs +2 -2
  133. package/dist/http/middleware/spa.mjs.map +1 -1
  134. package/dist/http/middleware/upload.d.mts +2 -2
  135. package/dist/http/middleware/upload.mjs +2 -2
  136. package/dist/http/middleware/upload.mjs.map +1 -1
  137. package/dist/http/middleware/validate.d.mts +1 -1
  138. package/dist/http/middleware/validate.mjs +1 -1
  139. package/dist/http/middleware/views.d.mts +1 -1
  140. package/dist/http/middleware/views.mjs +2 -2
  141. package/dist/http/middleware/views.mjs.map +1 -1
  142. package/dist/http/query/index.d.mts +1 -1
  143. package/dist/http/query/index.mjs +2 -2
  144. package/dist/http/router-builder.d.mts +1 -1
  145. package/dist/http/router-builder.mjs +2 -2
  146. package/dist/http/runtimes/express.d.mts +3 -2
  147. package/dist/http/runtimes/express.d.mts.map +1 -1
  148. package/dist/http/runtimes/express.mjs +2 -2
  149. package/dist/http/runtimes/fastify.d.mts +3 -3
  150. package/dist/http/runtimes/fastify.mjs +2 -2
  151. package/dist/http/runtimes/fastify.mjs.map +1 -1
  152. package/dist/http/runtimes/h3-web.mjs +1 -1
  153. package/dist/http/runtimes/h3.d.mts +1 -1
  154. package/dist/http/runtimes/h3.mjs +2 -2
  155. package/dist/http/runtimes/h3.mjs.map +1 -1
  156. package/dist/{index-ZbCnCyQx.d.mts → index-CtjmSXFy.d.mts} +11 -1
  157. package/dist/index-CtjmSXFy.d.mts.map +1 -0
  158. package/dist/{index-CFTwnev9.d.mts → index-DoukvKwh.d.mts} +2 -2
  159. package/dist/{index-CFTwnev9.d.mts.map → index-DoukvKwh.d.mts.map} +1 -1
  160. package/dist/index.d.mts +34 -28
  161. package/dist/index.mjs +2 -2
  162. package/dist/index.mjs.map +1 -1
  163. package/dist/{interfaces-BQhYh3lL.d.mts → interfaces-CvO9sAea.d.mts} +3 -3
  164. package/dist/{interfaces-BQhYh3lL.d.mts.map → interfaces-CvO9sAea.d.mts.map} +1 -1
  165. package/dist/{is-production-9QzMIRuO.mjs → is-production-LziEMGrc.mjs} +2 -2
  166. package/dist/{is-production-9QzMIRuO.mjs.map → is-production-LziEMGrc.mjs.map} +1 -1
  167. package/dist/{jobs-CuZqVDDG.mjs → jobs-D7ToA0yF.mjs} +3 -3
  168. package/dist/jobs-D7ToA0yF.mjs.map +1 -0
  169. package/dist/{kv-stores-wTD3VDPB.d.mts → kv-stores-DdGPLXQG.d.mts} +32 -7
  170. package/dist/kv-stores-DdGPLXQG.d.mts.map +1 -0
  171. package/dist/{kv-stores-C9CJ3xCB.mjs → kv-stores-DpM57Xr5.mjs} +3 -3
  172. package/dist/kv-stores-DpM57Xr5.mjs.map +1 -0
  173. package/dist/{lazy-serve-static-DVWmKM7Z.mjs → lazy-serve-static-DxI2K-zs.mjs} +3 -3
  174. package/dist/{lazy-serve-static-DVWmKM7Z.mjs.map → lazy-serve-static-DxI2K-zs.mjs.map} +1 -1
  175. package/dist/{logger-BL8MiSrm.d.mts → logger-ByJsVwqY.d.mts} +3 -3
  176. package/dist/{logger-BL8MiSrm.d.mts.map → logger-ByJsVwqY.d.mts.map} +1 -1
  177. package/dist/{metadata-BZRtQog3.mjs → metadata-nTTSnVTO.mjs} +1 -1
  178. package/dist/{observers-B4VnKAHK.mjs → observers-fQtCIKLq.mjs} +2 -2
  179. package/dist/observers-fQtCIKLq.mjs.map +1 -0
  180. package/dist/{precompressed-AxF66Ls0.mjs → precompressed-BtwmgzyS.mjs} +2 -2
  181. package/dist/{precompressed-AxF66Ls0.mjs.map → precompressed-BtwmgzyS.mjs.map} +1 -1
  182. package/dist/{query-BwUR-ssX.mjs → query-Dr28oT30.mjs} +2 -2
  183. package/dist/query-Dr28oT30.mjs.map +1 -0
  184. package/dist/{rate-limit-DMiV6bAq.d.mts → rate-limit-BQx_P6gG.d.mts} +11 -1
  185. package/dist/rate-limit-BQx_P6gG.d.mts.map +1 -0
  186. package/dist/{reactivity-Dski64km.d.mts → reactivity-KZOrwVeK.d.mts} +32 -1
  187. package/dist/reactivity-KZOrwVeK.d.mts.map +1 -0
  188. package/dist/{reply-B5kZ6VGv.mjs → reply-ChoI5SvM.mjs} +3 -3
  189. package/dist/{reply-B5kZ6VGv.mjs.map → reply-ChoI5SvM.mjs.map} +1 -1
  190. package/dist/{request-id-B_n-3A16.d.mts → request-id-B9Myiv75.d.mts} +2 -1
  191. package/dist/request-id-B9Myiv75.d.mts.map +1 -0
  192. package/dist/{request-logger-BV1C5r5q.d.mts → request-logger-CYyAuPmo.d.mts} +6 -1
  193. package/dist/request-logger-CYyAuPmo.d.mts.map +1 -0
  194. package/dist/{request-scope-D2WQwatk.mjs → request-scope-BfSNdmz9.mjs} +3 -3
  195. package/dist/{request-scope-D2WQwatk.mjs.map → request-scope-BfSNdmz9.mjs.map} +1 -1
  196. package/dist/{respond-C6ohI69y.mjs → respond-1BjaDME9.mjs} +2 -2
  197. package/dist/{respond-C6ohI69y.mjs.map → respond-1BjaDME9.mjs.map} +1 -1
  198. package/dist/rolldown-runtime-B5KeNctS.mjs +11 -0
  199. package/dist/{route-flag-CHiMvgar.mjs → route-flag-B6ZmhkfI.mjs} +3 -3
  200. package/dist/{route-flag-CHiMvgar.mjs.map → route-flag-B6ZmhkfI.mjs.map} +1 -1
  201. package/dist/{route-policy-ckK7N1eN.mjs → route-policy-BG--gAcF.mjs} +2 -2
  202. package/dist/route-policy-BG--gAcF.mjs.map +1 -0
  203. package/dist/{router-builder-Dtyya4qP.d.mts → router-builder-BkIW_qjz.d.mts} +3 -2
  204. package/dist/router-builder-BkIW_qjz.d.mts.map +1 -0
  205. package/dist/{router-builder-D2cly8Wt.mjs → router-builder-DHKtp4I8.mjs} +3 -3
  206. package/dist/router-builder-DHKtp4I8.mjs.map +1 -0
  207. package/dist/{runtime-D9TN6CpL.mjs → runtime-CUfFIHiC.mjs} +3 -3
  208. package/dist/runtime-CUfFIHiC.mjs.map +1 -0
  209. package/dist/{session-CXWu2rXW.d.mts → session-DPTbfwKO.d.mts} +40 -1
  210. package/dist/session-DPTbfwKO.d.mts.map +1 -0
  211. package/dist/{settings-v2N3V8Bl.mjs → settings-I7GUX5ps.mjs} +3 -3
  212. package/dist/{settings-v2N3V8Bl.mjs.map → settings-I7GUX5ps.mjs.map} +1 -1
  213. package/dist/{token-DtW16tw3.mjs → token-uWfhVlfe.mjs} +1 -1
  214. package/dist/{upload-eNNueUxR.d.mts → upload-O3VTcODy.d.mts} +3 -3
  215. package/dist/{upload-eNNueUxR.d.mts.map → upload-O3VTcODy.d.mts.map} +1 -1
  216. package/dist/{upload-config-BXjBiNjC.mjs → upload-config-BXqBuyza.mjs} +2 -2
  217. package/dist/{upload-config-BXjBiNjC.mjs.map → upload-config-BXqBuyza.mjs.map} +1 -1
  218. package/dist/url-for-CuMaQ2wS.mjs +12 -0
  219. package/dist/url-for-CuMaQ2wS.mjs.map +1 -0
  220. package/dist/{validate-BbthfLBb.d.mts → validate-CTgfm7oE.d.mts} +2 -2
  221. package/dist/{validate-BbthfLBb.d.mts.map → validate-CTgfm7oE.d.mts.map} +1 -1
  222. package/dist/{view-renderer-C4sMEruA.mjs → view-renderer-Bf1Wy-DQ.mjs} +3 -3
  223. package/dist/view-renderer-Bf1Wy-DQ.mjs.map +1 -0
  224. package/dist/{web-crypto-SXVOPDxW.mjs → web-crypto-JzoGmiG0.mjs} +2 -2
  225. package/dist/{web-crypto-SXVOPDxW.mjs.map → web-crypto-JzoGmiG0.mjs.map} +1 -1
  226. package/dist/web.d.mts +6 -6
  227. package/dist/web.d.mts.map +1 -1
  228. package/dist/web.mjs +2 -2
  229. package/dist/web.mjs.map +1 -1
  230. package/package.json +10 -10
  231. package/dist/adapter-B64IOivZ.d.mts.map +0 -1
  232. package/dist/allowed-hosts-U12_gESr.d.mts.map +0 -1
  233. package/dist/application-BzimU62Q.mjs +0 -14
  234. package/dist/application-BzimU62Q.mjs.map +0 -1
  235. package/dist/application-CGcY8SZZ.d.mts.map +0 -1
  236. package/dist/bootstrap-Bvk3BWJX.mjs.map +0 -1
  237. package/dist/breach-padding-DfT9MXGb.d.mts.map +0 -1
  238. package/dist/container-4iJdDkRH.d.mts +0 -3
  239. package/dist/context-BvZLaTeE.mjs.map +0 -1
  240. package/dist/context-errors-BZVS0B1O.mjs.map +0 -1
  241. package/dist/contributor-runner-fdKy6Tme.mjs.map +0 -1
  242. package/dist/core-CCIpjo6g.mjs +0 -12
  243. package/dist/core-CCIpjo6g.mjs.map +0 -1
  244. package/dist/cors-J-q6PuSU.d.mts.map +0 -1
  245. package/dist/cron-DGV1AE0R.d.mts.map +0 -1
  246. package/dist/csrf-DjtJPgA3.d.mts.map +0 -1
  247. package/dist/decorators-BAD8qjuq.d.mts.map +0 -1
  248. package/dist/define-adapter-DMo6og81.mjs.map +0 -1
  249. package/dist/di-hooks-DCqt2yJ9.mjs.map +0 -1
  250. package/dist/errors-DZGuPLoZ.d.mts.map +0 -1
  251. package/dist/helmet-Rwkbp9IS.d.mts.map +0 -1
  252. package/dist/index-ZbCnCyQx.d.mts.map +0 -1
  253. package/dist/jobs-CuZqVDDG.mjs.map +0 -1
  254. package/dist/kv-stores-C9CJ3xCB.mjs.map +0 -1
  255. package/dist/kv-stores-wTD3VDPB.d.mts.map +0 -1
  256. package/dist/observers-B4VnKAHK.mjs.map +0 -1
  257. package/dist/query-BwUR-ssX.mjs.map +0 -1
  258. package/dist/rate-limit-DMiV6bAq.d.mts.map +0 -1
  259. package/dist/reactivity-Dski64km.d.mts.map +0 -1
  260. package/dist/request-id-B_n-3A16.d.mts.map +0 -1
  261. package/dist/request-logger-BV1C5r5q.d.mts.map +0 -1
  262. package/dist/rolldown-runtime-DuhQYUab.mjs +0 -11
  263. package/dist/route-policy-ckK7N1eN.mjs.map +0 -1
  264. package/dist/router-builder-D2cly8Wt.mjs.map +0 -1
  265. package/dist/router-builder-Dtyya4qP.d.mts.map +0 -1
  266. package/dist/runtime-D9TN6CpL.mjs.map +0 -1
  267. package/dist/session-CXWu2rXW.d.mts.map +0 -1
  268. package/dist/url-for-C4Eomib7.mjs +0 -12
  269. package/dist/url-for-C4Eomib7.mjs.map +0 -1
  270. package/dist/view-renderer-C4sMEruA.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"upload.mjs","names":[],"sources":["../../../src/http/middleware/upload.ts"],"sourcesContent":["import { HttpException, HttpStatus } from '../../core/errors'\nimport { unlink } from 'node:fs/promises'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n ConnectHandler as RequestHandler,\n} from '../connect'\nimport type { Options as MulterOptions } from 'multer'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core'\n\n// `multer` is an optional peer dependency, imported when the first upload\n// arrives — adopters who never take uploads don't need it installed. An\n// `import()`, not `createRequire`: a bundler follows it, so a Netlify or\n// Vercel function built by `kick build:*` carries multer with it.\ntype MulterFactory = typeof import('multer')\ntype Multer = ReturnType<MulterFactory>\nlet _multer: Promise<MulterFactory> | undefined\n\nfunction loadMulter(): Promise<MulterFactory> {\n return (_multer ??= import('multer').then(\n // multer is CJS `export = multer`: the factory is the module's default.\n (mod) => ((mod as { default?: unknown }).default ?? mod) as MulterFactory,\n () => {\n throw new Error(\n \"@forinda/kickjs: file uploads require the 'multer' package, which is not installed. \" +\n 'Add it to your dependencies.',\n )\n },\n ))\n}\n\n// Pure upload core (MIME map, type filter, applyUploadConfig) moved to\n// `./upload-config` so the edge-safe web entry can use it without this\n// module's node-only surface. Re-exported here for compatibility.\nexport {\n buildFileTypeFilter,\n resolveMimeTypes,\n applyUploadConfig,\n type UploadedFileLike,\n type UploadedFile,\n type UploadStorageEngine,\n type RawUploadPart,\n} from './upload-config'\nimport { Transform, type Writable } from 'node:stream'\nimport { tooLarge } from '../body-policy'\nimport {\n MAX_UPLOAD_FIELDS,\n UPLOAD_FIELDS_ALLOWANCE,\n buildFileTypeFilter,\n normalizeOriginalName,\n serverFileName,\n tooManyFiles,\n uploadLimits,\n type UploadedFile,\n type UploadStorageEngine,\n} from './upload-config'\n\n/**\n * Upload options for the middleware.\n * Extends BaseUploadOptions from core (shared with @FileUpload decorator)\n * and adds Multer-specific storage options.\n */\nexport interface UploadOptions extends BaseUploadOptions {\n /** Multer storage engine (default: memory storage) */\n storage?: UploadStorageEngine\n /** Multer dest for disk storage shorthand */\n dest?: string\n}\n\n/**\n * Turn multer's own errors into the exceptions the other runtimes raise.\n *\n * multer reports a file over the limit as `MulterError: File too large`, a\n * plain error the handler maps to 500 — so an oversized upload was reported as\n * a server fault on Express while Fastify and h3 answered 413. The message is\n * matched to `applyUploadConfig` so the response does not depend on the engine.\n */\nfunction translateMulterErrors(\n mw: RequestHandler,\n options: UploadOptions,\n files?: { field: string; max: number },\n): RequestHandler {\n const maxSize = options.maxSize ?? 5 * 1024 * 1024\n return (req, res, next) => {\n mw(req, res, (err?: unknown) => {\n // multer reports one file more than the field takes as an unexpected one.\n if (\n files &&\n (err as { code?: string } | undefined)?.code === 'LIMIT_UNEXPECTED_FILE' &&\n (err as { field?: string }).field === files.field\n ) {\n return next(tooManyFiles(files.max))\n }\n if (err && (err as { code?: string }).code === 'LIMIT_FILE_SIZE') {\n const name = (err as { field?: string }).field ?? 'file'\n return next(\n new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${name} exceeds the ${maxSize}-byte limit`,\n ),\n )\n }\n if (!err) {\n try {\n nameUploads(req as { file?: unknown; files?: unknown }, options)\n } catch (error) {\n return next(error as never)\n }\n }\n next(err as never)\n })\n }\n}\n\n/**\n * The names every engine gives an upload: the client's name normalized, and a\n * server-side `filename` — kept when disk storage already wrote the file under one.\n */\nfunction nameUploads(req: { file?: unknown; files?: unknown }, options: UploadOptions) {\n const files = [req.file, ...(Array.isArray(req.files) ? req.files : [])]\n for (const file of files as Array<UploadedFile | undefined>) {\n if (!file) continue\n file.originalname = normalizeOriginalName(file.originalname)\n file.filename ??= serverFileName(file, options)\n }\n}\n\nfunction createMulter(options: UploadOptions) {\n const limits: MulterOptions['limits'] = {\n fileSize: options.maxSize ?? 5 * 1024 * 1024,\n fields: MAX_UPLOAD_FIELDS,\n fieldSize: UPLOAD_FIELDS_ALLOWANCE,\n }\n\n let fileFilter: MulterOptions['fileFilter'] | undefined\n if (options.allowedTypes) {\n const typeAllowed = buildFileTypeFilter(options.allowedTypes, options.customMimeMap)\n fileFilter = (_req, file, cb) => {\n if (typeAllowed(file.mimetype, file.originalname)) {\n cb(null, true)\n } else {\n // Same exception the Fastify and h3 path raises from\n // `applyUploadConfig`. A plain Error here reached the handler as a 500,\n // so Express blamed itself for the client's file — and leaked a multer\n // stack doing it.\n cb(\n new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${file.mimetype} is not allowed`,\n ),\n )\n }\n }\n }\n\n const multerOptions: MulterOptions = {\n limits,\n // busboy reads a part's filename as latin1 unless told otherwise, so a\n // UTF-8 name — 中文, an emoji — arrived as mojibake (\"中æ\").\n defParamCharset: 'utf8',\n ...(fileFilter ? { fileFilter } : {}),\n ...(options.storage ? { storage: options.storage } : {}),\n ...(options.dest ? { dest: options.dest } : {}),\n }\n\n // Built on the first request that needs it, then reused.\n let built: Promise<Multer> | undefined\n const lazy = (pick: (multer: Multer) => RequestHandler): RequestHandler => {\n let handler: Promise<RequestHandler> | undefined\n return (req, res, next) => {\n handler ??= (built ??= loadMulter().then((multer) => multer(multerOptions))).then(pick)\n handler.then(\n (run) => run(req, res, next),\n (err) => {\n // Not cached: multer installed while `kick dev` runs works on the next upload.\n handler = built = _multer = undefined\n next(err)\n },\n )\n }\n }\n return {\n single: (field: string) => lazy((m) => m.single(field) as RequestHandler),\n array: (field: string, maxCount: number) =>\n lazy((m) => m.array(field, maxCount) as RequestHandler),\n none: () => lazy((m) => m.none() as RequestHandler),\n }\n}\n\n/**\n * Single file upload middleware. Attaches the file to `req.file`.\n *\n * @example\n * ```ts\n * @Post('/avatar')\n * @Middleware(upload.single('avatar', { maxSize: 2 * 1024 * 1024, allowedTypes: ['jpg', 'png'] }))\n * async uploadAvatar(ctx: RequestContext) {\n * ctx.json({ filename: ctx.file.originalname })\n * }\n * ```\n */\n/**\n * The handler, callable both ways it gets used: as Express middleware\n * `(req, res, next)` — `middlewares: [upload.single(...)]`, and what\n * `@FileUpload` builds — and as a route middleware `(ctx, next)`, which is\n * how `@Middleware(upload.single(...))` calls it. Called the second way,\n * Multer got the context as its request and failed on every upload.\n */\nfunction bothConventions(handler: RequestHandler): RequestHandler {\n return ((first: any, second: any, third?: any) => {\n const isRouteMiddleware =\n third === undefined &&\n typeof second === 'function' &&\n first !== null &&\n typeof first === 'object' &&\n 'req' in first &&\n 'res' in first\n if (!isRouteMiddleware) return handler(first, second, third)\n return new Promise<void>((resolve, reject) => {\n handler(first.req, first.res, (err?: unknown) => {\n if (err) return reject(err)\n resolve()\n second()\n })\n })\n }) as RequestHandler\n}\n\n/**\n * Hold a multipart body to `limit` bytes while multer reads it: by\n * Content-Length up front, and counted as it streams for a body that doesn't\n * declare one. multer has a per-file and per-field size but no total, so\n * without this a request could carry any number of fields.\n */\nfunction capBody(mw: RequestHandler, limit: number): RequestHandler {\n return (req, res, next) => {\n if (Number(req.headers['content-length']) > limit) return next(tooLarge(limit))\n if (typeof req.pipe !== 'function') return mw(req, res, next)\n const pipe = req.pipe.bind(req)\n // multer reads the request with `req.pipe(busboy)`; count what passes.\n req.pipe = (<T extends NodeJS.WritableStream>(destination: T): T => {\n let received = 0\n const counter = new Transform({\n transform(chunk: Buffer, _encoding, done) {\n received += chunk.length\n if (received <= limit) return done(null, chunk)\n // busboy's error reaches multer, which hands it to `next`.\n if (received - chunk.length <= limit) {\n ;(destination as unknown as Writable).destroy(tooLarge(limit))\n }\n done()\n },\n })\n pipe(counter)\n return counter.pipe(destination)\n }) as typeof req.pipe\n mw(req, res, next)\n }\n}\n\nfunction single(fieldName: string, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n const { total } = uploadLimits({ mode: 'single', maxSize: options.maxSize })\n return bothConventions(\n capBody(\n translateMulterErrors(m.single(fieldName), options, { field: fieldName, max: 1 }),\n total,\n ),\n )\n}\n\n/**\n * Multiple file upload middleware. Attaches files to `req.files`.\n */\nfunction array(fieldName: string, maxCount = 10, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n const { total } = uploadLimits({ mode: 'array', maxSize: options.maxSize, maxCount })\n return bothConventions(\n capBody(\n translateMulterErrors(m.array(fieldName, maxCount), options, {\n field: fieldName,\n max: maxCount,\n }),\n total,\n ),\n )\n}\n\n/**\n * No file upload — just parse multipart form data without file fields.\n */\nfunction none(options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n const { total } = uploadLimits({ mode: 'none' })\n return bothConventions(capBody(translateMulterErrors(m.none(), options), total))\n}\n\n/**\n * Removes temporary files from disk after the response is sent.\n * Attach this as Express middleware after the upload middleware.\n * Works with both `req.file` (single) and `req.files` (array).\n *\n * @example\n * ```ts\n * @Post('/process')\n * @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())\n * async processDocument(ctx: RequestContext) {\n * ctx.json({ ok: true })\n * }\n * ```\n */\nexport function cleanupFiles() {\n return (req: Request, res: Response, next: NextFunction) => {\n res.on('finish', async () => {\n const files: any[] = []\n\n if ((req as any).file?.path) {\n files.push((req as any).file)\n }\n if (Array.isArray((req as any).files)) {\n for (const f of (req as any).files) {\n if (f?.path) files.push(f)\n }\n }\n\n for (const file of files) {\n try {\n await unlink(file.path)\n } catch {\n // File may already be moved/deleted by the handler — ignore\n }\n }\n })\n\n next()\n }\n}\n\n/**\n * Build upload middleware from a @FileUpload decorator config.\n * Used internally by the router builder when it detects FILE_UPLOAD metadata.\n * Accepts the same FileUploadConfig interface used by the @FileUpload decorator.\n */\nexport function buildUploadMiddleware(config: FileUploadConfig): RequestHandler {\n const options: UploadOptions = {}\n if (config.maxSize) options.maxSize = config.maxSize\n if (config.allowedTypes) options.allowedTypes = config.allowedTypes\n if (config.customMimeMap) options.customMimeMap = config.customMimeMap\n if (config.rename) options.rename = config.rename\n\n const fieldName = config.fieldName ?? 'file'\n\n switch (config.mode) {\n case 'single':\n return single(fieldName, options)\n case 'array':\n return array(fieldName, config.maxCount ?? 10, options)\n case 'none':\n return none(options)\n }\n}\n\n/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */\nexport const upload = { single, array, none }\n"],"mappings":";;;;;;;;;;A,ybAiBA,IAAI,QAEJ,SAAS,YAAqC,CAC5C,MAAQ,WAAY,OAAO,SAAS,CAAC,KAElC,KAAU,IAA8B,SAAW,QAC9C,CACJ,MAAU,MACR,kHAEF,CACF,CACF,CACF,CAgDA,SAAS,sBACP,GACA,QACA,MACgB,CAChB,IAAM,QAAU,QAAQ,SAAW,QACnC,OAAQ,IAAK,IAAK,OAAS,CACzB,GAAG,IAAK,IAAM,KAAkB,CAE9B,GACE,OACC,KAAuC,OAAS,yBAChD,IAA2B,QAAU,MAAM,MAE5C,OAAO,KAAK,aAAa,MAAM,GAAG,CAA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B,OAA0C,CAC9E,IAAM,QAAyB,CAAC,EAC5B,OAAO,UAAS,QAAQ,QAAU,OAAO,SACzC,OAAO,eAAc,QAAQ,aAAe,OAAO,cACnD,OAAO,gBAAe,QAAQ,cAAgB,OAAO,eACrD,OAAO,SAAQ,QAAQ,OAAS,OAAO,QAE3C,IAAM,UAAY,OAAO,WAAa,OAEtC,OAAQ,OAAO,KAAf,CACE,IAAK,SACH,OAAO,OAAO,UAAW,OAAO,EAClC,IAAK,QACH,OAAO,MAAM,UAAW,OAAO,UAAY,GAAI,OAAO,EACxD,IAAK,OACH,OAAO,KAAK,OAAO,CACvB,CACF,CAGA,MAAa,OAAS,CAAE,OAAQ,MAAO,IAAK,E"}
1
+ {"version":3,"file":"upload.mjs","names":[],"sources":["../../../src/http/middleware/upload.ts"],"sourcesContent":["import { HttpException, HttpStatus } from '../../core/errors'\nimport { unlink } from 'node:fs/promises'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n ConnectHandler as RequestHandler,\n} from '../connect'\nimport type { Options as MulterOptions } from 'multer'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core'\n\n// `multer` is an optional peer dependency, imported when the first upload\n// arrives — adopters who never take uploads don't need it installed. An\n// `import()`, not `createRequire`: a bundler follows it, so a Netlify or\n// Vercel function built by `kick build:*` carries multer with it.\ntype MulterFactory = typeof import('multer')\ntype Multer = ReturnType<MulterFactory>\nlet _multer: Promise<MulterFactory> | undefined\n\nfunction loadMulter(): Promise<MulterFactory> {\n return (_multer ??= import('multer').then(\n // multer is CJS `export = multer`: the factory is the module's default.\n (mod) => ((mod as { default?: unknown }).default ?? mod) as MulterFactory,\n () => {\n throw new Error(\n \"@forinda/kickjs: file uploads require the 'multer' package, which is not installed. \" +\n 'Add it to your dependencies.',\n )\n },\n ))\n}\n\n// Pure upload core (MIME map, type filter, applyUploadConfig) moved to\n// `./upload-config` so the edge-safe web entry can use it without this\n// module's node-only surface. Re-exported here for compatibility.\nexport {\n buildFileTypeFilter,\n resolveMimeTypes,\n applyUploadConfig,\n type UploadedFileLike,\n type UploadedFile,\n type UploadStorageEngine,\n type RawUploadPart,\n} from './upload-config'\nimport { Transform, type Writable } from 'node:stream'\nimport { tooLarge } from '../body-policy'\nimport {\n MAX_UPLOAD_FIELDS,\n UPLOAD_FIELDS_ALLOWANCE,\n buildFileTypeFilter,\n normalizeOriginalName,\n serverFileName,\n tooManyFiles,\n uploadLimits,\n type UploadedFile,\n type UploadStorageEngine,\n} from './upload-config'\n\n/**\n * Upload options for the middleware.\n * Extends BaseUploadOptions from core (shared with @FileUpload decorator)\n * and adds Multer-specific storage options.\n */\nexport interface UploadOptions extends BaseUploadOptions {\n /** Multer storage engine (default: memory storage) */\n storage?: UploadStorageEngine\n /** Multer dest for disk storage shorthand */\n dest?: string\n}\n\n/**\n * Turn multer's own errors into the exceptions the other runtimes raise.\n *\n * multer reports a file over the limit as `MulterError: File too large`, a\n * plain error the handler maps to 500 — so an oversized upload was reported as\n * a server fault on Express while Fastify and h3 answered 413. The message is\n * matched to `applyUploadConfig` so the response does not depend on the engine.\n */\nfunction translateMulterErrors(\n mw: RequestHandler,\n options: UploadOptions,\n files?: { field: string; max: number },\n): RequestHandler {\n const maxSize = options.maxSize ?? 5 * 1024 * 1024\n return (req, res, next) => {\n mw(req, res, (err?: unknown) => {\n // multer reports one file more than the field takes as an unexpected one.\n if (\n files &&\n (err as { code?: string } | undefined)?.code === 'LIMIT_UNEXPECTED_FILE' &&\n (err as { field?: string }).field === files.field\n ) {\n return next(tooManyFiles(files.max))\n }\n if (err && (err as { code?: string }).code === 'LIMIT_FILE_SIZE') {\n const name = (err as { field?: string }).field ?? 'file'\n return next(\n new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${name} exceeds the ${maxSize}-byte limit`,\n ),\n )\n }\n if (!err) {\n try {\n nameUploads(req as { file?: unknown; files?: unknown }, options)\n } catch (error) {\n return next(error as never)\n }\n }\n next(err as never)\n })\n }\n}\n\n/**\n * The names every engine gives an upload: the client's name normalized, and a\n * server-side `filename` — kept when disk storage already wrote the file under one.\n */\nfunction nameUploads(req: { file?: unknown; files?: unknown }, options: UploadOptions) {\n const files = [req.file, ...(Array.isArray(req.files) ? req.files : [])]\n for (const file of files as Array<UploadedFile | undefined>) {\n if (!file) continue\n file.originalname = normalizeOriginalName(file.originalname)\n file.filename ??= serverFileName(file, options)\n }\n}\n\nfunction createMulter(options: UploadOptions) {\n const limits: MulterOptions['limits'] = {\n fileSize: options.maxSize ?? 5 * 1024 * 1024,\n fields: MAX_UPLOAD_FIELDS,\n fieldSize: UPLOAD_FIELDS_ALLOWANCE,\n }\n\n let fileFilter: MulterOptions['fileFilter'] | undefined\n if (options.allowedTypes) {\n const typeAllowed = buildFileTypeFilter(options.allowedTypes, options.customMimeMap)\n fileFilter = (_req, file, cb) => {\n if (typeAllowed(file.mimetype, file.originalname)) {\n cb(null, true)\n } else {\n // Same exception the Fastify and h3 path raises from\n // `applyUploadConfig`. A plain Error here reached the handler as a 500,\n // so Express blamed itself for the client's file — and leaked a multer\n // stack doing it.\n cb(\n new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${file.mimetype} is not allowed`,\n ),\n )\n }\n }\n }\n\n const multerOptions: MulterOptions = {\n limits,\n // busboy reads a part's filename as latin1 unless told otherwise, so a\n // UTF-8 name — 中文, an emoji — arrived as mojibake (\"中æ\").\n defParamCharset: 'utf8',\n ...(fileFilter ? { fileFilter } : {}),\n ...(options.storage ? { storage: options.storage } : {}),\n ...(options.dest ? { dest: options.dest } : {}),\n }\n\n // Built on the first request that needs it, then reused.\n let built: Promise<Multer> | undefined\n const lazy = (pick: (multer: Multer) => RequestHandler): RequestHandler => {\n let handler: Promise<RequestHandler> | undefined\n return (req, res, next) => {\n handler ??= (built ??= loadMulter().then((multer) => multer(multerOptions))).then(pick)\n handler.then(\n (run) => run(req, res, next),\n (err) => {\n // Not cached: multer installed while `kick dev` runs works on the next upload.\n handler = built = _multer = undefined\n next(err)\n },\n )\n }\n }\n return {\n single: (field: string) => lazy((m) => m.single(field) as RequestHandler),\n array: (field: string, maxCount: number) =>\n lazy((m) => m.array(field, maxCount) as RequestHandler),\n none: () => lazy((m) => m.none() as RequestHandler),\n }\n}\n\n/**\n * Single file upload middleware. Attaches the file to `req.file`.\n *\n * @example\n * ```ts\n * @Post('/avatar')\n * @Middleware(upload.single('avatar', { maxSize: 2 * 1024 * 1024, allowedTypes: ['jpg', 'png'] }))\n * async uploadAvatar(ctx: RequestContext) {\n * ctx.json({ filename: ctx.file.originalname })\n * }\n * ```\n */\n/**\n * The handler, callable both ways it gets used: as Express middleware\n * `(req, res, next)` — `middlewares: [upload.single(...)]`, and what\n * `@FileUpload` builds — and as a route middleware `(ctx, next)`, which is\n * how `@Middleware(upload.single(...))` calls it. Called the second way,\n * Multer got the context as its request and failed on every upload.\n */\nfunction bothConventions(handler: RequestHandler): RequestHandler {\n return ((first: any, second: any, third?: any) => {\n const isRouteMiddleware =\n third === undefined &&\n typeof second === 'function' &&\n first !== null &&\n typeof first === 'object' &&\n 'req' in first &&\n 'res' in first\n if (!isRouteMiddleware) return handler(first, second, third)\n return new Promise<void>((resolve, reject) => {\n handler(first.req, first.res, (err?: unknown) => {\n if (err) return reject(err)\n resolve()\n second()\n })\n })\n }) as RequestHandler\n}\n\n/**\n * Hold a multipart body to `limit` bytes while multer reads it: by\n * Content-Length up front, and counted as it streams for a body that doesn't\n * declare one. multer has a per-file and per-field size but no total, so\n * without this a request could carry any number of fields.\n */\nfunction capBody(mw: RequestHandler, limit: number): RequestHandler {\n return (req, res, next) => {\n if (Number(req.headers['content-length']) > limit) return next(tooLarge(limit))\n if (typeof req.pipe !== 'function') return mw(req, res, next)\n const pipe = req.pipe.bind(req)\n // multer reads the request with `req.pipe(busboy)`; count what passes.\n req.pipe = (<T extends NodeJS.WritableStream>(destination: T): T => {\n let received = 0\n const counter = new Transform({\n transform(chunk: Buffer, _encoding, done) {\n received += chunk.length\n if (received <= limit) return done(null, chunk)\n // busboy's error reaches multer, which hands it to `next`.\n if (received - chunk.length <= limit) {\n ;(destination as unknown as Writable).destroy(tooLarge(limit))\n }\n done()\n },\n })\n pipe(counter)\n return counter.pipe(destination)\n }) as typeof req.pipe\n mw(req, res, next)\n }\n}\n\nfunction single(fieldName: string, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n const { total } = uploadLimits({ mode: 'single', maxSize: options.maxSize })\n return bothConventions(\n capBody(\n translateMulterErrors(m.single(fieldName), options, { field: fieldName, max: 1 }),\n total,\n ),\n )\n}\n\n/**\n * Multiple file upload middleware. Attaches files to `req.files`.\n */\nfunction array(fieldName: string, maxCount = 10, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n const { total } = uploadLimits({ mode: 'array', maxSize: options.maxSize, maxCount })\n return bothConventions(\n capBody(\n translateMulterErrors(m.array(fieldName, maxCount), options, {\n field: fieldName,\n max: maxCount,\n }),\n total,\n ),\n )\n}\n\n/**\n * No file upload — just parse multipart form data without file fields.\n */\nfunction none(options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n const { total } = uploadLimits({ mode: 'none' })\n return bothConventions(capBody(translateMulterErrors(m.none(), options), total))\n}\n\n/**\n * Removes temporary files from disk after the response is sent.\n * Attach this as Express middleware after the upload middleware.\n * Works with both `req.file` (single) and `req.files` (array).\n *\n * @example\n * ```ts\n * @Post('/process')\n * @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())\n * async processDocument(ctx: RequestContext) {\n * ctx.json({ ok: true })\n * }\n * ```\n */\nexport function cleanupFiles() {\n return (req: Request, res: Response, next: NextFunction) => {\n res.on('finish', async () => {\n const files: any[] = []\n\n if ((req as any).file?.path) {\n files.push((req as any).file)\n }\n if (Array.isArray((req as any).files)) {\n for (const f of (req as any).files) {\n if (f?.path) files.push(f)\n }\n }\n\n for (const file of files) {\n try {\n await unlink(file.path)\n } catch {\n // File may already be moved/deleted by the handler — ignore\n }\n }\n })\n\n next()\n }\n}\n\n/**\n * Build upload middleware from a @FileUpload decorator config.\n * Used internally by the router builder when it detects FILE_UPLOAD metadata.\n * Accepts the same FileUploadConfig interface used by the @FileUpload decorator.\n */\nexport function buildUploadMiddleware(config: FileUploadConfig): RequestHandler {\n const options: UploadOptions = {}\n if (config.maxSize) options.maxSize = config.maxSize\n if (config.allowedTypes) options.allowedTypes = config.allowedTypes\n if (config.customMimeMap) options.customMimeMap = config.customMimeMap\n if (config.rename) options.rename = config.rename\n\n const fieldName = config.fieldName ?? 'file'\n\n switch (config.mode) {\n case 'single':\n return single(fieldName, options)\n case 'array':\n return array(fieldName, config.maxCount ?? 10, options)\n case 'none':\n return none(options)\n }\n}\n\n/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */\nexport const upload = { single, array, none }\n"],"mappings":";;;;;;;;;;A,ybAiBA,IAAI,QAEJ,SAAS,YAAqC,CAC5C,MAAQ,WAAY,OAAO,SAAS,CAAC,KAElC,KAAU,IAA8B,SAAW,QAC9C,CACJ,MAAU,MACR,kHAEF,CACF,CACF,CACF,CAgDA,SAAS,sBACP,GACA,QACA,MACgB,CAChB,IAAM,QAAU,QAAQ,SAAW,QACnC,OAAQ,IAAK,IAAK,OAAS,CACzB,GAAG,IAAK,IAAM,KAAkB,CAE9B,GACE,OACC,KAAuC,OAAS,yBAChD,IAA2B,QAAU,MAAM,MAE5C,OAAO,KAAK,aAAa,MAAM,GAAG,CAAC,EAErC,GAAI,KAAQ,IAA0B,OAAS,kBAAmB,CAChE,IAAM,KAAQ,IAA2B,OAAS,OAClD,OAAO,KACL,IAAI,cACF,WAAW,kBACX,QAAQ,KAAK,eAAe,QAAQ,YACtC,CACF,CACF,CACA,GAAI,CAAC,IACH,GAAI,CACF,YAAY,IAA4C,OAAO,CACjE,OAAS,MAAO,CACd,OAAO,KAAK,KAAc,CAC5B,CAEF,KAAK,GAAY,CACnB,CAAC,CACH,CACF,CAMA,SAAS,YAAY,IAA0C,QAAwB,CACrF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GAAI,OAAO,EACxD,IAAK,OACH,OAAO,KAAK,OAAO,CACvB,CACF,CAGA,MAAa,OAAS,CAAE,OAAQ,MAAO,IAAK,E"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as validate, i as defaultValidationError, n as ValidationFailure, r as ValidationSchema, t as ValidationErrorFactory } from "../../validate-BbthfLBb.mjs";
2
+ import { a as validate, i as defaultValidationError, n as ValidationFailure, r as ValidationSchema, t as ValidationErrorFactory } from "../../validate-CTgfm7oE.mjs";
3
3
  export { ValidationErrorFactory, ValidationFailure, ValidationSchema, defaultValidationError, validate };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { C as ViewAdapterOptions, S as ViewAdapter, w as viewDirs } from "../../application-CGcY8SZZ.mjs";
2
+ import { C as ViewAdapterOptions, S as ViewAdapter, w as viewDirs } from "../../application-ClCq0AgY.mjs";
3
3
  export { ViewAdapter, ViewAdapterOptions, viewDirs };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Logger}from"../../core/logger.mjs";import"../../core-CCIpjo6g.mjs";import{t as defineAdapter}from"../../define-adapter-DMo6og81.mjs";import{dirname,resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app:engineApp}){let app=engineApp,{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,viewDirs(viewsDir)),log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(`, `)})`)}})});function viewDirs(viewsDir){let root=resolve(process.env.KICK_APP_ROOT??process.cwd(),viewsDir),entry=process.argv[1]?resolve(dirname(resolve(process.argv[1])),viewsDir):root;return[.../* @__PURE__ */ new Set([root,entry])]}export{ViewAdapter,viewDirs};
11
+ import{Logger}from"../../core/logger.mjs";import"../../core-Dqzah_BX.mjs";import{t as defineAdapter}from"../../define-adapter-DCjNTP6m.mjs";import{dirname,resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app:engineApp}){let app=engineApp,{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,viewDirs(viewsDir)),log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(`, `)})`)}})});function viewDirs(viewsDir){let root=resolve(process.env.KICK_APP_ROOT??process.cwd(),viewsDir),entry=process.argv[1]?resolve(dirname(resolve(process.argv[1])),viewsDir):root;return[.../* @__PURE__ */ new Set([root,entry])]}export{ViewAdapter,viewDirs};
12
12
  //# sourceMappingURL=views.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { dirname, resolve } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\n\nconst log = Logger.for('ViewEngine')\n\nexport interface ViewAdapterOptions {\n /**\n * Template engine — pass the engine module or a render function.\n * Supported engines: ejs, pug, handlebars, nunjucks, or any\n * Express-compatible engine with a __express property.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * ViewAdapter({ engine: ejs, ext: 'ejs' })\n *\n * import pug from 'pug'\n * ViewAdapter({ engine: pug, ext: 'pug' })\n * ```\n */\n engine: any\n\n /** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */\n ext: string\n\n /**\n * Directory containing template files (default: 'src/views'), relative to\n * the project. Also looked up beside the running entry file, where\n * `copyDirs: ['src/views']` puts it in a build (`dist/src/views`), so a\n * deployment holding only `dist/` still finds it.\n */\n viewsDir?: string\n\n /** Default layout template (optional — depends on engine) */\n layout?: string\n}\n\n/**\n * View/template adapter — pluggable template engine support for KickJS.\n *\n * Registers an Express view engine and sets the views directory.\n * Use `ctx.render()` in controllers to render templates.\n *\n * Migrated to the `defineAdapter()` factory in v4 — call without `new`.\n * The pre-v4 `new ViewAdapter({...})` form is gone; see\n * `docs/guide/migration-v3-to-v4.md` for the rename.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * import { ViewAdapter } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),\n * ],\n * })\n *\n * // In a controller:\n * @Get('/dashboard')\n * async dashboard(ctx: RequestContext) {\n * ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })\n * }\n * ```\n */\nexport const ViewAdapter = defineAdapter<ViewAdapterOptions>({\n name: 'ViewAdapter',\n build: (options) => ({\n beforeMount({ app: engineApp }) {\n // Express-only: template engines register on Express's app settings.\n const app = engineApp as {\n engine(ext: string, fn: unknown): unknown\n set(setting: string, value: unknown): unknown\n }\n const { engine, ext, viewsDir = 'src/views' } = options\n\n // Register the engine. Three resolution paths cover every\n // mainstream template engine + a fall-through for custom ones.\n if (engine.__express) {\n // EJS, Pug — have __express method\n app.engine(ext, engine.__express)\n } else if (typeof engine.renderFile === 'function') {\n // Engines with renderFile (nunjucks-style)\n app.engine(\n ext,\n (path: string, opts: any, callback: (err: Error | null, html?: string) => void) => {\n engine.renderFile(path, opts, callback)\n },\n )\n } else if (typeof engine === 'function') {\n // Custom render function: (path, options, callback) => void\n app.engine(ext, engine)\n } else {\n log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`)\n app.engine(ext, engine)\n }\n\n app.set('view engine', ext)\n app.set('views', viewDirs(viewsDir))\n\n log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(', ')})`)\n },\n }),\n})\n\n/**\n * Where to look for `viewsDir`: the project — `KICK_APP_ROOT` when set (the\n * Netlify and Vercel functions `kick build:*` writes set it to where\n * `deploy.include` files land), else the working directory — then beside the\n * running entry file (`node dist/index.js` → `dist/<viewsDir>`, where\n * `copyDirs` copies it). Express tries them in order.\n */\nexport function viewDirs(viewsDir: string): string[] {\n const root = resolve(process.env.KICK_APP_ROOT ?? process.cwd(), viewsDir)\n const entry = process.argv[1] ? resolve(dirname(resolve(process.argv[1])), viewsDir) : root\n return [...new Set([root, entry])]\n}\n"],"mappings":";;;;;;;;;;A,mLAGA,MAAM,IAAM,OAAO,IAAI,YAAY,EA+DtB,YAAc,cAAkC,CAC3D,KAAM,cACN,MAAQ,UAAa,CACnB,YAAY,CAAE,IAAK,WAAa,CAE9B,IAAM,IAAM,UAIN,CAAE,OAAQ,IAAK,SAAW,aAAgB,QAI5C,OAAO,UAET,IAAI,OAAO,IAAK,OAAO,SAAS,EACvB,OAAO,OAAO,YAAe,WAEtC,IAAI,OACF,KACC,KAAc,KAAW,WAAyD,CACjF,OAAO,WAAW,KAAM,KAAM,QAAQ,CACxC,CACF,GACS,OAAO,QAAW,YAI3B,IAAI,KAAK,eAAe,IAAI,sDAAsD,EAClF,IAAI,OAAO,IAAK,MAAM,GAGxB,IAAI,IAAI,cAAe,GAAG,EAC1B,IAAI,IAAI,QAAS,SAAS,QAAQ,CAAC,EAEnC,IAAI,MAAM,gBAAgB,IAAI,IAAI,SAAS,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,EAAE,CACpE,CACF,EACF,CAAC,EASD,SAAgB,SAAS,SAA4B,CACnD,IAAM,KAAO,QAAQ,QAAQ,IAAI,eAAiB,QAAQ,IAAI,EAAG,QAAQ,EACnE,MAAQ,QAAQ,KAAK,GAAK,QAAQ,QAAQ,QAAQ,QAAQ,KAAK,EAAE,CAAC,EAAG,QAAQ,EAAI,KACvF,MAAO,CAAC,mBAAG,IAAI,IAAI,CAAC,KAAM,KAAK,CAAC,CAAC,CACnC,C"}
1
+ {"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { dirname, resolve } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\n\nconst log = Logger.for('ViewEngine')\n\n/**\n * Options for {@link ViewAdapter}.\n *\n * @see https://kickjs.app/guide/view-engines\n */\nexport interface ViewAdapterOptions {\n /**\n * Template engine — pass the engine module or a render function.\n * Supported engines: ejs, pug, handlebars, nunjucks, or any\n * Express-compatible engine with a __express property.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * ViewAdapter({ engine: ejs, ext: 'ejs' })\n *\n * import pug from 'pug'\n * ViewAdapter({ engine: pug, ext: 'pug' })\n * ```\n */\n engine: any\n\n /** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */\n ext: string\n\n /**\n * Directory containing template files (default: 'src/views'), relative to\n * the project. Also looked up beside the running entry file, where\n * `copyDirs: ['src/views']` puts it in a build (`dist/src/views`), so a\n * deployment holding only `dist/` still finds it.\n */\n viewsDir?: string\n\n /** Default layout template (optional — depends on engine) */\n layout?: string\n}\n\n/**\n * View/template adapter — pluggable template engine support for KickJS.\n *\n * Registers an Express view engine and sets the views directory.\n * Use `ctx.render()` in controllers to render templates.\n *\n * Migrated to the `defineAdapter()` factory in v4 — call without `new`.\n * The pre-v4 `new ViewAdapter({...})` form is gone; see\n * https://kickjs.app/guide/migration-v3-to-v4#viewadapter-—-drop-the-new-keyword\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * import { ViewAdapter } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),\n * ],\n * })\n *\n * // In a controller:\n * @Get('/dashboard')\n * async dashboard(ctx: RequestContext) {\n * ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })\n * }\n * ```\n */\nexport const ViewAdapter = defineAdapter<ViewAdapterOptions>({\n name: 'ViewAdapter',\n build: (options) => ({\n beforeMount({ app: engineApp }) {\n // Express-only: template engines register on Express's app settings.\n const app = engineApp as {\n engine(ext: string, fn: unknown): unknown\n set(setting: string, value: unknown): unknown\n }\n const { engine, ext, viewsDir = 'src/views' } = options\n\n // Register the engine. Three resolution paths cover every\n // mainstream template engine + a fall-through for custom ones.\n if (engine.__express) {\n // EJS, Pug — have __express method\n app.engine(ext, engine.__express)\n } else if (typeof engine.renderFile === 'function') {\n // Engines with renderFile (nunjucks-style)\n app.engine(\n ext,\n (path: string, opts: any, callback: (err: Error | null, html?: string) => void) => {\n engine.renderFile(path, opts, callback)\n },\n )\n } else if (typeof engine === 'function') {\n // Custom render function: (path, options, callback) => void\n app.engine(ext, engine)\n } else {\n log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`)\n app.engine(ext, engine)\n }\n\n app.set('view engine', ext)\n app.set('views', viewDirs(viewsDir))\n\n log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(', ')})`)\n },\n }),\n})\n\n/**\n * Where to look for `viewsDir`: the project — `KICK_APP_ROOT` when set (the\n * Netlify and Vercel functions `kick build:*` writes set it to where\n * `deploy.include` files land), else the working directory — then beside the\n * running entry file (`node dist/index.js` → `dist/<viewsDir>`, where\n * `copyDirs` copies it). Express tries them in order.\n */\nexport function viewDirs(viewsDir: string): string[] {\n const root = resolve(process.env.KICK_APP_ROOT ?? process.cwd(), viewsDir)\n const entry = process.argv[1] ? resolve(dirname(resolve(process.argv[1])), viewsDir) : root\n return [...new Set([root, entry])]\n}\n"],"mappings":";;;;;;;;;;A,mLAGA,MAAM,IAAM,OAAO,IAAI,YAAY,EAoEtB,YAAc,cAAkC,CAC3D,KAAM,cACN,MAAQ,UAAa,CACnB,YAAY,CAAE,IAAK,WAAa,CAE9B,IAAM,IAAM,UAIN,CAAE,OAAQ,IAAK,SAAW,aAAgB,QAI5C,OAAO,UAET,IAAI,OAAO,IAAK,OAAO,SAAS,EACvB,OAAO,OAAO,YAAe,WAEtC,IAAI,OACF,KACC,KAAc,KAAW,WAAyD,CACjF,OAAO,WAAW,KAAM,KAAM,QAAQ,CACxC,CACF,GACS,OAAO,QAAW,YAI3B,IAAI,KAAK,eAAe,IAAI,sDAAsD,EAClF,IAAI,OAAO,IAAK,MAAM,GAGxB,IAAI,IAAI,cAAe,GAAG,EAC1B,IAAI,IAAI,QAAS,SAAS,QAAQ,CAAC,EAEnC,IAAI,MAAM,gBAAgB,IAAI,IAAI,SAAS,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,EAAE,CACpE,CACF,EACF,CAAC,EASD,SAAgB,SAAS,SAA4B,CACnD,IAAM,KAAO,QAAQ,QAAQ,IAAI,eAAiB,QAAQ,IAAI,EAAG,QAAQ,EACnE,MAAQ,QAAQ,KAAK,GAAK,QAAQ,QAAQ,QAAQ,QAAQ,KAAK,EAAE,CAAC,EAAG,QAAQ,EAAI,KACvF,MAAO,CAAC,mBAAG,IAAI,IAAI,CAAC,KAAM,KAAK,CAAC,CAAC,CACnC,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { A as TypedParsedQuery, C as PaginatedResponse, D as QueryFieldConfig, E as QueryBuilderAdapter, O as SortItem, S as FilterOperator, T as ParsedQuery, _ as CursorQuery, a as getQueryParsingDefaults, b as FieldsOf, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as CursorPosition, h as CursorPaginatedResponse, i as buildQueryParams, k as StringQueryFieldConfig, l as parseSearchQuery, m as CursorPaginateOptions, n as QueryRejectReason, o as parseFilters, p as ColumnQueryFieldConfig, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as CursorValue, w as PaginationParams, x as FilterItem, y as FILTER_OPERATORS } from "../../index-ZbCnCyQx.mjs";
2
+ import { A as TypedParsedQuery, C as PaginatedResponse, D as QueryFieldConfig, E as QueryBuilderAdapter, O as SortItem, S as FilterOperator, T as ParsedQuery, _ as CursorQuery, a as getQueryParsingDefaults, b as FieldsOf, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as CursorPosition, h as CursorPaginatedResponse, i as buildQueryParams, k as StringQueryFieldConfig, l as parseSearchQuery, m as CursorPaginateOptions, n as QueryRejectReason, o as parseFilters, p as ColumnQueryFieldConfig, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as CursorValue, w as PaginationParams, x as FilterItem, y as FILTER_OPERATORS } from "../../index-CtjmSXFy.mjs";
3
3
  export { type ColumnQueryFieldConfig, type CursorPaginateOptions, type CursorPaginatedResponse, type CursorPosition, type CursorQuery, type CursorValue, FILTER_OPERATORS, type FieldsOf, type FilterItem, type FilterOperator, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, type SortItem, type StringQueryFieldConfig, type TypedParsedQuery, buildQueryParams, getQueryParsingDefaults, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, resetQueryParsingDefaults, setQueryParsingDefaults };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-BwUR-ssX.mjs";
11
+ export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-Dr28oT30.mjs";
@@ -1,3 +1,3 @@
1
1
 
2
- import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-Dtyya4qP.mjs";
2
+ import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-BkIW_qjz.mjs";
3
3
  export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-D2cly8Wt.mjs";
11
+ export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-DHKtp4I8.mjs";
@@ -1,7 +1,8 @@
1
1
 
2
- import { t as BuildRoutesOptions } from "../../router-builder-Dtyya4qP.mjs";
2
+ /** `@forinda/kickjs/express` — the Express runtime and its native types. */
3
+ import { t as BuildRoutesOptions } from "../../router-builder-BkIW_qjz.mjs";
3
4
  import { n as ConnectHandler } from "../../connect-DamOelO8.mjs";
4
- import { d as HttpRuntime, h as RouteEntry } from "../../adapter-B64IOivZ.mjs";
5
+ import { d as HttpRuntime, h as RouteEntry } from "../../adapter-D_nUmKEQ.mjs";
5
6
  import { Express, Request, Response } from "express";
6
7
  /**
7
8
  * Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.
@@ -1 +1 @@
1
- {"version":3,"file":"express.d.mts","names":[],"sources":["../../../src/http/runtimes/express.ts","../../../src/http/runtimes/express-types.ts"],"mappings":";;;;;;;;;;;;;;wBAkDgB,kBAAkB,SAAS,eAAe;;;;;;;;;wBA4F1C,YACd,sBACA,UAAS,qBACR;;;;;wBAQa,kBAAkB;;;;;;;;UC9IjB;EACf,SAAS;EACT,UAAU;EACV,KAAK"}
1
+ {"version":3,"file":"express.d.mts","names":[],"sources":["../../../src/http/runtimes/express.ts","../../../src/http/runtimes/express-types.ts"],"mappings":";;;;;;;;;;;;;;;wBAkDgB,kBAAkB,SAAS,eAAe;;;;;;;;;wBA4F1C,YACd,sBACA,UAAS,qBACR;;;;;wBAQa,kBAAkB;;;;;;;;UC9IjB;EACf,SAAS;EACT,UAAU;EACV,KAAK"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as buildRoutes,n as expressRuntime,i as materializeRouter}from"../../express-f9CTA8qO.mjs";
11
+ export{t as buildRoutes,n as expressRuntime,i as materializeRouter}from"../../express-JAXx9MK0.mjs";
@@ -1,5 +1,5 @@
1
1
 
2
- import { d as HttpRuntime } from "../../adapter-B64IOivZ.mjs";
2
+ import { d as HttpRuntime } from "../../adapter-D_nUmKEQ.mjs";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  interface FastifyReplyLike {
5
5
  code(statusCode: number): FastifyReplyLike;
@@ -63,14 +63,14 @@ interface MultipartPart {
63
63
  }
64
64
  /**
65
65
  * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.
66
- * Per spec §10: Fastify's built-in pino logger is disabled (`logger: false`) so
66
+ * Fastify's built-in pino logger is disabled (`logger: false`) so
67
67
  * the kickjs `requestLogger` middleware stays the single log format.
68
68
  */
69
69
  export declare function fastifyRuntime(): HttpRuntime<FastifyAppLike>;
70
70
  /**
71
71
  * The Fastify runtime's engine-native types — what the runtime-typed escape
72
72
  * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`
73
- * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`
73
+ * augmentation pointing here. `AdapterContext.app` / `getRuntimeApp()`
74
74
  * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.
75
75
  * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.
76
76
  */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{HttpException}from"../../core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,f as tooLarge,i as formFields,p as unsupportedMediaTypeError,s as parseForm}from"../../body-policy-Be3Y0hjq.mjs";import{t as RequestContext}from"../../context-BvZLaTeE.mjs";import{n as publishMatchedRoute,r as stringifyJson}from"../../runtime-D9TN6CpL.mjs";import{n as applyHandlerResult}from"../../reply-B5kZ6VGv.mjs";import{f as requestStore}from"../../view-renderer-C4sMEruA.mjs";import{n as disposeRequestStore,t as createRequestStore}from"../../request-scope-D2WQwatk.mjs";import{validate}from"../middleware/validate.mjs";import"../middleware/upload.mjs";import{c as tooManyFiles,l as uploadLimits,n as UPLOAD_FIELDS_ALLOWANCE,r as applyUploadConfig,t as MAX_UPLOAD_FIELDS}from"../../upload-config-BXjBiNjC.mjs";import{t as lazyServeStatic}from"../../lazy-serve-static-DVWmKM7Z.mjs";import{createLogger}from"../../core/logger.mjs";import Fastify from"fastify";const pluginOf=mod=>mod.default??mod,createFastify=Fastify,log=createLogger(`FastifyRuntime`),QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),STORE=Symbol(`kickjs.fastify.store`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};function settleOrFail(reply,returned){typeof returned?.then==`function`&&Promise.resolve(returned).then(void 0,()=>{!reply.sent&&!reply.raw.headersSent&&reply.code(500).send({message:`Internal Server Error`})})}function inRouteStore(raw,res,fn){let own=raw[STORE];if(own)return void requestStore.run(own,fn);if(requestStore.getStore())return fn();let header=raw.headers[`x-request-id`],store=createRequestStore(raw.requestId||(Array.isArray(header)?header[0]:header));res.once(`close`,()=>disposeRequestStore(store)),requestStore.run(store,fn)}const NO_FALLTHROUGH=Symbol(`kickjs.fastify.noFallthrough`);function multipartError(err,limits,file){switch(err?.code){case`FST_REQ_FILE_TOO_LARGE`:return new HttpException(413,`File ${file} exceeds the ${limits.fileSize}-byte limit`);case`FST_FILES_LIMIT`:return tooManyFiles(limits.files);case`FST_FIELDS_LIMIT`:case`FST_PARTS_LIMIT`:return new HttpException(413,`Too many form fields`);case`FST_PROTO_VIOLATION`:return prototypeKeyError();default:return err}}var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.getHeader(`content-type`)||this.reply.type(`application/json; charset=utf-8`),this.reply.serializer(stringifyJson).send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}getHeader(name){return this.reply.getHeader(name)}setHeader(name,value){return this.reply.removeHeader(name),this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.headersSent?this.reply.raw.end(data):this.reply.send(data??``),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
11
+ import{HttpException}from"../../core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,f as tooLarge,i as formFields,p as unsupportedMediaTypeError,s as parseForm}from"../../body-policy-D8LveWmO.mjs";import{t as RequestContext}from"../../context-BzFNflxV.mjs";import{n as publishMatchedRoute,r as stringifyJson}from"../../runtime-CUfFIHiC.mjs";import{n as applyHandlerResult}from"../../reply-ChoI5SvM.mjs";import{f as requestStore}from"../../view-renderer-Bf1Wy-DQ.mjs";import{n as disposeRequestStore,t as createRequestStore}from"../../request-scope-BfSNdmz9.mjs";import{validate}from"../middleware/validate.mjs";import"../middleware/upload.mjs";import{c as tooManyFiles,l as uploadLimits,n as UPLOAD_FIELDS_ALLOWANCE,r as applyUploadConfig,t as MAX_UPLOAD_FIELDS}from"../../upload-config-BXqBuyza.mjs";import{t as lazyServeStatic}from"../../lazy-serve-static-DxI2K-zs.mjs";import{createLogger}from"../../core/logger.mjs";import Fastify from"fastify";const pluginOf=mod=>mod.default??mod,createFastify=Fastify,log=createLogger(`FastifyRuntime`),QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),STORE=Symbol(`kickjs.fastify.store`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};function settleOrFail(reply,returned){typeof returned?.then==`function`&&Promise.resolve(returned).then(void 0,()=>{!reply.sent&&!reply.raw.headersSent&&reply.code(500).send({message:`Internal Server Error`})})}function inRouteStore(raw,res,fn){let own=raw[STORE];if(own)return void requestStore.run(own,fn);if(requestStore.getStore())return fn();let header=raw.headers[`x-request-id`],store=createRequestStore(raw.requestId||(Array.isArray(header)?header[0]:header));res.once(`close`,()=>disposeRequestStore(store)),requestStore.run(store,fn)}const NO_FALLTHROUGH=Symbol(`kickjs.fastify.noFallthrough`);function multipartError(err,limits,file){switch(err?.code){case`FST_REQ_FILE_TOO_LARGE`:return new HttpException(413,`File ${file} exceeds the ${limits.fileSize}-byte limit`);case`FST_FILES_LIMIT`:return tooManyFiles(limits.files);case`FST_FIELDS_LIMIT`:case`FST_PARTS_LIMIT`:return new HttpException(413,`Too many form fields`);case`FST_PROTO_VIOLATION`:return prototypeKeyError();default:return err}}var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.getHeader(`content-type`)||this.reply.type(`application/json; charset=utf-8`),this.reply.serializer(stringifyJson).send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}getHeader(name){return this.reply.getHeader(name)}setHeader(name,value){return this.reply.removeHeader(name),this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.headersSent?this.reply.raw.end(data):this.reply.send(data??``),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
12
12
  Install it as a peer dependency: pnpm add @fastify/multipart.`);let limits=uploadLimits(entry.meta.upload),rawParts=[],fields=[],current=`file`,received=0,count=bytes=>{if(received+=bytes,received>limits.total)throw tooLarge(limits.total)};try{for await(let part of request.parts({limits:{fileSize:limits.fileSize,files:limits.files,fields:MAX_UPLOAD_FIELDS,fieldSize:UPLOAD_FIELDS_ALLOWANCE}}))if(part.type===`file`&&part.toBuffer){current=part.filename??part.fieldname;let buffer=await part.toBuffer();count(buffer.length),rawParts.push({fieldname:part.fieldname,filename:part.filename??``,mimetype:part.mimetype??`application/octet-stream`,buffer})}else{let value=String(part.value);count(Buffer.byteLength(part.fieldname)+Buffer.byteLength(value)),fields.push([part.fieldname,value])}}catch(err){throw multipartError(err,limits,current)}let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);raw.file=file,raw.files=files,raw.body={...raw.body,...formFields(fields)}}if(hasPrototypeKey(raw.body))throw prototypeKeyError();let headerId=raw.headers[`x-request-id`],requestId=raw.requestId||(Array.isArray(headerId)?headerId[0]:headerId),store=createRequestStore(requestId);raw.requestId=store.requestId,raw[STORE]=store,reply.getHeader(`x-request-id`)||reply.header(`x-request-id`,store.requestId),reply.raw.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(raw,entry);let ctx=new RequestContext(raw,reply,NOOP_NEXT,replyDriver(reply));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),reply.sent))return;validator&&await new Promise((resolve,reject)=>{validator(raw,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||reply.sent)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),reply.sent)return;let result=await entry.handler(ctx);!reply.sent&&!await applyHandlerResult(ctx,result)&&reply.callNotFound()})}}function hopTrust(hops){return(_ip,hopIndex)=>hopIndex<hops}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=createFastify({logger:!1,routerOptions:{ignoreTrailingSlash:!0},...options.bodyLimit===void 0?{}:{bodyLimit:options.bodyLimit},trustProxy:typeof options.trustProxy==`number`?hopTrust(options.trustProxy):options.trustProxy});app[QUEUE]=[];let addParser=app.addContentTypeParser?.bind(app);return addParser&&(addParser(/^application\/[\w.+-]+\+json$/,{parseAs:`string`},(_req,body,done)=>{if(body===``)return done(null,void 0);try{done(null,JSON.parse(body))}catch(err){done(HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`),void 0)}}),addParser(`application/x-www-form-urlencoded`,{parseAs:`string`},(_req,body,done)=>{done(null,parseForm(body))}),addParser(/^text\//,{parseAs:`string`},(_req,body,done)=>{done(null,body)}),addParser(`*`,{parseAs:`string`},(req,body,done)=>{if(!body)return done(null,void 0);done(unsupportedMediaTypeError(req.headers?.[`content-type`]),void 0)})),options.notFoundFallthrough===!1&&(app[NO_FALLTHROUGH]=!0),app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=pluginOf(await import(`@fastify/multipart`));await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=pluginOf(await import(`@fastify/middie`));await app.register(middie);for(let{mw,opts}of state[QUEUE]??[])opts?.path===void 0?app.use(mw):app.use(opts.path,mw);await app.ready()})());let readyP=state[READY],ready=!1;return readyP.then(()=>ready=!0,()=>{}),(req,res,next)=>{next&&(req[NEXT]=next),ready?app.routing(req,res):readyP.then(()=>app.routing(req,res)).catch(err=>{if(next)return next(err);log.error(err,`Fastify failed to start`),res.statusCode=500,res.end(`Internal Server Error`)})}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){entry.meta.upload&&(app[NEEDS_MULTIPART]=!0);let url=joinPath(mountPath,entry.path);app.route({method:entry.method,url,handler:routeHandler(entry)})}},useConnect(app,mw,opts){app[QUEUE]?.push({mw,opts})},serveStatic(app,prefix,dir){this.useConnect(app,lazyServeStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];next&&!app[NO_FALLTHROUGH]?(reply.hijack(),next()):inRouteStore(request.raw,reply.raw,()=>settleOrFail(reply,mw(request.raw,replyDriver(reply),NOOP_NEXT)))})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{inRouteStore(request.raw,reply.raw,()=>settleOrFail(reply,mw(err,request.raw,replyDriver(reply),NOOP_NEXT)))})},close(app){return app.close()},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{fastifyRuntime};
13
13
  //# sourceMappingURL=fastify.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.mjs","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"sourcesContent":["// The Fastify runtime — `@forinda/kickjs/fastify`.\n//\n// Implements the same HttpRuntime contract as expressRuntime, over Fastify 5.\n// KickJS still owns decorators → RouteTable, the contributor pipeline, and the\n// RequestContext surface; this runtime materializes routes as NATIVE Fastify\n// routes and wraps `reply` in a RuntimeResponse so `ctx.json` / `ctx.html` /\n// `ctx.sse` work unchanged.\n//\n// `fastify`, `@fastify/middie` are optional peers — install them alongside\n// `@forinda/kickjs` to use this subpath.\n//\n// Lifecycle note: Fastify registration (`register` / `use` / `route`) is\n// deferred until `ready()`. Connect middleware needs `@fastify/middie`\n// registered first, so `useConnect` only QUEUES middleware; `nodeHandler`\n// registers middie, then the queued middleware, then awaits `ready()`.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport Fastify from 'fastify'\n\nimport { HttpException } from '../../core/errors'\nimport {\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n tooLarge,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute, stringifyJson } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport type { RequestStore } from '../request-store'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport {\n MAX_UPLOAD_FIELDS,\n UPLOAD_FIELDS_ALLOWANCE,\n tooManyFiles,\n uploadLimits,\n} from '../middleware/upload-config'\nimport { lazyServeStatic } from './lazy-serve-static'\nimport { createLogger } from '../../core/logger'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\n// The peers load through `import`, never `createRequire`: a bundler follows an\n// import, so `kick build:netlify|vercel` inlines them into the function. A\n// computed require is left for the platform to resolve, and the function has\n// no node_modules. `fastify` is static (this entry is the Fastify runtime);\n// the plugins are imported when first needed.\nconst pluginOf = (mod: { default?: unknown }): any => mod.default ?? mod\n// Typed structurally below (FastifyAppLike), as when this was required untyped.\nconst createFastify = Fastify as unknown as (options: object) => unknown\nconst log = createLogger('FastifyRuntime')\n\n// Minimal structural surface we use from Fastify — avoids a hard type dep so\n// the root package never needs `fastify` installed to typecheck.\ninterface FastifyReplyLike {\n code(statusCode: number): FastifyReplyLike\n send(payload?: unknown): FastifyReplyLike\n header(name: string, value: unknown): FastifyReplyLike\n removeHeader(name: string): FastifyReplyLike\n type(contentType: string): FastifyReplyLike\n serializer(fn: (payload: unknown) => string): FastifyReplyLike\n getHeader(name: string): unknown\n hijack(): void\n /** Hand the request to the not-found handler (Fastify 5). */\n callNotFound(): void\n readonly sent: boolean\n readonly raw: ServerResponse\n}\ninterface FastifyRequestLike {\n raw: IncomingMessage\n body?: unknown\n params?: unknown\n query?: unknown\n /** Request headers, as Fastify normalises them (lowercased keys). */\n headers?: Record<string, string | string[] | undefined>\n /** Present once @fastify/multipart is registered — async iterator of parts. */\n parts?: (options?: { limits?: Record<string, number> }) => AsyncIterableIterator<MultipartPart>\n isMultipart?: () => boolean\n}\ntype FastifyHandler = (request: FastifyRequestLike, reply: FastifyReplyLike) => void | Promise<void>\ninterface FastifyAppLike {\n close(): Promise<void>\n register(plugin: unknown, opts?: unknown): Promise<void> | FastifyAppLike\n use(path: unknown, mw?: unknown): unknown\n route(opts: { method: string; url: string; handler: FastifyHandler }): unknown\n setNotFoundHandler(handler: FastifyHandler): unknown\n setErrorHandler(\n handler: (err: unknown, req: FastifyRequestLike, reply: FastifyReplyLike) => void,\n ): unknown\n ready(): Promise<void>\n routing(req: IncomingMessage, res: ServerResponse): void\n /**\n * Fastify's content-type parser registry. Typed here rather than reached for\n * with a cast so the callback shape is checked at the call site — these\n * parsers decide what `ctx.body` is on this runtime.\n */\n addContentTypeParser?(\n matcher: string | RegExp | string[],\n opts: { parseAs: 'string' | 'buffer' },\n parser: FastifyBodyParser,\n ): unknown\n}\n\n/** The `done` callback a Fastify content-type parser calls. */\ntype FastifyParserDone = (err: Error | null, body?: unknown) => void\n\n/** `done`-style callback Fastify hands a content-type parser. */\ntype FastifyBodyParser = (\n req: FastifyRequestLike,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n) => void\n\nconst QUEUE = Symbol('kickjs.fastify.connectQueue')\nconst READY = Symbol('kickjs.fastify.ready')\nconst NEXT = Symbol('kickjs.fastify.next')\n/** The route's request store, re-entered by the error and not-found handlers. */\nconst STORE = Symbol('kickjs.fastify.store')\n// Set during mountRoutes when any route carries @FileUpload metadata, so\n// nodeHandler knows to register @fastify/multipart before ready().\nconst NEEDS_MULTIPART = Symbol('kickjs.fastify.needsMultipart')\nconst NOOP_NEXT = (): void => {}\n\n/**\n * An async error / not-found handler that rejects never answers; answer 500\n * so the request ends instead of hanging until the client gives up.\n */\nfunction settleOrFail(reply: FastifyReplyLike, returned: unknown): void {\n if (typeof (returned as PromiseLike<void> | undefined)?.then !== 'function') return\n Promise.resolve(returned).then(undefined, () => {\n if (!reply.sent && !reply.raw.headersSent) {\n // The 500 body every engine's built-in error handler starts from.\n reply.code(500).send({ message: 'Internal Server Error' })\n }\n })\n}\n/**\n * Run `fn` in the store the matched route opened. An error before any route\n * ran (a body Fastify couldn't parse) uses the store already active, or one\n * of its own, disposed when the response closes.\n */\nfunction inRouteStore(raw: IncomingMessage, res: ServerResponse, fn: () => void): void {\n const own = (raw as { [STORE]?: RequestStore })[STORE]\n if (own) return void requestStore.run(own, fn)\n if (requestStore.getStore()) return fn()\n const header = raw.headers['x-request-id']\n const store = createRequestStore(\n (raw as { requestId?: string }).requestId || (Array.isArray(header) ? header[0] : header),\n )\n res.once('close', () => disposeRequestStore(store))\n requestStore.run(store, fn)\n}\n\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.fastify.noFallthrough')\n\n/**\n * @fastify/multipart's limit errors as the exceptions every engine raises —\n * the same status and message as `applyUploadConfig` and the web runtime.\n */\nfunction multipartError(\n err: unknown,\n limits: { fileSize: number; files: number },\n file: string,\n): unknown {\n switch ((err as { code?: string } | null)?.code) {\n case 'FST_REQ_FILE_TOO_LARGE':\n return new HttpException(413, `File ${file} exceeds the ${limits.fileSize}-byte limit`)\n case 'FST_FILES_LIMIT':\n return tooManyFiles(limits.files)\n case 'FST_FIELDS_LIMIT':\n case 'FST_PARTS_LIMIT':\n return new HttpException(413, 'Too many form fields')\n case 'FST_PROTO_VIOLATION':\n return prototypeKeyError()\n default:\n return err\n }\n}\n\n// A @fastify/multipart part as we consume it from `request.parts()`.\ninterface MultipartPart {\n type: 'file' | 'field'\n fieldname: string\n filename?: string\n mimetype?: string\n value?: unknown\n toBuffer?: () => Promise<Buffer>\n}\n\n/**\n * Wrap a Fastify reply so the RequestContext response helpers drive it.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass FastifyReplyDriver implements RuntimeResponse {\n constructor(private readonly reply: FastifyReplyLike) {}\n status(code: number): this {\n this.reply.code(code)\n return this\n }\n json(data: unknown): this {\n // A custom serializer drops Fastify's default content-type; keep one the\n // caller chose (`application/problem+json`).\n if (!this.reply.getHeader('content-type')) this.reply.type('application/json; charset=utf-8')\n this.reply.serializer(stringifyJson).send(data)\n return this\n }\n send(data: unknown): this {\n this.reply.send(data)\n return this\n }\n type(contentType: string): this {\n this.reply.type(contentType)\n return this\n }\n getHeader(name: string): unknown {\n return this.reply.getHeader(name)\n }\n setHeader(name: string, value: unknown): this {\n // Replace, as node's `res.setHeader` and the web driver do. Fastify's\n // `header()` appends for `set-cookie`, so `setCookie()` — which passes the\n // whole list each time — sent the first cookie twice.\n this.reply.removeHeader(name)\n this.reply.header(name, value)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the Fastify runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n // Streaming / SSE: take over the raw socket so Fastify doesn't try to\n // serialize a reply we're writing by hand.\n this.reply.hijack()\n this.reply.raw.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n ;(this.reply.raw as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.()\n return this\n }\n write(chunk: unknown): boolean {\n return this.reply.raw.write(chunk as never)\n }\n end(data?: unknown): this {\n // After writeHead (streaming, SSE) the reply is hijacked and the raw\n // socket is ours to finish. Otherwise finish through the reply, so the\n // status and headers set on it are sent — `ctx.redirect()` writes its\n // Location with setHeader() and then calls end().\n if (this.reply.raw.headersSent) this.reply.raw.end(data as never)\n else this.reply.send(data ?? '')\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.reply.raw.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.reply.sent || this.reply.raw.headersSent\n }\n}\n\nfunction replyDriver(reply: FastifyReplyLike): RuntimeResponse {\n return new FastifyReplyDriver(reply) as unknown as RuntimeResponse\n}\n\n/** Build the Fastify per-route handler that runs the kickjs pipeline. */\nfunction routeHandler(entry: RouteEntry): FastifyHandler {\n // Validation middleware is built ONCE per route (parity with the Express\n // materializer) — `validate()` constructs a fresh closure, so calling it\n // per request was pure allocation waste.\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n return async (request, reply) => {\n // Fastify runs the route handler OUTSIDE the connect-middleware chain, so\n // (unlike Express) the requestScopeMiddleware ALS frame isn't active here.\n // Establish it around the pipeline so REQUEST-scoped DI, contributors, and\n // ctx.set/get work. Reuse the inbound x-request-id, or the id a connect\n // middleware (requestId / requestScope, run earlier via middie) already\n // stamped on the raw request, before generating a fresh one.\n // Use the raw node request as `ctx.req`: it natively provides the stream\n // events (`on('close')` / `once`) that SSE and `ctx.signal` need — Fastify's\n // request object doesn't. Copy Fastify's parsed body/params/query onto it so\n // `ctx.body` / `ctx.params` / `ctx.query` keep working.\n const raw = request.raw as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n raw.body = request.body\n raw.params = request.params\n raw.query = request.query\n\n // @FileUpload: buffer multipart parts into the multer-shaped file(s) that\n // `ctx.file` / `ctx.files` expose. Fastify doesn't parse multipart natively\n // — @fastify/multipart (registered in nodeHandler when any route needs it)\n // provides `request.parts()`. Non-file fields are merged onto `raw.body` so\n // validation / `ctx.body` see them, matching multer's req.body behavior.\n if (entry.meta.upload && entry.meta.upload.mode !== 'none') {\n if (typeof request.parts !== 'function') {\n throw new Error(\n \"@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.\\n\" +\n 'Install it as a peer dependency: pnpm add @fastify/multipart.',\n )\n }\n // The parser stops at the route's limits instead of buffering whatever\n // arrives: a file past maxSize, or more files than the route takes, is a 413.\n const limits = uploadLimits(entry.meta.upload)\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n let current = 'file'\n // Per-part limits alone allow many parts; the whole body is held to the\n // route's budget too, the same total h3 and the web entry read at most.\n let received = 0\n const count = (bytes: number) => {\n received += bytes\n if (received > limits.total) {\n throw tooLarge(limits.total)\n }\n }\n try {\n for await (const part of request.parts({\n limits: {\n fileSize: limits.fileSize,\n files: limits.files,\n fields: MAX_UPLOAD_FIELDS,\n fieldSize: UPLOAD_FIELDS_ALLOWANCE,\n },\n })) {\n if (part.type === 'file' && part.toBuffer) {\n current = part.filename ?? part.fieldname\n const buffer = await part.toBuffer()\n count(buffer.length)\n rawParts.push({\n fieldname: part.fieldname,\n filename: part.filename ?? '',\n mimetype: part.mimetype ?? 'application/octet-stream',\n buffer,\n })\n } else {\n const value = String(part.value)\n count(Buffer.byteLength(part.fieldname) + Buffer.byteLength(value))\n fields.push([part.fieldname, value])\n }\n }\n } catch (err) {\n throw multipartError(err, limits, current)\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload)\n raw.file = file\n raw.files = files\n raw.body = { ...(raw.body as Record<string, unknown> | undefined), ...formFields(fields) }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (hasPrototypeKey(raw.body)) throw prototypeKeyError()\n\n const headerId = raw.headers['x-request-id']\n // An id already assigned (requestId() middleware) wins over the header,\n // as on Express and h3.\n const requestId = raw.requestId || (Array.isArray(headerId) ? headerId[0] : headerId)\n const store = createRequestStore(requestId)\n // Propagate the resolved id back onto the raw request so anything reading\n // `req.requestId` inside the frame (e.g. request-logger) matches the store\n // and the X-Request-Id response header — parity with Express.\n raw.requestId = store.requestId\n ;(raw as { [STORE]?: RequestStore })[STORE] = store\n if (!reply.getHeader('x-request-id')) reply.header('x-request-id', store.requestId)\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n reply.raw.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(raw, entry)\n const ctx = new RequestContext(raw as never, reply as never, NOOP_NEXT, replyDriver(reply))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (reply.sent) return\n }\n\n // Validation (from @Get(path, schema) / route.validation). `validator` is a\n // connect-style middleware built once at route registration; it mutates\n // req.body/query/params to the parsed value and calls next(err) on failure\n // — it never touches `res`, so it runs cleanly here. A rejection\n // propagates to the error handler (422).\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(raw as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n // Class + method middleware — `(ctx, next)`; await each, stop if it ended\n // the response or called next(err).\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || reply.sent) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (reply.sent) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // Nothing written and nothing returned falls through to the 404 handler,\n // as on Express and h3 — not Fastify's own empty 200.\n if (!reply.sent && !(await applyHandlerResult(ctx, result))) reply.callNotFound()\n })\n }\n}\n\n/** Express's `trust proxy` number: trust the first `hops` addresses from the socket. */\nfunction hopTrust(hops: number): (ip: string, hopIndex: number) => boolean {\n return (_ip, hopIndex) => hopIndex < hops\n}\n\n/**\n * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.\n * Per spec §10: Fastify's built-in pino logger is disabled (`logger: false`) so\n * the kickjs `requestLogger` middleware stays the single log format.\n */\nexport function fastifyRuntime(): HttpRuntime<FastifyAppLike> {\n return {\n name: 'fastify',\n\n createApp(options: RuntimeAppOptions = {}): FastifyAppLike {\n const app = createFastify({\n logger: false,\n // Match Express / h3 routing leniency: `/api/v1/hello` and\n // `/api/v1/hello/` resolve to the same route. Without this, Fastify's\n // strict router 404s a trailing-slash request — e.g. a controller's\n // root `@Get('/')` (mounted at the prefix) misses `${prefix}/`. Set under\n // `routerOptions` (Fastify 5+; top-level `ignoreTrailingSlash` is\n // deprecated, removed in Fastify 6).\n routerOptions: { ignoreTrailingSlash: true },\n // `jsonLimit`, which Fastify otherwise ignores in favour of its own 1 MiB.\n ...(options.bodyLimit !== undefined ? { bodyLimit: options.bodyLimit } : {}),\n // Express semantics for every form. Fastify takes a predicate as-is,\n // but reads a hop count as \"trust nothing\", where Express trusts that\n // many hops from the socket.\n trustProxy:\n typeof options.trustProxy === 'number'\n ? hopTrust(options.trustProxy)\n : options.trustProxy,\n }) as FastifyAppLike & {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n }\n app[QUEUE] = []\n\n // Fastify ships parsers for `application/json` and `text/plain` only, and\n // answers 415 for everything else. That made a form post work on Express\n // and h3 but fail on Fastify alone (#590). Register the rest of the\n // framework's supported set so all engines agree.\n //\n // Deliberately NOT a `'*'` catch-all: that would swallow multipart, and\n // `@fastify/multipart` is itself the multipart content-type parser,\n // registered conditionally in `nodeHandler` when a route needs it.\n const addParser = app.addContentTypeParser?.bind(app)\n if (addParser) {\n // `application/*+json` — RFC 6838 §4.2.8 guarantees the bytes are JSON.\n addParser(\n /^application\\/[\\w.+-]+\\+json$/,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n if (body === '') return done(null, undefined)\n try {\n done(null, JSON.parse(body as string))\n } catch (err) {\n // A bare SyntaxError carries no status, so the shared error handler\n // would call it a 500 — Fastify's own JSON parser answers 400\n // (FST_ERR_CTP_INVALID_JSON_BODY), and so must this one.\n done(\n HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n ),\n undefined,\n )\n }\n },\n )\n addParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, parseForm(body as string))\n },\n )\n // `text/*` beyond Fastify's built-in `text/plain`. Raw string, never\n // JSON: `text/plain` is CORS-safelisted, so parsing it as JSON would\n // re-open no-preflight CSRF against a JSON API.\n addParser(\n /^text\\//,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, body)\n },\n )\n // Fastify already answers 415 for a type it has no parser for, but with\n // its own message and no `Accept`. `'*'` is Fastify's documented\n // fallback — consulted only when nothing more specific matches — so it\n // does not shadow the parsers above, nor `@fastify/multipart`, which\n // registers `multipart/form-data` when an upload route needs it.\n addParser(\n '*',\n { parseAs: 'string' },\n (req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n // No body is not an unsupported body. Fastify calls the parser even\n // for an empty payload, so without this a bodyless POST carrying an\n // unrelated content type would be rejected.\n if (!body) return done(null, undefined)\n done(unsupportedMediaTypeError(req.headers?.['content-type']), undefined)\n },\n )\n }\n\n if (options.notFoundFallthrough === false) {\n ;(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH] = true\n }\n return app\n },\n\n nodeHandler(app) {\n // Register middie + queued connect middleware + finalize `ready()` exactly\n // ONCE per app, even though Application may call nodeHandler per request.\n const state = app as {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n [READY]?: Promise<void>\n [NEEDS_MULTIPART]?: boolean\n }\n if (!state[READY]) {\n state[READY] = (async () => {\n // Register @fastify/multipart first when any route uses @FileUpload so\n // `request.parts()` is available. Our applyUploadConfig enforces the\n // real per-file maxSize, so give the plugin a generous fileSize ceiling\n // (its 1MB default would silently truncate larger uploads first).\n if (state[NEEDS_MULTIPART]) {\n const multipart = pluginOf(await import('@fastify/multipart'))\n await app.register(multipart, { limits: { fileSize: Number.MAX_SAFE_INTEGER } })\n }\n const middie = pluginOf(await import('@fastify/middie'))\n await app.register(middie)\n for (const { mw, opts } of state[QUEUE] ?? []) {\n if (opts?.path !== undefined)\n (app.use as (p: unknown, m: unknown) => void)(opts.path, mw)\n else (app.use as (m: unknown) => void)(mw)\n }\n await app.ready()\n })()\n }\n const readyP = state[READY]\n // Once ready, route synchronously — no promise hop per request.\n let ready = false\n readyP.then(\n () => (ready = true),\n () => {},\n )\n\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n if (ready) {\n app.routing(req, res)\n return\n }\n readyP\n .then(() => app.routing(req, res))\n .catch((err) => {\n if (next) return next(err)\n // No host to hand the error to: answer rather than leave the request open.\n log.error(err, 'Fastify failed to start')\n res.statusCode = 500\n res.end('Internal Server Error')\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n if (entry.meta.upload) (app as { [NEEDS_MULTIPART]?: boolean })[NEEDS_MULTIPART] = true\n const url = joinPath(mountPath, entry.path)\n app.route({ method: entry.method, url, handler: routeHandler(entry) })\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const queue = (\n app as { [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }> }\n )[QUEUE]\n queue?.push({ mw, opts })\n },\n\n serveStatic(app, prefix, dir) {\n // Serve via `serve-static` (the standalone connect middleware behind\n // express.static) so the Fastify runtime carries no `express` dependency —\n // queued like any other connect middleware, bridged through middie.\n this.useConnect(app, lazyServeStatic(dir), { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n app.setNotFoundHandler((request, reply) => {\n const next = (request.raw as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT]\n if (next && !(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH]) {\n // Vite dev fall-through: hand the request back to the outer chain.\n reply.hijack()\n next()\n return\n }\n // Pass the reply DRIVER (not raw res) so the connect-style\n // notFoundHandler's `res.status().json()` lands on the Fastify reply.\n // In the route's store when a route handed over (`callNotFound()`).\n inRouteStore(request.raw, reply.raw, () =>\n settleOrFail(\n reply,\n (mw as (req: unknown, res: unknown, next: () => void) => unknown)(\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n ),\n )\n })\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n app.setErrorHandler((err, request, reply) => {\n // Reply driver (not raw res) so the connect-style errorHandler's\n // `res.status().json()` / `setHeader` land on the Fastify reply.\n // In the route's store: Fastify calls this outside it, and an error\n // page should see the handler's ctx values and REQUEST-scoped instances.\n inRouteStore(request.raw, reply.raw, () =>\n settleOrFail(\n reply,\n (mw as (e: unknown, req: unknown, res: unknown, next: () => void) => unknown)(\n err,\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n ),\n )\n })\n },\n\n close(app) {\n // Runs the instance's onClose hooks (plugins registered on it).\n return app.close()\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The Fastify runtime's engine-native types — what the runtime-typed escape\n * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.\n * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.\n */\nexport interface FastifyRuntimeTypes {\n request: import('fastify').FastifyRequest\n response: import('fastify').FastifyReply\n app: import('fastify').FastifyInstance\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n // A root route path ('/' or '') maps to the mount prefix itself — otherwise a\n // controller `@Post('/')` would register at `${prefix}/`, and a request to\n // `${prefix}` (no trailing slash) wouldn't match under Fastify's strict router.\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;A,q8BA2DA,MAAM,SAAY,KAAoC,IAAI,SAAW,IAE/D,cAAgB,QAChB,IAAM,aAAa,gBAAgB,EA+DnC,MAAQ,OAAO,6BAA6B,EAC5C,MAAQ,OAAO,sBAAsB,EACrC,KAAO,OAAO,qBAAqB,EAEnC,MAAQ,OAAO,sBAAsB,EAGrC,gBAAkB,OAAO,+BAA+B,EACxD,cAAwB,CAAC,EAM/B,SAAS,aAAa,MAA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C,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CACF,CAAC,CACH,EAEA,gBAAgB,IAAK,GAAuB,CAC1C,IAAI,iBAAiB,IAAK,QAAS,QAAU,CAK3C,aAAa,QAAQ,IAAK,MAAM,QAC9B,aACE,MACC,GACC,IACA,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CACF,CAAC,CACH,EAEA,MAAM,IAAK,CAET,OAAO,IAAI,MAAM,CACnB,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAgBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAM7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C,C"}
1
+ {"version":3,"file":"fastify.mjs","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"sourcesContent":["// The Fastify runtime — `@forinda/kickjs/fastify`.\n//\n// Implements the same HttpRuntime contract as expressRuntime, over Fastify 5.\n// KickJS still owns decorators → RouteTable, the contributor pipeline, and the\n// RequestContext surface; this runtime materializes routes as NATIVE Fastify\n// routes and wraps `reply` in a RuntimeResponse so `ctx.json` / `ctx.html` /\n// `ctx.sse` work unchanged.\n//\n// `fastify`, `@fastify/middie` are optional peers — install them alongside\n// `@forinda/kickjs` to use this subpath.\n//\n// Lifecycle note: Fastify registration (`register` / `use` / `route`) is\n// deferred until `ready()`. Connect middleware needs `@fastify/middie`\n// registered first, so `useConnect` only QUEUES middleware; `nodeHandler`\n// registers middie, then the queued middleware, then awaits `ready()`.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport Fastify from 'fastify'\n\nimport { HttpException } from '../../core/errors'\nimport {\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n tooLarge,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute, stringifyJson } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport type { RequestStore } from '../request-store'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport {\n MAX_UPLOAD_FIELDS,\n UPLOAD_FIELDS_ALLOWANCE,\n tooManyFiles,\n uploadLimits,\n} from '../middleware/upload-config'\nimport { lazyServeStatic } from './lazy-serve-static'\nimport { createLogger } from '../../core/logger'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\n// The peers load through `import`, never `createRequire`: a bundler follows an\n// import, so `kick build:netlify|vercel` inlines them into the function. A\n// computed require is left for the platform to resolve, and the function has\n// no node_modules. `fastify` is static (this entry is the Fastify runtime);\n// the plugins are imported when first needed.\nconst pluginOf = (mod: { default?: unknown }): any => mod.default ?? mod\n// Typed structurally below (FastifyAppLike), as when this was required untyped.\nconst createFastify = Fastify as unknown as (options: object) => unknown\nconst log = createLogger('FastifyRuntime')\n\n// Minimal structural surface we use from Fastify — avoids a hard type dep so\n// the root package never needs `fastify` installed to typecheck.\ninterface FastifyReplyLike {\n code(statusCode: number): FastifyReplyLike\n send(payload?: unknown): FastifyReplyLike\n header(name: string, value: unknown): FastifyReplyLike\n removeHeader(name: string): FastifyReplyLike\n type(contentType: string): FastifyReplyLike\n serializer(fn: (payload: unknown) => string): FastifyReplyLike\n getHeader(name: string): unknown\n hijack(): void\n /** Hand the request to the not-found handler (Fastify 5). */\n callNotFound(): void\n readonly sent: boolean\n readonly raw: ServerResponse\n}\ninterface FastifyRequestLike {\n raw: IncomingMessage\n body?: unknown\n params?: unknown\n query?: unknown\n /** Request headers, as Fastify normalises them (lowercased keys). */\n headers?: Record<string, string | string[] | undefined>\n /** Present once @fastify/multipart is registered — async iterator of parts. */\n parts?: (options?: { limits?: Record<string, number> }) => AsyncIterableIterator<MultipartPart>\n isMultipart?: () => boolean\n}\ntype FastifyHandler = (request: FastifyRequestLike, reply: FastifyReplyLike) => void | Promise<void>\ninterface FastifyAppLike {\n close(): Promise<void>\n register(plugin: unknown, opts?: unknown): Promise<void> | FastifyAppLike\n use(path: unknown, mw?: unknown): unknown\n route(opts: { method: string; url: string; handler: FastifyHandler }): unknown\n setNotFoundHandler(handler: FastifyHandler): unknown\n setErrorHandler(\n handler: (err: unknown, req: FastifyRequestLike, reply: FastifyReplyLike) => void,\n ): unknown\n ready(): Promise<void>\n routing(req: IncomingMessage, res: ServerResponse): void\n /**\n * Fastify's content-type parser registry. Typed here rather than reached for\n * with a cast so the callback shape is checked at the call site — these\n * parsers decide what `ctx.body` is on this runtime.\n */\n addContentTypeParser?(\n matcher: string | RegExp | string[],\n opts: { parseAs: 'string' | 'buffer' },\n parser: FastifyBodyParser,\n ): unknown\n}\n\n/** The `done` callback a Fastify content-type parser calls. */\ntype FastifyParserDone = (err: Error | null, body?: unknown) => void\n\n/** `done`-style callback Fastify hands a content-type parser. */\ntype FastifyBodyParser = (\n req: FastifyRequestLike,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n) => void\n\nconst QUEUE = Symbol('kickjs.fastify.connectQueue')\nconst READY = Symbol('kickjs.fastify.ready')\nconst NEXT = Symbol('kickjs.fastify.next')\n/** The route's request store, re-entered by the error and not-found handlers. */\nconst STORE = Symbol('kickjs.fastify.store')\n// Set during mountRoutes when any route carries @FileUpload metadata, so\n// nodeHandler knows to register @fastify/multipart before ready().\nconst NEEDS_MULTIPART = Symbol('kickjs.fastify.needsMultipart')\nconst NOOP_NEXT = (): void => {}\n\n/**\n * An async error / not-found handler that rejects never answers; answer 500\n * so the request ends instead of hanging until the client gives up.\n */\nfunction settleOrFail(reply: FastifyReplyLike, returned: unknown): void {\n if (typeof (returned as PromiseLike<void> | undefined)?.then !== 'function') return\n Promise.resolve(returned).then(undefined, () => {\n if (!reply.sent && !reply.raw.headersSent) {\n // The 500 body every engine's built-in error handler starts from.\n reply.code(500).send({ message: 'Internal Server Error' })\n }\n })\n}\n/**\n * Run `fn` in the store the matched route opened. An error before any route\n * ran (a body Fastify couldn't parse) uses the store already active, or one\n * of its own, disposed when the response closes.\n */\nfunction inRouteStore(raw: IncomingMessage, res: ServerResponse, fn: () => void): void {\n const own = (raw as { [STORE]?: RequestStore })[STORE]\n if (own) return void requestStore.run(own, fn)\n if (requestStore.getStore()) return fn()\n const header = raw.headers['x-request-id']\n const store = createRequestStore(\n (raw as { requestId?: string }).requestId || (Array.isArray(header) ? header[0] : header),\n )\n res.once('close', () => disposeRequestStore(store))\n requestStore.run(store, fn)\n}\n\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.fastify.noFallthrough')\n\n/**\n * @fastify/multipart's limit errors as the exceptions every engine raises —\n * the same status and message as `applyUploadConfig` and the web runtime.\n */\nfunction multipartError(\n err: unknown,\n limits: { fileSize: number; files: number },\n file: string,\n): unknown {\n switch ((err as { code?: string } | null)?.code) {\n case 'FST_REQ_FILE_TOO_LARGE':\n return new HttpException(413, `File ${file} exceeds the ${limits.fileSize}-byte limit`)\n case 'FST_FILES_LIMIT':\n return tooManyFiles(limits.files)\n case 'FST_FIELDS_LIMIT':\n case 'FST_PARTS_LIMIT':\n return new HttpException(413, 'Too many form fields')\n case 'FST_PROTO_VIOLATION':\n return prototypeKeyError()\n default:\n return err\n }\n}\n\n// A @fastify/multipart part as we consume it from `request.parts()`.\ninterface MultipartPart {\n type: 'file' | 'field'\n fieldname: string\n filename?: string\n mimetype?: string\n value?: unknown\n toBuffer?: () => Promise<Buffer>\n}\n\n/**\n * Wrap a Fastify reply so the RequestContext response helpers drive it.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass FastifyReplyDriver implements RuntimeResponse {\n constructor(private readonly reply: FastifyReplyLike) {}\n status(code: number): this {\n this.reply.code(code)\n return this\n }\n json(data: unknown): this {\n // A custom serializer drops Fastify's default content-type; keep one the\n // caller chose (`application/problem+json`).\n if (!this.reply.getHeader('content-type')) this.reply.type('application/json; charset=utf-8')\n this.reply.serializer(stringifyJson).send(data)\n return this\n }\n send(data: unknown): this {\n this.reply.send(data)\n return this\n }\n type(contentType: string): this {\n this.reply.type(contentType)\n return this\n }\n getHeader(name: string): unknown {\n return this.reply.getHeader(name)\n }\n setHeader(name: string, value: unknown): this {\n // Replace, as node's `res.setHeader` and the web driver do. Fastify's\n // `header()` appends for `set-cookie`, so `setCookie()` — which passes the\n // whole list each time — sent the first cookie twice.\n this.reply.removeHeader(name)\n this.reply.header(name, value)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the Fastify runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n // Streaming / SSE: take over the raw socket so Fastify doesn't try to\n // serialize a reply we're writing by hand.\n this.reply.hijack()\n this.reply.raw.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n ;(this.reply.raw as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.()\n return this\n }\n write(chunk: unknown): boolean {\n return this.reply.raw.write(chunk as never)\n }\n end(data?: unknown): this {\n // After writeHead (streaming, SSE) the reply is hijacked and the raw\n // socket is ours to finish. Otherwise finish through the reply, so the\n // status and headers set on it are sent — `ctx.redirect()` writes its\n // Location with setHeader() and then calls end().\n if (this.reply.raw.headersSent) this.reply.raw.end(data as never)\n else this.reply.send(data ?? '')\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.reply.raw.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.reply.sent || this.reply.raw.headersSent\n }\n}\n\nfunction replyDriver(reply: FastifyReplyLike): RuntimeResponse {\n return new FastifyReplyDriver(reply) as unknown as RuntimeResponse\n}\n\n/** Build the Fastify per-route handler that runs the kickjs pipeline. */\nfunction routeHandler(entry: RouteEntry): FastifyHandler {\n // Validation middleware is built ONCE per route (parity with the Express\n // materializer) — `validate()` constructs a fresh closure, so calling it\n // per request was pure allocation waste.\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n return async (request, reply) => {\n // Fastify runs the route handler OUTSIDE the connect-middleware chain, so\n // (unlike Express) the requestScopeMiddleware ALS frame isn't active here.\n // Establish it around the pipeline so REQUEST-scoped DI, contributors, and\n // ctx.set/get work. Reuse the inbound x-request-id, or the id a connect\n // middleware (requestId / requestScope, run earlier via middie) already\n // stamped on the raw request, before generating a fresh one.\n // Use the raw node request as `ctx.req`: it natively provides the stream\n // events (`on('close')` / `once`) that SSE and `ctx.signal` need — Fastify's\n // request object doesn't. Copy Fastify's parsed body/params/query onto it so\n // `ctx.body` / `ctx.params` / `ctx.query` keep working.\n const raw = request.raw as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n raw.body = request.body\n raw.params = request.params\n raw.query = request.query\n\n // @FileUpload: buffer multipart parts into the multer-shaped file(s) that\n // `ctx.file` / `ctx.files` expose. Fastify doesn't parse multipart natively\n // — @fastify/multipart (registered in nodeHandler when any route needs it)\n // provides `request.parts()`. Non-file fields are merged onto `raw.body` so\n // validation / `ctx.body` see them, matching multer's req.body behavior.\n if (entry.meta.upload && entry.meta.upload.mode !== 'none') {\n if (typeof request.parts !== 'function') {\n throw new Error(\n \"@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.\\n\" +\n 'Install it as a peer dependency: pnpm add @fastify/multipart.',\n )\n }\n // The parser stops at the route's limits instead of buffering whatever\n // arrives: a file past maxSize, or more files than the route takes, is a 413.\n const limits = uploadLimits(entry.meta.upload)\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n let current = 'file'\n // Per-part limits alone allow many parts; the whole body is held to the\n // route's budget too, the same total h3 and the web entry read at most.\n let received = 0\n const count = (bytes: number) => {\n received += bytes\n if (received > limits.total) {\n throw tooLarge(limits.total)\n }\n }\n try {\n for await (const part of request.parts({\n limits: {\n fileSize: limits.fileSize,\n files: limits.files,\n fields: MAX_UPLOAD_FIELDS,\n fieldSize: UPLOAD_FIELDS_ALLOWANCE,\n },\n })) {\n if (part.type === 'file' && part.toBuffer) {\n current = part.filename ?? part.fieldname\n const buffer = await part.toBuffer()\n count(buffer.length)\n rawParts.push({\n fieldname: part.fieldname,\n filename: part.filename ?? '',\n mimetype: part.mimetype ?? 'application/octet-stream',\n buffer,\n })\n } else {\n const value = String(part.value)\n count(Buffer.byteLength(part.fieldname) + Buffer.byteLength(value))\n fields.push([part.fieldname, value])\n }\n }\n } catch (err) {\n throw multipartError(err, limits, current)\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload)\n raw.file = file\n raw.files = files\n raw.body = { ...(raw.body as Record<string, unknown> | undefined), ...formFields(fields) }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (hasPrototypeKey(raw.body)) throw prototypeKeyError()\n\n const headerId = raw.headers['x-request-id']\n // An id already assigned (requestId() middleware) wins over the header,\n // as on Express and h3.\n const requestId = raw.requestId || (Array.isArray(headerId) ? headerId[0] : headerId)\n const store = createRequestStore(requestId)\n // Propagate the resolved id back onto the raw request so anything reading\n // `req.requestId` inside the frame (e.g. request-logger) matches the store\n // and the X-Request-Id response header — parity with Express.\n raw.requestId = store.requestId\n ;(raw as { [STORE]?: RequestStore })[STORE] = store\n if (!reply.getHeader('x-request-id')) reply.header('x-request-id', store.requestId)\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n reply.raw.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(raw, entry)\n const ctx = new RequestContext(raw as never, reply as never, NOOP_NEXT, replyDriver(reply))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (reply.sent) return\n }\n\n // Validation (from @Get(path, schema) / route.validation). `validator` is a\n // connect-style middleware built once at route registration; it mutates\n // req.body/query/params to the parsed value and calls next(err) on failure\n // — it never touches `res`, so it runs cleanly here. A rejection\n // propagates to the error handler (422).\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(raw as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n // Class + method middleware — `(ctx, next)`; await each, stop if it ended\n // the response or called next(err).\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || reply.sent) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (reply.sent) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // Nothing written and nothing returned falls through to the 404 handler,\n // as on Express and h3 — not Fastify's own empty 200.\n if (!reply.sent && !(await applyHandlerResult(ctx, result))) reply.callNotFound()\n })\n }\n}\n\n/** Express's `trust proxy` number: trust the first `hops` addresses from the socket. */\nfunction hopTrust(hops: number): (ip: string, hopIndex: number) => boolean {\n return (_ip, hopIndex) => hopIndex < hops\n}\n\n/**\n * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.\n * Fastify's built-in pino logger is disabled (`logger: false`) so\n * the kickjs `requestLogger` middleware stays the single log format.\n */\nexport function fastifyRuntime(): HttpRuntime<FastifyAppLike> {\n return {\n name: 'fastify',\n\n createApp(options: RuntimeAppOptions = {}): FastifyAppLike {\n const app = createFastify({\n logger: false,\n // Match Express / h3 routing leniency: `/api/v1/hello` and\n // `/api/v1/hello/` resolve to the same route. Without this, Fastify's\n // strict router 404s a trailing-slash request — e.g. a controller's\n // root `@Get('/')` (mounted at the prefix) misses `${prefix}/`. Set under\n // `routerOptions` (Fastify 5+; top-level `ignoreTrailingSlash` is\n // deprecated, removed in Fastify 6).\n routerOptions: { ignoreTrailingSlash: true },\n // `jsonLimit`, which Fastify otherwise ignores in favour of its own 1 MiB.\n ...(options.bodyLimit !== undefined ? { bodyLimit: options.bodyLimit } : {}),\n // Express semantics for every form. Fastify takes a predicate as-is,\n // but reads a hop count as \"trust nothing\", where Express trusts that\n // many hops from the socket.\n trustProxy:\n typeof options.trustProxy === 'number'\n ? hopTrust(options.trustProxy)\n : options.trustProxy,\n }) as FastifyAppLike & {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n }\n app[QUEUE] = []\n\n // Fastify ships parsers for `application/json` and `text/plain` only, and\n // answers 415 for everything else. That made a form post work on Express\n // and h3 but fail on Fastify alone (#590). Register the rest of the\n // framework's supported set so all engines agree.\n //\n // Deliberately NOT a `'*'` catch-all: that would swallow multipart, and\n // `@fastify/multipart` is itself the multipart content-type parser,\n // registered conditionally in `nodeHandler` when a route needs it.\n const addParser = app.addContentTypeParser?.bind(app)\n if (addParser) {\n // `application/*+json` — RFC 6838 §4.2.8 guarantees the bytes are JSON.\n addParser(\n /^application\\/[\\w.+-]+\\+json$/,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n if (body === '') return done(null, undefined)\n try {\n done(null, JSON.parse(body as string))\n } catch (err) {\n // A bare SyntaxError carries no status, so the shared error handler\n // would call it a 500 — Fastify's own JSON parser answers 400\n // (FST_ERR_CTP_INVALID_JSON_BODY), and so must this one.\n done(\n HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n ),\n undefined,\n )\n }\n },\n )\n addParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, parseForm(body as string))\n },\n )\n // `text/*` beyond Fastify's built-in `text/plain`. Raw string, never\n // JSON: `text/plain` is CORS-safelisted, so parsing it as JSON would\n // re-open no-preflight CSRF against a JSON API.\n addParser(\n /^text\\//,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, body)\n },\n )\n // Fastify already answers 415 for a type it has no parser for, but with\n // its own message and no `Accept`. `'*'` is Fastify's documented\n // fallback — consulted only when nothing more specific matches — so it\n // does not shadow the parsers above, nor `@fastify/multipart`, which\n // registers `multipart/form-data` when an upload route needs it.\n addParser(\n '*',\n { parseAs: 'string' },\n (req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n // No body is not an unsupported body. Fastify calls the parser even\n // for an empty payload, so without this a bodyless POST carrying an\n // unrelated content type would be rejected.\n if (!body) return done(null, undefined)\n done(unsupportedMediaTypeError(req.headers?.['content-type']), undefined)\n },\n )\n }\n\n if (options.notFoundFallthrough === false) {\n ;(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH] = true\n }\n return app\n },\n\n nodeHandler(app) {\n // Register middie + queued connect middleware + finalize `ready()` exactly\n // ONCE per app, even though Application may call nodeHandler per request.\n const state = app as {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n [READY]?: Promise<void>\n [NEEDS_MULTIPART]?: boolean\n }\n if (!state[READY]) {\n state[READY] = (async () => {\n // Register @fastify/multipart first when any route uses @FileUpload so\n // `request.parts()` is available. Our applyUploadConfig enforces the\n // real per-file maxSize, so give the plugin a generous fileSize ceiling\n // (its 1MB default would silently truncate larger uploads first).\n if (state[NEEDS_MULTIPART]) {\n const multipart = pluginOf(await import('@fastify/multipart'))\n await app.register(multipart, { limits: { fileSize: Number.MAX_SAFE_INTEGER } })\n }\n const middie = pluginOf(await import('@fastify/middie'))\n await app.register(middie)\n for (const { mw, opts } of state[QUEUE] ?? []) {\n if (opts?.path !== undefined)\n (app.use as (p: unknown, m: unknown) => void)(opts.path, mw)\n else (app.use as (m: unknown) => void)(mw)\n }\n await app.ready()\n })()\n }\n const readyP = state[READY]\n // Once ready, route synchronously — no promise hop per request.\n let ready = false\n readyP.then(\n () => (ready = true),\n () => {},\n )\n\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n if (ready) {\n app.routing(req, res)\n return\n }\n readyP\n .then(() => app.routing(req, res))\n .catch((err) => {\n if (next) return next(err)\n // No host to hand the error to: answer rather than leave the request open.\n log.error(err, 'Fastify failed to start')\n res.statusCode = 500\n res.end('Internal Server Error')\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n if (entry.meta.upload) (app as { [NEEDS_MULTIPART]?: boolean })[NEEDS_MULTIPART] = true\n const url = joinPath(mountPath, entry.path)\n app.route({ method: entry.method, url, handler: routeHandler(entry) })\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const queue = (\n app as { [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }> }\n )[QUEUE]\n queue?.push({ mw, opts })\n },\n\n serveStatic(app, prefix, dir) {\n // Serve via `serve-static` (the standalone connect middleware behind\n // express.static) so the Fastify runtime carries no `express` dependency —\n // queued like any other connect middleware, bridged through middie.\n this.useConnect(app, lazyServeStatic(dir), { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n app.setNotFoundHandler((request, reply) => {\n const next = (request.raw as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT]\n if (next && !(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH]) {\n // Vite dev fall-through: hand the request back to the outer chain.\n reply.hijack()\n next()\n return\n }\n // Pass the reply DRIVER (not raw res) so the connect-style\n // notFoundHandler's `res.status().json()` lands on the Fastify reply.\n // In the route's store when a route handed over (`callNotFound()`).\n inRouteStore(request.raw, reply.raw, () =>\n settleOrFail(\n reply,\n (mw as (req: unknown, res: unknown, next: () => void) => unknown)(\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n ),\n )\n })\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n app.setErrorHandler((err, request, reply) => {\n // Reply driver (not raw res) so the connect-style errorHandler's\n // `res.status().json()` / `setHeader` land on the Fastify reply.\n // In the route's store: Fastify calls this outside it, and an error\n // page should see the handler's ctx values and REQUEST-scoped instances.\n inRouteStore(request.raw, reply.raw, () =>\n settleOrFail(\n reply,\n (mw as (e: unknown, req: unknown, res: unknown, next: () => void) => unknown)(\n err,\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n ),\n )\n })\n },\n\n close(app) {\n // Runs the instance's onClose hooks (plugins registered on it).\n return app.close()\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The Fastify runtime's engine-native types — what the runtime-typed escape\n * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here. `AdapterContext.app` / `getRuntimeApp()`\n * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.\n * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.\n */\nexport interface FastifyRuntimeTypes {\n request: import('fastify').FastifyRequest\n response: import('fastify').FastifyReply\n app: import('fastify').FastifyInstance\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n // A root route path ('/' or '') maps to the mount prefix itself — otherwise a\n // controller `@Post('/')` would register at `${prefix}/`, and a request to\n // `${prefix}` (no trailing slash) wouldn't match under Fastify's strict router.\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;A,q8BA2DA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W,IAAK,gBAAgB,GAAG,EAAG,CAAE,KAAM,MAAO,CAAC,CAC7D,EAEA,YAAY,IAAK,GAAuB,CACtC,IAAI,oBAAoB,QAAS,QAAU,CACzC,IAAM,KAAQ,QAAQ,IAA+D,MACjF,MAAQ,CAAE,IAAuC,iBAEnD,MAAM,OAAO,EACb,KAAK,GAMP,aAAa,QAAQ,IAAK,MAAM,QAC9B,aACE,MACC,GACC,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CACF,CAAC,CACH,EAEA,gBAAgB,IAAK,GAAuB,CAC1C,IAAI,iBAAiB,IAAK,QAAS,QAAU,CAK3C,aAAa,QAAQ,IAAK,MAAM,QAC9B,aACE,MACC,GACC,IACA,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CACF,CAAC,CACH,EAEA,MAAM,IAAK,CAET,OAAO,IAAI,MAAM,CACnB,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAgBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAM7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C,C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
 
2
- import { d as HttpRuntime } from "../../adapter-B64IOivZ.mjs";
2
+ import { d as HttpRuntime } from "../../adapter-D_nUmKEQ.mjs";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  interface H3AppLike {
5
5
  on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.2
2
+ * @forinda/kickjs v10.15.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as lazyServeStatic}from"../../lazy-serve-static-DVWmKM7Z.mjs";import{n as headFromGet,r as readThrough,t as compileWebRoute}from"../../handler-B66laQY0.mjs";import{f as requestStore}from"../../view-renderer-C4sMEruA.mjs";import{n as disposeRequestStore,t as createRequestStore}from"../../request-scope-D2WQwatk.mjs";import{n as WebResponseDriver,t as WebRequestShim}from"../../driver-oZBQDJZz.mjs";import{createLogger}from"../../core/logger.mjs";import{errorHandler,notFoundHandler}from"../middleware/error-handler.mjs";import*as h3Peer from"h3";const builtInError=errorHandler(),builtInNotFound=notFoundHandler(),log=createLogger(`H3Runtime`),NOTFOUND_MW=Symbol(`kickjs.h3web.notFoundMw`),ERROR_MW=Symbol(`kickjs.h3web.errorMw`),ASSEMBLED=Symbol(`kickjs.h3web.assembled`),NOOP_NEXT=()=>{},NEXT=Symbol(`kickjs.h3web.next`),NO_FALLTHROUGH=Symbol(`kickjs.h3web.noFallthrough`),TRUST_PROXY=Symbol(`kickjs.h3.trustProxy`),BODY_LIMIT=Symbol(`kickjs.h3.bodyLimit`),H3_HANDLED=Symbol.for(`h3.handled`);function unwrapH3Module(mod){let m=mod;return m&&m.__esModule&&m.default?{...m.default,...m}:m}function loadH3v2(injected){let resolved=unwrapH3Module(injected??h3Peer);if(typeof resolved.H3!=`function`)throw Error(`@forinda/kickjs: h3Runtime() requires h3 v2, but the installed h3 has no H3 class — that is the v1 line, which this version of KickJS no longer supports. Upgrade h3 to ^2.`);return resolved}async function runConnectTerminal(mw,event,err){let shim=new WebRequestShim(event.req,event.url),carry=event.req.runtime?.node?.req??FETCH_CONNECT.get(event)?.req,req=carry?readThrough(shim,carry):shim,driver=new WebResponseDriver(event.req.signal),store=createRequestStore(req.requestId||(event.req.headers.get(`x-request-id`)??``)),work=requestStore.run(store,()=>answerTerminal(mw,req,driver,err)),dispose=()=>disposeRequestStore(store);return work.then(()=>driver.ready).then(dispose,dispose),await work,driver.ready}async function answerTerminal(mw,req,driver,err){let failure=err;if(mw){let returned=err===void 0?mw(req,driver,NOOP_NEXT):mw(err,req,driver,NOOP_NEXT);if(typeof returned?.then==`function`)try{await returned}catch(handlerErr){log.error(handlerErr,`h3: the ${err===void 0?`not-found`:`error`} handler failed`),failure??=handlerErr}}driver.settled||(failure===void 0?builtInNotFound(req,driver,NOOP_NEXT):await builtInError(failure,req,driver,NOOP_NEXT))}const FETCH_CONNECT=/* @__PURE__ */ new WeakMap;function fetchConnectState(event){let state=FETCH_CONNECT.get(event);return state||(state={req:new WebRequestShim(event.req,event.url),headers:new Headers},FETCH_CONNECT.set(event,state)),state}function withConnectHeaders(event,response){let state=FETCH_CONNECT.get(event);if(!state)return response;let missing=[...state.headers].filter(([name])=>name===`set-cookie`||!response.headers.has(name));if(state.headers=new Headers,missing.length===0)return response;try{for(let[name,value]of missing)response.headers.append(name,value);return response}catch{let headers=new Headers(response.headers);for(let[name,value]of missing)headers.append(name,value);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}var FetchConnectResponse=class extends WebResponseDriver{prepared;code=200;listeners=[];constructor(prepared,signal){super(signal),this.prepared=prepared}get statusCode(){return this.code}set statusCode(code){this.status(code)}status(code){return this.code=code,super.status(code)}writeHead(code,headers){return this.code=code,super.writeHead(code,headers)}setHeader(name,value){if(Array.isArray(value)){this.prepared.delete(name);for(let v of value)this.prepared.append(name,String(v))}else this.prepared.set(name,String(value));return this}getHeader(name){return this.prepared.get(name)??void 0}hasHeader(name){return this.prepared.has(name)}removeHeader(name){this.prepared.delete(name)}once(event,listener){return this.listeners.push([event,listener]),this}on(event,listener){return this.once(event,listener)}removeListener(event,listener){return this.listeners=this.listeners.filter(([e,l])=>e!==event||l!==listener),this}off(event,listener){return this.removeListener(event,listener)}done(){let pending=[];for(let event of[`finish`,`close`]){for(let[e,listener]of this.listeners){if(e!==event)continue;let out;try{out=listener()}catch(err){log.error(err,`h3: a '${event}' listener failed`);continue}out&&typeof out.then==`function`&&pending.push(Promise.resolve(out).catch(()=>{}))}this.listeners=this.listeners.filter(([e])=>e!==event)}return Promise.all(pending).then(()=>{})}};function runConnectOnFetch(mw,event,next){let state=fetchConnectState(event),res=new FetchConnectResponse(state.headers,event.req.signal);return new Promise((resolve,reject)=>{let respond=response=>{res.done().then(()=>resolve(withConnectHeaders(event,response)))},fail=err=>{res.done().then(()=>reject(err))};res.ready.then(respond);let connectNext=err=>{if(err)return fail(err);if(res.settled)return;let id=state.req.requestId;if(id&&event.req.headers.get(`x-request-id`)!==id)try{event.req.headers.set(`x-request-id`,id)}catch{}let downstream;try{downstream=next()}catch(e){return fail(e)}Promise.resolve(downstream).then(value=>{if(value instanceof Response)return respond(value);res.done().then(()=>resolve(value))},fail)};try{mw(state.req,res,connectNext)}catch(err){fail(err)}})}function assembleCatchAll(app){let state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,app.all(`/**`,event=>{let node=event.req.runtime?.node,next=node?.req?.[NEXT];if(node&&next&&!state[NO_FALLTHROUGH])return new Promise(resolve=>{let done=()=>resolve(H3_HANDLED);node.res.once(`finish`,done),node.res.once(`close`,done),next()});let mw=state[NOTFOUND_MW];return runConnectTerminal(mw,event)}))}function proxyTrust(option){if(option!==void 0&&option!==!1){if(option===!0)return()=>!0;if(typeof option==`number`)return(_address,hop)=>hop<option;if(typeof option==`function`)return option;log.warn(`h3: trustProxy as an address or subnet list is not supported; client IPs use the socket address. Use a hop count or a function instead.`)}}function forwardedClientIp(req,trust){let socket=req.socket?.remoteAddress;if(!socket)return;let header=req.headers[`x-forwarded-for`],chain=[socket,...(Array.isArray(header)?header.join(`,`):header??``).split(`,`).map(s=>s.trim()).filter(Boolean).toReversed()];for(let hop=0;hop<chain.length-1;hop++)if(!trust(chain[hop],hop))return chain[hop];return chain[chain.length-1]}function stripMountPrefix(path,mw){let prefix=path.endsWith(`/`)?path.slice(0,-1):path;return prefix===``?mw:((req,res,next)=>{let url=req.url??`/`,rest=url.startsWith(prefix)?url.slice(prefix.length):null;return rest===null||rest!==``&&rest[0]!==`/`&&rest[0]!==`?`?mw(req,res,next):(req.originalUrl??=url,req.url=rest.startsWith(`/`)?rest:`/${rest}`,mw(req,res,err=>{req.url=url,next(err)}))})}function h3Runtime(options={}){let{H3,toNodeHandler,fromNodeHandler}=loadH3v2(options.h3);return{name:`h3`,createApp(options={}){let holder={},app=new H3({onError:(error,event)=>{let mw=holder.app?.[ERROR_MW];return runConnectTerminal(mw,event,error).then(response=>withConnectHeaders(event,response))}});return holder.app=app,app[NO_FALLTHROUGH]=options.notFoundFallthrough===!1,app[TRUST_PROXY]=proxyTrust(options.trustProxy),app[BODY_LIMIT]=options.bodyLimit,app},nodeHandler(app){assembleCatchAll(app);let listener=toNodeHandler(app),trust=app[TRUST_PROXY];return(req,res,next)=>{if(next&&(req[NEXT]=next),trust&&!req.ip){let ip=forwardedClientIp(req,trust);ip&&(req.ip=ip)}res.setMaxListeners(0);try{let result=listener(req,res);result&&typeof result.then==`function`&&result.catch(err=>next?.(err))}catch(err){next?.(err)}}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path),run=compileWebRoute(entry,{onError:async(err,req,driver)=>{let mw=app[ERROR_MW];if(mw)try{await mw(err,req,driver,NOOP_NEXT)}catch(handlerErr){log.error(handlerErr,`h3: the error handler failed`),driver.settled||await builtInError(err,req,driver,NOOP_NEXT)}}},{bodyLimit:app[BODY_LIMIT]}),handler=event=>run({request:event.req,url:event.url,params:event.context.params??{},carry:event.req.runtime?.node?.req??FETCH_CONNECT.get(event)?.req});app.on(entry.method,url,handler),entry.method===`GET`&&app.on(`HEAD`,url,event=>headFromGet(handler(event)))}},useConnect(app,rawMw,opts){let path=opts?.path;if(Array.isArray(path)){for(let member of path)this.useConnect(app,rawMw,{path:member});return}let mw=typeof path==`string`?stripMountPrefix(path,rawMw):rawMw,viaNode=fromNodeHandler(mw),handler=(event,next)=>event.req.runtime?.node?.res?viaNode(event):runConnectOnFetch(mw,event,next);path instanceof RegExp?app.use((event,next)=>path.test(event.url.pathname)?handler(event,next):next()):typeof path==`string`?app.use(joinPath(path,`/**`),handler):app.use(handler)},serveStatic(app,prefix,dir){this.useConnect(app,lazyServeStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw,assembleCatchAll(app)},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}const h3WebRuntime=h3Runtime;export{h3Runtime,h3WebRuntime};
11
+ import{t as lazyServeStatic}from"../../lazy-serve-static-DxI2K-zs.mjs";import{n as headFromGet,r as readThrough,t as compileWebRoute}from"../../handler-C8iAD_xz.mjs";import{f as requestStore}from"../../view-renderer-Bf1Wy-DQ.mjs";import{n as disposeRequestStore,t as createRequestStore}from"../../request-scope-BfSNdmz9.mjs";import{n as WebResponseDriver,t as WebRequestShim}from"../../driver-D59oWDec.mjs";import{createLogger}from"../../core/logger.mjs";import{errorHandler,notFoundHandler}from"../middleware/error-handler.mjs";import*as h3Peer from"h3";const builtInError=errorHandler(),builtInNotFound=notFoundHandler(),log=createLogger(`H3Runtime`),NOTFOUND_MW=Symbol(`kickjs.h3web.notFoundMw`),ERROR_MW=Symbol(`kickjs.h3web.errorMw`),ASSEMBLED=Symbol(`kickjs.h3web.assembled`),NOOP_NEXT=()=>{},NEXT=Symbol(`kickjs.h3web.next`),NO_FALLTHROUGH=Symbol(`kickjs.h3web.noFallthrough`),TRUST_PROXY=Symbol(`kickjs.h3.trustProxy`),BODY_LIMIT=Symbol(`kickjs.h3.bodyLimit`),H3_HANDLED=Symbol.for(`h3.handled`);function unwrapH3Module(mod){let m=mod;return m&&m.__esModule&&m.default?{...m.default,...m}:m}function loadH3v2(injected){let resolved=unwrapH3Module(injected??h3Peer);if(typeof resolved.H3!=`function`)throw Error(`@forinda/kickjs: h3Runtime() requires h3 v2, but the installed h3 has no H3 class — that is the v1 line, which this version of KickJS no longer supports. Upgrade h3 to ^2.`);return resolved}async function runConnectTerminal(mw,event,err){let shim=new WebRequestShim(event.req,event.url),carry=event.req.runtime?.node?.req??FETCH_CONNECT.get(event)?.req,req=carry?readThrough(shim,carry):shim,driver=new WebResponseDriver(event.req.signal),store=createRequestStore(req.requestId||(event.req.headers.get(`x-request-id`)??``)),work=requestStore.run(store,()=>answerTerminal(mw,req,driver,err)),dispose=()=>disposeRequestStore(store);return work.then(()=>driver.ready).then(dispose,dispose),await work,driver.ready}async function answerTerminal(mw,req,driver,err){let failure=err;if(mw){let returned=err===void 0?mw(req,driver,NOOP_NEXT):mw(err,req,driver,NOOP_NEXT);if(typeof returned?.then==`function`)try{await returned}catch(handlerErr){log.error(handlerErr,`h3: the ${err===void 0?`not-found`:`error`} handler failed`),failure??=handlerErr}}driver.settled||(failure===void 0?builtInNotFound(req,driver,NOOP_NEXT):await builtInError(failure,req,driver,NOOP_NEXT))}const FETCH_CONNECT=/* @__PURE__ */ new WeakMap;function fetchConnectState(event){let state=FETCH_CONNECT.get(event);return state||(state={req:new WebRequestShim(event.req,event.url),headers:new Headers},FETCH_CONNECT.set(event,state)),state}function withConnectHeaders(event,response){let state=FETCH_CONNECT.get(event);if(!state)return response;let missing=[...state.headers].filter(([name])=>name===`set-cookie`||!response.headers.has(name));if(state.headers=new Headers,missing.length===0)return response;try{for(let[name,value]of missing)response.headers.append(name,value);return response}catch{let headers=new Headers(response.headers);for(let[name,value]of missing)headers.append(name,value);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}var FetchConnectResponse=class extends WebResponseDriver{prepared;code=200;listeners=[];constructor(prepared,signal){super(signal),this.prepared=prepared}get statusCode(){return this.code}set statusCode(code){this.status(code)}status(code){return this.code=code,super.status(code)}writeHead(code,headers){return this.code=code,super.writeHead(code,headers)}setHeader(name,value){if(Array.isArray(value)){this.prepared.delete(name);for(let v of value)this.prepared.append(name,String(v))}else this.prepared.set(name,String(value));return this}getHeader(name){return this.prepared.get(name)??void 0}hasHeader(name){return this.prepared.has(name)}removeHeader(name){this.prepared.delete(name)}once(event,listener){return this.listeners.push([event,listener]),this}on(event,listener){return this.once(event,listener)}removeListener(event,listener){return this.listeners=this.listeners.filter(([e,l])=>e!==event||l!==listener),this}off(event,listener){return this.removeListener(event,listener)}done(){let pending=[];for(let event of[`finish`,`close`]){for(let[e,listener]of this.listeners){if(e!==event)continue;let out;try{out=listener()}catch(err){log.error(err,`h3: a '${event}' listener failed`);continue}out&&typeof out.then==`function`&&pending.push(Promise.resolve(out).catch(()=>{}))}this.listeners=this.listeners.filter(([e])=>e!==event)}return Promise.all(pending).then(()=>{})}};function runConnectOnFetch(mw,event,next){let state=fetchConnectState(event),res=new FetchConnectResponse(state.headers,event.req.signal);return new Promise((resolve,reject)=>{let respond=response=>{res.done().then(()=>resolve(withConnectHeaders(event,response)))},fail=err=>{res.done().then(()=>reject(err))};res.ready.then(respond);let connectNext=err=>{if(err)return fail(err);if(res.settled)return;let id=state.req.requestId;if(id&&event.req.headers.get(`x-request-id`)!==id)try{event.req.headers.set(`x-request-id`,id)}catch{}let downstream;try{downstream=next()}catch(e){return fail(e)}Promise.resolve(downstream).then(value=>{if(value instanceof Response)return respond(value);res.done().then(()=>resolve(value))},fail)};try{mw(state.req,res,connectNext)}catch(err){fail(err)}})}function assembleCatchAll(app){let state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,app.all(`/**`,event=>{let node=event.req.runtime?.node,next=node?.req?.[NEXT];if(node&&next&&!state[NO_FALLTHROUGH])return new Promise(resolve=>{let done=()=>resolve(H3_HANDLED);node.res.once(`finish`,done),node.res.once(`close`,done),next()});let mw=state[NOTFOUND_MW];return runConnectTerminal(mw,event)}))}function proxyTrust(option){if(option!==void 0&&option!==!1){if(option===!0)return()=>!0;if(typeof option==`number`)return(_address,hop)=>hop<option;if(typeof option==`function`)return option;log.warn(`h3: trustProxy as an address or subnet list is not supported; client IPs use the socket address. Use a hop count or a function instead.`)}}function forwardedClientIp(req,trust){let socket=req.socket?.remoteAddress;if(!socket)return;let header=req.headers[`x-forwarded-for`],chain=[socket,...(Array.isArray(header)?header.join(`,`):header??``).split(`,`).map(s=>s.trim()).filter(Boolean).toReversed()];for(let hop=0;hop<chain.length-1;hop++)if(!trust(chain[hop],hop))return chain[hop];return chain[chain.length-1]}function stripMountPrefix(path,mw){let prefix=path.endsWith(`/`)?path.slice(0,-1):path;return prefix===``?mw:((req,res,next)=>{let url=req.url??`/`,rest=url.startsWith(prefix)?url.slice(prefix.length):null;return rest===null||rest!==``&&rest[0]!==`/`&&rest[0]!==`?`?mw(req,res,next):(req.originalUrl??=url,req.url=rest.startsWith(`/`)?rest:`/${rest}`,mw(req,res,err=>{req.url=url,next(err)}))})}function h3Runtime(options={}){let{H3,toNodeHandler,fromNodeHandler}=loadH3v2(options.h3);return{name:`h3`,createApp(options={}){let holder={},app=new H3({onError:(error,event)=>{let mw=holder.app?.[ERROR_MW];return runConnectTerminal(mw,event,error).then(response=>withConnectHeaders(event,response))}});return holder.app=app,app[NO_FALLTHROUGH]=options.notFoundFallthrough===!1,app[TRUST_PROXY]=proxyTrust(options.trustProxy),app[BODY_LIMIT]=options.bodyLimit,app},nodeHandler(app){assembleCatchAll(app);let listener=toNodeHandler(app),trust=app[TRUST_PROXY];return(req,res,next)=>{if(next&&(req[NEXT]=next),trust&&!req.ip){let ip=forwardedClientIp(req,trust);ip&&(req.ip=ip)}res.setMaxListeners(0);try{let result=listener(req,res);result&&typeof result.then==`function`&&result.catch(err=>next?.(err))}catch(err){next?.(err)}}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path),run=compileWebRoute(entry,{onError:async(err,req,driver)=>{let mw=app[ERROR_MW];if(mw)try{await mw(err,req,driver,NOOP_NEXT)}catch(handlerErr){log.error(handlerErr,`h3: the error handler failed`),driver.settled||await builtInError(err,req,driver,NOOP_NEXT)}}},{bodyLimit:app[BODY_LIMIT]}),handler=event=>run({request:event.req,url:event.url,params:event.context.params??{},carry:event.req.runtime?.node?.req??FETCH_CONNECT.get(event)?.req});app.on(entry.method,url,handler),entry.method===`GET`&&app.on(`HEAD`,url,event=>headFromGet(handler(event)))}},useConnect(app,rawMw,opts){let path=opts?.path;if(Array.isArray(path)){for(let member of path)this.useConnect(app,rawMw,{path:member});return}let mw=typeof path==`string`?stripMountPrefix(path,rawMw):rawMw,viaNode=fromNodeHandler(mw),handler=(event,next)=>event.req.runtime?.node?.res?viaNode(event):runConnectOnFetch(mw,event,next);path instanceof RegExp?app.use((event,next)=>path.test(event.url.pathname)?handler(event,next):next()):typeof path==`string`?app.use(joinPath(path,`/**`),handler):app.use(handler)},serveStatic(app,prefix,dir){this.useConnect(app,lazyServeStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw,assembleCatchAll(app)},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}const h3WebRuntime=h3Runtime;export{h3Runtime,h3WebRuntime};
12
12
  //# sourceMappingURL=h3.mjs.map