@forinda/kickjs 10.14.0 → 10.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/dist/{adapter-DL9JPcvC.d.mts → adapter-B64IOivZ.d.mts} +13 -53
  2. package/dist/adapter-B64IOivZ.d.mts.map +1 -0
  3. package/dist/{allowed-hosts-BpKwviq5.d.mts → allowed-hosts-U12_gESr.d.mts} +2 -4
  4. package/dist/allowed-hosts-U12_gESr.d.mts.map +1 -0
  5. package/dist/{app-module-Dk2Wenqx.d.mts → app-module-EmIojM4d.d.mts} +5 -11
  6. package/dist/app-module-EmIojM4d.d.mts.map +1 -0
  7. package/dist/application-BzimU62Q.mjs +14 -0
  8. package/dist/application-BzimU62Q.mjs.map +1 -0
  9. package/dist/{application-D921r4MW.d.mts → application-CGcY8SZZ.d.mts} +22 -74
  10. package/dist/application-CGcY8SZZ.d.mts.map +1 -0
  11. package/dist/{body-policy-CaerQ_lu.mjs → body-policy-Be3Y0hjq.mjs} +2 -2
  12. package/dist/{body-policy-CaerQ_lu.mjs.map → body-policy-Be3Y0hjq.mjs.map} +1 -1
  13. package/dist/{bootstrap-BXLsEeMW.mjs → bootstrap-Bvk3BWJX.mjs} +3 -3
  14. package/dist/{bootstrap-BXLsEeMW.mjs.map → bootstrap-Bvk3BWJX.mjs.map} +1 -1
  15. package/dist/{bounded-counters-DFef_B7d.mjs → bounded-counters-Bh5jeT9I.mjs} +2 -2
  16. package/dist/{bounded-counters-DFef_B7d.mjs.map → bounded-counters-Bh5jeT9I.mjs.map} +1 -1
  17. package/dist/{breach-padding-FBVGmcBb.d.mts → breach-padding-DfT9MXGb.d.mts} +2 -4
  18. package/dist/breach-padding-DfT9MXGb.d.mts.map +1 -0
  19. package/dist/{cache-CdRHSXow.d.mts → cache-DMIt3c6M.d.mts} +1 -3
  20. package/dist/cache-DMIt3c6M.d.mts.map +1 -0
  21. package/dist/{client-ip-DE5vkJWL.mjs → client-ip-CGH_IvnC.mjs} +2 -2
  22. package/dist/{client-ip-DE5vkJWL.mjs.map → client-ip-CGH_IvnC.mjs.map} +1 -1
  23. package/dist/config/index.d.mts +1 -1
  24. package/dist/config/index.mjs +2 -2
  25. package/dist/{config-De3xzaiZ.mjs → config-CjFxvh0v.mjs} +3 -3
  26. package/dist/{config-De3xzaiZ.mjs.map → config-CjFxvh0v.mjs.map} +1 -1
  27. package/dist/{connect-BlIamapT.d.mts → connect-DamOelO8.d.mts} +1 -3
  28. package/dist/connect-DamOelO8.d.mts.map +1 -0
  29. package/dist/{context-DBLyIErA.mjs → context-BvZLaTeE.mjs} +3 -3
  30. package/dist/{context-DBLyIErA.mjs.map → context-BvZLaTeE.mjs.map} +1 -1
  31. package/dist/{context-errors-By-pwipc.mjs → context-errors-BZVS0B1O.mjs} +2 -2
  32. package/dist/{context-errors-By-pwipc.mjs.map → context-errors-BZVS0B1O.mjs.map} +1 -1
  33. package/dist/{contributor-runner-BuMi_eLU.mjs → contributor-runner-fdKy6Tme.mjs} +3 -3
  34. package/dist/{contributor-runner-BuMi_eLU.mjs.map → contributor-runner-fdKy6Tme.mjs.map} +1 -1
  35. package/dist/core/adapter.d.mts +1 -1
  36. package/dist/core/adapter.mjs +1 -1
  37. package/dist/core/app-module.d.mts +1 -1
  38. package/dist/core/app-module.mjs +1 -1
  39. package/dist/core/cache.d.mts +1 -1
  40. package/dist/core/cache.mjs +1 -1
  41. package/dist/core/cache.mjs.map +1 -1
  42. package/dist/core/container.mjs +2 -2
  43. package/dist/core/cron.d.mts +1 -1
  44. package/dist/core/cron.mjs +2 -2
  45. package/dist/core/cron.mjs.map +1 -1
  46. package/dist/core/decorators.d.mts +1 -1
  47. package/dist/core/decorators.mjs +2 -2
  48. package/dist/core/decorators.mjs.map +1 -1
  49. package/dist/core/errors.d.mts +1 -1
  50. package/dist/core/errors.mjs +1 -1
  51. package/dist/core/errors.mjs.map +1 -1
  52. package/dist/core/interfaces.d.mts +1 -1
  53. package/dist/core/interfaces.mjs +1 -1
  54. package/dist/core/interfaces.mjs.map +1 -1
  55. package/dist/core/logger.d.mts +1 -1
  56. package/dist/core/logger.mjs +1 -1
  57. package/dist/core/logger.mjs.map +1 -1
  58. package/dist/core/path.d.mts +1 -1
  59. package/dist/core/path.mjs +1 -1
  60. package/dist/core/path.mjs.map +1 -1
  61. package/dist/core/plugin.d.mts +1 -1
  62. package/dist/core/plugin.mjs +1 -1
  63. package/dist/core/reactivity.d.mts +1 -1
  64. package/dist/core/reactivity.mjs +2 -2
  65. package/dist/core/reactivity.mjs.map +1 -1
  66. package/dist/{core-BziwPF77.mjs → core-CCIpjo6g.mjs} +3 -3
  67. package/dist/{core-BziwPF77.mjs.map → core-CCIpjo6g.mjs.map} +1 -1
  68. package/dist/{cors-BlR_b0Qb.d.mts → cors-J-q6PuSU.d.mts} +2 -4
  69. package/dist/cors-J-q6PuSU.d.mts.map +1 -0
  70. package/dist/{cron-BTGytNg-.d.mts → cron-DGV1AE0R.d.mts} +1 -3
  71. package/dist/cron-DGV1AE0R.d.mts.map +1 -0
  72. package/dist/{csrf-DOAaYozG.d.mts → csrf-DjtJPgA3.d.mts} +4 -6
  73. package/dist/csrf-DjtJPgA3.d.mts.map +1 -0
  74. package/dist/decorate-DRbXCNQz.mjs +13 -0
  75. package/dist/decorate-DRbXCNQz.mjs.map +1 -0
  76. package/dist/{decorators-DxNb5mWw.d.mts → decorators-BAD8qjuq.d.mts} +1 -5
  77. package/dist/decorators-BAD8qjuq.d.mts.map +1 -0
  78. package/dist/{define-adapter-CbVg-Fyh.mjs → define-adapter-DMo6og81.mjs} +2 -2
  79. package/dist/{define-adapter-CbVg-Fyh.mjs.map → define-adapter-DMo6og81.mjs.map} +1 -1
  80. package/dist/{di-hooks-DN_UC8Nc.mjs → di-hooks-DCqt2yJ9.mjs} +2 -2
  81. package/dist/{di-hooks-DN_UC8Nc.mjs.map → di-hooks-DCqt2yJ9.mjs.map} +1 -1
  82. package/dist/{disposables-C4BLa-Pc.mjs → disposables-BsdVu69-.mjs} +1 -1
  83. package/dist/{driver-DyWsGdcD.mjs → driver-oZBQDJZz.mjs} +3 -3
  84. package/dist/{driver-DyWsGdcD.mjs.map → driver-oZBQDJZz.mjs.map} +1 -1
  85. package/dist/{error-handler-D7DLWe1Q.d.mts → error-handler-Dl_gZRNK.d.mts} +2 -4
  86. package/dist/error-handler-Dl_gZRNK.d.mts.map +1 -0
  87. package/dist/{errors-By6UueCm.d.mts → errors-DZGuPLoZ.d.mts} +1 -3
  88. package/dist/errors-DZGuPLoZ.d.mts.map +1 -0
  89. package/dist/{express-FnNSFECr.mjs → express-f9CTA8qO.mjs} +3 -3
  90. package/dist/{express-FnNSFECr.mjs.map → express-f9CTA8qO.mjs.map} +1 -1
  91. package/dist/{express-lazy-B8AFaCA-.mjs → express-lazy-DMxcLBpT.mjs} +3 -3
  92. package/dist/{express-lazy-B8AFaCA-.mjs.map → express-lazy-DMxcLBpT.mjs.map} +1 -1
  93. package/dist/{handler--lTqJdpj.mjs → handler-B66laQY0.mjs} +3 -3
  94. package/dist/{handler--lTqJdpj.mjs.map → handler-B66laQY0.mjs.map} +1 -1
  95. package/dist/{helmet-BVuVBl-D.d.mts → helmet-Rwkbp9IS.d.mts} +2 -4
  96. package/dist/helmet-Rwkbp9IS.d.mts.map +1 -0
  97. package/dist/{host-Dn2rI7s7.mjs → host-DalMsn5Z.mjs} +2 -2
  98. package/dist/{host-Dn2rI7s7.mjs.map → host-DalMsn5Z.mjs.map} +1 -1
  99. package/dist/http/application.d.mts +1 -1
  100. package/dist/http/application.mjs +2 -2
  101. package/dist/http/bootstrap.d.mts +1 -1
  102. package/dist/http/bootstrap.mjs +2 -2
  103. package/dist/http/context.d.mts +2 -2
  104. package/dist/http/context.mjs +2 -2
  105. package/dist/http/middleware/allowed-hosts.d.mts +1 -1
  106. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  107. package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
  108. package/dist/http/middleware/breach-padding.d.mts +1 -1
  109. package/dist/http/middleware/breach-padding.mjs +1 -1
  110. package/dist/http/middleware/breach-padding.mjs.map +1 -1
  111. package/dist/http/middleware/cors.d.mts +1 -1
  112. package/dist/http/middleware/cors.mjs +1 -1
  113. package/dist/http/middleware/cors.mjs.map +1 -1
  114. package/dist/http/middleware/csrf.d.mts +1 -1
  115. package/dist/http/middleware/csrf.mjs +2 -2
  116. package/dist/http/middleware/csrf.mjs.map +1 -1
  117. package/dist/http/middleware/error-handler.d.mts +1 -1
  118. package/dist/http/middleware/error-handler.mjs +2 -2
  119. package/dist/http/middleware/error-handler.mjs.map +1 -1
  120. package/dist/http/middleware/helmet.d.mts +1 -1
  121. package/dist/http/middleware/helmet.mjs +1 -1
  122. package/dist/http/middleware/helmet.mjs.map +1 -1
  123. package/dist/http/middleware/rate-limit.d.mts +1 -1
  124. package/dist/http/middleware/rate-limit.mjs +2 -2
  125. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  126. package/dist/http/middleware/request-id.d.mts +1 -1
  127. package/dist/http/middleware/request-id.mjs +1 -1
  128. package/dist/http/middleware/request-id.mjs.map +1 -1
  129. package/dist/http/middleware/request-logger.d.mts +1 -1
  130. package/dist/http/middleware/request-logger.mjs +2 -2
  131. package/dist/http/middleware/request-logger.mjs.map +1 -1
  132. package/dist/http/middleware/session.d.mts +1 -1
  133. package/dist/http/middleware/session.mjs +2 -2
  134. package/dist/http/middleware/session.mjs.map +1 -1
  135. package/dist/http/middleware/spa.d.mts +1 -1
  136. package/dist/http/middleware/spa.mjs +2 -2
  137. package/dist/http/middleware/spa.mjs.map +1 -1
  138. package/dist/http/middleware/upload.d.mts +2 -2
  139. package/dist/http/middleware/upload.mjs +2 -2
  140. package/dist/http/middleware/upload.mjs.map +1 -1
  141. package/dist/http/middleware/validate.d.mts +1 -1
  142. package/dist/http/middleware/validate.mjs +1 -1
  143. package/dist/http/middleware/validate.mjs.map +1 -1
  144. package/dist/http/middleware/views.d.mts +1 -1
  145. package/dist/http/middleware/views.mjs +2 -2
  146. package/dist/http/middleware/views.mjs.map +1 -1
  147. package/dist/http/query/index.d.mts +1 -1
  148. package/dist/http/query/index.mjs +2 -2
  149. package/dist/http/router-builder.d.mts +1 -1
  150. package/dist/http/router-builder.mjs +2 -2
  151. package/dist/http/runtimes/express.d.mts +3 -7
  152. package/dist/http/runtimes/express.d.mts.map +1 -1
  153. package/dist/http/runtimes/express.mjs +2 -2
  154. package/dist/http/runtimes/fastify.d.mts +1 -3
  155. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  156. package/dist/http/runtimes/fastify.mjs +2 -2
  157. package/dist/http/runtimes/fastify.mjs.map +1 -1
  158. package/dist/http/runtimes/h3-web.mjs +1 -1
  159. package/dist/http/runtimes/h3.d.mts +1 -3
  160. package/dist/http/runtimes/h3.d.mts.map +1 -1
  161. package/dist/http/runtimes/h3.mjs +2 -2
  162. package/dist/http/runtimes/h3.mjs.map +1 -1
  163. package/dist/{index-DP_I4puv.d.mts → index-CFTwnev9.d.mts} +3 -7
  164. package/dist/index-CFTwnev9.d.mts.map +1 -0
  165. package/dist/{index-Blgka75E.d.mts → index-ZbCnCyQx.d.mts} +1 -5
  166. package/dist/index-ZbCnCyQx.d.mts.map +1 -0
  167. package/dist/index.d.mts +30 -30
  168. package/dist/index.mjs +2 -2
  169. package/dist/index.mjs.map +1 -1
  170. package/dist/{interfaces-C6LHcYsg.d.mts → interfaces-BQhYh3lL.d.mts} +1 -3
  171. package/dist/interfaces-BQhYh3lL.d.mts.map +1 -0
  172. package/dist/{is-production-Cx4PGne9.mjs → is-production-9QzMIRuO.mjs} +2 -2
  173. package/dist/{is-production-Cx4PGne9.mjs.map → is-production-9QzMIRuO.mjs.map} +1 -1
  174. package/dist/{jobs-Bgtz3Hlq.mjs → jobs-CuZqVDDG.mjs} +3 -3
  175. package/dist/{jobs-Bgtz3Hlq.mjs.map → jobs-CuZqVDDG.mjs.map} +1 -1
  176. package/dist/{kv-stores-LBIBEueO.mjs → kv-stores-C9CJ3xCB.mjs} +3 -3
  177. package/dist/{kv-stores-LBIBEueO.mjs.map → kv-stores-C9CJ3xCB.mjs.map} +1 -1
  178. package/dist/{kv-stores-CwJdsMln.d.mts → kv-stores-wTD3VDPB.d.mts} +6 -18
  179. package/dist/kv-stores-wTD3VDPB.d.mts.map +1 -0
  180. package/dist/{lazy-serve-static-B9xQ0OE1.mjs → lazy-serve-static-DVWmKM7Z.mjs} +3 -3
  181. package/dist/{lazy-serve-static-B9xQ0OE1.mjs.map → lazy-serve-static-DVWmKM7Z.mjs.map} +1 -1
  182. package/dist/{logger-xE9qI_FS.d.mts → logger-BL8MiSrm.d.mts} +1 -3
  183. package/dist/logger-BL8MiSrm.d.mts.map +1 -0
  184. package/dist/{metadata-DS4TBMoC.mjs → metadata-BZRtQog3.mjs} +1 -1
  185. package/dist/{observers-Dokycjj0.mjs → observers-B4VnKAHK.mjs} +2 -2
  186. package/dist/{observers-Dokycjj0.mjs.map → observers-B4VnKAHK.mjs.map} +1 -1
  187. package/dist/{path-CMwIHsdv.d.mts → path-DsenzqJ7.d.mts} +1 -3
  188. package/dist/path-DsenzqJ7.d.mts.map +1 -0
  189. package/dist/{precompressed-BLYcqIAM.mjs → precompressed-AxF66Ls0.mjs} +2 -2
  190. package/dist/{precompressed-BLYcqIAM.mjs.map → precompressed-AxF66Ls0.mjs.map} +1 -1
  191. package/dist/{query-Cmtgo_-P.mjs → query-BwUR-ssX.mjs} +2 -2
  192. package/dist/{query-Cmtgo_-P.mjs.map → query-BwUR-ssX.mjs.map} +1 -1
  193. package/dist/{rate-limit-DQDk6bAH.d.mts → rate-limit-DMiV6bAq.d.mts} +3 -5
  194. package/dist/rate-limit-DMiV6bAq.d.mts.map +1 -0
  195. package/dist/{reactivity-DZrc3Yhu.d.mts → reactivity-Dski64km.d.mts} +1 -3
  196. package/dist/reactivity-Dski64km.d.mts.map +1 -0
  197. package/dist/{reply-Dcm0NAr0.mjs → reply-B5kZ6VGv.mjs} +3 -3
  198. package/dist/{reply-Dcm0NAr0.mjs.map → reply-B5kZ6VGv.mjs.map} +1 -1
  199. package/dist/{request-id-Dn64nEHK.d.mts → request-id-B_n-3A16.d.mts} +2 -4
  200. package/dist/request-id-B_n-3A16.d.mts.map +1 -0
  201. package/dist/{request-logger-TgcKRNDD.d.mts → request-logger-BV1C5r5q.d.mts} +1 -3
  202. package/dist/request-logger-BV1C5r5q.d.mts.map +1 -0
  203. package/dist/{request-scope-BmhPPGPk.mjs → request-scope-D2WQwatk.mjs} +3 -3
  204. package/dist/{request-scope-BmhPPGPk.mjs.map → request-scope-D2WQwatk.mjs.map} +1 -1
  205. package/dist/{respond-NCvYMEwC.mjs → respond-C6ohI69y.mjs} +2 -2
  206. package/dist/{respond-NCvYMEwC.mjs.map → respond-C6ohI69y.mjs.map} +1 -1
  207. package/dist/{rolldown-runtime-DKvcoND8.mjs → rolldown-runtime-DuhQYUab.mjs} +1 -1
  208. package/dist/{route-flag-DRM2yEZT.mjs → route-flag-CHiMvgar.mjs} +3 -3
  209. package/dist/{route-flag-DRM2yEZT.mjs.map → route-flag-CHiMvgar.mjs.map} +1 -1
  210. package/dist/{route-flag-B1lQht6v.d.mts → route-flag-CjXQl-oX.d.mts} +1 -3
  211. package/dist/route-flag-CjXQl-oX.d.mts.map +1 -0
  212. package/dist/{route-policy-T8RavXEx.mjs → route-policy-ckK7N1eN.mjs} +2 -2
  213. package/dist/{route-policy-T8RavXEx.mjs.map → route-policy-ckK7N1eN.mjs.map} +1 -1
  214. package/dist/{router-builder-iEHiFSZh.mjs → router-builder-D2cly8Wt.mjs} +3 -3
  215. package/dist/{router-builder-iEHiFSZh.mjs.map → router-builder-D2cly8Wt.mjs.map} +1 -1
  216. package/dist/{router-builder-C5EtcFSL.d.mts → router-builder-Dtyya4qP.d.mts} +3 -5
  217. package/dist/router-builder-Dtyya4qP.d.mts.map +1 -0
  218. package/dist/{runtime-D9KW2aLY.mjs → runtime-D9TN6CpL.mjs} +3 -3
  219. package/dist/{runtime-D9KW2aLY.mjs.map → runtime-D9TN6CpL.mjs.map} +1 -1
  220. package/dist/{session-DQG72vCf.d.mts → session-CXWu2rXW.d.mts} +2 -4
  221. package/dist/session-CXWu2rXW.d.mts.map +1 -0
  222. package/dist/{settings-DgZLgcNU.d.mts → settings-CB6lh6_s.d.mts} +1 -3
  223. package/dist/settings-CB6lh6_s.d.mts.map +1 -0
  224. package/dist/{settings-hG4DH8hQ.mjs → settings-v2N3V8Bl.mjs} +4 -4
  225. package/dist/settings-v2N3V8Bl.mjs.map +1 -0
  226. package/dist/{token-i5RynFrd.mjs → token-DtW16tw3.mjs} +1 -1
  227. package/dist/{upload-config-CTwzXhph.mjs → upload-config-BXjBiNjC.mjs} +2 -2
  228. package/dist/{upload-config-CTwzXhph.mjs.map → upload-config-BXjBiNjC.mjs.map} +1 -1
  229. package/dist/{upload-DnwvZQyi.d.mts → upload-eNNueUxR.d.mts} +4 -6
  230. package/dist/upload-eNNueUxR.d.mts.map +1 -0
  231. package/dist/{url-for-CQNJYjRH.mjs → url-for-C4Eomib7.mjs} +3 -3
  232. package/dist/{url-for-CQNJYjRH.mjs.map → url-for-C4Eomib7.mjs.map} +1 -1
  233. package/dist/{validate-D4Poe2EE.d.mts → validate-BbthfLBb.d.mts} +3 -5
  234. package/dist/validate-BbthfLBb.d.mts.map +1 -0
  235. package/dist/{view-renderer-BV2rwEUI.mjs → view-renderer-C4sMEruA.mjs} +3 -3
  236. package/dist/{view-renderer-BV2rwEUI.mjs.map → view-renderer-C4sMEruA.mjs.map} +1 -1
  237. package/dist/{web-crypto-hpIdycSO.mjs → web-crypto-SXVOPDxW.mjs} +2 -2
  238. package/dist/{web-crypto-hpIdycSO.mjs.map → web-crypto-SXVOPDxW.mjs.map} +1 -1
  239. package/dist/web.d.mts +7 -13
  240. package/dist/web.d.mts.map +1 -1
  241. package/dist/web.mjs +2 -2
  242. package/dist/web.mjs.map +1 -1
  243. package/package.json +4 -4
  244. package/dist/adapter-DL9JPcvC.d.mts.map +0 -1
  245. package/dist/allowed-hosts-BpKwviq5.d.mts.map +0 -1
  246. package/dist/app-module-Dk2Wenqx.d.mts.map +0 -1
  247. package/dist/application-CHBdxwF5.mjs +0 -14
  248. package/dist/application-CHBdxwF5.mjs.map +0 -1
  249. package/dist/application-D921r4MW.d.mts.map +0 -1
  250. package/dist/breach-padding-FBVGmcBb.d.mts.map +0 -1
  251. package/dist/cache-CdRHSXow.d.mts.map +0 -1
  252. package/dist/connect-BlIamapT.d.mts.map +0 -1
  253. package/dist/cors-BlR_b0Qb.d.mts.map +0 -1
  254. package/dist/cron-BTGytNg-.d.mts.map +0 -1
  255. package/dist/csrf-DOAaYozG.d.mts.map +0 -1
  256. package/dist/decorate-DgGmrJOP.mjs +0 -13
  257. package/dist/decorate-DgGmrJOP.mjs.map +0 -1
  258. package/dist/decorators-DxNb5mWw.d.mts.map +0 -1
  259. package/dist/error-handler-D7DLWe1Q.d.mts.map +0 -1
  260. package/dist/errors-By6UueCm.d.mts.map +0 -1
  261. package/dist/helmet-BVuVBl-D.d.mts.map +0 -1
  262. package/dist/index-Blgka75E.d.mts.map +0 -1
  263. package/dist/index-DP_I4puv.d.mts.map +0 -1
  264. package/dist/interfaces-C6LHcYsg.d.mts.map +0 -1
  265. package/dist/kv-stores-CwJdsMln.d.mts.map +0 -1
  266. package/dist/logger-xE9qI_FS.d.mts.map +0 -1
  267. package/dist/path-CMwIHsdv.d.mts.map +0 -1
  268. package/dist/rate-limit-DQDk6bAH.d.mts.map +0 -1
  269. package/dist/reactivity-DZrc3Yhu.d.mts.map +0 -1
  270. package/dist/request-id-Dn64nEHK.d.mts.map +0 -1
  271. package/dist/request-logger-TgcKRNDD.d.mts.map +0 -1
  272. package/dist/route-flag-B1lQht6v.d.mts.map +0 -1
  273. package/dist/router-builder-C5EtcFSL.d.mts.map +0 -1
  274. package/dist/session-DQG72vCf.d.mts.map +0 -1
  275. package/dist/settings-DgZLgcNU.d.mts.map +0 -1
  276. package/dist/settings-hG4DH8hQ.mjs.map +0 -1
  277. package/dist/upload-DnwvZQyi.d.mts.map +0 -1
  278. package/dist/validate-D4Poe2EE.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cache.mjs","names":[],"sources":["../../src/core/cache.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { createLogger } from './logger'\n\n// String metadata key (post-Symbol migration). Slash-delimited\n// `kick/cacheable` so it can't collide with adopter metadata keys.\nconst CACHEABLE_META = 'kick/cacheable'\n\n// ── CacheProvider Interface ─────────────────────────────────────────────\n\n/**\n * Abstract cache backend. Implement this interface to use Redis, Memcached,\n * or any other cache store with @Cacheable and @CacheEvict.\n *\n * @example\n * ```ts\n * class RedisCacheProvider implements CacheProvider {\n * private client: RedisClient\n * constructor(client: RedisClient) { this.client = client }\n * async get(key: string) {\n * const val = await this.client.get(key)\n * return val ? JSON.parse(val) : null\n * }\n * async set(key: string, value: any, ttlMs: number) {\n * await this.client.set(key, JSON.stringify(value), 'PX', ttlMs)\n * }\n * async del(key: string) { await this.client.del(key) }\n * async delByPrefix(prefix: string) {\n * // SCAN, not KEYS — KEYS blocks Redis while it walks the keyspace\n * for await (const keys of this.client.scanStream({ match: prefix + '*' })) {\n * if (keys.length) await this.client.del(...keys)\n * }\n * }\n * }\n * ```\n */\nexport interface CacheProvider {\n /** Retrieve a cached value. Return null if not found or expired. */\n get(key: string): Promise<any | null>\n /** Store a value with a TTL in milliseconds. */\n set(key: string, value: any, ttlMs: number): Promise<void>\n /** Delete a specific cache key. */\n del(key: string): Promise<void>\n /** Delete all keys matching a prefix. Used by @CacheEvict. */\n delByPrefix?(prefix: string): Promise<void>\n /** Optional cleanup on shutdown. */\n shutdown?(): Promise<void>\n}\n\n// ── Built-in Memory Provider ────────────────────────────────────────────\n\n/**\n * Default in-memory cache provider using a Map with LRU eviction.\n * Suitable for development and single-instance deployments.\n * For multi-instance or production, use a Redis-backed provider.\n *\n * Bounded: at most `maxEntries` (default 10 000) live entries. Expiry is\n * lazy (checked on read); the size cap is what bounds memory — without it,\n * a `@Cacheable` method over high-cardinality args grew the Map without\n * limit, since write-once-never-read keys were never revisited.\n */\nexport class MemoryCacheProvider implements CacheProvider {\n private store = new Map<string, { data: any; expiresAt: number }>()\n\n constructor(private readonly maxEntries = 10_000) {}\n\n async get(key: string): Promise<any | null> {\n const entry = this.store.get(key)\n if (!entry) return null\n if (entry.expiresAt <= Date.now()) {\n this.store.delete(key)\n return null\n }\n // LRU touch: re-insert so Map iteration order tracks recency and\n // eviction removes the least-recently-used key, not the oldest write.\n this.store.delete(key)\n this.store.set(key, entry)\n return entry.data\n }\n\n async set(key: string, value: any, ttlMs: number): Promise<void> {\n if (!this.store.has(key) && this.store.size >= this.maxEntries) {\n // Evict the least-recently-used entry (first in iteration order).\n const oldest = this.store.keys().next().value\n if (oldest !== undefined) this.store.delete(oldest)\n }\n this.store.delete(key)\n this.store.set(key, { data: value, expiresAt: Date.now() + ttlMs })\n }\n\n async del(key: string): Promise<void> {\n this.store.delete(key)\n }\n\n async delByPrefix(prefix: string): Promise<void> {\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.store.delete(key)\n }\n }\n }\n\n async shutdown(): Promise<void> {\n this.store.clear()\n }\n}\n\n// ── Global Cache Registry ───────────────────────────────────────────────\n\nlet _cacheProvider: CacheProvider = new MemoryCacheProvider()\n\n/**\n * Set the global cache provider used by @Cacheable and @CacheEvict.\n * Call this before bootstrapping your app.\n *\n * @example\n * ```ts\n * import { setCacheProvider } from '@forinda/kickjs'\n * import { RedisCacheProvider } from './redis-cache'\n *\n * setCacheProvider(new RedisCacheProvider(redisClient))\n * ```\n */\nexport function setCacheProvider(provider: CacheProvider): void {\n _cacheProvider = provider\n}\n\n/** Get the current cache provider */\nexport function getCacheProvider(): CacheProvider {\n return _cacheProvider\n}\n\n// ── Cache Options ───────────────────────────────────────────────────────\n\nexport interface CacheOptions {\n /** Time-to-live in seconds (default: 60) */\n ttl?: number\n /** Cache key prefix (default: `methodName:ClassName`) */\n key?: string\n}\n\n// ── @Cacheable Decorator ────────────────────────────────────────────────\n\n/**\n * Cache the return value of a method for the specified TTL.\n * Uses the globally registered CacheProvider (default: MemoryCacheProvider).\n *\n * Call `setCacheProvider()` to use Redis or any custom backend.\n *\n * @param ttl - Time-to-live in seconds (default: 60). `0` turns caching off.\n * @param options.key - A key prefix, followed by the arguments; or a function\n * of the arguments that returns the whole key — e.g. `(id) => \"product:\" + id`.\n */\n// Sentinel stored in place of a legitimate `null` result. Providers signal\n// \"miss\" with null, so caching null directly was indistinguishable from a\n// miss — the method re-executed on every call (cache stampede on the exact\n// path caching should protect). An object envelope (structurally checked,\n// so it survives any JSON round-trip through Redis etc.) rather than a bare\n// string: a method legitimately RETURNING that string (echoing user input,\n// etc.) must not be replayed as null. A user value could still forge this\n// exact single-key shape, but that requires deliberately constructing it —\n// not a value class that occurs by accident.\nconst CACHED_NULL = { __kickjs_cached_null__: true }\n\nfunction isCachedNull(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>).__kickjs_cached_null__ === true &&\n Object.keys(value).length === 1\n )\n}\n\n/**\n * Loads in flight, by cache key — simultaneous misses on one key share a\n * single call instead of each running the method (a cache stampede).\n * Per process: instances sharing a remote cache still each load once.\n */\nconst inFlight = new Map<string, Promise<unknown>>()\n\nexport function Cacheable(\n ttl?: number,\n options?: { key?: string | ((...args: any[]) => string) },\n): MethodDecorator {\n return (target, propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n const cacheTtl = (ttl ?? 60) * 1000\n // The default key keeps the method name FIRST — `@CacheEvict('findAll')`\n // is a prefix match and must keep reaching it — and adds the class after\n // it, so `UserService.findAll` and `PostService.findAll` no longer share\n // entries. The class NAME, not an identity, so every instance behind a\n // shared cache computes the same key. An explicit `key` is used as given:\n // the caller chose it, possibly to share it.\n const owner = typeof target === 'function' ? target.name : target.constructor?.name\n const keyOf = typeof options?.key === 'function' ? options.key : undefined\n const keyPrefix =\n typeof options?.key === 'string'\n ? options.key\n : `${String(propertyKey)}:${owner ?? 'anonymous'}`\n\n descriptor.value = async function (...args: any[]) {\n // A TTL of 0 stores nothing — and Redis rejects `PX 0`.\n if (cacheTtl <= 0) return original.apply(this, args)\n const cacheKey = keyOf ? keyOf(...args) : `${keyPrefix}:${JSON.stringify(args)}`\n const provider = getCacheProvider()\n\n const cached = await provider.get(cacheKey)\n if (cached !== null) {\n return isCachedNull(cached) ? null : cached\n }\n\n const pending = inFlight.get(cacheKey)\n if (pending) return pending\n\n const load = (async () => {\n const result = await original.apply(this, args)\n // Cache legit-null results via the sentinel; `undefined` stays\n // uncached (callers returning undefined get pre-existing behavior).\n if (result === null) await provider.set(cacheKey, CACHED_NULL, cacheTtl)\n else if (result !== undefined) await provider.set(cacheKey, result, cacheTtl)\n return result\n })()\n inFlight.set(cacheKey, load)\n try {\n return await load\n } finally {\n // Settled either way: a failed load is not cached, so the next call retries.\n inFlight.delete(cacheKey)\n }\n }\n\n return descriptor\n }\n}\n\nconst log = createLogger('Cache')\nlet warnedNoDelByPrefix = false\n\n// ── @CacheEvict Decorator ───────────────────────────────────────────────\n\n/**\n * Evict cached values matching a key prefix after the method executes.\n * Works with any CacheProvider that implements `delByPrefix`.\n *\n * @param key - Cache key prefix to evict (matches the @Cacheable key), or a\n * function of the method's arguments that returns it — e.g. `(id) => \"product:\" + id`.\n */\nexport function CacheEvict(key: string | ((...args: any[]) => string)): MethodDecorator {\n return (_target, _propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n\n descriptor.value = async function (...args: any[]) {\n const result = await original.apply(this, args)\n const provider = getCacheProvider()\n if (provider.delByPrefix) {\n await provider.delByPrefix(typeof key === 'function' ? key(...args) : key)\n } else if (!warnedNoDelByPrefix) {\n warnedNoDelByPrefix = true\n log.warn('@CacheEvict: the cache provider has no delByPrefix(), so nothing is evicted')\n }\n return result\n }\n\n return descriptor\n }\n}\n\nexport { CACHEABLE_META }\n"],"mappings":";;;;;;;;;;gEAKA,MA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,GAAG,KAAa,CACjD,IAAM,OAAS,MAAM,SAAS,MAAM,KAAM,IAAI,EACxC,SAAW,iBAAiB,EAOlC,OANI,SAAS,YACX,MAAM,SAAS,YAAY,OAAO,KAAQ,WAAa,IAAI,GAAG,IAAI,EAAI,GAAG,EAC/D,sBACV,oBAAsB,GACtB,IAAI,KAAK,6EAA6E,GAEjF,MACT,EAEO,UACT,CACF"}
1
+ {"version":3,"file":"cache.mjs","names":[],"sources":["../../src/core/cache.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { createLogger } from './logger'\n\n// String metadata key (post-Symbol migration). Slash-delimited\n// `kick/cacheable` so it can't collide with adopter metadata keys.\nconst CACHEABLE_META = 'kick/cacheable'\n\n// ── CacheProvider Interface ─────────────────────────────────────────────\n\n/**\n * Abstract cache backend. Implement this interface to use Redis, Memcached,\n * or any other cache store with @Cacheable and @CacheEvict.\n *\n * @example\n * ```ts\n * class RedisCacheProvider implements CacheProvider {\n * private client: RedisClient\n * constructor(client: RedisClient) { this.client = client }\n * async get(key: string) {\n * const val = await this.client.get(key)\n * return val ? JSON.parse(val) : null\n * }\n * async set(key: string, value: any, ttlMs: number) {\n * await this.client.set(key, JSON.stringify(value), 'PX', ttlMs)\n * }\n * async del(key: string) { await this.client.del(key) }\n * async delByPrefix(prefix: string) {\n * // SCAN, not KEYS — KEYS blocks Redis while it walks the keyspace\n * for await (const keys of this.client.scanStream({ match: prefix + '*' })) {\n * if (keys.length) await this.client.del(...keys)\n * }\n * }\n * }\n * ```\n */\nexport interface CacheProvider {\n /** Retrieve a cached value. Return null if not found or expired. */\n get(key: string): Promise<any | null>\n /** Store a value with a TTL in milliseconds. */\n set(key: string, value: any, ttlMs: number): Promise<void>\n /** Delete a specific cache key. */\n del(key: string): Promise<void>\n /** Delete all keys matching a prefix. Used by @CacheEvict. */\n delByPrefix?(prefix: string): Promise<void>\n /** Optional cleanup on shutdown. */\n shutdown?(): Promise<void>\n}\n\n// ── Built-in Memory Provider ────────────────────────────────────────────\n\n/**\n * Default in-memory cache provider using a Map with LRU eviction.\n * Suitable for development and single-instance deployments.\n * For multi-instance or production, use a Redis-backed provider.\n *\n * Bounded: at most `maxEntries` (default 10 000) live entries. Expiry is\n * lazy (checked on read); the size cap is what bounds memory — without it,\n * a `@Cacheable` method over high-cardinality args grew the Map without\n * limit, since write-once-never-read keys were never revisited.\n */\nexport class MemoryCacheProvider implements CacheProvider {\n private store = new Map<string, { data: any; expiresAt: number }>()\n\n constructor(private readonly maxEntries = 10_000) {}\n\n async get(key: string): Promise<any | null> {\n const entry = this.store.get(key)\n if (!entry) return null\n if (entry.expiresAt <= Date.now()) {\n this.store.delete(key)\n return null\n }\n // LRU touch: re-insert so Map iteration order tracks recency and\n // eviction removes the least-recently-used key, not the oldest write.\n this.store.delete(key)\n this.store.set(key, entry)\n return entry.data\n }\n\n async set(key: string, value: any, ttlMs: number): Promise<void> {\n if (!this.store.has(key) && this.store.size >= this.maxEntries) {\n // Evict the least-recently-used entry (first in iteration order).\n const oldest = this.store.keys().next().value\n if (oldest !== undefined) this.store.delete(oldest)\n }\n this.store.delete(key)\n this.store.set(key, { data: value, expiresAt: Date.now() + ttlMs })\n }\n\n async del(key: string): Promise<void> {\n this.store.delete(key)\n }\n\n async delByPrefix(prefix: string): Promise<void> {\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.store.delete(key)\n }\n }\n }\n\n async shutdown(): Promise<void> {\n this.store.clear()\n }\n}\n\n// ── Global Cache Registry ───────────────────────────────────────────────\n\nlet _cacheProvider: CacheProvider = new MemoryCacheProvider()\n\n/**\n * Set the global cache provider used by @Cacheable and @CacheEvict.\n * Call this before bootstrapping your app.\n *\n * @example\n * ```ts\n * import { setCacheProvider } from '@forinda/kickjs'\n * import { RedisCacheProvider } from './redis-cache'\n *\n * setCacheProvider(new RedisCacheProvider(redisClient))\n * ```\n */\nexport function setCacheProvider(provider: CacheProvider): void {\n _cacheProvider = provider\n}\n\n/** Get the current cache provider */\nexport function getCacheProvider(): CacheProvider {\n return _cacheProvider\n}\n\n// ── Cache Options ───────────────────────────────────────────────────────\n\nexport interface CacheOptions {\n /** Time-to-live in seconds (default: 60) */\n ttl?: number\n /** Cache key prefix (default: `methodName:ClassName`) */\n key?: string\n}\n\n// ── @Cacheable Decorator ────────────────────────────────────────────────\n\n/**\n * Cache the return value of a method for the specified TTL.\n * Uses the globally registered CacheProvider (default: MemoryCacheProvider).\n *\n * Call `setCacheProvider()` to use Redis or any custom backend.\n *\n * @param ttl - Time-to-live in seconds (default: 60). `0` turns caching off.\n * @param options.key - A key prefix, followed by the arguments; or a function\n * of the arguments that returns the whole key — e.g. `(id) => \"product:\" + id`.\n */\n// Sentinel stored in place of a legitimate `null` result. Providers signal\n// \"miss\" with null, so caching null directly was indistinguishable from a\n// miss — the method re-executed on every call (cache stampede on the exact\n// path caching should protect). An object envelope (structurally checked,\n// so it survives any JSON round-trip through Redis etc.) rather than a bare\n// string: a method legitimately RETURNING that string (echoing user input,\n// etc.) must not be replayed as null. A user value could still forge this\n// exact single-key shape, but that requires deliberately constructing it —\n// not a value class that occurs by accident.\nconst CACHED_NULL = { __kickjs_cached_null__: true }\n\nfunction isCachedNull(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>).__kickjs_cached_null__ === true &&\n Object.keys(value).length === 1\n )\n}\n\n/**\n * Loads in flight, by cache key — simultaneous misses on one key share a\n * single call instead of each running the method (a cache stampede).\n * Per process: instances sharing a remote cache still each load once.\n */\nconst inFlight = new Map<string, Promise<unknown>>()\n\nexport function Cacheable(\n ttl?: number,\n options?: { key?: string | ((...args: any[]) => string) },\n): MethodDecorator {\n return (target, propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n const cacheTtl = (ttl ?? 60) * 1000\n // The default key keeps the method name FIRST — `@CacheEvict('findAll')`\n // is a prefix match and must keep reaching it — and adds the class after\n // it, so `UserService.findAll` and `PostService.findAll` no longer share\n // entries. The class NAME, not an identity, so every instance behind a\n // shared cache computes the same key. An explicit `key` is used as given:\n // the caller chose it, possibly to share it.\n const owner = typeof target === 'function' ? target.name : target.constructor?.name\n const keyOf = typeof options?.key === 'function' ? options.key : undefined\n const keyPrefix =\n typeof options?.key === 'string'\n ? options.key\n : `${String(propertyKey)}:${owner ?? 'anonymous'}`\n\n descriptor.value = async function (...args: any[]) {\n // A TTL of 0 stores nothing — and Redis rejects `PX 0`.\n if (cacheTtl <= 0) return original.apply(this, args)\n const cacheKey = keyOf ? keyOf(...args) : `${keyPrefix}:${JSON.stringify(args)}`\n const provider = getCacheProvider()\n\n const cached = await provider.get(cacheKey)\n if (cached !== null) {\n return isCachedNull(cached) ? null : cached\n }\n\n const pending = inFlight.get(cacheKey)\n if (pending) return pending\n\n const load = (async () => {\n const result = await original.apply(this, args)\n // Cache legit-null results via the sentinel; `undefined` stays\n // uncached (callers returning undefined get pre-existing behavior).\n if (result === null) await provider.set(cacheKey, CACHED_NULL, cacheTtl)\n else if (result !== undefined) await provider.set(cacheKey, result, cacheTtl)\n return result\n })()\n inFlight.set(cacheKey, load)\n try {\n return await load\n } finally {\n // Settled either way: a failed load is not cached, so the next call retries.\n inFlight.delete(cacheKey)\n }\n }\n\n return descriptor\n }\n}\n\nconst log = createLogger('Cache')\nlet warnedNoDelByPrefix = false\n\n// ── @CacheEvict Decorator ───────────────────────────────────────────────\n\n/**\n * Evict cached values matching a key prefix after the method executes.\n * Works with any CacheProvider that implements `delByPrefix`.\n *\n * @param key - Cache key prefix to evict (matches the @Cacheable key), or a\n * function of the method's arguments that returns it — e.g. `(id) => \"product:\" + id`.\n */\nexport function CacheEvict(key: string | ((...args: any[]) => string)): MethodDecorator {\n return (_target, _propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n\n descriptor.value = async function (...args: any[]) {\n const result = await original.apply(this, args)\n const provider = getCacheProvider()\n if (provider.delByPrefix) {\n await provider.delByPrefix(typeof key === 'function' ? key(...args) : key)\n } else if (!warnedNoDelByPrefix) {\n warnedNoDelByPrefix = true\n log.warn('@CacheEvict: the cache provider has no delByPrefix(), so nothing is evicted')\n }\n return result\n }\n\n return descriptor\n }\n}\n\nexport { CACHEABLE_META }\n"],"mappings":";;;;;;;;;;A,gEAKA,MAAM,eAAiB,iBAuDvB,IAAa,oBAAb,KAA0D,CAG3B,WAF7B,sBAAgB,IAAI,IAEpB,YAAY,WAA8B,IAAQ,CAArB,KAAA,WAAA,UAAsB,CAEnD,MAAM,IAAI,IAAkC,CAC1C,IAAM,MAAQ,KAAK,MAAM,IAAI,GAAG,EAUhC,OATK,MACD,MAAM,WAAa,KAAK,IAAI,GAC9B,KAAK,MAAM,OAAO,GAAG,EACd,OAIT,KAAK,MAAM,OAAO,GAAG,EACrB,KAAK,MAAM,IAAI,IAAK,KAAK,EAClB,MAAM,MATM,IAUrB,CAEA,MAAM,IAAI,IAAa,MAAY,MAA8B,CAC/D,GAAI,CAAC,KAAK,MAAM,IAAI,GAAG,GAAK,KAAK,MAAM,MAAQ,KAAK,WAAY,CAE9D,IAAM,OAAS,KAAK,MAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MACpC,SAAW,IAAA,IAAW,KAAK,MAAM,OAAO,MAAM,CACpD,CACA,KAAK,MAAM,OAAO,GAAG,EACrB,KAAK,MAAM,IAAI,IAAK,CAAE,KAAM,MAAO,UAAW,KAAK,IAAI,EAAI,KAAM,CAAC,CACpE,CAEA,MAAM,IAAI,IAA4B,CACpC,KAAK,MAAM,OAAO,GAAG,CACvB,CAEA,MAAM,YAAY,OAA+B,CAC/C,IAAK,IAAM,OAAO,KAAK,MAAM,KAAK,EAC5B,IAAI,WAAW,MAAM,GACvB,KAAK,MAAM,OAAO,GAAG,CAG3B,CAEA,MAAM,UAA0B,CAC9B,KAAK,MAAM,MAAM,CACnB,CACF,EAIA,IAAI,eAAgC,IAAI,oBAcxC,SAAgB,iBAAiB,SAA+B,CAC9D,eAAiB,QACnB,CAGA,SAAgB,kBAAkC,CAChD,OAAO,cACT,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aAAa,OAAO,EAChC,IAAI,oBAAsB,GAW1B,SAAgB,WAAW,IAA6D,CACtF,OAAQ,QAAS,aAAc,aAAmC,CAChE,IAAM,SAAW,WAAW,MAc5B,MAZA,YAAW,MAAQ,eAAgB,GAAG,KAAa,CACjD,IAAM,OAAS,MAAM,SAAS,MAAM,KAAM,IAAI,EACxC,SAAW,iBAAiB,EAOlC,OANI,SAAS,YACX,MAAM,SAAS,YAAY,OAAO,KAAQ,WAAa,IAAI,GAAG,IAAI,EAAI,GAAG,EAC/D,sBACV,oBAAsB,GACtB,IAAI,KAAK,6EAA6E,GAEjF,MACT,EAEO,UACT,CACF,C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import"../di-hooks-DN_UC8Nc.mjs";export{Container,tokenName}from"@forinda/kickjs-di";
11
+ import"../di-hooks-DCqt2yJ9.mjs";export{Container,tokenName}from"@forinda/kickjs-di";
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as CronOptions, c as getCronJobs, d as runCronJob, f as runCronJobs, i as CronJobMeta, l as isCronJobEnabled, n as Cron, o as CronRun, r as CronJob, s as cronScheduleId, t as CRON_META, u as listCronJobs } from "../cron-BTGytNg-.mjs";
2
+ import { a as CronOptions, c as getCronJobs, d as runCronJob, f as runCronJobs, i as CronJobMeta, l as isCronJobEnabled, n as Cron, o as CronRun, r as CronJob, s as cronScheduleId, t as CRON_META, u as listCronJobs } from "../cron-DGV1AE0R.mjs";
3
3
  export { CRON_META, Cron, CronJob, CronJobMeta, CronOptions, CronRun, cronScheduleId, getCronJobs, isCronJobEnabled, listCronJobs, runCronJob, runCronJobs };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"./logger.mjs";import{c as pushClassMeta,t as getClassMeta}from"../metadata-DS4TBMoC.mjs";import{r as reportError}from"../observers-Dokycjj0.mjs";const CRON_META=`kick/cron`,log=createLogger(`KickCron`),cronClasses=/* @__PURE__ */ new Map;function Cron(expression,options){return(target,propertyKey)=>{pushClassMeta(CRON_META,target.constructor,{...options,expression,handlerName:propertyKey}),cronClasses.set(target.constructor.name,target.constructor)}}function getCronJobs(target){return getClassMeta(CRON_META,target,[])}function listCronJobs(container){let jobs=[];for(let target of cronClasses.values())if(container.has(target))for(let meta of getCronJobs(target))jobs.push({...meta,name:meta.name??`${target.name}.${meta.handlerName}`,scheduleId:cronScheduleId(meta.expression),target});return jobs}function isCronJobEnabled(job){let{enabled}=job;return typeof enabled==`function`?enabled():enabled!==!1}const running=/* @__PURE__ */ new Set;async function runCronJob(job,container,trigger){if(!isCronJobEnabled(job))return!1;let key=`${job.target.name}.${job.handlerName}`;if(!job.overlap&&running.has(key))return log.warn(`${job.name} is still running — skipped this tick`),!1;running.add(key);try{return await container.resolve(job.target)[job.handlerName]({name:job.name,expression:job.expression,meta:job.meta??{},firedAt:/* @__PURE__ */ new Date,trigger}),!0}catch(err){throw log.error({err},`Cron job ${job.name} failed`),reportError(err,{source:`cron`,context:{job:job.name,expression:job.expression,trigger}}),err}finally{running.delete(key)}}async function runCronJobs(container,filter,trigger){let jobs=listCronJobs(container).filter(job=>(filter.name===void 0||job.name===filter.name)&&(filter.scheduleId===void 0||job.scheduleId===filter.scheduleId)&&(filter.expression===void 0||job.expression===filter.expression)),results=await Promise.allSettled(jobs.map(job=>runCronJob(job,container,trigger)));return{ran:results.filter(r=>r.status===`fulfilled`&&r.value).length,failed:results.filter(r=>r.status===`rejected`).length}}function cronScheduleId(expression){let hash=2166136261;for(let char of expression.trim().replace(/\s+/g,` `))hash^=char.codePointAt(0),hash=Math.imul(hash,16777619)>>>0;return hash.toString(36)}export{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs};
11
+ import{c as pushClassMeta,t as getClassMeta}from"../metadata-BZRtQog3.mjs";import{r as reportError}from"../observers-B4VnKAHK.mjs";import{createLogger}from"./logger.mjs";const CRON_META=`kick/cron`,log=createLogger(`KickCron`),cronClasses=/* @__PURE__ */ new Map;function Cron(expression,options){return(target,propertyKey)=>{pushClassMeta(CRON_META,target.constructor,{...options,expression,handlerName:propertyKey}),cronClasses.set(target.constructor.name,target.constructor)}}function getCronJobs(target){return getClassMeta(CRON_META,target,[])}function listCronJobs(container){let jobs=[];for(let target of cronClasses.values())if(container.has(target))for(let meta of getCronJobs(target))jobs.push({...meta,name:meta.name??`${target.name}.${meta.handlerName}`,scheduleId:cronScheduleId(meta.expression),target});return jobs}function isCronJobEnabled(job){let{enabled}=job;return typeof enabled==`function`?enabled():enabled!==!1}const running=/* @__PURE__ */ new Set;async function runCronJob(job,container,trigger){if(!isCronJobEnabled(job))return!1;let key=`${job.target.name}.${job.handlerName}`;if(!job.overlap&&running.has(key))return log.warn(`${job.name} is still running — skipped this tick`),!1;running.add(key);try{return await container.resolve(job.target)[job.handlerName]({name:job.name,expression:job.expression,meta:job.meta??{},firedAt:/* @__PURE__ */ new Date,trigger}),!0}catch(err){throw log.error({err},`Cron job ${job.name} failed`),reportError(err,{source:`cron`,context:{job:job.name,expression:job.expression,trigger}}),err}finally{running.delete(key)}}async function runCronJobs(container,filter,trigger){let jobs=listCronJobs(container).filter(job=>(filter.name===void 0||job.name===filter.name)&&(filter.scheduleId===void 0||job.scheduleId===filter.scheduleId)&&(filter.expression===void 0||job.expression===filter.expression)),results=await Promise.allSettled(jobs.map(job=>runCronJob(job,container,trigger)));return{ran:results.filter(r=>r.status===`fulfilled`&&r.value).length,failed:results.filter(r=>r.status===`rejected`).length}}function cronScheduleId(expression){let hash=2166136261;for(let char of expression.trim().replace(/\s+/g,` `))hash^=char.codePointAt(0),hash=Math.imul(hash,16777619)>>>0;return hash.toString(36)}export{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs};
12
12
  //# sourceMappingURL=cron.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cron.mjs","names":[],"sources":["../../src/core/cron.ts"],"sourcesContent":["import { pushClassMeta, getClassMeta } from './metadata'\nimport { reportError } from './observers'\nimport { createLogger } from './logger'\n\n// String metadata key (post-Symbol migration). Slash-delimited\n// `kick/cron` so it can't collide with adopter metadata keys.\nconst CRON_META = 'kick/cron'\n\nconst log = createLogger('KickCron')\n\nexport interface CronOptions<Meta extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Stable job name for logs, error reports and `runCronJobs({ name })`.\n * Defaults to `ClassName.method`.\n */\n name?: string\n /** Human-readable label for logging */\n description?: string\n /** IANA timezone (e.g. 'Africa/Nairobi'). Node runner and Workers only — Vercel crons are UTC. */\n timezone?: string\n /** Run once at startup (Node server), before the first scheduled tick */\n runOnInit?: boolean\n /**\n * Allow a run to start while the previous one is still going. Default\n * `false`: a tick that finds the job busy is skipped, so a job slower than\n * its interval never stacks up.\n */\n overlap?: boolean\n /**\n * Turn the job off without removing the decorator — a boolean, or a function\n * checked on every tick (e.g. `() => process.env.JOBS === 'on'`).\n */\n enabled?: boolean | (() => boolean)\n /**\n * Free-form data for the job: arguments the handler reads from its run\n * context (`run.meta`), and anything a custom runner or the DevTools want\n * to know. Stored as-is with the job metadata.\n */\n meta?: Meta\n}\n\nexport interface CronJobMeta<\n Meta extends Record<string, unknown> = Record<string, unknown>,\n> extends CronOptions<Meta> {\n expression: string\n handlerName: string\n}\n\n/** What a `@Cron` handler receives when it runs. */\nexport interface CronRun<Meta extends Record<string, unknown> = Record<string, unknown>> {\n name: string\n expression: string\n meta: Meta\n firedAt: Date\n /** What started this run. */\n trigger: 'schedule' | 'init' | 'http' | 'workers' | 'manual'\n}\n\n// Cron format: minute hour day month weekday\n// Examples:\n// '* * * * *' - every minute\n// '0 * * * *' - every hour\n// '0 0 * * *' - daily at midnight\n// '0 9 * * MON-FRI' - weekdays at 9am\n// '0 0 1 * *' - first of each month\n\n/**\n * Every class that declares at least one `@Cron` job, keyed by class name like\n * the DI registry: an HMR re-evaluation replaces the old class instead of\n * leaving it to run beside the new one.\n */\nconst cronClasses = new Map<string, Function>()\n\n/**\n * Schedule a method to run on a cron expression.\n *\n * - On the Node server, `KickCronAdapter()` schedules it (opt-in; install the\n * optional peer `croner`). Without it — or with your own adapter — `@Cron`\n * only records metadata.\n * - On Vercel, `kick build:vercel` emits a cron entry that triggers it.\n * - On Cloudflare Workers, the web entry's `scheduled()` runs it.\n *\n * The handler receives a {@link CronRun} (name, expression, `meta`, trigger).\n *\n * @param expression - Standard 5-part cron: minute hour day month weekday.\n * @example\n * ```ts\n * @Cron('0 * * * *', { name: 'digest', meta: { batch: 500 } })\n * async sendDigest(run: CronRun<{ batch: number }>) {\n * await this.mailer.flush(run.meta.batch)\n * }\n * ```\n */\nexport function Cron<Meta extends Record<string, unknown> = Record<string, unknown>>(\n expression: string,\n options?: CronOptions<Meta>,\n): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<CronJobMeta<Meta>>(CRON_META, target.constructor, {\n ...options,\n expression,\n handlerName: propertyKey as string,\n })\n cronClasses.set(target.constructor.name, target.constructor)\n }\n}\n\n/** Read cron jobs registered on a class */\nexport function getCronJobs(target: any): CronJobMeta[] {\n return getClassMeta<CronJobMeta[]>(CRON_META, target, [])\n}\n\n/** One declared job, ready to run: its class, metadata and resolved name. */\nexport interface CronJob extends CronJobMeta {\n name: string\n /** {@link cronScheduleId} of the expression — how HTTP triggers address it. */\n scheduleId: string\n target: Function\n}\n\n/**\n * Every `@Cron` job whose class the container can resolve. Classes the\n * container doesn't know (not in a module, or left over from before an HMR\n * reload) are skipped.\n */\nexport function listCronJobs(container: { has(token: unknown): boolean }): CronJob[] {\n const jobs: CronJob[] = []\n for (const target of cronClasses.values()) {\n if (!container.has(target)) continue\n for (const meta of getCronJobs(target)) {\n jobs.push({\n ...meta,\n name: meta.name ?? `${target.name}.${meta.handlerName}`,\n scheduleId: cronScheduleId(meta.expression),\n target,\n })\n }\n }\n return jobs\n}\n\n/** Whether the job's `enabled` option currently allows it to run. */\nexport function isCronJobEnabled(job: Pick<CronJobMeta, 'enabled'>): boolean {\n const { enabled } = job\n return typeof enabled === 'function' ? enabled() : enabled !== false\n}\n\nconst running = new Set<string>()\n\n/**\n * Run one job now: resolve its class from the container and call the handler\n * with a {@link CronRun}. Skips a disabled job, and — unless `overlap: true` —\n * a job whose previous run hasn't finished. A failure is logged and reported to\n * the error observers (`source: 'cron'`), then rethrown for the caller.\n * Returns whether the job ran.\n */\nexport async function runCronJob(\n job: CronJob,\n container: { resolve(token: unknown): unknown },\n trigger: CronRun['trigger'],\n): Promise<boolean> {\n if (!isCronJobEnabled(job)) return false\n // Keyed by class + method: `name` is user-chosen and may repeat.\n const key = `${job.target.name}.${job.handlerName}`\n if (!job.overlap && running.has(key)) {\n log.warn(`${job.name} is still running — skipped this tick`)\n return false\n }\n running.add(key)\n try {\n const instance = container.resolve(job.target) as Record<string, (run: CronRun) => unknown>\n await instance[job.handlerName]({\n name: job.name,\n expression: job.expression,\n meta: job.meta ?? {},\n firedAt: new Date(),\n trigger,\n })\n return true\n } catch (err) {\n log.error({ err }, `Cron job ${job.name} failed`)\n reportError(err, {\n source: 'cron',\n context: { job: job.name, expression: job.expression, trigger },\n })\n throw err\n } finally {\n running.delete(key)\n }\n}\n\n/**\n * Run every job matching `filter` (by name, schedule id, or exact expression),\n * in parallel. Resolves once all have settled; never rejects — failures are\n * already reported. Returns how many ran and how many failed.\n */\nexport async function runCronJobs(\n container: { has(token: unknown): boolean; resolve(token: unknown): unknown },\n filter: { name?: string; scheduleId?: string; expression?: string },\n trigger: CronRun['trigger'],\n): Promise<{ ran: number; failed: number }> {\n const jobs = listCronJobs(container).filter(\n (job) =>\n (filter.name === undefined || job.name === filter.name) &&\n (filter.scheduleId === undefined || job.scheduleId === filter.scheduleId) &&\n (filter.expression === undefined || job.expression === filter.expression),\n )\n const results = await Promise.allSettled(jobs.map((job) => runCronJob(job, container, trigger)))\n return {\n ran: results.filter((r) => r.status === 'fulfilled' && r.value).length,\n failed: results.filter((r) => r.status === 'rejected').length,\n }\n}\n\n/**\n * A short, stable id for a cron expression (FNV-1a, base 36) — how HTTP\n * triggers address a schedule. Derived from the expression, not the class or\n * method name, because a minified serverless bundle may rename classes; the\n * CLI computes the same id from source at build time.\n */\nexport function cronScheduleId(expression: string): string {\n let hash = 0x811c9dc5\n for (const char of expression.trim().replace(/\\s+/g, ' ')) {\n hash ^= char.codePointAt(0)!\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n return hash.toString(36)\n}\n\nexport { CRON_META }\n"],"mappings":";;;;;;;;;;0KAMA,MAAM,UAAY,YAEZ,IAAM,aAAa,UAAU,EA+D7B,4BAAc,IAAI,IAsBxB,SAAgB,KACd,WACA,QACiB,CACjB,OAAQ,OAAQ,cAAgB,CAC9B,cAAiC,UAAW,OAAO,YAAa,CAC9D,GAAG,QACH,WACA,YAAa,WACf,CAAC,EACD,YAAY,IAAI,OAAO,YAAY,KAAM,OAAO,WAAW,CAC7D,CACF,CAGA,SAAgB,YAAY,OAA4B,CACtD,OAAO,aAA4B,UAAW,OAAQ,CAAC,CAAC,CAC1D,CAeA,SAAgB,aAAa,UAAwD,CACnF,IAAM,KAAkB,CAAC,EACzB,IAAK,IAAM,UAAU,YAAY,OAAO,EACtC,GAAK,UAAU,IAAI,MAAM,EACzB,IAAK,IAAM,QAAQ,YAAY,MAAM,EACnC,KAAK,KAAK,CACR,GAAG,KACH,KAAM,KAAK,MAAQ,GAAG,OAAO,KAAK,GAAG,KAAK,cAC1C,WAAY,eAAe,KAAK,UAAU,EAC1C,MACF,CAAC,EAGL,OAAO,IACT,CAGA,SAAgB,iBAAiB,IAA4C,CAC3E,GAAM,CAAE,SAAY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U,CAAC,CAAC,MACzD,CACF,CAQA,SAAgB,eAAe,WAA4B,CACzD,IAAI,KAAO,WACX,IAAK,IAAM,QAAQ,WAAW,KAAK,CAAC,CAAC,QAAQ,OAAQ,GAAG,EACtD,MAAQ,KAAK,YAAY,CAAC,EAC1B,KAAO,KAAK,KAAK,KAAM,QAAU,IAAM,EAEzC,OAAO,KAAK,SAAS,EAAE,CACzB"}
1
+ {"version":3,"file":"cron.mjs","names":[],"sources":["../../src/core/cron.ts"],"sourcesContent":["import { pushClassMeta, getClassMeta } from './metadata'\nimport { reportError } from './observers'\nimport { createLogger } from './logger'\n\n// String metadata key (post-Symbol migration). Slash-delimited\n// `kick/cron` so it can't collide with adopter metadata keys.\nconst CRON_META = 'kick/cron'\n\nconst log = createLogger('KickCron')\n\nexport interface CronOptions<Meta extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Stable job name for logs, error reports and `runCronJobs({ name })`.\n * Defaults to `ClassName.method`.\n */\n name?: string\n /** Human-readable label for logging */\n description?: string\n /** IANA timezone (e.g. 'Africa/Nairobi'). Node runner and Workers only — Vercel crons are UTC. */\n timezone?: string\n /** Run once at startup (Node server), before the first scheduled tick */\n runOnInit?: boolean\n /**\n * Allow a run to start while the previous one is still going. Default\n * `false`: a tick that finds the job busy is skipped, so a job slower than\n * its interval never stacks up.\n */\n overlap?: boolean\n /**\n * Turn the job off without removing the decorator — a boolean, or a function\n * checked on every tick (e.g. `() => process.env.JOBS === 'on'`).\n */\n enabled?: boolean | (() => boolean)\n /**\n * Free-form data for the job: arguments the handler reads from its run\n * context (`run.meta`), and anything a custom runner or the DevTools want\n * to know. Stored as-is with the job metadata.\n */\n meta?: Meta\n}\n\nexport interface CronJobMeta<\n Meta extends Record<string, unknown> = Record<string, unknown>,\n> extends CronOptions<Meta> {\n expression: string\n handlerName: string\n}\n\n/** What a `@Cron` handler receives when it runs. */\nexport interface CronRun<Meta extends Record<string, unknown> = Record<string, unknown>> {\n name: string\n expression: string\n meta: Meta\n firedAt: Date\n /** What started this run. */\n trigger: 'schedule' | 'init' | 'http' | 'workers' | 'manual'\n}\n\n// Cron format: minute hour day month weekday\n// Examples:\n// '* * * * *' - every minute\n// '0 * * * *' - every hour\n// '0 0 * * *' - daily at midnight\n// '0 9 * * MON-FRI' - weekdays at 9am\n// '0 0 1 * *' - first of each month\n\n/**\n * Every class that declares at least one `@Cron` job, keyed by class name like\n * the DI registry: an HMR re-evaluation replaces the old class instead of\n * leaving it to run beside the new one.\n */\nconst cronClasses = new Map<string, Function>()\n\n/**\n * Schedule a method to run on a cron expression.\n *\n * - On the Node server, `KickCronAdapter()` schedules it (opt-in; install the\n * optional peer `croner`). Without it — or with your own adapter — `@Cron`\n * only records metadata.\n * - On Vercel, `kick build:vercel` emits a cron entry that triggers it.\n * - On Cloudflare Workers, the web entry's `scheduled()` runs it.\n *\n * The handler receives a {@link CronRun} (name, expression, `meta`, trigger).\n *\n * @param expression - Standard 5-part cron: minute hour day month weekday.\n * @example\n * ```ts\n * @Cron('0 * * * *', { name: 'digest', meta: { batch: 500 } })\n * async sendDigest(run: CronRun<{ batch: number }>) {\n * await this.mailer.flush(run.meta.batch)\n * }\n * ```\n */\nexport function Cron<Meta extends Record<string, unknown> = Record<string, unknown>>(\n expression: string,\n options?: CronOptions<Meta>,\n): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<CronJobMeta<Meta>>(CRON_META, target.constructor, {\n ...options,\n expression,\n handlerName: propertyKey as string,\n })\n cronClasses.set(target.constructor.name, target.constructor)\n }\n}\n\n/** Read cron jobs registered on a class */\nexport function getCronJobs(target: any): CronJobMeta[] {\n return getClassMeta<CronJobMeta[]>(CRON_META, target, [])\n}\n\n/** One declared job, ready to run: its class, metadata and resolved name. */\nexport interface CronJob extends CronJobMeta {\n name: string\n /** {@link cronScheduleId} of the expression — how HTTP triggers address it. */\n scheduleId: string\n target: Function\n}\n\n/**\n * Every `@Cron` job whose class the container can resolve. Classes the\n * container doesn't know (not in a module, or left over from before an HMR\n * reload) are skipped.\n */\nexport function listCronJobs(container: { has(token: unknown): boolean }): CronJob[] {\n const jobs: CronJob[] = []\n for (const target of cronClasses.values()) {\n if (!container.has(target)) continue\n for (const meta of getCronJobs(target)) {\n jobs.push({\n ...meta,\n name: meta.name ?? `${target.name}.${meta.handlerName}`,\n scheduleId: cronScheduleId(meta.expression),\n target,\n })\n }\n }\n return jobs\n}\n\n/** Whether the job's `enabled` option currently allows it to run. */\nexport function isCronJobEnabled(job: Pick<CronJobMeta, 'enabled'>): boolean {\n const { enabled } = job\n return typeof enabled === 'function' ? enabled() : enabled !== false\n}\n\nconst running = new Set<string>()\n\n/**\n * Run one job now: resolve its class from the container and call the handler\n * with a {@link CronRun}. Skips a disabled job, and — unless `overlap: true` —\n * a job whose previous run hasn't finished. A failure is logged and reported to\n * the error observers (`source: 'cron'`), then rethrown for the caller.\n * Returns whether the job ran.\n */\nexport async function runCronJob(\n job: CronJob,\n container: { resolve(token: unknown): unknown },\n trigger: CronRun['trigger'],\n): Promise<boolean> {\n if (!isCronJobEnabled(job)) return false\n // Keyed by class + method: `name` is user-chosen and may repeat.\n const key = `${job.target.name}.${job.handlerName}`\n if (!job.overlap && running.has(key)) {\n log.warn(`${job.name} is still running — skipped this tick`)\n return false\n }\n running.add(key)\n try {\n const instance = container.resolve(job.target) as Record<string, (run: CronRun) => unknown>\n await instance[job.handlerName]({\n name: job.name,\n expression: job.expression,\n meta: job.meta ?? {},\n firedAt: new Date(),\n trigger,\n })\n return true\n } catch (err) {\n log.error({ err }, `Cron job ${job.name} failed`)\n reportError(err, {\n source: 'cron',\n context: { job: job.name, expression: job.expression, trigger },\n })\n throw err\n } finally {\n running.delete(key)\n }\n}\n\n/**\n * Run every job matching `filter` (by name, schedule id, or exact expression),\n * in parallel. Resolves once all have settled; never rejects — failures are\n * already reported. Returns how many ran and how many failed.\n */\nexport async function runCronJobs(\n container: { has(token: unknown): boolean; resolve(token: unknown): unknown },\n filter: { name?: string; scheduleId?: string; expression?: string },\n trigger: CronRun['trigger'],\n): Promise<{ ran: number; failed: number }> {\n const jobs = listCronJobs(container).filter(\n (job) =>\n (filter.name === undefined || job.name === filter.name) &&\n (filter.scheduleId === undefined || job.scheduleId === filter.scheduleId) &&\n (filter.expression === undefined || job.expression === filter.expression),\n )\n const results = await Promise.allSettled(jobs.map((job) => runCronJob(job, container, trigger)))\n return {\n ran: results.filter((r) => r.status === 'fulfilled' && r.value).length,\n failed: results.filter((r) => r.status === 'rejected').length,\n }\n}\n\n/**\n * A short, stable id for a cron expression (FNV-1a, base 36) — how HTTP\n * triggers address a schedule. Derived from the expression, not the class or\n * method name, because a minified serverless bundle may rename classes; the\n * CLI computes the same id from source at build time.\n */\nexport function cronScheduleId(expression: string): string {\n let hash = 0x811c9dc5\n for (const char of expression.trim().replace(/\\s+/g, ' ')) {\n hash ^= char.codePointAt(0)!\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n return hash.toString(36)\n}\n\nexport { CRON_META }\n"],"mappings":";;;;;;;;;;A,0KAMA,MAAM,UAAY,YAEZ,IAAM,aAAa,UAAU,EA+D7B,4BAAc,IAAI,IAsBxB,SAAgB,KACd,WACA,QACiB,CACjB,OAAQ,OAAQ,cAAgB,CAC9B,cAAiC,UAAW,OAAO,YAAa,CAC9D,GAAG,QACH,WACA,YAAa,WACf,CAAC,EACD,YAAY,IAAI,OAAO,YAAY,KAAM,OAAO,WAAW,CAC7D,CACF,CAGA,SAAgB,YAAY,OAA4B,CACtD,OAAO,aAA4B,UAAW,OAAQ,CAAC,CAAC,CAC1D,CAeA,SAAgB,aAAa,UAAwD,CACnF,IAAM,KAAkB,CAAC,EACzB,IAAK,IAAM,UAAU,YAAY,OAAO,EACtC,GAAK,UAAU,IAAI,MAAM,EACzB,IAAK,IAAM,QAAQ,YAAY,MAAM,EACnC,KAAK,KAAK,CACR,GAAG,KACH,KAAM,KAAK,MAAQ,GAAG,OAAO,KAAK,GAAG,KAAK,cAC1C,WAAY,eAAe,KAAK,UAAU,EAC1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AW,aAAe,EAAE,KAAK,CAAC,CAAC,OAChE,OAAQ,QAAQ,OAAQ,GAAM,EAAE,SAAW,UAAU,CAAC,CAAC,MACzD,CACF,CAQA,SAAgB,eAAe,WAA4B,CACzD,IAAI,KAAO,WACX,IAAK,IAAM,QAAQ,WAAW,KAAK,CAAC,CAAC,QAAQ,OAAQ,GAAG,EACtD,MAAQ,KAAK,YAAY,CAAC,EAC1B,KAAO,KAAK,KAAK,KAAM,QAAU,IAAM,EAEzC,OAAO,KAAK,SAAS,EAAE,CACzB,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { A as Service, C as Post, D as Put, E as PropertyOrParameterDecorator, M as normalizeApiQueryParamsConfig, N as withBuilder, O as Repository, S as Patch, T as PreDestroy, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as Value, k as RouteDefinition, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable } from "../decorators-DxNb5mWw.mjs";
2
+ import { A as Service, C as Post, D as Put, E as PropertyOrParameterDecorator, M as normalizeApiQueryParamsConfig, N as withBuilder, O as Repository, S as Patch, T as PreDestroy, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as Value, k as RouteDefinition, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable } from "../decorators-BAD8qjuq.mjs";
3
3
  export { ApiQueryParams, ApiQueryParamsConfig, Asset, AssetKey, Autowired, BaseUploadOptions, Builder, ColumnApiQueryParamsConfig, Component, Controller, Delete, type Env, type EnvKey, FileTypeFilter, FileUpload, FileUploadConfig, Get, Inject, Injectable, Middleware, MiddlewareHandler, Patch, Post, PostConstruct, PreDestroy, type PropertyOrParameterDecorator, Put, Repository, RouteDefinition, Service, Value, normalizeApiQueryParamsConfig, withBuilder };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import"../di-hooks-DN_UC8Nc.mjs";import{METADATA,Scope}from"./interfaces.mjs";import{c as pushClassMeta,d as setInMetaMap,l as pushMethodMeta,p as setMethodMeta,u as setClassMeta}from"../metadata-DS4TBMoC.mjs";import"reflect-metadata";import{Autowired,Builder,Component,Inject,Injectable,PostConstruct,PreDestroy,Repository,Service,Value,registerInjectable,withBuilder}from"@forinda/kickjs-di";function Controller(){return target=>{setClassMeta(METADATA.CLASS_KIND,`controller`,target),registerInjectable(target,Scope.SINGLETON)}}function Asset(assetKey){return(target,propertyKey)=>{setInMetaMap(METADATA.ASSET,target,propertyKey,{assetKey})}}function createRouteDecorator(method){return(path,validation)=>(target,propertyKey)=>{pushClassMeta(METADATA.ROUTES,target.constructor,{method,path:path||`/`,handlerName:propertyKey,validation})}}const Get=createRouteDecorator(`GET`),Post=createRouteDecorator(`POST`),Put=createRouteDecorator(`PUT`),Delete=createRouteDecorator(`DELETE`),Patch=createRouteDecorator(`PATCH`);function normalizeApiQueryParamsConfig(config){return`columns`in config&&config.columns&&typeof config.columns==`object`?{filterable:Object.keys(config.columns),sortable:config.sortable?Object.keys(config.sortable):void 0,searchable:config.searchColumns?config.searchColumns.map(col=>col?.name??``).filter(Boolean):void 0}:config}function ApiQueryParams(config){return(target,propertyKey)=>{let normalized=normalizeApiQueryParamsConfig(config);setMethodMeta(METADATA.QUERY_PARAMS,normalized,target.constructor,propertyKey)}}function Middleware(...handlers){return(target,propertyKey)=>{propertyKey?pushMethodMeta(METADATA.METHOD_MIDDLEWARES,target.constructor,propertyKey,...handlers):pushClassMeta(METADATA.CLASS_MIDDLEWARES,target,...handlers)}}function FileUpload(config){return(target,propertyKey)=>{setMethodMeta(METADATA.FILE_UPLOAD,config,target.constructor,propertyKey)}}export{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder};
11
+ import"../di-hooks-DCqt2yJ9.mjs";import{METADATA,Scope}from"./interfaces.mjs";import{c as pushClassMeta,d as setInMetaMap,l as pushMethodMeta,p as setMethodMeta,u as setClassMeta}from"../metadata-BZRtQog3.mjs";import"reflect-metadata";import{Autowired,Builder,Component,Inject,Injectable,PostConstruct,PreDestroy,Repository,Service,Value,registerInjectable,withBuilder}from"@forinda/kickjs-di";function Controller(){return target=>{setClassMeta(METADATA.CLASS_KIND,`controller`,target),registerInjectable(target,Scope.SINGLETON)}}function Asset(assetKey){return(target,propertyKey)=>{setInMetaMap(METADATA.ASSET,target,propertyKey,{assetKey})}}function createRouteDecorator(method){return(path,validation)=>(target,propertyKey)=>{pushClassMeta(METADATA.ROUTES,target.constructor,{method,path:path||`/`,handlerName:propertyKey,validation})}}const Get=createRouteDecorator(`GET`),Post=createRouteDecorator(`POST`),Put=createRouteDecorator(`PUT`),Delete=createRouteDecorator(`DELETE`),Patch=createRouteDecorator(`PATCH`);function normalizeApiQueryParamsConfig(config){return`columns`in config&&config.columns&&typeof config.columns==`object`?{filterable:Object.keys(config.columns),sortable:config.sortable?Object.keys(config.sortable):void 0,searchable:config.searchColumns?config.searchColumns.map(col=>col?.name??``).filter(Boolean):void 0}:config}function ApiQueryParams(config){return(target,propertyKey)=>{let normalized=normalizeApiQueryParamsConfig(config);setMethodMeta(METADATA.QUERY_PARAMS,normalized,target.constructor,propertyKey)}}function Middleware(...handlers){return(target,propertyKey)=>{propertyKey?pushMethodMeta(METADATA.METHOD_MIDDLEWARES,target.constructor,propertyKey,...handlers):pushClassMeta(METADATA.CLASS_MIDDLEWARES,target,...handlers)}}function FileUpload(config){return(target,propertyKey)=>{setMethodMeta(METADATA.FILE_UPLOAD,config,target.constructor,propertyKey)}}export{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder};
12
12
  //# sourceMappingURL=decorators.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport './di-hooks'\nimport { registerInjectable } from '@forinda/kickjs-di'\nimport { METADATA, Scope } from './interfaces'\nimport {\n setClassMeta,\n setMethodMeta,\n pushClassMeta,\n pushMethodMeta,\n setInMetaMap,\n} from './metadata'\n\n// The DI decorators (`@Service`, `@Inject`, `@Value`, …) live in `@forinda/kickjs-di`;\n// this module adds the HTTP ones and `@Asset`, and re-exports both.\nexport {\n Injectable,\n Service,\n Component,\n Repository,\n PostConstruct,\n PreDestroy,\n Autowired,\n Inject,\n Value,\n Builder,\n withBuilder,\n type PropertyOrParameterDecorator,\n type EnvKey,\n type Env,\n} from '@forinda/kickjs-di'\n\n/**\n * Mark a class as an HTTP controller and register it in the DI container.\n *\n * Route prefixes are defined by the module's `routes().path` — the single\n * source of truth for where routes mount. The legacy\n * `@Controller('/path')` parameter was removed in v4; if your code\n * still passes a string, see `docs/guide/migration-v3-to-v4.md` for\n * the rename map.\n */\nexport function Controller(): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInjectable(target, Scope.SINGLETON)\n }\n}\n\n// ── @Asset — typed asset path injection ─────────────────────────────────\n\nimport type { KickAssets } from './assets'\n\n/**\n * Flatten the nested `KickAssets` augmentation (typegen-emitted in\n * PR 4) into a string-literal union of dot/slash-joined paths.\n *\n * `interface KickAssets { mails: { welcome: () => string; orders: {\n * confirmation: () => string } } }` becomes\n * `'mails/welcome' | 'mails/orders/confirmation'`.\n *\n * Returns `never` when `KickAssets` is empty (no typegen has run yet)\n * so `AssetKeyArg` falls through to accept any string.\n */\ntype FlattenAssets<T, Prefix extends string = ''> = {\n [K in keyof T & string]: T[K] extends () => string\n ? `${Prefix}${K}`\n : T[K] extends Record<string, unknown>\n ? FlattenAssets<T[K], `${Prefix}${K}/`>\n : never\n}[keyof T & string]\n\n/** Flat union of every known `<namespace>/<key>` path. */\nexport type AssetKey = FlattenAssets<KickAssets>\n\n/**\n * Constraint mirroring `ValueKey<K>` — accepts any string when\n * `AssetKey` is `never` (back-compat for adopters who haven't run\n * `kick typegen` yet) but locks the argument to known literals once\n * the typegen-augmented `KickAssets` interface is populated.\n */\ntype AssetKeyArg<K extends string> = [AssetKey] extends [never] ? K : K & AssetKey\n\n/**\n * Inject the resolved file-system path for a typed asset. Mirrors\n * `@Value`'s lazy-getter pattern — the asset is resolved on every\n * property access, NOT at class instantiation, so:\n *\n * - Tests can swap fixtures + clear the cache without re-instantiating\n * the consuming class.\n * - The first access cost is paid once per process (the manifest cache\n * in `core/assets.ts` makes subsequent calls cheap).\n *\n * Type-safety:\n *\n * - Without typegen, any string key is accepted (back-compat — same\n * trick as `@Value`).\n * - After typegen, `KickAssets` is populated and `AssetKey` is a\n * union of every flattened `<namespace>/<key>` path. Unknown keys\n * become a TS error.\n *\n * @example\n * ```ts\n * import { Service, Asset } from '@forinda/kickjs'\n *\n * `@Service()`\n * class MailService {\n * `@Asset('mails/welcome')`\n * private welcomeTemplate!: string\n *\n * send(user: User) {\n * return ejs.renderFile(this.welcomeTemplate, { user })\n * }\n * }\n * ```\n */\nexport function Asset<K extends string>(assetKey: AssetKeyArg<K>): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.ASSET, target, propertyKey as string, { assetKey })\n }\n}\n\n// ── HTTP Route Decorators ───────────────────────────────────────────────\n\nexport interface RouteDefinition {\n method: string\n path: string\n handlerName: string\n validation?: {\n /** Schema validating the request body — Zod, Valibot, Yup, any Standard Schema or KickSchema. */\n body?: any\n /** Schema validating query parameters — any library `detectSchema` accepts. */\n query?: any\n /** Schema validating URL params — any library `detectSchema` accepts. */\n params?: any\n /**\n * DECLARED response schema — never validated at runtime. Feeds two\n * consumers from one source of truth: the Swagger adapter's success\n * response schema, and `kick typegen`'s `KickRoutes[...].response`\n * (winning over return-type inference when present).\n */\n response?: any\n /** Schema name in OpenAPI components/schemas for the request body. Auto-generated from handler name if omitted. */\n name?: string\n }\n}\n\nfunction createRouteDecorator(method: string) {\n return (path?: string, validation?: RouteDefinition['validation']): MethodDecorator => {\n return (target, propertyKey) => {\n pushClassMeta<RouteDefinition>(METADATA.ROUTES, target.constructor, {\n method,\n path: path || '/',\n handlerName: propertyKey as string,\n validation,\n })\n }\n }\n}\n\nexport const Get = createRouteDecorator('GET')\nexport const Post = createRouteDecorator('POST')\nexport const Put = createRouteDecorator('PUT')\nexport const Delete = createRouteDecorator('DELETE')\nexport const Patch = createRouteDecorator('PATCH')\n\n// ── Query Params Decorator ─────────────────────────────────────────────\n\nexport interface ApiQueryParamsConfig {\n /** Fields that can be used in filter queries (e.g., `?filter=status:eq:active`) */\n filterable?: string[]\n /** Fields that can be used in sort queries (e.g., `?sort=createdAt:desc`) */\n sortable?: string[]\n /** Fields that are searched with the `?q=` parameter */\n searchable?: string[]\n}\n\n/**\n * Column-object-based query params config (e.g., from DrizzleQueryParamsConfig).\n * `Object.keys()` is used to derive field names for OpenAPI docs.\n */\nexport interface ColumnApiQueryParamsConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/**\n * Normalize a query params config to the string-based ApiQueryParamsConfig.\n * Handles both string-based and column-object-based configs.\n */\nexport function normalizeApiQueryParamsConfig(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): ApiQueryParamsConfig {\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: config.searchColumns\n ? config.searchColumns.map((col: any) => col?.name ?? '').filter(Boolean)\n : undefined,\n }\n }\n return config as ApiQueryParamsConfig\n}\n\n/**\n * Document the query parameters accepted by a GET endpoint.\n * Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params\n * in the OpenAPI spec, with descriptions listing the allowed fields.\n *\n * Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).\n *\n * @example\n * ```ts\n * // String-based\n * @ApiQueryParams({\n * filterable: ['status', 'category', 'price'],\n * sortable: ['name', 'createdAt', 'price'],\n * searchable: ['name', 'description'],\n * })\n *\n * // Column-object-based (Drizzle)\n * @ApiQueryParams(TASK_QUERY_CONFIG)\n * ```\n */\nexport function ApiQueryParams(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): MethodDecorator {\n return (target, propertyKey) => {\n const normalized = normalizeApiQueryParamsConfig(config)\n setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey as string)\n }\n}\n\n// ── Middleware Decorators ───────────────────────────────────────────────\n\n/**\n * Middleware handler function.\n * Generic `TCtx` defaults to `any` — import `RequestContext` from\n * `@forinda/kickjs` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs'\n * import type { RequestContext } from '@forinda/kickjs'\n *\n * const auth: MiddlewareHandler<RequestContext> = (ctx, next) => {\n * ctx.body // fully typed\n * next()\n * }\n * ```\n *\n * A guard stops the request by writing a response and not calling `next()`.\n * Whatever it returns is ignored, so `if (!user) return ctx.problem.unauthorized()`\n * — the idiom handlers use — type-checks here too.\n */\nexport type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => unknown\n\n/** Attach middleware handlers to a class or method */\nexport function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n pushMethodMeta(\n METADATA.METHOD_MIDDLEWARES,\n target.constructor,\n propertyKey as string,\n ...handlers,\n )\n } else {\n pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers)\n }\n }\n}\n\n// ── File Upload Decorator ───────────────────────────────────────────────\n\n/**\n * File filter — accepts short extensions ('jpg'), full MIME types ('image/jpeg'),\n * wildcards ('image/*'), or a function `(mimetype, filename) => boolean` for full control.\n */\nexport type FileTypeFilter = string[] | ((mimetype: string, filename: string) => boolean)\n\n/**\n * Shared upload options used by both the `@FileUpload` decorator and the\n * `upload.single()` / `upload.array()` / `upload.none()` middleware.\n */\nexport interface BaseUploadOptions {\n /** Max file size in bytes (default: 5MB) */\n maxSize?: number\n /**\n * Allowed file types:\n * - **string[]** — short extensions ('jpg'), full MIME types ('image/jpeg'), or wildcards ('image/*')\n * - **function** — `(mimetype, filename) => boolean` for full control\n */\n allowedTypes?: FileTypeFilter\n /** Extend the built-in extension-to-MIME map */\n customMimeMap?: Record<string, string>\n /**\n * The file's server-side name, `file.filename`, from what the client sent.\n * Default: a random UUID plus the client name's extension when it names the\n * file's type (`3f2b….png`) — never the client's name itself. The result must not\n * contain a slash or backslash, nor be `.` or `..`. Disk storage (`dest`) keeps the name\n * it wrote the file under.\n */\n rename?: (file: {\n originalname: string\n mimetype: string\n fieldname: string\n size: number\n }) => string\n}\n\nexport interface FileUploadConfig extends BaseUploadOptions {\n mode: 'single' | 'array' | 'none'\n /** Form field name (default: 'file') */\n fieldName?: string\n /** Max files for array mode (default: 10) */\n maxCount?: number\n}\n\n/** Configure file upload handling for a controller method */\nexport function FileUpload(config: FileUploadConfig): MethodDecorator {\n return (target, propertyKey) => {\n setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey as string)\n }\n}\n"],"mappings":";;;;;;;;;;0YAwCA,SAAgB,YAA6B,CAC3C,MAAQ,SAAgB,CACtB,aAAa,SAAS,WAAY,aAAc,MAAM,EACtD,mB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3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport './di-hooks'\nimport { registerInjectable } from '@forinda/kickjs-di'\nimport { METADATA, Scope } from './interfaces'\nimport {\n setClassMeta,\n setMethodMeta,\n pushClassMeta,\n pushMethodMeta,\n setInMetaMap,\n} from './metadata'\n\n// The DI decorators (`@Service`, `@Inject`, `@Value`, …) live in `@forinda/kickjs-di`;\n// this module adds the HTTP ones and `@Asset`, and re-exports both.\nexport {\n Injectable,\n Service,\n Component,\n Repository,\n PostConstruct,\n PreDestroy,\n Autowired,\n Inject,\n Value,\n Builder,\n withBuilder,\n type PropertyOrParameterDecorator,\n type EnvKey,\n type Env,\n} from '@forinda/kickjs-di'\n\n/**\n * Mark a class as an HTTP controller and register it in the DI container.\n *\n * Route prefixes are defined by the module's `routes().path` — the single\n * source of truth for where routes mount. The legacy\n * `@Controller('/path')` parameter was removed in v4; if your code\n * still passes a string, see `docs/guide/migration-v3-to-v4.md` for\n * the rename map.\n */\nexport function Controller(): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInjectable(target, Scope.SINGLETON)\n }\n}\n\n// ── @Asset — typed asset path injection ─────────────────────────────────\n\nimport type { KickAssets } from './assets'\n\n/**\n * Flatten the nested `KickAssets` augmentation (typegen-emitted in\n * PR 4) into a string-literal union of dot/slash-joined paths.\n *\n * `interface KickAssets { mails: { welcome: () => string; orders: {\n * confirmation: () => string } } }` becomes\n * `'mails/welcome' | 'mails/orders/confirmation'`.\n *\n * Returns `never` when `KickAssets` is empty (no typegen has run yet)\n * so `AssetKeyArg` falls through to accept any string.\n */\ntype FlattenAssets<T, Prefix extends string = ''> = {\n [K in keyof T & string]: T[K] extends () => string\n ? `${Prefix}${K}`\n : T[K] extends Record<string, unknown>\n ? FlattenAssets<T[K], `${Prefix}${K}/`>\n : never\n}[keyof T & string]\n\n/** Flat union of every known `<namespace>/<key>` path. */\nexport type AssetKey = FlattenAssets<KickAssets>\n\n/**\n * Constraint mirroring `ValueKey<K>` — accepts any string when\n * `AssetKey` is `never` (back-compat for adopters who haven't run\n * `kick typegen` yet) but locks the argument to known literals once\n * the typegen-augmented `KickAssets` interface is populated.\n */\ntype AssetKeyArg<K extends string> = [AssetKey] extends [never] ? K : K & AssetKey\n\n/**\n * Inject the resolved file-system path for a typed asset. Mirrors\n * `@Value`'s lazy-getter pattern — the asset is resolved on every\n * property access, NOT at class instantiation, so:\n *\n * - Tests can swap fixtures + clear the cache without re-instantiating\n * the consuming class.\n * - The first access cost is paid once per process (the manifest cache\n * in `core/assets.ts` makes subsequent calls cheap).\n *\n * Type-safety:\n *\n * - Without typegen, any string key is accepted (back-compat — same\n * trick as `@Value`).\n * - After typegen, `KickAssets` is populated and `AssetKey` is a\n * union of every flattened `<namespace>/<key>` path. Unknown keys\n * become a TS error.\n *\n * @example\n * ```ts\n * import { Service, Asset } from '@forinda/kickjs'\n *\n * `@Service()`\n * class MailService {\n * `@Asset('mails/welcome')`\n * private welcomeTemplate!: string\n *\n * send(user: User) {\n * return ejs.renderFile(this.welcomeTemplate, { user })\n * }\n * }\n * ```\n */\nexport function Asset<K extends string>(assetKey: AssetKeyArg<K>): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.ASSET, target, propertyKey as string, { assetKey })\n }\n}\n\n// ── HTTP Route Decorators ───────────────────────────────────────────────\n\nexport interface RouteDefinition {\n method: string\n path: string\n handlerName: string\n validation?: {\n /** Schema validating the request body — Zod, Valibot, Yup, any Standard Schema or KickSchema. */\n body?: any\n /** Schema validating query parameters — any library `detectSchema` accepts. */\n query?: any\n /** Schema validating URL params — any library `detectSchema` accepts. */\n params?: any\n /**\n * DECLARED response schema — never validated at runtime. Feeds two\n * consumers from one source of truth: the Swagger adapter's success\n * response schema, and `kick typegen`'s `KickRoutes[...].response`\n * (winning over return-type inference when present).\n */\n response?: any\n /** Schema name in OpenAPI components/schemas for the request body. Auto-generated from handler name if omitted. */\n name?: string\n }\n}\n\nfunction createRouteDecorator(method: string) {\n return (path?: string, validation?: RouteDefinition['validation']): MethodDecorator => {\n return (target, propertyKey) => {\n pushClassMeta<RouteDefinition>(METADATA.ROUTES, target.constructor, {\n method,\n path: path || '/',\n handlerName: propertyKey as string,\n validation,\n })\n }\n }\n}\n\nexport const Get = createRouteDecorator('GET')\nexport const Post = createRouteDecorator('POST')\nexport const Put = createRouteDecorator('PUT')\nexport const Delete = createRouteDecorator('DELETE')\nexport const Patch = createRouteDecorator('PATCH')\n\n// ── Query Params Decorator ─────────────────────────────────────────────\n\nexport interface ApiQueryParamsConfig {\n /** Fields that can be used in filter queries (e.g., `?filter=status:eq:active`) */\n filterable?: string[]\n /** Fields that can be used in sort queries (e.g., `?sort=createdAt:desc`) */\n sortable?: string[]\n /** Fields that are searched with the `?q=` parameter */\n searchable?: string[]\n}\n\n/**\n * Column-object-based query params config (e.g., from DrizzleQueryParamsConfig).\n * `Object.keys()` is used to derive field names for OpenAPI docs.\n */\nexport interface ColumnApiQueryParamsConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/**\n * Normalize a query params config to the string-based ApiQueryParamsConfig.\n * Handles both string-based and column-object-based configs.\n */\nexport function normalizeApiQueryParamsConfig(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): ApiQueryParamsConfig {\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: config.searchColumns\n ? config.searchColumns.map((col: any) => col?.name ?? '').filter(Boolean)\n : undefined,\n }\n }\n return config as ApiQueryParamsConfig\n}\n\n/**\n * Document the query parameters accepted by a GET endpoint.\n * Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params\n * in the OpenAPI spec, with descriptions listing the allowed fields.\n *\n * Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).\n *\n * @example\n * ```ts\n * // String-based\n * @ApiQueryParams({\n * filterable: ['status', 'category', 'price'],\n * sortable: ['name', 'createdAt', 'price'],\n * searchable: ['name', 'description'],\n * })\n *\n * // Column-object-based (Drizzle)\n * @ApiQueryParams(TASK_QUERY_CONFIG)\n * ```\n */\nexport function ApiQueryParams(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): MethodDecorator {\n return (target, propertyKey) => {\n const normalized = normalizeApiQueryParamsConfig(config)\n setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey as string)\n }\n}\n\n// ── Middleware Decorators ───────────────────────────────────────────────\n\n/**\n * Middleware handler function.\n * Generic `TCtx` defaults to `any` — import `RequestContext` from\n * `@forinda/kickjs` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs'\n * import type { RequestContext } from '@forinda/kickjs'\n *\n * const auth: MiddlewareHandler<RequestContext> = (ctx, next) => {\n * ctx.body // fully typed\n * next()\n * }\n * ```\n *\n * A guard stops the request by writing a response and not calling `next()`.\n * Whatever it returns is ignored, so `if (!user) return ctx.problem.unauthorized()`\n * — the idiom handlers use — type-checks here too.\n */\nexport type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => unknown\n\n/** Attach middleware handlers to a class or method */\nexport function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n pushMethodMeta(\n METADATA.METHOD_MIDDLEWARES,\n target.constructor,\n propertyKey as string,\n ...handlers,\n )\n } else {\n pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers)\n }\n }\n}\n\n// ── File Upload Decorator ───────────────────────────────────────────────\n\n/**\n * File filter — accepts short extensions ('jpg'), full MIME types ('image/jpeg'),\n * wildcards ('image/*'), or a function `(mimetype, filename) => boolean` for full control.\n */\nexport type FileTypeFilter = string[] | ((mimetype: string, filename: string) => boolean)\n\n/**\n * Shared upload options used by both the `@FileUpload` decorator and the\n * `upload.single()` / `upload.array()` / `upload.none()` middleware.\n */\nexport interface BaseUploadOptions {\n /** Max file size in bytes (default: 5MB) */\n maxSize?: number\n /**\n * Allowed file types:\n * - **string[]** — short extensions ('jpg'), full MIME types ('image/jpeg'), or wildcards ('image/*')\n * - **function** — `(mimetype, filename) => boolean` for full control\n */\n allowedTypes?: FileTypeFilter\n /** Extend the built-in extension-to-MIME map */\n customMimeMap?: Record<string, string>\n /**\n * The file's server-side name, `file.filename`, from what the client sent.\n * Default: a random UUID plus the client name's extension when it names the\n * file's type (`3f2b….png`) — never the client's name itself. The result must not\n * contain a slash or backslash, nor be `.` or `..`. Disk storage (`dest`) keeps the name\n * it wrote the file under.\n */\n rename?: (file: {\n originalname: string\n mimetype: string\n fieldname: string\n size: number\n }) => string\n}\n\nexport interface FileUploadConfig extends BaseUploadOptions {\n mode: 'single' | 'array' | 'none'\n /** Form field name (default: 'file') */\n fieldName?: string\n /** Max files for array mode (default: 10) */\n maxCount?: number\n}\n\n/** Configure file upload handling for a controller method */\nexport function FileUpload(config: FileUploadConfig): MethodDecorator {\n return (target, propertyKey) => {\n setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey as string)\n }\n}\n"],"mappings":";;;;;;;;;;A,0YAwCA,SAAgB,YAA6B,CAC3C,MAAQ,SAAgB,CACtB,aAAa,SAAS,WAAY,aAAc,MAAM,EACtD,mBAAmB,OAAQ,MAAM,SAAS,CAC5C,CACF,CAqEA,SAAgB,MAAwB,SAA6C,CACnF,OAAQ,OAAQ,cAAgB,CAC9B,aAAa,SAAS,MAAO,OAAQ,YAAuB,CAAE,QAAS,CAAC,CAC1E,CACF,CA2BA,SAAS,qBAAqB,OAAgB,CAC5C,OAAQ,KAAe,cACb,OAAQ,cAAgB,CAC9B,cAA+B,SAAS,OAAQ,OAAO,YAAa,CAClE,OACA,KAAM,MAAQ,IACd,YAAa,YACb,UACF,CAAC,CACH,CAEJ,CAEA,MAAa,IAAM,qBAAqB,KAAK,EAChC,KAAO,qBAAqB,MAAM,EAClC,IAAM,qBAAqB,KAAK,EAChC,OAAS,qBAAqB,QAAQ,EACtC,MAAQ,qBAAqB,OAAO,EA4BjD,SAAgB,8BACd,OACsB,CAUtB,MATI,YAAa,QAAU,OAAO,SAAW,OAAO,OAAO,SAAY,SAC9D,CACL,WAAY,OAAO,KAAK,OAAO,OAAO,EACtC,SAAU,OAAO,SAAW,OAAO,KAAK,OAAO,QAAQ,EAAI,IAAA,GAC3D,WAAY,OAAO,cACf,OAAO,cAAc,IAAK,KAAa,KAAK,MAAQ,EAAE,CAAC,CAAC,OAAO,OAAO,EACtE,IAAA,EACN,EAEK,MACT,CAsBA,SAAgB,eACd,OACiB,CACjB,OAAQ,OAAQ,cAAgB,CAC9B,IAAM,WAAa,8BAA8B,MAAM,EACvD,cAAc,SAAS,aAAc,WAAY,OAAO,YAAa,WAAqB,CAC5F,CACF,CA0BA,SAAgB,WAAW,GAAG,SAAiE,CAC7F,OAAQ,OAAa,cAAkC,CACjD,YACF,eACE,SAAS,mBACT,OAAO,YACP,YACA,GAAG,QACL,EAEA,cAAc,SAAS,kBAAmB,OAAQ,GAAG,QAAQ,CAEjE,CACF,CAiDA,SAAgB,WAAW,OAA2C,CACpE,OAAQ,OAAQ,cAAgB,CAC9B,cAAc,SAAS,YAAa,OAAQ,OAAO,YAAa,WAAqB,CACvF,CACF,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "../errors-By6UueCm.mjs";
2
+ import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "../errors-DZGuPLoZ.mjs";
3
3
  export { HttpException, HttpStatus, HttpStatusCode, ProblemDetails, ProblemException, Problems, ValidationError, defaultProblemTitle, normalizeProblem };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["/**\n * Standard HTTP status codes as a const enum.\n * Use instead of raw numbers for readability and type safety.\n *\n * @example\n * ```ts\n * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n * ctx.res.status(HttpStatus.CREATED).json(data)\n * ```\n */\nexport const HttpStatus = {\n // 2xx Success\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NO_CONTENT: 204,\n\n // 3xx Redirection\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n NOT_MODIFIED: 304,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // 4xx Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n CONFLICT: 409,\n GONE: 410,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // 5xx Server Errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const\n\nexport type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]\n\n/**\n * IANA HTTP status reason phrases for the codes the framework's typed\n * helpers cover. Used as the default `title` when a {@link ProblemException}\n * is constructed without one. Keep in sync with {@link HttpStatus}.\n */\nconst STATUS_REASONS: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 413: 'Payload Too Large',\n 415: 'Unsupported Media Type',\n 422: 'Unprocessable Entity',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n}\n\n/** Validation error detail — shape used by `unprocessable()` and `fromZodError()`. */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * RFC 9457 — Problem Details for HTTP APIs.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * Canonical error shape for HTTP responses. Only `status` is required;\n * everything else has a sensible default. Extension members (any other\n * JSON-compatible field) are allowed per §3.2 — pass them on the same\n * object and the framework forwards them through.\n *\n * @example\n * ```ts\n * const problem: ProblemDetails = {\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * // extension members per §3.2\n * balance: 30,\n * }\n * ```\n */\nexport interface ProblemDetails {\n /**\n * URI reference identifying the problem type. Per §4.2.1, when\n * dereferenced it SHOULD return human-readable documentation. Defaults\n * to `about:blank` when omitted (RFC 9457 §3.1.1).\n */\n type?: string\n /**\n * Short human-readable summary, advisable to be the same regardless of\n * the occurrence (§3.1.4). Defaults to the IANA reason phrase for\n * `status` when omitted.\n */\n title?: string\n /** HTTP status code generated by the origin server. Required. */\n status: number\n /**\n * Human-readable explanation specific to this occurrence (§3.1.5).\n * Per the RFC's safety guidance, do not include sensitive information\n * (tokens, full SQL, stack traces) — those belong in logs.\n */\n detail?: string\n /**\n * URI reference identifying the specific occurrence (§3.1.6).\n * Typically the request path. Adopters set this explicitly — the\n * framework does not auto-populate it to avoid leaking unexpected\n * structure.\n */\n instance?: string\n /**\n * Extension members per §3.2 — any other JSON-compatible field.\n * Common examples: `balance`, `errors`, `traceId`, `accounts`.\n */\n [key: string]: unknown\n}\n\n/**\n * Typed HTTP exception with status code, free-form details, and optional\n * response headers. Provides static factory methods for common HTTP errors.\n *\n * `details` is intentionally typed as `unknown` — it serializes straight into\n * the response body's `errors` field, so any JSON-compatible shape works\n * (string, object, array of mixed values, ValidationError[]).\n *\n * `headers` are merged into the response by the global error handler so\n * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)\n * stay on the exception, not on ad-hoc try/catch chains.\n *\n * For RFC 9457 — Problem Details responses, throw {@link ProblemException}\n * instead — the global error handler emits `application/problem+json` for\n * those automatically.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: unknown,\n public readonly headers?: Record<string, string>,\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): HttpException {\n return new HttpException(this.status, this.message, this.details, {\n ...this.headers,\n ...headers,\n })\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n const details: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n details,\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized', wwwAuthenticate?: string) {\n return new HttpException(\n HttpStatus.UNAUTHORIZED,\n message,\n undefined,\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n }\n static forbidden(message = 'Forbidden') {\n return new HttpException(HttpStatus.FORBIDDEN, message)\n }\n static notFound(message = 'Not Found') {\n return new HttpException(HttpStatus.NOT_FOUND, message)\n }\n static methodNotAllowed(allowedMethods: string[], message = 'Method Not Allowed') {\n return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, undefined, {\n Allow: allowedMethods.join(', '),\n })\n }\n static conflict(message = 'Conflict') {\n return new HttpException(HttpStatus.CONFLICT, message)\n }\n static unprocessable(message = 'Unprocessable Entity', details?: ValidationError[]) {\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n }\n static tooManyRequests(message = 'Too Many Requests', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.TOO_MANY_REQUESTS,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static serviceUnavailable(message = 'Service Unavailable', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.SERVICE_UNAVAILABLE,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static internal(message = 'Internal Server Error') {\n return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message)\n }\n}\n\n/**\n * Default `title` for an RFC 9457 problem with the given status — the IANA\n * reason phrase, or `'Error'` for codes outside the framework's table.\n * Exposed so {@link ProblemException} construction and {@link RequestContext}'s\n * `problem` helpers share a single source of truth.\n */\nexport function defaultProblemTitle(status: number): string {\n return STATUS_REASONS[status] ?? 'Error'\n}\n\n/**\n * Exception that carries an RFC 9457 — Problem Details payload. When\n * thrown, the framework error handler emits `application/problem+json`\n * with the canonical shape; `type` defaults to `about:blank`, `title`\n * to the IANA reason phrase for `status`.\n *\n * Extends {@link HttpException} so existing `instanceof HttpException`\n * catches still see it. Use `new ProblemException(...)` directly for\n * full control, or {@link Problems} for the pre-filled-status\n * convenience factories.\n *\n * Static factories deliberately live on {@link Problems} rather than\n * this class — putting them here would shadow `HttpException`'s\n * same-named statics with incompatible (object vs string) signatures,\n * which TypeScript correctly rejects.\n *\n * @example\n * ```ts\n * throw new ProblemException({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * balance: 30, // extension\n * })\n *\n * // Or via the Problems convenience factory:\n * throw Problems.forbidden({\n * type: 'https://api.example.com/problems/out-of-credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30,\n * })\n * ```\n */\nexport class ProblemException extends HttpException {\n public readonly problem: ProblemDetails\n\n constructor(problem: ProblemDetails, headers?: Record<string, string>) {\n const title = problem.title ?? defaultProblemTitle(problem.status)\n const detail = problem.detail ?? title\n super(problem.status, detail, undefined, headers)\n this.name = 'ProblemException'\n this.problem = { ...problem, title }\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): ProblemException {\n return new ProblemException(this.problem, { ...this.headers, ...headers })\n }\n}\n\n/**\n * Convenience factories for {@link ProblemException}. Pre-fill `status`\n * (and `title` via {@link defaultProblemTitle}) for the common HTTP\n * codes — same shortcut set the `ctx.problem.*` response helpers cover.\n *\n * Lives in a separate namespace rather than as statics on\n * {@link ProblemException} to avoid shadowing {@link HttpException}'s\n * same-named statics, which would create a TypeScript variance\n * conflict (parent's `notFound(message?: string)` vs the child's\n * desired `notFound(input?: ProblemInput)`).\n *\n * @example\n * ```ts\n * throw Problems.notFound({ detail: 'User abc not found' })\n * throw Problems.tooManyRequests({}, 60) // sets Retry-After: 60\n * throw Problems.fromZodError(zodResult.error)\n * ```\n */\nexport const Problems = {\n /** 400 Bad Request with optional detail / instance / extensions. */\n badRequest(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 400, ...input })\n },\n /** 401 Unauthorized. Pass a `WWW-Authenticate` challenge via the headers arg. */\n unauthorized(\n input: Omit<ProblemDetails, 'status'> = {},\n wwwAuthenticate?: string,\n ): ProblemException {\n return new ProblemException(\n { status: 401, ...input },\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n },\n /** 403 Forbidden. */\n forbidden(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 403, ...input })\n },\n /** 404 Not Found. */\n notFound(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 404, ...input })\n },\n /** 405 Method Not Allowed. Pass the allowed methods so the Allow header is set. */\n methodNotAllowed(\n allowedMethods: string[],\n input: Omit<ProblemDetails, 'status'> = {},\n ): ProblemException {\n return new ProblemException({ status: 405, ...input }, { Allow: allowedMethods.join(', ') })\n },\n /** 409 Conflict. */\n conflict(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 409, ...input })\n },\n /**\n * 422 Unprocessable Entity. Pass per-field issues via the `errors`\n * extension — keep the array shape per the RFC's recommended convention\n * (`{ field, message, code }`).\n */\n unprocessable(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 422, ...input })\n },\n /** 429 Too Many Requests. Pass `retryAfterSeconds` to set the Retry-After header. */\n tooManyRequests(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 429, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 503 Service Unavailable. */\n serviceUnavailable(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 503, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 500 Internal Server Error. */\n internal(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 500, ...input })\n },\n\n /**\n * Build from a Zod error — 422 with the issues serialized into the\n * `errors` extension per RFC 9457 §3.2's array convention.\n */\n fromZodError(error: any, input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n const issues: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new ProblemException({\n status: 422,\n detail: error.issues?.[0]?.message,\n ...input,\n errors: issues,\n })\n },\n} as const\n\n/**\n * Normalize an RFC 9457 problem into the wire shape — fill in `type` →\n * `'about:blank'` and `title` → IANA reason phrase. The same function is\n * used by {@link RequestContext}'s `problem` helpers and the global\n * error handler so the response is identical regardless of entry point.\n *\n * Defaults are applied **after** the spread, so a caller passing\n * `{ type: undefined }` (e.g. a partial built up from optional fields)\n * still gets `'about:blank'` on the wire — `...input` would otherwise\n * re-overwrite the fallback with the explicit `undefined`.\n */\nexport function normalizeProblem(input: ProblemDetails): ProblemDetails {\n return {\n ...input,\n type: input.type ?? 'about:blank',\n title: input.title ?? defaultProblemTitle(input.status),\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,WAAa,CAExB,GAAI,IACJ,QAAS,IACT,SAAU,IACV,WAAY,IAGZ,kBAAmB,IACnB,MAAO,IACP,aAAc,IACd,mBAAoB,IACpB,mBAAoB,IAGpB,YAAa,IACb,aAAc,IACd,iBAAkB,IAClB,UAAW,IACX,UAAW,IACX,mBAAoB,IACpB,eAAgB,IAChB,SAAU,IACV,KAAM,IACN,kBAAmB,IACnB,uBAAwB,IACxB,qBAAsB,IACtB,kBAAmB,IAGnB,sBAAuB,IACvB,gBAAiB,IACjB,YAAa,IACb,oBAAqB,IACrB,gBAAiB,GACnB,EASM,eAAyC,CAC7C,IAAK,cACL,IAAK,eACL,IAAK,mBACL,IAAK,YACL,IAAK,YACL,IAAK,qBACL,IAAK,iBACL,IAAK,WACL,IAAK,OACL,IAAK,sBACL,IAAK,oBACL,IAAK,yBACL,IAAK,uBACL,IAAK,oBACL,IAAK,wBACL,IAAK,kBACL,IAAK,cACL,IAAK,sBACL,IAAK,iBACP,EAkFA,IAAa,cAAb,MAAa,sBAAsB,KAAM,CAErB,OAEA,QACA,QAJlB,YACE,OACA,QACA,QACA,QACA,CACA,MAAM,OAAO,EALG,KAAA,OAAA,OAEA,KAAA,QAAA,QACA,KAAA,QAAA,QAGhB,KAAK,KAAO,eACd,CAG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AAM,CACxD,CACF"}
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["/**\n * Standard HTTP status codes as a const enum.\n * Use instead of raw numbers for readability and type safety.\n *\n * @example\n * ```ts\n * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n * ctx.res.status(HttpStatus.CREATED).json(data)\n * ```\n */\nexport const HttpStatus = {\n // 2xx Success\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NO_CONTENT: 204,\n\n // 3xx Redirection\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n NOT_MODIFIED: 304,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // 4xx Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n CONFLICT: 409,\n GONE: 410,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // 5xx Server Errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const\n\nexport type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]\n\n/**\n * IANA HTTP status reason phrases for the codes the framework's typed\n * helpers cover. Used as the default `title` when a {@link ProblemException}\n * is constructed without one. Keep in sync with {@link HttpStatus}.\n */\nconst STATUS_REASONS: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 413: 'Payload Too Large',\n 415: 'Unsupported Media Type',\n 422: 'Unprocessable Entity',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n}\n\n/** Validation error detail — shape used by `unprocessable()` and `fromZodError()`. */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * RFC 9457 — Problem Details for HTTP APIs.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * Canonical error shape for HTTP responses. Only `status` is required;\n * everything else has a sensible default. Extension members (any other\n * JSON-compatible field) are allowed per §3.2 — pass them on the same\n * object and the framework forwards them through.\n *\n * @example\n * ```ts\n * const problem: ProblemDetails = {\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * // extension members per §3.2\n * balance: 30,\n * }\n * ```\n */\nexport interface ProblemDetails {\n /**\n * URI reference identifying the problem type. Per §4.2.1, when\n * dereferenced it SHOULD return human-readable documentation. Defaults\n * to `about:blank` when omitted (RFC 9457 §3.1.1).\n */\n type?: string\n /**\n * Short human-readable summary, advisable to be the same regardless of\n * the occurrence (§3.1.4). Defaults to the IANA reason phrase for\n * `status` when omitted.\n */\n title?: string\n /** HTTP status code generated by the origin server. Required. */\n status: number\n /**\n * Human-readable explanation specific to this occurrence (§3.1.5).\n * Per the RFC's safety guidance, do not include sensitive information\n * (tokens, full SQL, stack traces) — those belong in logs.\n */\n detail?: string\n /**\n * URI reference identifying the specific occurrence (§3.1.6).\n * Typically the request path. Adopters set this explicitly — the\n * framework does not auto-populate it to avoid leaking unexpected\n * structure.\n */\n instance?: string\n /**\n * Extension members per §3.2 — any other JSON-compatible field.\n * Common examples: `balance`, `errors`, `traceId`, `accounts`.\n */\n [key: string]: unknown\n}\n\n/**\n * Typed HTTP exception with status code, free-form details, and optional\n * response headers. Provides static factory methods for common HTTP errors.\n *\n * `details` is intentionally typed as `unknown` — it serializes straight into\n * the response body's `errors` field, so any JSON-compatible shape works\n * (string, object, array of mixed values, ValidationError[]).\n *\n * `headers` are merged into the response by the global error handler so\n * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)\n * stay on the exception, not on ad-hoc try/catch chains.\n *\n * For RFC 9457 — Problem Details responses, throw {@link ProblemException}\n * instead — the global error handler emits `application/problem+json` for\n * those automatically.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: unknown,\n public readonly headers?: Record<string, string>,\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): HttpException {\n return new HttpException(this.status, this.message, this.details, {\n ...this.headers,\n ...headers,\n })\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n const details: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n details,\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized', wwwAuthenticate?: string) {\n return new HttpException(\n HttpStatus.UNAUTHORIZED,\n message,\n undefined,\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n }\n static forbidden(message = 'Forbidden') {\n return new HttpException(HttpStatus.FORBIDDEN, message)\n }\n static notFound(message = 'Not Found') {\n return new HttpException(HttpStatus.NOT_FOUND, message)\n }\n static methodNotAllowed(allowedMethods: string[], message = 'Method Not Allowed') {\n return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, undefined, {\n Allow: allowedMethods.join(', '),\n })\n }\n static conflict(message = 'Conflict') {\n return new HttpException(HttpStatus.CONFLICT, message)\n }\n static unprocessable(message = 'Unprocessable Entity', details?: ValidationError[]) {\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n }\n static tooManyRequests(message = 'Too Many Requests', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.TOO_MANY_REQUESTS,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static serviceUnavailable(message = 'Service Unavailable', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.SERVICE_UNAVAILABLE,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static internal(message = 'Internal Server Error') {\n return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message)\n }\n}\n\n/**\n * Default `title` for an RFC 9457 problem with the given status — the IANA\n * reason phrase, or `'Error'` for codes outside the framework's table.\n * Exposed so {@link ProblemException} construction and {@link RequestContext}'s\n * `problem` helpers share a single source of truth.\n */\nexport function defaultProblemTitle(status: number): string {\n return STATUS_REASONS[status] ?? 'Error'\n}\n\n/**\n * Exception that carries an RFC 9457 — Problem Details payload. When\n * thrown, the framework error handler emits `application/problem+json`\n * with the canonical shape; `type` defaults to `about:blank`, `title`\n * to the IANA reason phrase for `status`.\n *\n * Extends {@link HttpException} so existing `instanceof HttpException`\n * catches still see it. Use `new ProblemException(...)` directly for\n * full control, or {@link Problems} for the pre-filled-status\n * convenience factories.\n *\n * Static factories deliberately live on {@link Problems} rather than\n * this class — putting them here would shadow `HttpException`'s\n * same-named statics with incompatible (object vs string) signatures,\n * which TypeScript correctly rejects.\n *\n * @example\n * ```ts\n * throw new ProblemException({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * balance: 30, // extension\n * })\n *\n * // Or via the Problems convenience factory:\n * throw Problems.forbidden({\n * type: 'https://api.example.com/problems/out-of-credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30,\n * })\n * ```\n */\nexport class ProblemException extends HttpException {\n public readonly problem: ProblemDetails\n\n constructor(problem: ProblemDetails, headers?: Record<string, string>) {\n const title = problem.title ?? defaultProblemTitle(problem.status)\n const detail = problem.detail ?? title\n super(problem.status, detail, undefined, headers)\n this.name = 'ProblemException'\n this.problem = { ...problem, title }\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): ProblemException {\n return new ProblemException(this.problem, { ...this.headers, ...headers })\n }\n}\n\n/**\n * Convenience factories for {@link ProblemException}. Pre-fill `status`\n * (and `title` via {@link defaultProblemTitle}) for the common HTTP\n * codes — same shortcut set the `ctx.problem.*` response helpers cover.\n *\n * Lives in a separate namespace rather than as statics on\n * {@link ProblemException} to avoid shadowing {@link HttpException}'s\n * same-named statics, which would create a TypeScript variance\n * conflict (parent's `notFound(message?: string)` vs the child's\n * desired `notFound(input?: ProblemInput)`).\n *\n * @example\n * ```ts\n * throw Problems.notFound({ detail: 'User abc not found' })\n * throw Problems.tooManyRequests({}, 60) // sets Retry-After: 60\n * throw Problems.fromZodError(zodResult.error)\n * ```\n */\nexport const Problems = {\n /** 400 Bad Request with optional detail / instance / extensions. */\n badRequest(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 400, ...input })\n },\n /** 401 Unauthorized. Pass a `WWW-Authenticate` challenge via the headers arg. */\n unauthorized(\n input: Omit<ProblemDetails, 'status'> = {},\n wwwAuthenticate?: string,\n ): ProblemException {\n return new ProblemException(\n { status: 401, ...input },\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n },\n /** 403 Forbidden. */\n forbidden(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 403, ...input })\n },\n /** 404 Not Found. */\n notFound(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 404, ...input })\n },\n /** 405 Method Not Allowed. Pass the allowed methods so the Allow header is set. */\n methodNotAllowed(\n allowedMethods: string[],\n input: Omit<ProblemDetails, 'status'> = {},\n ): ProblemException {\n return new ProblemException({ status: 405, ...input }, { Allow: allowedMethods.join(', ') })\n },\n /** 409 Conflict. */\n conflict(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 409, ...input })\n },\n /**\n * 422 Unprocessable Entity. Pass per-field issues via the `errors`\n * extension — keep the array shape per the RFC's recommended convention\n * (`{ field, message, code }`).\n */\n unprocessable(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 422, ...input })\n },\n /** 429 Too Many Requests. Pass `retryAfterSeconds` to set the Retry-After header. */\n tooManyRequests(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 429, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 503 Service Unavailable. */\n serviceUnavailable(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 503, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 500 Internal Server Error. */\n internal(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 500, ...input })\n },\n\n /**\n * Build from a Zod error — 422 with the issues serialized into the\n * `errors` extension per RFC 9457 §3.2's array convention.\n */\n fromZodError(error: any, input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n const issues: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new ProblemException({\n status: 422,\n detail: error.issues?.[0]?.message,\n ...input,\n errors: issues,\n })\n },\n} as const\n\n/**\n * Normalize an RFC 9457 problem into the wire shape — fill in `type` →\n * `'about:blank'` and `title` → IANA reason phrase. The same function is\n * used by {@link RequestContext}'s `problem` helpers and the global\n * error handler so the response is identical regardless of entry point.\n *\n * Defaults are applied **after** the spread, so a caller passing\n * `{ type: undefined }` (e.g. a partial built up from optional fields)\n * still gets `'about:blank'` on the wire — `...input` would otherwise\n * re-overwrite the fallback with the explicit `undefined`.\n */\nexport function normalizeProblem(input: ProblemDetails): ProblemDetails {\n return {\n ...input,\n type: input.type ?? 'about:blank',\n title: input.title ?? defaultProblemTitle(input.status),\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,WAAa,CAExB,GAAI,IACJ,QAAS,IACT,SAAU,IACV,WAAY,IAGZ,kBAAmB,IACnB,MAAO,IACP,aAAc,IACd,mBAAoB,IACpB,mBAAoB,IAGpB,YAAa,IACb,aAAc,IACd,iBAAkB,IAClB,UAAW,IACX,UAAW,IACX,mBAAoB,IACpB,eAAgB,IAChB,SAAU,IACV,KAAM,IACN,kBAAmB,IACnB,uBAAwB,IACxB,qBAAsB,IACtB,kBAAmB,IAGnB,sBAAuB,IACvB,gBAAiB,IACjB,YAAa,IACb,oBAAqB,IACrB,gBAAiB,GACnB,EASM,eAAyC,CAC7C,IAAK,cACL,IAAK,eACL,IAAK,mBACL,IAAK,YACL,IAAK,YACL,IAAK,qBACL,IAAK,iBACL,IAAK,WACL,IAAK,OACL,IAAK,sBACL,IAAK,oBACL,IAAK,yBACL,IAAK,uBACL,IAAK,oBACL,IAAK,wBACL,IAAK,kBACL,IAAK,cACL,IAAK,sBACL,IAAK,iBACP,EAkFA,IAAa,cAAb,MAAa,sBAAsB,KAAM,CAErB,OAEA,QACA,QAJlB,YACE,OACA,QACA,QACA,QACA,CACA,MAAM,OAAO,EALG,KAAA,OAAA,OAEA,KAAA,QAAA,QACA,KAAA,QAAA,QAGhB,KAAK,KAAO,eACd,CAGA,YAAY,QAAgD,CAC1D,OAAO,IAAI,cAAc,KAAK,OAAQ,KAAK,QAAS,KAAK,QAAS,CAChE,GAAG,KAAK,QACR,GAAG,OACL,CAAC,CACH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, s as MaybePromise, t as Buildable, u as ServiceOptions } from "../interfaces-C6LHcYsg.mjs";
2
+ import { a as DI_METADATA, c as PostConstructStatus, i as Constructor, l as Scope, n as BuilderOf, o as METADATA, r as ClassKind, s as MaybePromise, t as Buildable, u as ServiceOptions } from "../interfaces-BQhYh3lL.mjs";
3
3
  export { type Buildable, type BuilderOf, type ClassKind, type Constructor, DI_METADATA, METADATA, MaybePromise, type PostConstructStatus, Scope, type ServiceOptions };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"interfaces.mjs","names":["DI_METADATA"],"sources":["../../src/core/interfaces.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { DI_METADATA } from '@forinda/kickjs-di'\n\nexport {\n Scope,\n DI_METADATA,\n type Constructor,\n type ServiceOptions,\n type BuilderOf,\n type Buildable,\n type ClassKind,\n type PostConstructStatus,\n} from '@forinda/kickjs-di'\n\n/** A value that may or may not be wrapped in a Promise */\nexport type MaybePromise<T = void> = T | Promise<T>\n\n/** Metadata keys: the DI ones (`DI_METADATA`) plus the HTTP layer's and `@Asset`'s. */\nexport const METADATA = {\n ...DI_METADATA,\n QUERY_PARAMS: 'kick:query:params',\n ROUTES: 'kick:routes',\n CLASS_MIDDLEWARES: 'kick:class:middlewares',\n METHOD_MIDDLEWARES: 'kick:method:middlewares',\n CLASS_CONTRIBUTORS: 'kick:class:contributors',\n METHOD_CONTRIBUTORS: 'kick:method:contributors',\n CLASS_FLAGS: 'kick:class:flags',\n METHOD_FLAGS: 'kick:method:flags',\n FILE_UPLOAD: 'kick:file:upload',\n ASSET: 'kick:asset',\n} as const\n"],"mappings":";;;;;;;;;;wGAkBA,MAAa,SAAW,CACtB,GAAGA,cACH,aAAc,oBACd,OAAQ,cACR,kBAAmB,yBACnB,mBAAoB,0BACpB,mBAAoB,0BACpB,oBAAqB,2BACrB,YAAa,mBACb,aAAc,oBACd,YAAa,mBACb,MAAO,YACT"}
1
+ {"version":3,"file":"interfaces.mjs","names":["DI_METADATA"],"sources":["../../src/core/interfaces.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { DI_METADATA } from '@forinda/kickjs-di'\n\nexport {\n Scope,\n DI_METADATA,\n type Constructor,\n type ServiceOptions,\n type BuilderOf,\n type Buildable,\n type ClassKind,\n type PostConstructStatus,\n} from '@forinda/kickjs-di'\n\n/** A value that may or may not be wrapped in a Promise */\nexport type MaybePromise<T = void> = T | Promise<T>\n\n/** Metadata keys: the DI ones (`DI_METADATA`) plus the HTTP layer's and `@Asset`'s. */\nexport const METADATA = {\n ...DI_METADATA,\n QUERY_PARAMS: 'kick:query:params',\n ROUTES: 'kick:routes',\n CLASS_MIDDLEWARES: 'kick:class:middlewares',\n METHOD_MIDDLEWARES: 'kick:method:middlewares',\n CLASS_CONTRIBUTORS: 'kick:class:contributors',\n METHOD_CONTRIBUTORS: 'kick:method:contributors',\n CLASS_FLAGS: 'kick:class:flags',\n METHOD_FLAGS: 'kick:method:flags',\n FILE_UPLOAD: 'kick:file:upload',\n ASSET: 'kick:asset',\n} as const\n"],"mappings":";;;;;;;;;;A,wGAkBA,MAAa,SAAW,CACtB,GAAGA,cACH,aAAc,oBACd,OAAQ,cACR,kBAAmB,yBACnB,mBAAoB,0BACpB,mBAAoB,0BACpB,oBAAqB,2BACrB,YAAa,mBACb,aAAc,oBACd,YAAa,mBACb,MAAO,YACT,E"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as describeError, i as createLogger, n as Logger, o as jsonLine, r as LoggerProvider, s as serializeError, t as ConsoleLoggerProvider } from "../logger-xE9qI_FS.mjs";
2
+ import { a as describeError, i as createLogger, n as Logger, o as jsonLine, r as LoggerProvider, s as serializeError, t as ConsoleLoggerProvider } from "../logger-BL8MiSrm.mjs";
3
3
  export { ConsoleLoggerProvider, Logger, LoggerProvider, createLogger, describeError, jsonLine, serializeError };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"logger.mjs","names":[],"sources":["../../src/core/logger.ts"],"sourcesContent":["// ── LoggerProvider interface ───────────────────────────────────────────\n\n/**\n * Pluggable logger backend.\n *\n * Implement this interface to plug in any logging library (pino,\n * winston, bunyan, console, etc.). The framework only ever calls the\n * methods declared here — it doesn't know or care which logger is\n * underneath.\n *\n * Default: `ConsoleLoggerProvider` (zero runtime deps).\n *\n * @example\n * ```ts\n * import pino from 'pino'\n * import { Logger, type LoggerProvider } from '@forinda/kickjs'\n *\n * class PinoProvider implements LoggerProvider {\n * constructor(private p = pino()) {}\n * info(msg, ...args) { this.p.info(msg, ...args) }\n * warn(msg, ...args) { this.p.warn(msg, ...args) }\n * error(msg, ...args) { this.p.error(msg, ...args) }\n * debug(msg, ...args) { this.p.debug(msg, ...args) }\n * child({ component }) { return new PinoProvider(this.p.child({ component })) }\n * }\n *\n * Logger.setProvider(new PinoProvider())\n * ```\n *\n * See `docs/guide/logging.md` for Pino, Winston, and silent-logger recipes.\n */\nexport interface LoggerProvider {\n info(msg: string, ...args: any[]): void\n warn(msg: string, ...args: any[]): void\n error(msg: string, ...args: any[]): void\n debug(msg: string, ...args: any[]): void\n trace?(msg: string, ...args: any[]): void\n fatal?(msg: string, ...args: any[]): void\n /**\n * Return a child provider scoped to the given component name. `bindings`\n * may also carry fields from `logger.child({ ... })` (a request id, a job\n * name) — a provider that ignores them keeps working as before.\n */\n child(bindings: { component: string; [field: string]: unknown }): LoggerProvider\n}\n\n// ── Log levels ─────────────────────────────────────────────────────────\n\n/** Severity ordering — a message prints only when its rank ≥ the threshold. */\nconst LEVEL_RANK: Record<string, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n silent: 100,\n}\n\n/**\n * Resolve the active threshold rank from `LOG_LEVEL` (default `info`).\n * Read per-call so a late `process.env.LOG_LEVEL` assignment still\n * takes effect. An unrecognised value falls back to `info`.\n */\nfunction thresholdRank(): number {\n // `process` is guarded because this module is reachable from the\n // edge-safe web pipeline (`@forinda/kickjs/web`), where strict runtimes\n // expose no `process` global at all. The colour probe below already\n // guarded; this one did not, so merely importing the logger could throw\n // on such a runtime.\n const level = (\n (typeof process !== 'undefined' ? process.env?.LOG_LEVEL : undefined) ?? 'info'\n ).toLowerCase()\n return LEVEL_RANK[level] ?? LEVEL_RANK.info\n}\n\n/** `LOG_FORMAT=json` switches the default provider to one JSON object per line. */\nfunction jsonFormat(): boolean {\n return (\n (typeof process !== 'undefined' ? process.env?.LOG_FORMAT : undefined)?.toLowerCase() === 'json'\n )\n}\n\n/** A plain `{ ... }` object — merged into a JSON line as fields. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * An error as a JSON field — `type`, `message`, `stack`, own enumerable\n * properties (a driver's `code`), and its `cause` chain, depth-capped and\n * cycle-guarded like {@link describeError}.\n */\nexport function serializeError(err: unknown, depth = 4, seen = new Set<unknown>()): unknown {\n if (!(err instanceof Error)) return err\n if (seen.has(err) || depth <= 0) return '[circular cause]'\n seen.add(err)\n const out: Record<string, unknown> = { type: err.name, message: err.message, stack: err.stack }\n for (const [key, value] of Object.entries(err)) if (!(key in out)) out[key] = value\n const cause = (err as { cause?: unknown }).cause\n if (cause !== undefined) out.cause = serializeError(cause, depth - 1, seen)\n return out\n}\n\n/**\n * Fill printf-style placeholders the way `console.log` does (`%s %d %i %f\n * %j %o %O`, `%%`), then append what's left — so `log.info('hi %s', name)`\n * reads the same in JSON as on a terminal.\n */\nfunction formatMessage(msg: string, args: unknown[]): string {\n let i = 0\n const filled = msg.replace(/%[sdifjoO%]/g, (token) => {\n if (token === '%%') return '%'\n if (i >= args.length) return token\n const value = args[i++]\n if (token === '%d' || token === '%i') return String(Math.trunc(Number(value)))\n if (token === '%f') return String(Number(value))\n if (token === '%s') return typeof value === 'string' ? value : safeStringify(value)\n return safeStringify(value)\n })\n const rest = args.slice(i).map((a) => (typeof a === 'string' ? a : safeStringify(a)))\n return rest.length ? `${filled} ${rest.join(' ')}` : filled\n}\n\n/** Keys of a JSON line only the logger writes — see {@link jsonLine}. */\nconst RESERVED_FIELDS = new Set(['level', 'time', 'component', 'msg', 'err'])\n\n/**\n * One JSON log line, field-compatible with pino (`level` 10–60, `time` in\n * epoch ms, `msg`) so `pino-pretty` and log shippers read it as-is. Trailing\n * plain objects become fields, an `Error` becomes `err`, and anything else\n * fills the message's placeholders or is appended to it.\n */\nexport function jsonLine(\n level: keyof typeof LEVEL_RANK,\n component: string,\n bindings: Record<string, unknown>,\n msg: string,\n args: unknown[],\n): string {\n // Null prototype: a `__proto__` key in logged data stays a plain field.\n const fields: Record<string, unknown> = Object.create(null)\n const rest: unknown[] = []\n let err: unknown\n for (const arg of args) {\n if (arg instanceof Error) err ??= serializeError(arg)\n else if (isPlainObject(arg)) Object.assign(fields, arg)\n else rest.push(arg)\n }\n const line: Record<string, unknown> = {\n level: LEVEL_RANK[level],\n time: Date.now(),\n ...(component ? { component } : {}),\n }\n // Logged data is often untrusted (a request body): it must not rewrite the\n // line's level, time, source or message, or pass a plain object off as the\n // error. Those come from the logger only; a field with one of those names is\n // dropped.\n for (const source of [bindings, fields]) {\n for (const key of Object.keys(source)) {\n if (!RESERVED_FIELDS.has(key)) line[key] = source[key]\n }\n }\n if (err !== undefined) line.err = err\n line.msg = formatMessage(msg, rest)\n try {\n return JSON.stringify(line, bigintSafe)\n } catch {\n // Something can't be written (a circular field). Drop only that: every\n // other field stays, and `err` — usually why the line exists — keeps at\n // least its type, message and stack.\n const safe: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(line)) {\n try {\n JSON.stringify(value, bigintSafe)\n safe[key] = value\n } catch {\n safe[key] =\n key === 'err' && value && typeof value === 'object'\n ? pick(value as Record<string, unknown>, ['type', 'message', 'stack'])\n : '[unserializable]'\n }\n }\n return JSON.stringify(safe, bigintSafe)\n }\n}\n\nconst bigintSafe = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value\n\nfunction pick(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const key of keys) if (typeof obj[key] === 'string') out[key] = obj[key]\n return out\n}\n\n// ── ConsoleLoggerProvider (default) ────────────────────────────────────\n\n/**\n * Default provider — emits through `console.*` methods. Zero deps.\n *\n * Respects the `LOG_LEVEL` env var (default `info`): messages below the\n * threshold are dropped, so the verbose startup detail (the route table,\n * DI wiring, HMR ticks — all `debug`) stays quiet by default and only\n * appears with `LOG_LEVEL=debug`. `error`/`fatal` always print unless\n * `LOG_LEVEL=silent`.\n *\n * `LOG_FORMAT=json` writes one pino-compatible JSON object per line instead\n * (all levels through `console.log`, so one stream carries them): fields\n * from `logger.child({ ... })` and from trailing plain-object arguments, and\n * an `Error` argument as `err` with its stack and `cause` chain. The default\n * text output is unchanged.\n *\n * Swap it for pino, winston, bunyan, or anything else by implementing\n * the `LoggerProvider` interface and calling `Logger.setProvider()`\n * before `bootstrap()`.\n */\nexport class ConsoleLoggerProvider implements LoggerProvider {\n private prefix: string\n private useColor: boolean\n /** Fields from `logger.child({ ... })` — written on JSON lines. */\n private bindings: Record<string, unknown>\n\n constructor(prefix?: string, bindings: Record<string, unknown> = {}) {\n this.prefix = prefix ?? ''\n this.bindings = bindings\n this.useColor =\n typeof process !== 'undefined' && process.stdout?.isTTY === true && !process.env.NO_COLOR\n }\n\n /** Write `msg` as a JSON line when `LOG_FORMAT=json`; returns whether it did. */\n private json(level: keyof typeof LEVEL_RANK, msg: string, args: unknown[]): boolean {\n if (!jsonFormat()) return false\n console.log(jsonLine(level, this.prefix, this.bindings, msg, args))\n return true\n }\n\n private fmt(level: string, color: string, msg: string): string {\n const tag = this.prefix ? `[${this.prefix}]` : ''\n if (this.useColor) {\n return `${color}${level}\\x1b[0m ${tag ? `\\x1b[36m${tag}\\x1b[0m ` : ''}${msg}`\n }\n return `${level} ${tag ? `${tag} ` : ''}${msg}`\n }\n\n /** Should a message at `rank` print under the current `LOG_LEVEL`? */\n private enabled(rank: number): boolean {\n return rank >= thresholdRank()\n }\n\n info(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.info) || this.json('info', msg, args)) return\n console.log(this.fmt('INFO', '\\x1b[32m', msg), ...args)\n }\n warn(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.warn) || this.json('warn', msg, args)) return\n console.warn(this.fmt('WARN', '\\x1b[33m', msg), ...args)\n }\n error(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.error) || this.json('error', msg, args)) return\n console.error(this.fmt('ERROR', '\\x1b[31m', msg), ...args)\n }\n debug(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.debug) || this.json('debug', msg, args)) return\n console.debug(this.fmt('DEBUG', '\\x1b[90m', msg), ...args)\n }\n trace(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.trace) || this.json('trace', msg, args)) return\n console.trace(this.fmt('TRACE', '\\x1b[90m', msg), ...args)\n }\n fatal(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.fatal) || this.json('fatal', msg, args)) return\n console.error(this.fmt('FATAL', '\\x1b[1m\\x1b[31m', msg), ...args)\n }\n child(bindings: { component: string; [field: string]: unknown }): LoggerProvider {\n const { component, ...fields } = bindings\n return new ConsoleLoggerProvider(component, { ...this.bindings, ...fields })\n }\n}\n\n// ── Active provider ────────────────────────────────────────────────────\n\nlet activeProvider: LoggerProvider = new ConsoleLoggerProvider()\n\n/** Cache of named loggers to avoid creating duplicates */\nconst loggerCache = new Map<string, Logger>()\n\n/**\n * Named logger with component context.\n *\n * @example\n * ```ts\n * // Static factory — preferred\n * const log = Logger.for('UserService')\n * log.info('User created')\n * // Output: [UserService] User created\n *\n * // Shorthand function\n * const log = createLogger('OrderService')\n *\n * // Pluggable backend — see docs/guide/logging.md\n * Logger.setProvider(new MyCustomProvider())\n *\n * // Injectable — auto-named from class\n * class MyService {\n * @Autowired() private logger!: Logger\n * // or inject a named one:\n * private log = Logger.for('MyService')\n * }\n * ```\n */\nexport class Logger {\n private _provider: LoggerProvider\n private _providerVersion: number\n private _name?: string\n private _fields?: Record<string, unknown>\n\n /** Incremented on every setProvider/resetProvider so instances know to refresh */\n private static _providerVersion = 0\n\n constructor(name?: string, fields?: Record<string, unknown>) {\n this._name = name\n this._fields = fields\n this._providerVersion = Logger._providerVersion\n this._provider = this.derive()\n }\n\n /** The active provider's child for this logger's name and fields. */\n private derive(): LoggerProvider {\n if (!this._name && !this._fields) return activeProvider\n return activeProvider.child({ ...this._fields, component: this._name ?? '' })\n }\n\n /** Re-derive the provider if setProvider() was called since construction/last access */\n private get provider(): LoggerProvider {\n if (this._providerVersion !== Logger._providerVersion) {\n this._providerVersion = Logger._providerVersion\n this._provider = this.derive()\n }\n return this._provider\n }\n\n /**\n * Replace the logging backend for **all** Logger instances created after\n * this call. Clears the logger cache so subsequent `Logger.for()` calls\n * pick up the new provider.\n *\n * @example\n * ```ts\n * Logger.setProvider(new MyWinstonProvider())\n * ```\n */\n static setProvider(provider: LoggerProvider): void {\n activeProvider = provider\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Return the currently active provider (useful for testing) */\n static getProvider(): LoggerProvider {\n return activeProvider\n }\n\n /**\n * Reset the provider back to the default `ConsoleLoggerProvider`.\n * Primarily intended for test teardown.\n */\n static resetProvider(): void {\n activeProvider = new ConsoleLoggerProvider()\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Create or retrieve a cached named logger */\n static for(name: string): Logger {\n let cached = loggerCache.get(name)\n if (!cached) {\n cached = new Logger(name)\n loggerCache.set(name, cached)\n }\n return cached\n }\n\n /** Create a child logger with a sub-component name */\n child(name: string): Logger\n /**\n * Create a child logger carrying `fields` on every line it writes — a\n * request id, a job name. Keeps this logger's name and fields. Written as\n * JSON fields under `LOG_FORMAT=json`; the default text output is unchanged.\n */\n child(fields: Record<string, unknown>): Logger\n child(nameOrFields: string | Record<string, unknown>): Logger {\n if (typeof nameOrFields === 'string') return new Logger(nameOrFields)\n return new Logger(this._name, { ...this._fields, ...nameOrFields })\n }\n\n info(msg: string, ...args: any[]) {\n this.provider.info(msg, ...args)\n }\n\n warn(msg: string, ...args: any[]) {\n this.provider.warn(msg, ...args)\n }\n\n /** Pino-style error-first form — `log.error(err, 'what failed')`. */\n error(err: unknown, msg: string, ...args: any[]): void\n /** Message-first form — `log.error('what failed', detail)`. */\n error(msg: string, ...args: any[]): void\n /** Error alone — `log.error(err)`. */\n error(err: unknown): void\n error(msgOrErr: any, ...rest: any[]): void {\n if (typeof msgOrErr === 'string') {\n // Message-first. `rest` used to be dropped on the floor, so\n // `log.error('save failed', { id })` logged only the string.\n this.provider.error(msgOrErr, ...rest)\n return\n }\n\n // Error-first (the framework's own idiom at ~16 call sites). The\n // error object used to be discarded entirely — `provider.error(msg)`\n // with the error nowhere in the call — so every `log.error(err, msg)`\n // in the codebase logged a bare sentence with NO stack, no error\n // name, and no `cause` chain. That is what made an unexpected 500\n // undiagnosable from the logs: you got the message and nothing else.\n //\n // The error is now forwarded as a trailing argument, which is what\n // the msg-first `LoggerProvider` contract can carry. `console.error`\n // renders the full stack from it; a pino/winston adapter receives it\n // as structured extra.\n const [maybeMsg, ...extra] = rest\n if (typeof maybeMsg === 'string') {\n this.provider.error(maybeMsg, msgOrErr, ...extra)\n } else {\n // No message supplied — use the error's own summary as the line so\n // the log stays readable, and still pass the object for the stack.\n this.provider.error(describeError(msgOrErr), msgOrErr, ...rest)\n }\n }\n\n debug(msg: string, ...args: any[]) {\n this.provider.debug(msg, ...args)\n }\n\n trace(msg: string, ...args: any[]) {\n if (this.provider.trace) this.provider.trace(msg, ...args)\n else this.provider.debug(msg, ...args)\n }\n\n fatal(msg: string, ...args: any[]) {\n if (this.provider.fatal) this.provider.fatal(msg, ...args)\n else this.provider.error(msg, ...args)\n }\n}\n\n/**\n * One-line summary of an unknown thrown value, including the error name\n * and — when present — the `cause` chain. ORM and driver errors routinely\n * wrap the useful detail in `cause`, so dropping it is how a 500 ends up\n * saying nothing actionable.\n *\n * Depth-capped and cycle-guarded: `cause` is attacker-influenced in some\n * stacks and self-referential chains do occur.\n */\nexport function describeError(err: unknown, maxDepth = 4): string {\n const parts: string[] = []\n const seen = new Set<unknown>()\n let current: unknown = err\n for (let depth = 0; current !== undefined && current !== null && depth < maxDepth; depth++) {\n if (seen.has(current)) {\n parts.push('[circular cause]')\n break\n }\n seen.add(current)\n if (current instanceof Error) {\n parts.push(current.name ? `${current.name}: ${current.message}` : current.message)\n current = (current as { cause?: unknown }).cause\n } else {\n parts.push(typeof current === 'string' ? current : safeStringify(current))\n break\n }\n }\n return parts.length > 0 ? parts.join(' ← caused by ') : 'Unknown error'\n}\n\n/** `JSON.stringify` that never throws on circular / exotic values. */\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/** Shorthand for Logger.for(name) */\nexport function createLogger(name: string): Logger {\n return Logger.for(name)\n}\n"],"mappings":";;;;;;;;;;AAiDA,MAAM,WAAqC,CACzC,MAAO,GACP,MAAO,GACP,KAAM,GACN,KAAM,GACN,MAAO,GACP,MAAO,GACP,OAAQ,GACV,EAOA,SAAS,eAAwB,CAM/B,IAAM,QACH,OAAO,QAAY,IAAc,QAAQ,KAAK,UAAY,IAAA,KAAc,OAAA,CACzE,YAAY,EACd,OAAO,WAAW,QAAU,WAAW,IACzC,CAGA,SAAS,YAAsB,CAC7B,OACG,OAAO,QAAY,IAAc,QAAQ,KAAK,WAAa,IAAA,GAAA,EAAY,YAAY,IAAM,MAE9F,CAGA,SAAS,cAAc,MAAkD,CACvE,GAAsB,OAAO,OAAU,WAAnC,MAA6C,M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K,kBAAkB,EAC7B,KACF,CAEA,GADA,KAAK,IAAI,OAAO,EACZ,mBAAmB,MACrB,MAAM,KAAK,QAAQ,KAAO,GAAG,QAAQ,KAAK,IAAI,QAAQ,UAAY,QAAQ,OAAO,EACjF,QAAW,QAAgC,UACtC,CACL,MAAM,KAAK,OAAO,SAAY,SAAW,QAAU,cAAc,OAAO,CAAC,EACzE,KACF,CACF,CACA,OAAO,MAAM,OAAS,EAAI,MAAM,KAAK,eAAe,EAAI,eAC1D,CAGA,SAAS,cAAc,MAAwB,CAC7C,GAAI,CACF,OAAO,KAAK,UAAU,KAAK,GAAK,OAAO,KAAK,CAC9C,MAAQ,CACN,OAAO,OAAO,KAAK,CACrB,CACF,CAGA,SAAgB,aAAa,KAAsB,CACjD,OAAO,OAAO,IAAI,IAAI,CACxB"}
1
+ {"version":3,"file":"logger.mjs","names":[],"sources":["../../src/core/logger.ts"],"sourcesContent":["// ── LoggerProvider interface ───────────────────────────────────────────\n\n/**\n * Pluggable logger backend.\n *\n * Implement this interface to plug in any logging library (pino,\n * winston, bunyan, console, etc.). The framework only ever calls the\n * methods declared here — it doesn't know or care which logger is\n * underneath.\n *\n * Default: `ConsoleLoggerProvider` (zero runtime deps).\n *\n * @example\n * ```ts\n * import pino from 'pino'\n * import { Logger, type LoggerProvider } from '@forinda/kickjs'\n *\n * class PinoProvider implements LoggerProvider {\n * constructor(private p = pino()) {}\n * info(msg, ...args) { this.p.info(msg, ...args) }\n * warn(msg, ...args) { this.p.warn(msg, ...args) }\n * error(msg, ...args) { this.p.error(msg, ...args) }\n * debug(msg, ...args) { this.p.debug(msg, ...args) }\n * child({ component }) { return new PinoProvider(this.p.child({ component })) }\n * }\n *\n * Logger.setProvider(new PinoProvider())\n * ```\n *\n * See `docs/guide/logging.md` for Pino, Winston, and silent-logger recipes.\n */\nexport interface LoggerProvider {\n info(msg: string, ...args: any[]): void\n warn(msg: string, ...args: any[]): void\n error(msg: string, ...args: any[]): void\n debug(msg: string, ...args: any[]): void\n trace?(msg: string, ...args: any[]): void\n fatal?(msg: string, ...args: any[]): void\n /**\n * Return a child provider scoped to the given component name. `bindings`\n * may also carry fields from `logger.child({ ... })` (a request id, a job\n * name) — a provider that ignores them keeps working as before.\n */\n child(bindings: { component: string; [field: string]: unknown }): LoggerProvider\n}\n\n// ── Log levels ─────────────────────────────────────────────────────────\n\n/** Severity ordering — a message prints only when its rank ≥ the threshold. */\nconst LEVEL_RANK: Record<string, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n silent: 100,\n}\n\n/**\n * Resolve the active threshold rank from `LOG_LEVEL` (default `info`).\n * Read per-call so a late `process.env.LOG_LEVEL` assignment still\n * takes effect. An unrecognised value falls back to `info`.\n */\nfunction thresholdRank(): number {\n // `process` is guarded because this module is reachable from the\n // edge-safe web pipeline (`@forinda/kickjs/web`), where strict runtimes\n // expose no `process` global at all. The colour probe below already\n // guarded; this one did not, so merely importing the logger could throw\n // on such a runtime.\n const level = (\n (typeof process !== 'undefined' ? process.env?.LOG_LEVEL : undefined) ?? 'info'\n ).toLowerCase()\n return LEVEL_RANK[level] ?? LEVEL_RANK.info\n}\n\n/** `LOG_FORMAT=json` switches the default provider to one JSON object per line. */\nfunction jsonFormat(): boolean {\n return (\n (typeof process !== 'undefined' ? process.env?.LOG_FORMAT : undefined)?.toLowerCase() === 'json'\n )\n}\n\n/** A plain `{ ... }` object — merged into a JSON line as fields. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * An error as a JSON field — `type`, `message`, `stack`, own enumerable\n * properties (a driver's `code`), and its `cause` chain, depth-capped and\n * cycle-guarded like {@link describeError}.\n */\nexport function serializeError(err: unknown, depth = 4, seen = new Set<unknown>()): unknown {\n if (!(err instanceof Error)) return err\n if (seen.has(err) || depth <= 0) return '[circular cause]'\n seen.add(err)\n const out: Record<string, unknown> = { type: err.name, message: err.message, stack: err.stack }\n for (const [key, value] of Object.entries(err)) if (!(key in out)) out[key] = value\n const cause = (err as { cause?: unknown }).cause\n if (cause !== undefined) out.cause = serializeError(cause, depth - 1, seen)\n return out\n}\n\n/**\n * Fill printf-style placeholders the way `console.log` does (`%s %d %i %f\n * %j %o %O`, `%%`), then append what's left — so `log.info('hi %s', name)`\n * reads the same in JSON as on a terminal.\n */\nfunction formatMessage(msg: string, args: unknown[]): string {\n let i = 0\n const filled = msg.replace(/%[sdifjoO%]/g, (token) => {\n if (token === '%%') return '%'\n if (i >= args.length) return token\n const value = args[i++]\n if (token === '%d' || token === '%i') return String(Math.trunc(Number(value)))\n if (token === '%f') return String(Number(value))\n if (token === '%s') return typeof value === 'string' ? value : safeStringify(value)\n return safeStringify(value)\n })\n const rest = args.slice(i).map((a) => (typeof a === 'string' ? a : safeStringify(a)))\n return rest.length ? `${filled} ${rest.join(' ')}` : filled\n}\n\n/** Keys of a JSON line only the logger writes — see {@link jsonLine}. */\nconst RESERVED_FIELDS = new Set(['level', 'time', 'component', 'msg', 'err'])\n\n/**\n * One JSON log line, field-compatible with pino (`level` 10–60, `time` in\n * epoch ms, `msg`) so `pino-pretty` and log shippers read it as-is. Trailing\n * plain objects become fields, an `Error` becomes `err`, and anything else\n * fills the message's placeholders or is appended to it.\n */\nexport function jsonLine(\n level: keyof typeof LEVEL_RANK,\n component: string,\n bindings: Record<string, unknown>,\n msg: string,\n args: unknown[],\n): string {\n // Null prototype: a `__proto__` key in logged data stays a plain field.\n const fields: Record<string, unknown> = Object.create(null)\n const rest: unknown[] = []\n let err: unknown\n for (const arg of args) {\n if (arg instanceof Error) err ??= serializeError(arg)\n else if (isPlainObject(arg)) Object.assign(fields, arg)\n else rest.push(arg)\n }\n const line: Record<string, unknown> = {\n level: LEVEL_RANK[level],\n time: Date.now(),\n ...(component ? { component } : {}),\n }\n // Logged data is often untrusted (a request body): it must not rewrite the\n // line's level, time, source or message, or pass a plain object off as the\n // error. Those come from the logger only; a field with one of those names is\n // dropped.\n for (const source of [bindings, fields]) {\n for (const key of Object.keys(source)) {\n if (!RESERVED_FIELDS.has(key)) line[key] = source[key]\n }\n }\n if (err !== undefined) line.err = err\n line.msg = formatMessage(msg, rest)\n try {\n return JSON.stringify(line, bigintSafe)\n } catch {\n // Something can't be written (a circular field). Drop only that: every\n // other field stays, and `err` — usually why the line exists — keeps at\n // least its type, message and stack.\n const safe: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(line)) {\n try {\n JSON.stringify(value, bigintSafe)\n safe[key] = value\n } catch {\n safe[key] =\n key === 'err' && value && typeof value === 'object'\n ? pick(value as Record<string, unknown>, ['type', 'message', 'stack'])\n : '[unserializable]'\n }\n }\n return JSON.stringify(safe, bigintSafe)\n }\n}\n\nconst bigintSafe = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value\n\nfunction pick(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const key of keys) if (typeof obj[key] === 'string') out[key] = obj[key]\n return out\n}\n\n// ── ConsoleLoggerProvider (default) ────────────────────────────────────\n\n/**\n * Default provider — emits through `console.*` methods. Zero deps.\n *\n * Respects the `LOG_LEVEL` env var (default `info`): messages below the\n * threshold are dropped, so the verbose startup detail (the route table,\n * DI wiring, HMR ticks — all `debug`) stays quiet by default and only\n * appears with `LOG_LEVEL=debug`. `error`/`fatal` always print unless\n * `LOG_LEVEL=silent`.\n *\n * `LOG_FORMAT=json` writes one pino-compatible JSON object per line instead\n * (all levels through `console.log`, so one stream carries them): fields\n * from `logger.child({ ... })` and from trailing plain-object arguments, and\n * an `Error` argument as `err` with its stack and `cause` chain. The default\n * text output is unchanged.\n *\n * Swap it for pino, winston, bunyan, or anything else by implementing\n * the `LoggerProvider` interface and calling `Logger.setProvider()`\n * before `bootstrap()`.\n */\nexport class ConsoleLoggerProvider implements LoggerProvider {\n private prefix: string\n private useColor: boolean\n /** Fields from `logger.child({ ... })` — written on JSON lines. */\n private bindings: Record<string, unknown>\n\n constructor(prefix?: string, bindings: Record<string, unknown> = {}) {\n this.prefix = prefix ?? ''\n this.bindings = bindings\n this.useColor =\n typeof process !== 'undefined' && process.stdout?.isTTY === true && !process.env.NO_COLOR\n }\n\n /** Write `msg` as a JSON line when `LOG_FORMAT=json`; returns whether it did. */\n private json(level: keyof typeof LEVEL_RANK, msg: string, args: unknown[]): boolean {\n if (!jsonFormat()) return false\n console.log(jsonLine(level, this.prefix, this.bindings, msg, args))\n return true\n }\n\n private fmt(level: string, color: string, msg: string): string {\n const tag = this.prefix ? `[${this.prefix}]` : ''\n if (this.useColor) {\n return `${color}${level}\\x1b[0m ${tag ? `\\x1b[36m${tag}\\x1b[0m ` : ''}${msg}`\n }\n return `${level} ${tag ? `${tag} ` : ''}${msg}`\n }\n\n /** Should a message at `rank` print under the current `LOG_LEVEL`? */\n private enabled(rank: number): boolean {\n return rank >= thresholdRank()\n }\n\n info(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.info) || this.json('info', msg, args)) return\n console.log(this.fmt('INFO', '\\x1b[32m', msg), ...args)\n }\n warn(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.warn) || this.json('warn', msg, args)) return\n console.warn(this.fmt('WARN', '\\x1b[33m', msg), ...args)\n }\n error(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.error) || this.json('error', msg, args)) return\n console.error(this.fmt('ERROR', '\\x1b[31m', msg), ...args)\n }\n debug(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.debug) || this.json('debug', msg, args)) return\n console.debug(this.fmt('DEBUG', '\\x1b[90m', msg), ...args)\n }\n trace(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.trace) || this.json('trace', msg, args)) return\n console.trace(this.fmt('TRACE', '\\x1b[90m', msg), ...args)\n }\n fatal(msg: string, ...args: any[]) {\n if (!this.enabled(LEVEL_RANK.fatal) || this.json('fatal', msg, args)) return\n console.error(this.fmt('FATAL', '\\x1b[1m\\x1b[31m', msg), ...args)\n }\n child(bindings: { component: string; [field: string]: unknown }): LoggerProvider {\n const { component, ...fields } = bindings\n return new ConsoleLoggerProvider(component, { ...this.bindings, ...fields })\n }\n}\n\n// ── Active provider ────────────────────────────────────────────────────\n\nlet activeProvider: LoggerProvider = new ConsoleLoggerProvider()\n\n/** Cache of named loggers to avoid creating duplicates */\nconst loggerCache = new Map<string, Logger>()\n\n/**\n * Named logger with component context.\n *\n * @example\n * ```ts\n * // Static factory — preferred\n * const log = Logger.for('UserService')\n * log.info('User created')\n * // Output: [UserService] User created\n *\n * // Shorthand function\n * const log = createLogger('OrderService')\n *\n * // Pluggable backend — see docs/guide/logging.md\n * Logger.setProvider(new MyCustomProvider())\n *\n * // Injectable — auto-named from class\n * class MyService {\n * @Autowired() private logger!: Logger\n * // or inject a named one:\n * private log = Logger.for('MyService')\n * }\n * ```\n */\nexport class Logger {\n private _provider: LoggerProvider\n private _providerVersion: number\n private _name?: string\n private _fields?: Record<string, unknown>\n\n /** Incremented on every setProvider/resetProvider so instances know to refresh */\n private static _providerVersion = 0\n\n constructor(name?: string, fields?: Record<string, unknown>) {\n this._name = name\n this._fields = fields\n this._providerVersion = Logger._providerVersion\n this._provider = this.derive()\n }\n\n /** The active provider's child for this logger's name and fields. */\n private derive(): LoggerProvider {\n if (!this._name && !this._fields) return activeProvider\n return activeProvider.child({ ...this._fields, component: this._name ?? '' })\n }\n\n /** Re-derive the provider if setProvider() was called since construction/last access */\n private get provider(): LoggerProvider {\n if (this._providerVersion !== Logger._providerVersion) {\n this._providerVersion = Logger._providerVersion\n this._provider = this.derive()\n }\n return this._provider\n }\n\n /**\n * Replace the logging backend for **all** Logger instances created after\n * this call. Clears the logger cache so subsequent `Logger.for()` calls\n * pick up the new provider.\n *\n * @example\n * ```ts\n * Logger.setProvider(new MyWinstonProvider())\n * ```\n */\n static setProvider(provider: LoggerProvider): void {\n activeProvider = provider\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Return the currently active provider (useful for testing) */\n static getProvider(): LoggerProvider {\n return activeProvider\n }\n\n /**\n * Reset the provider back to the default `ConsoleLoggerProvider`.\n * Primarily intended for test teardown.\n */\n static resetProvider(): void {\n activeProvider = new ConsoleLoggerProvider()\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Create or retrieve a cached named logger */\n static for(name: string): Logger {\n let cached = loggerCache.get(name)\n if (!cached) {\n cached = new Logger(name)\n loggerCache.set(name, cached)\n }\n return cached\n }\n\n /** Create a child logger with a sub-component name */\n child(name: string): Logger\n /**\n * Create a child logger carrying `fields` on every line it writes — a\n * request id, a job name. Keeps this logger's name and fields. Written as\n * JSON fields under `LOG_FORMAT=json`; the default text output is unchanged.\n */\n child(fields: Record<string, unknown>): Logger\n child(nameOrFields: string | Record<string, unknown>): Logger {\n if (typeof nameOrFields === 'string') return new Logger(nameOrFields)\n return new Logger(this._name, { ...this._fields, ...nameOrFields })\n }\n\n info(msg: string, ...args: any[]) {\n this.provider.info(msg, ...args)\n }\n\n warn(msg: string, ...args: any[]) {\n this.provider.warn(msg, ...args)\n }\n\n /** Pino-style error-first form — `log.error(err, 'what failed')`. */\n error(err: unknown, msg: string, ...args: any[]): void\n /** Message-first form — `log.error('what failed', detail)`. */\n error(msg: string, ...args: any[]): void\n /** Error alone — `log.error(err)`. */\n error(err: unknown): void\n error(msgOrErr: any, ...rest: any[]): void {\n if (typeof msgOrErr === 'string') {\n // Message-first. `rest` used to be dropped on the floor, so\n // `log.error('save failed', { id })` logged only the string.\n this.provider.error(msgOrErr, ...rest)\n return\n }\n\n // Error-first (the framework's own idiom at ~16 call sites). The\n // error object used to be discarded entirely — `provider.error(msg)`\n // with the error nowhere in the call — so every `log.error(err, msg)`\n // in the codebase logged a bare sentence with NO stack, no error\n // name, and no `cause` chain. That is what made an unexpected 500\n // undiagnosable from the logs: you got the message and nothing else.\n //\n // The error is now forwarded as a trailing argument, which is what\n // the msg-first `LoggerProvider` contract can carry. `console.error`\n // renders the full stack from it; a pino/winston adapter receives it\n // as structured extra.\n const [maybeMsg, ...extra] = rest\n if (typeof maybeMsg === 'string') {\n this.provider.error(maybeMsg, msgOrErr, ...extra)\n } else {\n // No message supplied — use the error's own summary as the line so\n // the log stays readable, and still pass the object for the stack.\n this.provider.error(describeError(msgOrErr), msgOrErr, ...rest)\n }\n }\n\n debug(msg: string, ...args: any[]) {\n this.provider.debug(msg, ...args)\n }\n\n trace(msg: string, ...args: any[]) {\n if (this.provider.trace) this.provider.trace(msg, ...args)\n else this.provider.debug(msg, ...args)\n }\n\n fatal(msg: string, ...args: any[]) {\n if (this.provider.fatal) this.provider.fatal(msg, ...args)\n else this.provider.error(msg, ...args)\n }\n}\n\n/**\n * One-line summary of an unknown thrown value, including the error name\n * and — when present — the `cause` chain. ORM and driver errors routinely\n * wrap the useful detail in `cause`, so dropping it is how a 500 ends up\n * saying nothing actionable.\n *\n * Depth-capped and cycle-guarded: `cause` is attacker-influenced in some\n * stacks and self-referential chains do occur.\n */\nexport function describeError(err: unknown, maxDepth = 4): string {\n const parts: string[] = []\n const seen = new Set<unknown>()\n let current: unknown = err\n for (let depth = 0; current !== undefined && current !== null && depth < maxDepth; depth++) {\n if (seen.has(current)) {\n parts.push('[circular cause]')\n break\n }\n seen.add(current)\n if (current instanceof Error) {\n parts.push(current.name ? `${current.name}: ${current.message}` : current.message)\n current = (current as { cause?: unknown }).cause\n } else {\n parts.push(typeof current === 'string' ? current : safeStringify(current))\n break\n }\n }\n return parts.length > 0 ? parts.join(' ← caused by ') : 'Unknown error'\n}\n\n/** `JSON.stringify` that never throws on circular / exotic values. */\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/** Shorthand for Logger.for(name) */\nexport function createLogger(name: string): Logger {\n return Logger.for(name)\n}\n"],"mappings":";;;;;;;;;;AAiDA,MAAM,WAAqC,CACzC,MAAO,GACP,MAAO,GACP,KA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I,CACvC,CAEA,MAAM,IAAa,GAAG,KAAa,CAC7B,KAAK,SAAS,MAAO,KAAK,SAAS,MAAM,IAAK,GAAG,IAAI,EACpD,KAAK,SAAS,MAAM,IAAK,GAAG,IAAI,CACvC,CACF,EAWA,SAAgB,cAAc,IAAc,SAAW,EAAW,CAChE,IAAM,MAAkB,CAAC,EACnB,qBAAO,IAAI,IACb,QAAmB,IACvB,IAAK,IAAI,MAAQ,EAAG,SAAqC,MAAQ,MAAQ,SAAU,QAAS,CAC1F,GAAI,KAAK,IAAI,OAAO,EAAG,CACrB,MAAM,KAAK,kBAAkB,EAC7B,KACF,CAEA,GADA,KAAK,IAAI,OAAO,EACZ,mBAAmB,MACrB,MAAM,KAAK,QAAQ,KAAO,GAAG,QAAQ,KAAK,IAAI,QAAQ,UAAY,QAAQ,OAAO,EACjF,QAAW,QAAgC,UACtC,CACL,MAAM,KAAK,OAAO,SAAY,SAAW,QAAU,cAAc,OAAO,CAAC,EACzE,KACF,CACF,CACA,OAAO,MAAM,OAAS,EAAI,MAAM,KAAK,eAAe,EAAI,eAC1D,CAGA,SAAS,cAAc,MAAwB,CAC7C,GAAI,CACF,OAAO,KAAK,UAAU,KAAK,GAAK,OAAO,KAAK,CAC9C,MAAQ,CACN,OAAO,OAAO,KAAK,CACrB,CACF,CAGA,SAAgB,aAAa,KAAsB,CACjD,OAAO,OAAO,IAAI,IAAI,CACxB,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as joinPaths, r as normalizePath, t as buildMountPath } from "../path-CMwIHsdv.mjs";
2
+ import { n as joinPaths, r as normalizePath, t as buildMountPath } from "../path-DsenzqJ7.mjs";
3
3
  export { buildMountPath, joinPaths, normalizePath };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.14.0
2
+ * @forinda/kickjs v10.14.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"path.mjs","names":[],"sources":["../../src/core/path.ts"],"sourcesContent":["/**\n * Normalize a URL path segment:\n * - '/' or '' or undefined → ''\n * - Ensures leading '/' if non-empty\n * - Strips trailing '/'\n * - Collapses consecutive '//' into single '/'\n */\nexport function normalizePath(path?: string): string {\n let p = path?.trim() || ''\n if (p === '/') return ''\n if (p && !p.startsWith('/')) p = `/${p}`\n // Strip trailing slash\n p = p.replace(/\\/+$/, '')\n // Collapse double slashes\n p = p.replace(/\\/\\/+/g, '/')\n return p\n}\n\n/**\n * Join path segments into a single normalized path.\n * Handles leading/trailing slashes and prevents double slashes.\n *\n * @example\n * joinPaths('/api/v1', '/users') // '/api/v1/users'\n * joinPaths('/api/v1/', '/users') // '/api/v1/users'\n * joinPaths('/api/v1', '/') // '/api/v1'\n * joinPaths('/api/v1', '') // '/api/v1'\n * joinPaths('/api/v1', 'users') // '/api/v1/users'\n */\nexport function joinPaths(...segments: (string | undefined)[]): string {\n const joined = segments\n .map((s) => s?.trim() || '')\n .filter(Boolean)\n .join('/')\n // Ensure leading slash, collapse doubles\n const normalized = ('/' + joined).replace(/\\/\\/+/g, '/')\n // Strip trailing slash (unless it's just '/')\n return normalized === '/' ? '/' : normalized.replace(/\\/+$/, '')\n}\n\n/**\n * Mount path for a module's routes: `{apiPrefix}/v{version}{path}`.\n *\n * `version: false` drops the `/v{n}` segment entirely — opting out of URL\n * versioning without giving up the prefix. Both mount sites (the node\n * `Application` and the web `createWebApp`) go through here so the two\n * cannot drift.\n */\nexport function buildMountPath(apiPrefix: string, version: number | false, path?: string): string {\n return joinPaths(apiPrefix, version === false ? undefined : `v${version}`, normalizePath(path))\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,cAAc,KAAuB,CACnD,IAAI,EAAI,MAAM,KAAK,GAAK,GAOxB,OANI,IAAM,IAAY,IAClB,GAAK,CAAC,EAAE,WAAW,GAAG,IAAG,EAAI,IAAI,KAErC,EAAI,EAAE,QAAQ,OAAQ,EAAE,EAExB,EAAI,EAAE,QAAQ,SAAU,GAAG,EACpB,EACT,CAaA,SAAgB,UAAU,GAAG,SAA0C,CAMrE,IAAM,YAAc,IALL,SACZ,IAAK,GAAM,GAAG,KAAK,GAAK,EAAE,CAAC,CAC3B,OAAO,OAAO,CAAC,CACf,KAAK,GAEuB,EAAA,CAAG,QAAQ,SAAU,GAAG,EAEvD,OAAO,aAAe,IAAM,IAAM,WAAW,QAAQ,OAAQ,EAAE,CACjE,CAUA,SAAgB,eAAe,UAAmB,QAAyB,KAAuB,CAChG,OAAO,UAAU,UAAW,UAAY,GAAQ,IAAA,GAAY,IAAI,UAAW,cAAc,IAAI,CAAC,CAChG"}
1
+ {"version":3,"file":"path.mjs","names":[],"sources":["../../src/core/path.ts"],"sourcesContent":["/**\n * Normalize a URL path segment:\n * - '/' or '' or undefined → ''\n * - Ensures leading '/' if non-empty\n * - Strips trailing '/'\n * - Collapses consecutive '//' into single '/'\n */\nexport function normalizePath(path?: string): string {\n let p = path?.trim() || ''\n if (p === '/') return ''\n if (p && !p.startsWith('/')) p = `/${p}`\n // Strip trailing slash\n p = p.replace(/\\/+$/, '')\n // Collapse double slashes\n p = p.replace(/\\/\\/+/g, '/')\n return p\n}\n\n/**\n * Join path segments into a single normalized path.\n * Handles leading/trailing slashes and prevents double slashes.\n *\n * @example\n * joinPaths('/api/v1', '/users') // '/api/v1/users'\n * joinPaths('/api/v1/', '/users') // '/api/v1/users'\n * joinPaths('/api/v1', '/') // '/api/v1'\n * joinPaths('/api/v1', '') // '/api/v1'\n * joinPaths('/api/v1', 'users') // '/api/v1/users'\n */\nexport function joinPaths(...segments: (string | undefined)[]): string {\n const joined = segments\n .map((s) => s?.trim() || '')\n .filter(Boolean)\n .join('/')\n // Ensure leading slash, collapse doubles\n const normalized = ('/' + joined).replace(/\\/\\/+/g, '/')\n // Strip trailing slash (unless it's just '/')\n return normalized === '/' ? '/' : normalized.replace(/\\/+$/, '')\n}\n\n/**\n * Mount path for a module's routes: `{apiPrefix}/v{version}{path}`.\n *\n * `version: false` drops the `/v{n}` segment entirely — opting out of URL\n * versioning without giving up the prefix. Both mount sites (the node\n * `Application` and the web `createWebApp`) go through here so the two\n * cannot drift.\n */\nexport function buildMountPath(apiPrefix: string, version: number | false, path?: string): string {\n return joinPaths(apiPrefix, version === false ? undefined : `v${version}`, normalizePath(path))\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,cAAc,KAAuB,CACnD,IAAI,EAAI,MAAM,KAAK,GAAK,GAOxB,OANI,IAAM,IAAY,IAClB,GAAK,CAAC,EAAE,WAAW,GAAG,IAAG,EAAI,IAAI,KAErC,EAAI,EAAE,QAAQ,OAAQ,EAAE,EAExB,EAAI,EAAE,QAAQ,SAAU,GAAG,EACpB,EACT,CAaA,SAAgB,UAAU,GAAG,SAA0C,CAMrE,IAAM,YAAc,IALL,SACZ,IAAK,GAAM,GAAG,KAAK,GAAK,EAAE,CAAC,CAC3B,OAAO,OAAO,CAAC,CACf,KAAK,GAEuB,EAAA,CAAG,QAAQ,SAAU,GAAG,EAEvD,OAAO,aAAe,IAAM,IAAM,WAAW,QAAQ,OAAQ,EAAE,CACjE,CAUA,SAAgB,eAAe,UAAmB,QAAyB,KAAuB,CAChG,OAAO,UAAU,UAAW,UAAY,GAAQ,IAAA,GAAY,IAAI,UAAW,cAAc,IAAI,CAAC,CAChG,C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { Pt as KickPlugin } from "../adapter-DL9JPcvC.mjs";
2
+ import { Pt as KickPlugin } from "../adapter-B64IOivZ.mjs";
3
3
  export { KickPlugin };