@forinda/kickjs 10.7.0 → 10.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/dist/{adapter-9sPr_5xt.d.mts → adapter-DLjn8q0c.d.mts} +14 -8
  2. package/dist/adapter-DLjn8q0c.d.mts.map +1 -0
  3. package/dist/{app-module-Cuu-Ma_E.d.mts → app-module-Bk3glnPP.d.mts} +3 -3
  4. package/dist/{app-module-Cuu-Ma_E.d.mts.map → app-module-Bk3glnPP.d.mts.map} +1 -1
  5. package/dist/application-2cqnmnMR.mjs +14 -0
  6. package/dist/application-2cqnmnMR.mjs.map +1 -0
  7. package/dist/{application-BZjDmsWb.d.mts → application-w0Xnc35j.d.mts} +54 -14
  8. package/dist/application-w0Xnc35j.d.mts.map +1 -0
  9. package/dist/{background-BJjLKrnK.mjs → background-X_AU4qmI.mjs} +3 -3
  10. package/dist/{background-BJjLKrnK.mjs.map → background-X_AU4qmI.mjs.map} +1 -1
  11. package/dist/{reply-BVdki3Z4.mjs → body-policy-BkjZt30w.mjs} +3 -3
  12. package/dist/body-policy-BkjZt30w.mjs.map +1 -0
  13. package/dist/{bootstrap-Dxax6Mcp.mjs → bootstrap-CF5TB3dt.mjs} +3 -3
  14. package/dist/{bootstrap-Dxax6Mcp.mjs.map → bootstrap-CF5TB3dt.mjs.map} +1 -1
  15. package/dist/{bounded-counters-_6sdDRhT.mjs → bounded-counters-BdHZ2tZ9.mjs} +2 -2
  16. package/dist/{bounded-counters-_6sdDRhT.mjs.map → bounded-counters-BdHZ2tZ9.mjs.map} +1 -1
  17. package/dist/{cache-C0qL0NSD.d.mts → cache-CdRHSXow.d.mts} +10 -7
  18. package/dist/cache-CdRHSXow.d.mts.map +1 -0
  19. package/dist/{client-ip-CrO5ktYs.mjs → client-ip-Db1WMxl6.mjs} +2 -2
  20. package/dist/{client-ip-CrO5ktYs.mjs.map → client-ip-Db1WMxl6.mjs.map} +1 -1
  21. package/dist/config/index.d.mts +1 -1
  22. package/dist/config/index.mjs +2 -2
  23. package/dist/{config-CWKj0Z66.mjs → config-DeWWBNz5.mjs} +3 -3
  24. package/dist/config-DeWWBNz5.mjs.map +1 -0
  25. package/dist/{context-BlJRkMyq.mjs → context-CfGBpRlD.mjs} +3 -3
  26. package/dist/{context-BlJRkMyq.mjs.map → context-CfGBpRlD.mjs.map} +1 -1
  27. package/dist/{context-errors-ykpXYECS.mjs → context-errors-QfmGMX4-.mjs} +2 -2
  28. package/dist/{context-errors-ykpXYECS.mjs.map → context-errors-QfmGMX4-.mjs.map} +1 -1
  29. package/dist/{contributor-runner-BM-5Wr19.mjs → contributor-runner-DmHsL9iD.mjs} +3 -3
  30. package/dist/{contributor-runner-BM-5Wr19.mjs.map → contributor-runner-DmHsL9iD.mjs.map} +1 -1
  31. package/dist/core/adapter.d.mts +1 -1
  32. package/dist/core/adapter.mjs +1 -1
  33. package/dist/core/app-module.d.mts +1 -1
  34. package/dist/core/app-module.mjs +1 -1
  35. package/dist/core/cache.d.mts +1 -1
  36. package/dist/core/cache.mjs +2 -2
  37. package/dist/core/cache.mjs.map +1 -1
  38. package/dist/core/container.mjs +2 -2
  39. package/dist/core/cron.mjs +2 -2
  40. package/dist/core/decorators.d.mts +1 -1
  41. package/dist/core/decorators.mjs +2 -2
  42. package/dist/core/decorators.mjs.map +1 -1
  43. package/dist/core/errors.mjs +1 -1
  44. package/dist/core/interfaces.mjs +1 -1
  45. package/dist/core/logger.mjs +1 -1
  46. package/dist/core/path.mjs +1 -1
  47. package/dist/core/plugin.d.mts +1 -1
  48. package/dist/core/plugin.mjs +1 -1
  49. package/dist/core/reactivity.d.mts +2 -2
  50. package/dist/core/reactivity.mjs +2 -2
  51. package/dist/core/reactivity.mjs.map +1 -1
  52. package/dist/core-DaYy5tKw.mjs +12 -0
  53. package/dist/{core-DlrlhjF4.mjs.map → core-DaYy5tKw.mjs.map} +1 -1
  54. package/dist/{csrf-ZFOrJZhJ.d.mts → csrf-w5bc-PGs.d.mts} +2 -2
  55. package/dist/{csrf-ZFOrJZhJ.d.mts.map → csrf-w5bc-PGs.d.mts.map} +1 -1
  56. package/dist/{decorate-BHhpOfEF.mjs → decorate-8MLQUvoW.mjs} +4 -4
  57. package/dist/{decorate-BHhpOfEF.mjs.map → decorate-8MLQUvoW.mjs.map} +1 -1
  58. package/dist/{decorators-Dvy0JZ5L.d.mts → decorators-DxNb5mWw.d.mts} +15 -2
  59. package/dist/{decorators-Dvy0JZ5L.d.mts.map → decorators-DxNb5mWw.d.mts.map} +1 -1
  60. package/dist/{define-adapter-CF-DJRq9.mjs → define-adapter-By20TI53.mjs} +2 -2
  61. package/dist/{define-adapter-CF-DJRq9.mjs.map → define-adapter-By20TI53.mjs.map} +1 -1
  62. package/dist/{di-hooks-CCKeiLT-.mjs → di-hooks-CGr13ce2.mjs} +7 -5
  63. package/dist/{di-hooks-CCKeiLT-.mjs.map → di-hooks-CGr13ce2.mjs.map} +1 -1
  64. package/dist/{disposables-bnkL4rG7.mjs → disposables-V3Xlgvgk.mjs} +1 -1
  65. package/dist/{error-handler-CH4PPZCK.d.mts → error-handler-BrihKETE.d.mts} +2 -2
  66. package/dist/{error-handler-CH4PPZCK.d.mts.map → error-handler-BrihKETE.d.mts.map} +1 -1
  67. package/dist/express-CZHu70JR.mjs +12 -0
  68. package/dist/express-CZHu70JR.mjs.map +1 -0
  69. package/dist/{express-lazy-D9MZnma8.mjs → express-lazy-BixrSsYx.mjs} +3 -3
  70. package/dist/{express-lazy-D9MZnma8.mjs.map → express-lazy-BixrSsYx.mjs.map} +1 -1
  71. package/dist/handler-DFZIsJH1.mjs +12 -0
  72. package/dist/handler-DFZIsJH1.mjs.map +1 -0
  73. package/dist/{host-CtpcIKcA.mjs → host-CJdqJGsr.mjs} +2 -2
  74. package/dist/{host-CtpcIKcA.mjs.map → host-CJdqJGsr.mjs.map} +1 -1
  75. package/dist/http/application.d.mts +1 -1
  76. package/dist/http/application.mjs +2 -2
  77. package/dist/http/bootstrap.d.mts +1 -1
  78. package/dist/http/bootstrap.mjs +2 -2
  79. package/dist/http/context.d.mts +2 -2
  80. package/dist/http/context.mjs +2 -2
  81. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  82. package/dist/http/middleware/breach-padding.mjs +1 -1
  83. package/dist/http/middleware/cors.mjs +1 -1
  84. package/dist/http/middleware/csrf.d.mts +1 -1
  85. package/dist/http/middleware/csrf.mjs +2 -2
  86. package/dist/http/middleware/error-handler.d.mts +1 -1
  87. package/dist/http/middleware/error-handler.mjs +2 -2
  88. package/dist/http/middleware/helmet.mjs +1 -1
  89. package/dist/http/middleware/rate-limit.mjs +2 -2
  90. package/dist/http/middleware/request-id.mjs +1 -1
  91. package/dist/http/middleware/request-logger.mjs +2 -2
  92. package/dist/http/middleware/session.mjs +2 -2
  93. package/dist/http/middleware/spa.d.mts +1 -1
  94. package/dist/http/middleware/spa.mjs +2 -2
  95. package/dist/http/middleware/upload.d.mts +2 -2
  96. package/dist/http/middleware/upload.mjs +2 -2
  97. package/dist/http/middleware/upload.mjs.map +1 -1
  98. package/dist/http/middleware/validate.mjs +1 -1
  99. package/dist/http/middleware/views.d.mts +1 -1
  100. package/dist/http/middleware/views.mjs +2 -2
  101. package/dist/http/query/index.mjs +2 -2
  102. package/dist/http/router-builder.d.mts +1 -1
  103. package/dist/http/router-builder.mjs +2 -2
  104. package/dist/http/runtimes/express.d.mts +2 -2
  105. package/dist/http/runtimes/express.d.mts.map +1 -1
  106. package/dist/http/runtimes/express.mjs +2 -2
  107. package/dist/http/runtimes/fastify.d.mts +4 -2
  108. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  109. package/dist/http/runtimes/fastify.mjs +3 -3
  110. package/dist/http/runtimes/fastify.mjs.map +1 -1
  111. package/dist/http/runtimes/h3-web.mjs +1 -1
  112. package/dist/http/runtimes/h3.d.mts +1 -1
  113. package/dist/http/runtimes/h3.mjs +2 -2
  114. package/dist/{index-B4aOLoId.d.mts → index-CNBYZDto.d.mts} +4 -4
  115. package/dist/{index-B4aOLoId.d.mts.map → index-CNBYZDto.d.mts.map} +1 -1
  116. package/dist/index.d.mts +15 -15
  117. package/dist/index.mjs +3 -3
  118. package/dist/index.mjs.map +1 -1
  119. package/dist/{is-production-BfIKY2Sw.mjs → is-production-CMJW948J.mjs} +2 -2
  120. package/dist/{is-production-BfIKY2Sw.mjs.map → is-production-CMJW948J.mjs.map} +1 -1
  121. package/dist/{jobs-BJfIOWUT.mjs → jobs-d2j_7_9R.mjs} +3 -3
  122. package/dist/{jobs-BJfIOWUT.mjs.map → jobs-d2j_7_9R.mjs.map} +1 -1
  123. package/dist/{kv-stores-C1sQs2Rb.d.mts → kv-stores-DJBnGQsJ.d.mts} +3 -3
  124. package/dist/{kv-stores-C1sQs2Rb.d.mts.map → kv-stores-DJBnGQsJ.d.mts.map} +1 -1
  125. package/dist/{kv-stores-BeDHfiyW.mjs → kv-stores-u0V_K-2O.mjs} +3 -3
  126. package/dist/{kv-stores-BeDHfiyW.mjs.map → kv-stores-u0V_K-2O.mjs.map} +1 -1
  127. package/dist/{lazy-serve-static-BUMcYDMn.mjs → lazy-serve-static-kB1m23xS.mjs} +3 -3
  128. package/dist/{lazy-serve-static-BUMcYDMn.mjs.map → lazy-serve-static-kB1m23xS.mjs.map} +1 -1
  129. package/dist/{metadata-x0eCJRTl.mjs → metadata-c1TNXrm_.mjs} +1 -1
  130. package/dist/{observers-Ss6-7Si7.mjs → observers-vX5EpqCX.mjs} +2 -2
  131. package/dist/{observers-Ss6-7Si7.mjs.map → observers-vX5EpqCX.mjs.map} +1 -1
  132. package/dist/{precompressed-BBXQUDXp.mjs → precompressed-DIkilvFq.mjs} +2 -2
  133. package/dist/{precompressed-BBXQUDXp.mjs.map → precompressed-DIkilvFq.mjs.map} +1 -1
  134. package/dist/{query-DIS_2QiJ.mjs → query-BIGYogvJ.mjs} +2 -2
  135. package/dist/{query-DIS_2QiJ.mjs.map → query-BIGYogvJ.mjs.map} +1 -1
  136. package/dist/{reactivity-BkMNA0kp.d.mts → reactivity-DZrc3Yhu.d.mts} +50 -15
  137. package/dist/reactivity-DZrc3Yhu.d.mts.map +1 -0
  138. package/dist/reply-CtSYYFK5.mjs +12 -0
  139. package/dist/reply-CtSYYFK5.mjs.map +1 -0
  140. package/dist/{request-scope-BTdpkAqv.mjs → request-scope-B1GH3d99.mjs} +3 -3
  141. package/dist/{request-scope-BTdpkAqv.mjs.map → request-scope-B1GH3d99.mjs.map} +1 -1
  142. package/dist/{respond-BUWP_L0Y.mjs → respond-D8cMACHW.mjs} +2 -2
  143. package/dist/{respond-BUWP_L0Y.mjs.map → respond-D8cMACHW.mjs.map} +1 -1
  144. package/dist/{rolldown-runtime-Dp0gGuQG.mjs → rolldown-runtime-CSRdE5Vk.mjs} +1 -1
  145. package/dist/{route-flag-p89Wzt0D.mjs → route-flag-Ce2FkkeT.mjs} +3 -3
  146. package/dist/{route-flag-p89Wzt0D.mjs.map → route-flag-Ce2FkkeT.mjs.map} +1 -1
  147. package/dist/{route-policy-DJMiiTrD.mjs → route-policy-BRcI3gmZ.mjs} +2 -2
  148. package/dist/{route-policy-DJMiiTrD.mjs.map → route-policy-BRcI3gmZ.mjs.map} +1 -1
  149. package/dist/{router-builder-dCWA4pdK.mjs → router-builder-BgxacQbc.mjs} +3 -3
  150. package/dist/router-builder-BgxacQbc.mjs.map +1 -0
  151. package/dist/{router-builder-BfbEdxew.d.mts → router-builder-CPJHwoL1.d.mts} +2 -2
  152. package/dist/{router-builder-BfbEdxew.d.mts.map → router-builder-CPJHwoL1.d.mts.map} +1 -1
  153. package/dist/{settings-BnE75hnr.d.mts → settings-BFQisfqG.d.mts} +2 -2
  154. package/dist/{settings-BnE75hnr.d.mts.map → settings-BFQisfqG.d.mts.map} +1 -1
  155. package/dist/{settings-BHYpcj_p.mjs → settings-hE0ewJKF.mjs} +3 -3
  156. package/dist/{settings-BHYpcj_p.mjs.map → settings-hE0ewJKF.mjs.map} +1 -1
  157. package/dist/token-0ZP--xsp.d.mts +3 -0
  158. package/dist/{token-Cz4YKuL-.mjs → token-DNQnEuMJ.mjs} +2 -2
  159. package/dist/{upload-Jgs9BFC4.d.mts → upload-DtQ1pdQw.d.mts} +3 -3
  160. package/dist/upload-DtQ1pdQw.d.mts.map +1 -0
  161. package/dist/upload-config-ikC1nZgF.mjs +12 -0
  162. package/dist/upload-config-ikC1nZgF.mjs.map +1 -0
  163. package/dist/{url-for-CDxa8ik-.mjs → url-for-Bh43Ax1C.mjs} +3 -3
  164. package/dist/{url-for-CDxa8ik-.mjs.map → url-for-Bh43Ax1C.mjs.map} +1 -1
  165. package/dist/{web-crypto-Bijc63tB.mjs → web-crypto-Dx8Nmh16.mjs} +2 -2
  166. package/dist/{web-crypto-Bijc63tB.mjs.map → web-crypto-Dx8Nmh16.mjs.map} +1 -1
  167. package/dist/web.d.mts +5 -5
  168. package/dist/web.d.mts.map +1 -1
  169. package/dist/web.mjs +2 -2
  170. package/dist/web.mjs.map +1 -1
  171. package/package.json +11 -11
  172. package/dist/adapter-9sPr_5xt.d.mts.map +0 -1
  173. package/dist/application-BSzwuTQ6.mjs +0 -14
  174. package/dist/application-BSzwuTQ6.mjs.map +0 -1
  175. package/dist/application-BZjDmsWb.d.mts.map +0 -1
  176. package/dist/cache-C0qL0NSD.d.mts.map +0 -1
  177. package/dist/config-CWKj0Z66.mjs.map +0 -1
  178. package/dist/core-DlrlhjF4.mjs +0 -12
  179. package/dist/express-4fvuMB5q.mjs +0 -12
  180. package/dist/express-4fvuMB5q.mjs.map +0 -1
  181. package/dist/handler-TzaD8jPN.mjs +0 -12
  182. package/dist/handler-TzaD8jPN.mjs.map +0 -1
  183. package/dist/reactivity-BkMNA0kp.d.mts.map +0 -1
  184. package/dist/reply-BVdki3Z4.mjs.map +0 -1
  185. package/dist/router-builder-dCWA4pdK.mjs.map +0 -1
  186. package/dist/token-D6jfTQLA.d.mts +0 -3
  187. package/dist/upload-Jgs9BFC4.d.mts.map +0 -1
  188. package/dist/upload-config-CkMQ5bW5.mjs +0 -12
  189. package/dist/upload-config-CkMQ5bW5.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"context-errors-ykpXYECS.mjs","names":[],"sources":["../src/core/context-errors.ts"],"sourcesContent":["/**\n * Errors thrown by the Context Contributor pipeline.\n *\n * `MissingContributorError`, `ContributorCycleError`, and\n * `DuplicateContributorError` are startup-time errors raised during\n * pipeline build (topo-sort + validation), not per-request — a\n * misconfigured app fails to boot rather than fails a request. Per the\n * locked design in `architecture.md` §20.4, the pipeline is validated\n * once when each route is mounted and the resolved order is cached on\n * the route.\n *\n * `MissingContextValueError` is the one request-time error here: it is\n * raised by `ctx.require(key)` when a value a handler declared it needs\n * is absent. See its doc comment for why that case can't be caught at\n * startup today.\n */\n\n/**\n * A contributor declared `dependsOn: ['<key>']` but no other contributor\n * (at any precedence level) produces that key for the same route.\n *\n * @example\n * ```text\n * MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id\n * declared at src/contributors/load-project.ts:42:18\n * ```\n */\nexport class MissingContributorError extends Error {\n readonly key: string\n readonly dependent: string\n readonly route?: string\n readonly dependentDefinedAt?: string\n\n constructor(key: string, dependent: string, route?: string, dependentDefinedAt?: string) {\n const where = route ? ` on route ${route}` : ''\n const declaredAt = formatDeclaredAt(dependentDefinedAt)\n super(`Missing context contributor '${key}' required by '${dependent}'${where}${declaredAt}`)\n this.name = 'MissingContributorError'\n this.key = key\n this.dependent = dependent\n this.route = route\n this.dependentDefinedAt = dependentDefinedAt\n }\n}\n\n/**\n * `ctx.require(key)` found no value under `key` in the per-request\n * metadata store.\n *\n * Thrown at request time, by design. `ctx.get(key)` returns\n * `T | undefined` for every key, so the usual workaround is a\n * non-null assertion — `ctx.get('tenant')!` — which compiles whether or\n * not the route actually carries the contributor that produces it. On\n * an authorization value that is the worst possible thing to leave\n * untypeable: dropping the decorator produces no diagnostic anywhere,\n * and the handler reads `undefined` as though it were a real value.\n *\n * `ctx.require()` converts that silent hole into a loud, named failure\n * that points at the missing contributor.\n *\n * A handler typed with a generated route type (`Ctx<KickRoutes…>`) also\n * gets compile-time narrowing, so a dropped decorator fails `tsc` rather\n * than reaching this error at all. This error remains the backstop for\n * routes typegen couldn't prove (module/adapter/bootstrap registrations),\n * handlers typed as plain `RequestContext`, and contributors that ran but\n * resolved to `undefined`. See `architecture.md` §20.14.\n *\n * @example\n * ```text\n * MissingContextValueError: No context value for 'tenantPerm' on GET /projects/:id\n * Nothing wrote this key before the handler ran. Either the contributor\n * that produces it isn't applied to this route, or it ran and resolved\n * to undefined (check `optional: true` contributors).\n * ```\n */\nexport class MissingContextValueError extends Error {\n readonly key: string\n readonly route?: string\n\n constructor(key: string, route?: string) {\n const where = route ? ` on ${route}` : ''\n super(\n `No context value for '${key}'${where}\\n` +\n ` Nothing wrote this key before the handler ran. Either the contributor\\n` +\n ` that produces it isn't applied to this route, or it ran and resolved\\n` +\n ` to undefined (check \\`optional: true\\` contributors).`,\n )\n this.name = 'MissingContextValueError'\n this.key = key\n this.route = route\n }\n}\n\n/**\n * Slice the first non-framework frame off a captured `Error.stack`\n * and format it as `\\n declared at <frame>` for inclusion in\n * boot-time error messages. Returns `''` when no useful frame is\n * available (hand-rolled registrations, missing stacks).\n */\nfunction formatDeclaredAt(stack: string | undefined): string {\n if (!stack) return ''\n const lines = stack.split('\\n')\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('at ')) continue\n // Skip frames inside this file or the decorator factory — the\n // adopter's call site is the next frame after those.\n if (trimmed.includes('context-decorator.')) continue\n if (trimmed.includes('context-errors.')) continue\n return `\\n declared at ${trimmed.replace(/^at /, '')}`\n }\n return ''\n}\n\n/**\n * Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field\n * lists the keys in the order they form the loop, with the first key\n * repeated at the end so the path reads naturally.\n *\n * @example\n * ```text\n * ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant\n * ```\n */\nexport class ContributorCycleError extends Error {\n readonly cycle: readonly string[]\n readonly route?: string\n\n constructor(cycle: readonly string[], route?: string) {\n const where = route ? ` on route ${route}` : ''\n super(`Cycle in context contributors${where}: ${cycle.join(' → ')}`)\n this.name = 'ContributorCycleError'\n this.cycle = Object.freeze([...cycle])\n this.route = route\n }\n}\n\n/**\n * Two contributors at the same precedence level both produce the same key\n * for the same route. Precedence resolution (method > class > module >\n * adapter > global, per architecture.md §20.4) silently drops\n * lower-precedence duplicates; this error fires only when ties occur\n * within a single level — e.g., two method-level decorators declaring\n * `key: 'tenant'`.\n *\n * `sources` is best-effort identifying labels for each conflicting\n * registration (typically the decorator's call site or registering\n * module/adapter name).\n *\n * @example\n * ```text\n * DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain\n * ```\n */\nexport class DuplicateContributorError extends Error {\n readonly key: string\n readonly sources: readonly string[]\n\n constructor(key: string, sources: readonly string[]) {\n super(\n `Duplicate context contributor for key '${key}' at the same precedence level. ` +\n `Sources: ${sources.join(', ')}`,\n )\n this.name = 'DuplicateContributorError'\n this.key = key\n this.sources = Object.freeze([...sources])\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,IAAa,wBAAb,cAA6C,KAAM,CACjD,IACA,UACA,MACA,mBAEA,YAAY,IAAa,UAAmB,MAAgB,mBAA6B,CACvF,IAAM,MAAQ,MAAQ,aAAa,QAAU,GACvC,WAAa,iBAAiB,kBAAkB,EACtD,MAAM,gCAAgC,IAAI,iBAAiB,UAAU,GAAG,QAAQ,YAAY,EAC5F,KAAK,KAAO,0BACZ,KAAK,IAAM,IACX,KAAK,UAAY,UACjB,KAAK,MAAQ,MACb,KAAK,mBAAqB,kBAC5B,CACF,EAgCa,yBAAb,cAA8C,KAAM,CAClD,IACA,MAEA,YAAY,IAAa,MAAgB,CACvC,IAAM,MAAQ,MAAQ,OAAO,QAAU,GACvC,MACE,yBAAyB,IAAI,GAAG,MAAM,iNAIxC,EACA,KAAK,KAAO,2BACZ,KAAK,IAAM,IACX,KAAK,MAAQ,KACf,CACF,EAQA,SAAS,iBAAiB,MAAmC,CAC3D,GAAI,CAAC,MAAO,MAAO,GACnB,IAAM,MAAQ,MAAM,MAAM;CAAI,EAC9B,IAAK,IAAM,QAAQ,MAAO,CACxB,IAAM,QAAU,KAAK,KAAK,EAC1B,GAAK,QAAQ,WAAW,KAAK,GAGzB,SAAQ,SAAS,oBAAoB,GACrC,SAAQ,SAAS,iBAAiB,EACtC,MAAO,qBAAqB,QAAQ,QAAQ,OAAQ,EAAE,GACxD,CACA,MAAO,EACT,CAYA,IAAa,sBAAb,cAA2C,KAAM,CAC/C,MACA,MAEA,YAAY,MAA0B,MAAgB,CACpD,IAAM,MAAQ,MAAQ,aAAa,QAAU,GAC7C,MAAM,gCAAgC,MAAM,IAAI,MAAM,KAAK,KAAK,GAAG,EACnE,KAAK,KAAO,wBACZ,KAAK,MAAQ,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC,EACrC,KAAK,MAAQ,KACf,CACF,EAmBa,0BAAb,cAA+C,KAAM,CACnD,IACA,QAEA,YAAY,IAAa,QAA4B,CACnD,MACE,0CAA0C,IAAI,2CAChC,QAAQ,KAAK,IAAI,GACjC,EACA,KAAK,KAAO,4BACZ,KAAK,IAAM,IACX,KAAK,QAAU,OAAO,OAAO,CAAC,GAAG,OAAO,CAAC,CAC3C,CACF"}
1
+ {"version":3,"file":"context-errors-QfmGMX4-.mjs","names":[],"sources":["../src/core/context-errors.ts"],"sourcesContent":["/**\n * Errors thrown by the Context Contributor pipeline.\n *\n * `MissingContributorError`, `ContributorCycleError`, and\n * `DuplicateContributorError` are startup-time errors raised during\n * pipeline build (topo-sort + validation), not per-request — a\n * misconfigured app fails to boot rather than fails a request. Per the\n * locked design in `architecture.md` §20.4, the pipeline is validated\n * once when each route is mounted and the resolved order is cached on\n * the route.\n *\n * `MissingContextValueError` is the one request-time error here: it is\n * raised by `ctx.require(key)` when a value a handler declared it needs\n * is absent. See its doc comment for why that case can't be caught at\n * startup today.\n */\n\n/**\n * A contributor declared `dependsOn: ['<key>']` but no other contributor\n * (at any precedence level) produces that key for the same route.\n *\n * @example\n * ```text\n * MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id\n * declared at src/contributors/load-project.ts:42:18\n * ```\n */\nexport class MissingContributorError extends Error {\n readonly key: string\n readonly dependent: string\n readonly route?: string\n readonly dependentDefinedAt?: string\n\n constructor(key: string, dependent: string, route?: string, dependentDefinedAt?: string) {\n const where = route ? ` on route ${route}` : ''\n const declaredAt = formatDeclaredAt(dependentDefinedAt)\n super(`Missing context contributor '${key}' required by '${dependent}'${where}${declaredAt}`)\n this.name = 'MissingContributorError'\n this.key = key\n this.dependent = dependent\n this.route = route\n this.dependentDefinedAt = dependentDefinedAt\n }\n}\n\n/**\n * `ctx.require(key)` found no value under `key` in the per-request\n * metadata store.\n *\n * Thrown at request time, by design. `ctx.get(key)` returns\n * `T | undefined` for every key, so the usual workaround is a\n * non-null assertion — `ctx.get('tenant')!` — which compiles whether or\n * not the route actually carries the contributor that produces it. On\n * an authorization value that is the worst possible thing to leave\n * untypeable: dropping the decorator produces no diagnostic anywhere,\n * and the handler reads `undefined` as though it were a real value.\n *\n * `ctx.require()` converts that silent hole into a loud, named failure\n * that points at the missing contributor.\n *\n * A handler typed with a generated route type (`Ctx<KickRoutes…>`) also\n * gets compile-time narrowing, so a dropped decorator fails `tsc` rather\n * than reaching this error at all. This error remains the backstop for\n * routes typegen couldn't prove (module/adapter/bootstrap registrations),\n * handlers typed as plain `RequestContext`, and contributors that ran but\n * resolved to `undefined`. See `architecture.md` §20.14.\n *\n * @example\n * ```text\n * MissingContextValueError: No context value for 'tenantPerm' on GET /projects/:id\n * Nothing wrote this key before the handler ran. Either the contributor\n * that produces it isn't applied to this route, or it ran and resolved\n * to undefined (check `optional: true` contributors).\n * ```\n */\nexport class MissingContextValueError extends Error {\n readonly key: string\n readonly route?: string\n\n constructor(key: string, route?: string) {\n const where = route ? ` on ${route}` : ''\n super(\n `No context value for '${key}'${where}\\n` +\n ` Nothing wrote this key before the handler ran. Either the contributor\\n` +\n ` that produces it isn't applied to this route, or it ran and resolved\\n` +\n ` to undefined (check \\`optional: true\\` contributors).`,\n )\n this.name = 'MissingContextValueError'\n this.key = key\n this.route = route\n }\n}\n\n/**\n * Slice the first non-framework frame off a captured `Error.stack`\n * and format it as `\\n declared at <frame>` for inclusion in\n * boot-time error messages. Returns `''` when no useful frame is\n * available (hand-rolled registrations, missing stacks).\n */\nfunction formatDeclaredAt(stack: string | undefined): string {\n if (!stack) return ''\n const lines = stack.split('\\n')\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('at ')) continue\n // Skip frames inside this file or the decorator factory — the\n // adopter's call site is the next frame after those.\n if (trimmed.includes('context-decorator.')) continue\n if (trimmed.includes('context-errors.')) continue\n return `\\n declared at ${trimmed.replace(/^at /, '')}`\n }\n return ''\n}\n\n/**\n * Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field\n * lists the keys in the order they form the loop, with the first key\n * repeated at the end so the path reads naturally.\n *\n * @example\n * ```text\n * ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant\n * ```\n */\nexport class ContributorCycleError extends Error {\n readonly cycle: readonly string[]\n readonly route?: string\n\n constructor(cycle: readonly string[], route?: string) {\n const where = route ? ` on route ${route}` : ''\n super(`Cycle in context contributors${where}: ${cycle.join(' → ')}`)\n this.name = 'ContributorCycleError'\n this.cycle = Object.freeze([...cycle])\n this.route = route\n }\n}\n\n/**\n * Two contributors at the same precedence level both produce the same key\n * for the same route. Precedence resolution (method > class > module >\n * adapter > global, per architecture.md §20.4) silently drops\n * lower-precedence duplicates; this error fires only when ties occur\n * within a single level — e.g., two method-level decorators declaring\n * `key: 'tenant'`.\n *\n * `sources` is best-effort identifying labels for each conflicting\n * registration (typically the decorator's call site or registering\n * module/adapter name).\n *\n * @example\n * ```text\n * DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain\n * ```\n */\nexport class DuplicateContributorError extends Error {\n readonly key: string\n readonly sources: readonly string[]\n\n constructor(key: string, sources: readonly string[]) {\n super(\n `Duplicate context contributor for key '${key}' at the same precedence level. ` +\n `Sources: ${sources.join(', ')}`,\n )\n this.name = 'DuplicateContributorError'\n this.key = key\n this.sources = Object.freeze([...sources])\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,IAAa,wBAAb,cAA6C,KAAM,CACjD,IACA,UACA,MACA,mBAEA,YAAY,IAAa,UAAmB,MAAgB,mBAA6B,CACvF,IAAM,MAAQ,MAAQ,aAAa,QAAU,GACvC,WAAa,iBAAiB,kBAAkB,EACtD,MAAM,gCAAgC,IAAI,iBAAiB,UAAU,GAAG,QAAQ,YAAY,EAC5F,KAAK,KAAO,0BACZ,KAAK,IAAM,IACX,KAAK,UAAY,UACjB,KAAK,MAAQ,MACb,KAAK,mBAAqB,kBAC5B,CACF,EAgCa,yBAAb,cAA8C,KAAM,CAClD,IACA,MAEA,YAAY,IAAa,MAAgB,CACvC,IAAM,MAAQ,MAAQ,OAAO,QAAU,GACvC,MACE,yBAAyB,IAAI,GAAG,MAAM,iNAIxC,EACA,KAAK,KAAO,2BACZ,KAAK,IAAM,IACX,KAAK,MAAQ,KACf,CACF,EAQA,SAAS,iBAAiB,MAAmC,CAC3D,GAAI,CAAC,MAAO,MAAO,GACnB,IAAM,MAAQ,MAAM,MAAM;CAAI,EAC9B,IAAK,IAAM,QAAQ,MAAO,CACxB,IAAM,QAAU,KAAK,KAAK,EAC1B,GAAK,QAAQ,WAAW,KAAK,GAGzB,SAAQ,SAAS,oBAAoB,GACrC,SAAQ,SAAS,iBAAiB,EACtC,MAAO,qBAAqB,QAAQ,QAAQ,OAAQ,EAAE,GACxD,CACA,MAAO,EACT,CAYA,IAAa,sBAAb,cAA2C,KAAM,CAC/C,MACA,MAEA,YAAY,MAA0B,MAAgB,CACpD,IAAM,MAAQ,MAAQ,aAAa,QAAU,GAC7C,MAAM,gCAAgC,MAAM,IAAI,MAAM,KAAK,KAAK,GAAG,EACnE,KAAK,KAAO,wBACZ,KAAK,MAAQ,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC,EACrC,KAAK,MAAQ,KACf,CACF,EAmBa,0BAAb,cAA+C,KAAM,CACnD,IACA,QAEA,YAAY,IAAa,QAA4B,CACnD,MACE,0CAA0C,IAAI,2CAChC,QAAQ,KAAK,IAAI,GACjC,EACA,KAAK,KAAO,4BACZ,KAAK,IAAM,IACX,KAAK,QAAU,OAAO,OAAO,CAAC,GAAG,OAAO,CAAC,CAC3C,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{s as matchesFlagTest}from"./route-flag-p89Wzt0D.mjs";function shouldRun(reg,ctx,flags){if(reg.skipWhen===void 0&&reg.onlyWhen===void 0)return!0;let resolved=flags??EMPTY_FLAGS,route=ctx.route;return!(reg.skipWhen!==void 0&&matchesFlagTest(reg.skipWhen,resolved,route)||reg.onlyWhen!==void 0&&!matchesFlagTest(reg.onlyWhen,resolved,route))}const EMPTY_FLAGS=/* @__PURE__ */ new Map;async function runContributors(options){let{pipeline,ctx,container,flags}=options;for(let reg of pipeline.contributors)shouldRun(reg,ctx,flags)&&await runOne(reg,ctx,container)}async function runOne(reg,ctx,container){let value;try{let deps=resolveDeps(reg,container);value=await reg.resolve(ctx,deps)}catch(err){if(reg.optional)return;if(reg.onError){let replacement=await reg.onError(err,ctx);if(replacement===void 0)return;ctx.set(reg.key,replacement);return}throw err}ctx.set(reg.key,value)}function resolveDeps(reg,container){let deps=depEntries.get(reg);deps||depEntries.set(reg,deps=Object.entries(reg.deps));let out={};for(let[key,token]of deps)out[key]=container.resolve(token);return out}const depEntries=/* @__PURE__ */ new WeakMap;export{runContributors as t};
12
- //# sourceMappingURL=contributor-runner-BM-5Wr19.mjs.map
11
+ import{s as matchesFlagTest}from"./route-flag-Ce2FkkeT.mjs";function shouldRun(reg,ctx,flags){if(reg.skipWhen===void 0&&reg.onlyWhen===void 0)return!0;let resolved=flags??EMPTY_FLAGS,route=ctx.route;return!(reg.skipWhen!==void 0&&matchesFlagTest(reg.skipWhen,resolved,route)||reg.onlyWhen!==void 0&&!matchesFlagTest(reg.onlyWhen,resolved,route))}const EMPTY_FLAGS=/* @__PURE__ */ new Map;async function runContributors(options){let{pipeline,ctx,container,flags}=options;for(let reg of pipeline.contributors)shouldRun(reg,ctx,flags)&&await runOne(reg,ctx,container)}async function runOne(reg,ctx,container){let value;try{let deps=resolveDeps(reg,container);value=await reg.resolve(ctx,deps)}catch(err){if(reg.optional)return;if(reg.onError){let replacement=await reg.onError(err,ctx);if(replacement===void 0)return;ctx.set(reg.key,replacement);return}throw err}ctx.set(reg.key,value)}function resolveDeps(reg,container){let deps=depEntries.get(reg);deps||depEntries.set(reg,deps=Object.entries(reg.deps));let out={};for(let[key,token]of deps)out[key]=container.resolve(token);return out}const depEntries=/* @__PURE__ */ new WeakMap;export{runContributors as t};
12
+ //# sourceMappingURL=contributor-runner-DmHsL9iD.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"contributor-runner-BM-5Wr19.mjs","names":[],"sources":["../src/core/contributor-runner.ts"],"sourcesContent":["import type { Container } from './container'\nimport type { ContributorRegistration } from './context-decorator'\nimport type { ExecutionContext } from './execution-context'\nimport type { ContributorPipeline } from './contributor-pipeline'\nimport { matchesFlagTest, type RouteFlags } from './route-flag'\nimport type { MatchedRoute } from '../http/runtime'\n\nexport interface RunContributorsOptions {\n /** Pre-built, validated, topo-sorted pipeline. */\n pipeline: ContributorPipeline\n /** The execution context contributors read from and write into. */\n ctx: ExecutionContext\n /** DI container used to resolve declared `deps`. */\n container: Container\n /**\n * Route flags in force for the matched route, used to honour a\n * registration's `skipWhen` / `onlyWhen`. Omitted outside a route (the\n * pipeline then runs every contributor, as before).\n */\n flags?: RouteFlags\n}\n\n/**\n * Should this contributor run on a route carrying `flags`?\n *\n * `skipWhen` is what makes exemption composable: today a contributor can only\n * be opted out of by registering a permissive twin under the same key, which\n * requires owning that key. A flag is declared on the route, so an adopter can\n * exempt a contributor shipped by a plugin without forking it.\n */\nfunction shouldRun(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n flags?: RouteFlags,\n): boolean {\n if (reg.skipWhen === undefined && reg.onlyWhen === undefined) return true\n const resolved = flags ?? EMPTY_FLAGS\n const route = (ctx as { route?: MatchedRoute }).route\n if (reg.skipWhen !== undefined && matchesFlagTest(reg.skipWhen, resolved, route)) return false\n if (reg.onlyWhen !== undefined && !matchesFlagTest(reg.onlyWhen, resolved, route)) return false\n return true\n}\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\n/**\n * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.\n *\n * Sequential — one contributor at a time, in the topo order chosen at\n * pipeline-build time. Per `architecture.md` §20.10, V1 does not run\n * contributors in parallel even within the same topo level; that is a\n * V2 follow-up gated on profiling.\n *\n * ## Error matrix (architecture.md §20.9)\n *\n * | resolve outcome | optional | onError defined | runner behaviour |\n * |-----------------|----------|-----------------|--------------------------------------------------|\n * | throws | true | — | skip; `ctx.get(key)` remains undefined |\n * | throws | false | yes | call hook; returned value (if any) stored |\n * | throws | false | no | propagate the original error |\n * | hook throws | — | yes | propagate the new error |\n * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |\n * | resolves | — | — | `ctx.set(key, value)` |\n *\n * Container.resolve() throwing while building `deps` is treated as a\n * resolve-side throw and flows through the same matrix — adopters who\n * need different behaviour for missing-DI vs. data-lookup failures can\n * wrap the container access inside their own `resolve()`.\n */\nexport async function runContributors(options: RunContributorsOptions): Promise<void> {\n const { pipeline, ctx, container, flags } = options\n\n for (const reg of pipeline.contributors) {\n if (!shouldRun(reg, ctx, flags)) continue\n await runOne(reg, ctx, container)\n }\n}\n\nasync function runOne(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n container: Container,\n): Promise<void> {\n let value: unknown\n try {\n const deps = resolveDeps(reg, container)\n value = await reg.resolve(ctx, deps)\n } catch (err) {\n if (reg.optional) return\n if (reg.onError) {\n // Hook throws are unconditionally propagated — there is no\n // second-chance hook. Returning undefined/void from the hook\n // means \"skip\"; returning a value means \"use this instead\".\n const replacement = await reg.onError(err, ctx)\n if (replacement === undefined) return\n ctx.set(reg.key, replacement as never)\n return\n }\n throw err\n }\n ctx.set(reg.key, value as never)\n}\n\n/**\n * Resolve a contributor's declared dependencies through the container,\n * preserving the property names from the spec so `resolve(ctx, deps)`\n * receives exactly the shape the user wrote.\n *\n * Empty `deps` produces an empty object — `resolve()` always sees an\n * object, never `undefined`.\n */\nfunction resolveDeps(reg: ContributorRegistration, container: Container): Record<string, unknown> {\n // The spec is fixed per registration; list its entries once, not per request.\n let deps = depEntries.get(reg)\n if (!deps) depEntries.set(reg, (deps = Object.entries(reg.deps)))\n const out: Record<string, unknown> = {}\n for (const [key, token] of deps) {\n out[key] = container.resolve(token as never)\n }\n return out\n}\n\nconst depEntries = new WeakMap<ContributorRegistration, Array<[string, unknown]>>()\n"],"mappings":";;;;;;;;;;4DA8BA,SAAS,UACP,IACA,IACA,MACS,CACT,GAAI,IAAI,WAAa,IAAA,IAAa,IAAI,WAAa,IAAA,GAAW,MAAO,GACrE,IAAM,SAAW,OAAS,YACpB,MAAS,IAAiC,MAGhD,MADA,EADI,IAAI,WAAa,IAAA,IAAa,gBAAgB,IAAI,SAAU,SAAU,KAAK,GAC3E,IAAI,WAAa,IAAA,IAAa,CAAC,gBAAgB,IAAI,SAAU,SAAU,KAAK,EAElF,CAEA,MAAM,4BAA0B,IAAI,IA0BpC,eAAsB,gBAAgB,QAAgD,CACpF,GAAM,CAAE,SAAU,IAAK,UAAW,OAAU,QAE5C,IAAK,IAAM,OAAO,SAAS,aACpB,UAAU,IAAK,IAAK,KAAK,GAC9B,MAAM,OAAO,IAAK,IAAK,SAAS,CAEpC,CAEA,eAAe,OACb,IACA,IACA,UACe,CACf,IAAI,MACJ,GAAI,CACF,IAAM,KAAO,YAAY,IAAK,SAAS,EACvC,MAAQ,MAAM,IAAI,QAAQ,IAAK,IAAI,CACrC,OAAS,IAAK,CACZ,GAAI,IAAI,SAAU,OAClB,GAAI,IAAI,QAAS,CAIf,IAAM,YAAc,MAAM,IAAI,QAAQ,IAAK,GAAG,EAC9C,GAAI,cAAgB,IAAA,GAAW,OAC/B,IAAI,IAAI,IAAI,IAAK,WAAoB,EACrC,MACF,CACA,MAAM,GACR,CACA,IAAI,IAAI,IAAI,IAAK,KAAc,CACjC,CAUA,SAAS,YAAY,IAA8B,UAA+C,CAEhG,IAAI,KAAO,WAAW,IAAI,GAAG,EACxB,MAAM,WAAW,IAAI,IAAM,KAAO,OAAO,QAAQ,IAAI,IAAI,CAAE,EAChE,IAAM,IAA+B,CAAC,EACtC,IAAK,GAAM,CAAC,IAAK,SAAU,KACzB,IAAI,KAAO,UAAU,QAAQ,KAAc,EAE7C,OAAO,GACT,CAEA,MAAM,2BAAa,IAAI"}
1
+ {"version":3,"file":"contributor-runner-DmHsL9iD.mjs","names":[],"sources":["../src/core/contributor-runner.ts"],"sourcesContent":["import type { Container } from './container'\nimport type { ContributorRegistration } from './context-decorator'\nimport type { ExecutionContext } from './execution-context'\nimport type { ContributorPipeline } from './contributor-pipeline'\nimport { matchesFlagTest, type RouteFlags } from './route-flag'\nimport type { MatchedRoute } from '../http/runtime'\n\nexport interface RunContributorsOptions {\n /** Pre-built, validated, topo-sorted pipeline. */\n pipeline: ContributorPipeline\n /** The execution context contributors read from and write into. */\n ctx: ExecutionContext\n /** DI container used to resolve declared `deps`. */\n container: Container\n /**\n * Route flags in force for the matched route, used to honour a\n * registration's `skipWhen` / `onlyWhen`. Omitted outside a route (the\n * pipeline then runs every contributor, as before).\n */\n flags?: RouteFlags\n}\n\n/**\n * Should this contributor run on a route carrying `flags`?\n *\n * `skipWhen` is what makes exemption composable: today a contributor can only\n * be opted out of by registering a permissive twin under the same key, which\n * requires owning that key. A flag is declared on the route, so an adopter can\n * exempt a contributor shipped by a plugin without forking it.\n */\nfunction shouldRun(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n flags?: RouteFlags,\n): boolean {\n if (reg.skipWhen === undefined && reg.onlyWhen === undefined) return true\n const resolved = flags ?? EMPTY_FLAGS\n const route = (ctx as { route?: MatchedRoute }).route\n if (reg.skipWhen !== undefined && matchesFlagTest(reg.skipWhen, resolved, route)) return false\n if (reg.onlyWhen !== undefined && !matchesFlagTest(reg.onlyWhen, resolved, route)) return false\n return true\n}\n\nconst EMPTY_FLAGS: RouteFlags = new Map() as RouteFlags\n\n/**\n * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.\n *\n * Sequential — one contributor at a time, in the topo order chosen at\n * pipeline-build time. Per `architecture.md` §20.10, V1 does not run\n * contributors in parallel even within the same topo level; that is a\n * V2 follow-up gated on profiling.\n *\n * ## Error matrix (architecture.md §20.9)\n *\n * | resolve outcome | optional | onError defined | runner behaviour |\n * |-----------------|----------|-----------------|--------------------------------------------------|\n * | throws | true | — | skip; `ctx.get(key)` remains undefined |\n * | throws | false | yes | call hook; returned value (if any) stored |\n * | throws | false | no | propagate the original error |\n * | hook throws | — | yes | propagate the new error |\n * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |\n * | resolves | — | — | `ctx.set(key, value)` |\n *\n * Container.resolve() throwing while building `deps` is treated as a\n * resolve-side throw and flows through the same matrix — adopters who\n * need different behaviour for missing-DI vs. data-lookup failures can\n * wrap the container access inside their own `resolve()`.\n */\nexport async function runContributors(options: RunContributorsOptions): Promise<void> {\n const { pipeline, ctx, container, flags } = options\n\n for (const reg of pipeline.contributors) {\n if (!shouldRun(reg, ctx, flags)) continue\n await runOne(reg, ctx, container)\n }\n}\n\nasync function runOne(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n container: Container,\n): Promise<void> {\n let value: unknown\n try {\n const deps = resolveDeps(reg, container)\n value = await reg.resolve(ctx, deps)\n } catch (err) {\n if (reg.optional) return\n if (reg.onError) {\n // Hook throws are unconditionally propagated — there is no\n // second-chance hook. Returning undefined/void from the hook\n // means \"skip\"; returning a value means \"use this instead\".\n const replacement = await reg.onError(err, ctx)\n if (replacement === undefined) return\n ctx.set(reg.key, replacement as never)\n return\n }\n throw err\n }\n ctx.set(reg.key, value as never)\n}\n\n/**\n * Resolve a contributor's declared dependencies through the container,\n * preserving the property names from the spec so `resolve(ctx, deps)`\n * receives exactly the shape the user wrote.\n *\n * Empty `deps` produces an empty object — `resolve()` always sees an\n * object, never `undefined`.\n */\nfunction resolveDeps(reg: ContributorRegistration, container: Container): Record<string, unknown> {\n // The spec is fixed per registration; list its entries once, not per request.\n let deps = depEntries.get(reg)\n if (!deps) depEntries.set(reg, (deps = Object.entries(reg.deps)))\n const out: Record<string, unknown> = {}\n for (const [key, token] of deps) {\n out[key] = container.resolve(token as never)\n }\n return out\n}\n\nconst depEntries = new WeakMap<ContributorRegistration, Array<[string, unknown]>>()\n"],"mappings":";;;;;;;;;;4DA8BA,SAAS,UACP,IACA,IACA,MACS,CACT,GAAI,IAAI,WAAa,IAAA,IAAa,IAAI,WAAa,IAAA,GAAW,MAAO,GACrE,IAAM,SAAW,OAAS,YACpB,MAAS,IAAiC,MAGhD,MADA,EADI,IAAI,WAAa,IAAA,IAAa,gBAAgB,IAAI,SAAU,SAAU,KAAK,GAC3E,IAAI,WAAa,IAAA,IAAa,CAAC,gBAAgB,IAAI,SAAU,SAAU,KAAK,EAElF,CAEA,MAAM,4BAA0B,IAAI,IA0BpC,eAAsB,gBAAgB,QAAgD,CACpF,GAAM,CAAE,SAAU,IAAK,UAAW,OAAU,QAE5C,IAAK,IAAM,OAAO,SAAS,aACpB,UAAU,IAAK,IAAK,KAAK,GAC9B,MAAM,OAAO,IAAK,IAAK,SAAS,CAEpC,CAEA,eAAe,OACb,IACA,IACA,UACe,CACf,IAAI,MACJ,GAAI,CACF,IAAM,KAAO,YAAY,IAAK,SAAS,EACvC,MAAQ,MAAM,IAAI,QAAQ,IAAK,IAAI,CACrC,OAAS,IAAK,CACZ,GAAI,IAAI,SAAU,OAClB,GAAI,IAAI,QAAS,CAIf,IAAM,YAAc,MAAM,IAAI,QAAQ,IAAK,GAAG,EAC9C,GAAI,cAAgB,IAAA,GAAW,OAC/B,IAAI,IAAI,IAAI,IAAK,WAAoB,EACrC,MACF,CACA,MAAM,GACR,CACA,IAAI,IAAI,IAAI,IAAK,KAAc,CACjC,CAUA,SAAS,YAAY,IAA8B,UAA+C,CAEhG,IAAI,KAAO,WAAW,IAAI,GAAG,EACxB,MAAM,WAAW,IAAI,IAAM,KAAO,OAAO,QAAQ,IAAI,IAAI,CAAE,EAChE,IAAM,IAA+B,CAAC,EACtC,IAAK,GAAM,CAAC,IAAK,SAAU,KACzB,IAAI,KAAO,UAAU,QAAQ,KAAc,EAE7C,OAAO,GACT,CAEA,MAAM,2BAAa,IAAI"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as KickServer, i as AppAdapterClass, n as AdapterMiddleware, o as MiddlewarePath, r as AppAdapter, s as MiddlewarePhase, t as AdapterContext } from "../adapter-9sPr_5xt.mjs";
2
+ import { a as KickServer, i as AppAdapterClass, n as AdapterMiddleware, o as MiddlewarePath, r as AppAdapter, s as MiddlewarePhase, t as AdapterContext } from "../adapter-DLjn8q0c.mjs";
3
3
  export { AdapterContext, AdapterMiddleware, AppAdapter, AppAdapterClass, KickServer, MiddlewarePath, MiddlewarePhase };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as ModuleRoutes, i as AppModuleFactoryEntry, n as AppModuleClass, r as AppModuleEntry, t as AppModule } from "../app-module-Cuu-Ma_E.mjs";
2
+ import { a as ModuleRoutes, i as AppModuleFactoryEntry, n as AppModuleClass, r as AppModuleEntry, t as AppModule } from "../app-module-Bk3glnPP.mjs";
3
3
  export { AppModule, AppModuleClass, AppModuleEntry, AppModuleFactoryEntry, ModuleRoutes };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider, t as CACHEABLE_META } from "../cache-C0qL0NSD.mjs";
2
+ import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider, t as CACHEABLE_META } from "../cache-CdRHSXow.mjs";
3
3
  export { CACHEABLE_META, CacheEvict, CacheOptions, CacheProvider, Cacheable, MemoryCacheProvider, getCacheProvider, setCacheProvider };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import"reflect-metadata";const CACHEABLE_META=`kick/cacheable`;var MemoryCacheProvider=class{maxEntries;store=/* @__PURE__ */ new Map;constructor(maxEntries=1e4){this.maxEntries=maxEntries}async get(key){let entry=this.store.get(key);return entry?entry.expiresAt<=Date.now()?(this.store.delete(key),null):(this.store.delete(key),this.store.set(key,entry),entry.data):null}async set(key,value,ttlMs){if(!this.store.has(key)&&this.store.size>=this.maxEntries){let oldest=this.store.keys().next().value;oldest!==void 0&&this.store.delete(oldest)}this.store.delete(key),this.store.set(key,{data:value,expiresAt:Date.now()+ttlMs})}async del(key){this.store.delete(key)}async delByPrefix(prefix){for(let key of this.store.keys())key.startsWith(prefix)&&this.store.delete(key)}async shutdown(){this.store.clear()}};let _cacheProvider=new MemoryCacheProvider;function setCacheProvider(provider){_cacheProvider=provider}function getCacheProvider(){return _cacheProvider}const CACHED_NULL={__kickjs_cached_null__:!0};function isCachedNull(value){return typeof value==`object`&&!!value&&value.__kickjs_cached_null__===!0&&Object.keys(value).length===1}const inFlight=/* @__PURE__ */ new Map;function Cacheable(ttl,options){return(target,propertyKey,descriptor)=>{let original=descriptor.value,cacheTtl=(ttl??60)*1e3,owner=typeof target==`function`?target.name:target.constructor?.name,keyPrefix=options?.key??`${String(propertyKey)}:${owner??`anonymous`}`;return descriptor.value=async function(...args){let cacheKey=`${keyPrefix}:${JSON.stringify(args)}`,provider=getCacheProvider(),cached=await provider.get(cacheKey);if(cached!==null)return isCachedNull(cached)?null:cached;let pending=inFlight.get(cacheKey);if(pending)return pending;let load=(async()=>{let result=await original.apply(this,args);return result===null?await provider.set(cacheKey,CACHED_NULL,cacheTtl):result!==void 0&&await provider.set(cacheKey,result,cacheTtl),result})();inFlight.set(cacheKey,load);try{return await load}finally{inFlight.delete(cacheKey)}},descriptor}}function CacheEvict(key){return(_target,_propertyKey,descriptor)=>{let original=descriptor.value;return descriptor.value=async function(...args){let result=await original.apply(this,args),provider=getCacheProvider();return provider.delByPrefix&&await provider.delByPrefix(key),result},descriptor}}export{CACHEABLE_META,CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider};
11
+ import{createLogger}from"./logger.mjs";import"reflect-metadata";const CACHEABLE_META=`kick/cacheable`;var MemoryCacheProvider=class{maxEntries;store=/* @__PURE__ */ new Map;constructor(maxEntries=1e4){this.maxEntries=maxEntries}async get(key){let entry=this.store.get(key);return entry?entry.expiresAt<=Date.now()?(this.store.delete(key),null):(this.store.delete(key),this.store.set(key,entry),entry.data):null}async set(key,value,ttlMs){if(!this.store.has(key)&&this.store.size>=this.maxEntries){let oldest=this.store.keys().next().value;oldest!==void 0&&this.store.delete(oldest)}this.store.delete(key),this.store.set(key,{data:value,expiresAt:Date.now()+ttlMs})}async del(key){this.store.delete(key)}async delByPrefix(prefix){for(let key of this.store.keys())key.startsWith(prefix)&&this.store.delete(key)}async shutdown(){this.store.clear()}};let _cacheProvider=new MemoryCacheProvider;function setCacheProvider(provider){_cacheProvider=provider}function getCacheProvider(){return _cacheProvider}const CACHED_NULL={__kickjs_cached_null__:!0};function isCachedNull(value){return typeof value==`object`&&!!value&&value.__kickjs_cached_null__===!0&&Object.keys(value).length===1}const inFlight=/* @__PURE__ */ new Map;function Cacheable(ttl,options){return(target,propertyKey,descriptor)=>{let original=descriptor.value,cacheTtl=(ttl??60)*1e3,owner=typeof target==`function`?target.name:target.constructor?.name,keyOf=typeof options?.key==`function`?options.key:void 0,keyPrefix=typeof options?.key==`string`?options.key:`${String(propertyKey)}:${owner??`anonymous`}`;return descriptor.value=async function(...args){if(cacheTtl<=0)return original.apply(this,args);let cacheKey=keyOf?keyOf(...args):`${keyPrefix}:${JSON.stringify(args)}`,provider=getCacheProvider(),cached=await provider.get(cacheKey);if(cached!==null)return isCachedNull(cached)?null:cached;let pending=inFlight.get(cacheKey);if(pending)return pending;let load=(async()=>{let result=await original.apply(this,args);return result===null?await provider.set(cacheKey,CACHED_NULL,cacheTtl):result!==void 0&&await provider.set(cacheKey,result,cacheTtl),result})();inFlight.set(cacheKey,load);try{return await load}finally{inFlight.delete(cacheKey)}},descriptor}}const log=createLogger(`Cache`);let warnedNoDelByPrefix=!1;function CacheEvict(key){return(_target,_propertyKey,descriptor)=>{let original=descriptor.value;return descriptor.value=async function(...args){let result=await original.apply(this,args),provider=getCacheProvider();return provider.delByPrefix?await provider.delByPrefix(typeof key==`function`?key(...args):key):warnedNoDelByPrefix||(warnedNoDelByPrefix=!0,log.warn(`@CacheEvict: the cache provider has no delByPrefix(), so nothing is evicted`)),result},descriptor}}export{CACHEABLE_META,CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider};
12
12
  //# sourceMappingURL=cache.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache.mjs","names":[],"sources":["../../src/core/cache.ts"],"sourcesContent":["import 'reflect-metadata'\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 * const keys = await this.client.keys(prefix + '*')\n * if (keys.length) await this.client.del(...keys)\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: ClassName.methodName) */\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)\n * @param options.key - Custom cache key prefix\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(ttl?: number, options?: { key?: string }): 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 keyPrefix = options?.key ?? `${String(propertyKey)}:${owner ?? 'anonymous'}`\n\n descriptor.value = async function (...args: any[]) {\n const cacheKey = `${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\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)\n */\nexport function CacheEvict(key: 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(key)\n }\n return result\n }\n\n return descriptor\n }\n}\n\nexport { CACHEABLE_META }\n"],"mappings":";;;;;;;;;;yBAIA,MAAM,eAAiB,iBAqDvB,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,OAA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IAAM,OAAS,MAAM,SAAS,MAAM,KAAM,IAAI,EAK9C,OAFI,SAAW,KAAM,MAAM,SAAS,IAAI,SAAU,YAAa,QAAQ,EAC9D,SAAW,IAAA,IAAW,MAAM,SAAS,IAAI,SAAU,OAAQ,QAAQ,EACrE,MACT,EAAA,CAAG,EACH,SAAS,IAAI,SAAU,IAAI,EAC3B,GAAI,CACF,OAAO,MAAM,IACf,QAAU,CAER,SAAS,OAAO,QAAQ,CAC1B,CACF,EAEO,UACT,CACF,CAUA,SAAgB,WAAW,IAA8B,CACvD,OAAQ,QAAS,aAAc,aAAmC,CAChE,IAAM,SAAW,WAAW,MAW5B,MATA,YAAW,MAAQ,eAAgB,GAAG,KAAa,CACjD,IAAM,OAAS,MAAM,SAAS,MAAM,KAAM,IAAI,EACxC,SAAW,iBAAiB,EAIlC,OAHI,SAAS,aACX,MAAM,SAAS,YAAY,GAAG,EAEzB,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":";;;;;;;;;;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,CACp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xB,IAAM,OAAS,MAAM,SAAS,MAAM,KAAM,IAAI,EAK9C,OAFI,SAAW,KAAM,MAAM,SAAS,IAAI,SAAU,YAAa,QAAQ,EAC9D,SAAW,IAAA,IAAW,MAAM,SAAS,IAAI,SAAU,OAAQ,QAAQ,EACrE,MACT,EAAA,CAAG,EACH,SAAS,IAAI,SAAU,IAAI,EAC3B,GAAI,CACF,OAAO,MAAM,IACf,QAAU,CAER,SAAS,OAAO,QAAQ,CAC1B,CACF,EAEO,UACT,CACF,CAEA,MAAM,IAAM,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"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import"../di-hooks-CCKeiLT-.mjs";export{Container,tokenName}from"@forinda/kickjs-di";
11
+ import"../di-hooks-CGr13ce2.mjs";export{Container,tokenName}from"@forinda/kickjs-di";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"./logger.mjs";import{c as pushClassMeta,t as getClassMeta}from"../metadata-x0eCJRTl.mjs";import{r as reportError}from"../observers-Ss6-7Si7.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{createLogger}from"./logger.mjs";import{c as pushClassMeta,t as getClassMeta}from"../metadata-c1TNXrm_.mjs";import{r as reportError}from"../observers-vX5EpqCX.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,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-Dvy0JZ5L.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-DxNb5mWw.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.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import"../di-hooks-CCKeiLT-.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-x0eCJRTl.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-CGr13ce2.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-c1TNXrm_.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\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":";;;;;;;;;;2YAwCA,SAAgB,YAA6B,CAC3C,MAAQ,SAAgB,CACtB,aAAa,SAAS,WAAY,aAAc,MAAM,EACtD,oBAAoB,OAAQ,MAAM,SAAS,CAC7C,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,CAoCA,SAAgB,WAAW,OAA2C,CACpE,OAAQ,OAAQ,cAAgB,CAC9B,cAAc,SAAS,YAAa,OAAQ,OAAO,YAAa,WAAqB,CACvF,CACF"}
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,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"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { Ot as KickPlugin } from "../adapter-9sPr_5xt.mjs";
2
+ import { Ot as KickPlugin } from "../adapter-DLjn8q0c.mjs";
3
3
  export { KickPlugin };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as isRef, c as toRefs, i as computed, l as unref, n as Ref, o as reactive, r as WatchOptions, s as ref, t as ComputedRef, u as watch } from "../reactivity-BkMNA0kp.mjs";
3
- export { ComputedRef, Ref, WatchOptions, computed, isRef, reactive, ref, toRefs, unref, watch };
2
+ import { a as batch, c as reactive, d as toRefs, f as unref, i as WatchOptions, l as ref, n as Ref, o as computed, p as watch, r as RefOptions, s as isRef, t as ComputedRef, u as toRef } from "../reactivity-DZrc3Yhu.mjs";
3
+ export { ComputedRef, Ref, RefOptions, WatchOptions, batch, computed, isRef, reactive, ref, toRef, toRefs, unref, watch };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- let activeEffect=null;const targetMap=/* @__PURE__ */ new WeakMap;function createEffect(fn){let effect=fn;return effect.deps=/* @__PURE__ */ new Set,effect}function cleanupEffect(effect){for(let depSet of effect.deps)depSet.delete(effect);effect.deps.clear()}function runTracked(effect,fn){cleanupEffect(effect);let prev=activeEffect;activeEffect=effect;try{return fn()}finally{activeEffect=prev}}function track(target,key){if(!activeEffect)return;let depsMap=targetMap.get(target);depsMap||(depsMap=/* @__PURE__ */ new Map,targetMap.set(target,depsMap));let deps=depsMap.get(key);deps||(deps=/* @__PURE__ */ new Set,depsMap.set(key,deps)),deps.add(activeEffect),activeEffect.deps.add(deps)}function trigger(target,key){let depsMap=targetMap.get(target);if(!depsMap)return;let deps=depsMap.get(key);if(deps&&deps.size!==0)for(let effect of Array.from(deps))effect()}function ref(initialValue){let subscribers=/* @__PURE__ */ new Set,wrapper={_value:initialValue};return{get value(){return track(wrapper,`_value`),wrapper._value},set value(newValue){let oldValue=wrapper._value;if(!Object.is(oldValue,newValue)){wrapper._value=newValue,trigger(wrapper,`_value`);for(let fn of subscribers)fn(newValue,oldValue)}},subscribe(fn){return subscribers.add(fn),()=>subscribers.delete(fn)},toJSON(){return wrapper._value}}}function computed(getter){let cached,dirty=!0,disposed=!1,wrapper={_value:void 0},effect=createEffect(()=>{dirty=!0,trigger(wrapper,`_value`)}),recompute=()=>{if(disposed){let prev=activeEffect;activeEffect=null;try{return getter()}finally{activeEffect=prev}}return dirty&&=(cached=runTracked(effect,getter),wrapper._value=cached,!1),cached};return{get value(){return track(wrapper,`_value`),recompute()},dispose(){disposed=!0,cleanupEffect(effect)},toJSON(){return recompute()}}}function watch(source,callback,options){let oldValue,stopped=!1,getter=typeof source==`function`?source:()=>source.value,job=createEffect(()=>{if(stopped)return;let newValue=runTracked(job,getter);Object.is(newValue,oldValue)||(callback(newValue,oldValue),oldValue=newValue)});return oldValue=runTracked(job,getter),options?.immediate&&callback(oldValue,void 0),()=>{stopped=!0,cleanupEffect(job)}}const proxyCache=/* @__PURE__ */ new WeakMap;function reactive(target){let existing=proxyCache.get(target);if(existing)return existing;let proxy=new Proxy(target,{get(obj,key,receiver){let value=Reflect.get(obj,key,receiver);return typeof key==`symbol`?value:(track(obj,key),typeof value==`object`&&value&&!Array.isArray(value)?reactive(value):value)},set(obj,key,value,receiver){let oldValue=Reflect.get(obj,key,receiver),result=Reflect.set(obj,key,value,receiver);return!Object.is(oldValue,value)&&typeof key!=`symbol`&&trigger(obj,key),result}});return proxyCache.set(target,proxy),proxy}function isRef(value){return typeof value==`object`&&!!value&&`subscribe`in value&&`value`in value}function unref(value){return isRef(value)?value.value:value}function toRefs(obj){let result={};for(let key in obj)result[key]=ref(obj[key]);return result}export{computed,isRef,reactive,ref,toRefs,unref,watch};
11
+ import{createLogger}from"./logger.mjs";import{r as reportError}from"../observers-vX5EpqCX.mjs";let activeEffect=null;const targetMap=/* @__PURE__ */ new WeakMap,ITERATE_KEY=Symbol(`iterate`);function createEffect(fn,computed=!1){let effect=fn;return effect.deps=/* @__PURE__ */ new Set,computed&&(effect.computed=!0),effect}function cleanupEffect(effect){for(let depSet of effect.deps)depSet.delete(effect);effect.deps.clear()}function runTracked(effect,fn){cleanupEffect(effect);let prev=activeEffect;activeEffect=effect;try{return fn()}finally{activeEffect=prev}}function untracked(fn){let prev=activeEffect;activeEffect=null;try{return fn()}finally{activeEffect=prev}}function track(target,key){if(!activeEffect)return;let depsMap=targetMap.get(target);depsMap||(depsMap=/* @__PURE__ */ new Map,targetMap.set(target,depsMap));let deps=depsMap.get(key);deps||(deps=/* @__PURE__ */ new Set,depsMap.set(key,deps)),deps.add(activeEffect),activeEffect.deps.add(deps)}function trigger(target,key){let deps=targetMap.get(target)?.get(key);if(deps&&deps.size!==0)for(let effect of Array.from(deps))schedule(effect)}let batchDepth=0;const queue=/* @__PURE__ */ new Set;function schedule(effect){batchDepth>0&&!effect.computed?queue.add(effect):runEffect(effect)}const running=/* @__PURE__ */ new Map,log=createLogger(`Reactivity`);function report(err){try{log.error({err},`A watcher threw. The change still applied, and the other watchers ran.`)}catch{}reportError(err,{source:`watch`})}function runEffect(effect){let depth=(running.get(effect)??0)+1;if(depth>100)report(/* @__PURE__ */ Error(`Reactivity loop: an effect re-triggered itself 100 levels deep — a watcher that writes to what it watches, or two that write to each other. Stopped it.`));else{running.set(effect,depth);try{effect()}catch(err){report(err)}finally{depth===1?running.delete(effect):running.set(effect,depth-1)}}}function batch(fn){batchDepth++;try{return fn()}finally{if(--batchDepth===0)for(;queue.size>0;){let pending=[...queue];queue.clear();for(let effect of pending)runEffect(effect)}}}const REF=Symbol.for(`kickjs.ref`);function ref(initialValue,options={}){let subscribers=/* @__PURE__ */ new Set,wrapper={_value:initialValue},deep=options.deep===!0,notify=(newValue,oldValue)=>{for(let fn of Array.from(subscribers))try{fn(newValue,oldValue)}catch(err){report(err)}},batchedFrom=null,flush=createEffect(()=>{let from=batchedFrom;batchedFrom=null,Object.is(from.value,wrapper._value)||notify(wrapper._value,from.value)});return{[REF]:!0,get value(){track(wrapper,`_value`);let value=wrapper._value;return deep&&typeof value==`object`&&value?reactive(value):value},set value(newValue){let oldValue=wrapper._value;Object.is(oldValue,newValue)||(wrapper._value=newValue,trigger(wrapper,`_value`),subscribers.size!==0&&(batchDepth>0?(batchedFrom??={value:oldValue},queue.add(flush)):notify(newValue,oldValue)))},subscribe(fn){return subscribers.add(fn),()=>subscribers.delete(fn)},toJSON(){return wrapper._value}}}function computed(getter){let cached,dirty=!0,disposed=!1,wrapper={_value:void 0},effect=createEffect(()=>{dirty=!0,trigger(wrapper,`_value`)},!0),recompute=()=>disposed?untracked(getter):(dirty&&=(cached=runTracked(effect,getter),wrapper._value=cached,!1),cached);return{[REF]:!0,get value(){return track(wrapper,`_value`),recompute()},dispose(){disposed=!0,cleanupEffect(effect)},toJSON(){return recompute()}}}function watch(source,callback,options){let oldValue,stopped=!1,getter=typeof source==`function`?source:()=>source.value,job=createEffect(()=>{if(stopped)return;let newValue=runTracked(job,getter);if(!Object.is(newValue,oldValue)){let previous=oldValue;oldValue=newValue,callback(newValue,previous)}});if(oldValue=runTracked(job,getter),options?.immediate)try{callback(oldValue,void 0)}catch(err){report(err)}return()=>{stopped=!0,queue.delete(job),cleanupEffect(job)}}const proxyCache=/* @__PURE__ */ new WeakMap,proxies=/* @__PURE__ */ new WeakSet,ARRAY_MUTATORS=/* @__PURE__ */ new Set([`push`,`pop`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]);function reactive(target){if(proxies.has(target))return target;let existing=proxyCache.get(target);if(existing)return existing;let isArray=Array.isArray(target),iterateKey=isArray?`length`:ITERATE_KEY,proxy=new Proxy(target,{get(obj,key,receiver){if(isArray&&typeof key==`string`&&ARRAY_MUTATORS.has(key)){let method=Reflect.get(obj,key,receiver);return(...args)=>batch(()=>untracked(()=>method.apply(proxy,args)))}let value=Reflect.get(obj,key,receiver);return typeof key==`symbol`?value:(track(obj,key),typeof value==`object`&&value?reactive(value):value)},set(obj,key,value,receiver){let hadKey=isArray&&typeof key==`string`&&/^\d+$/.test(key)?Number(key)<obj.length:Object.hasOwn(obj,key),oldValue=Reflect.get(obj,key,receiver),result=Reflect.set(obj,key,value,receiver);return typeof key==`symbol`||(hadKey?Object.is(oldValue,value)||trigger(obj,key):batch(()=>{trigger(obj,key),trigger(obj,iterateKey)})),result},deleteProperty(obj,key){let hadKey=Object.hasOwn(obj,key),result=Reflect.deleteProperty(obj,key);return result&&hadKey&&typeof key!=`symbol`&&batch(()=>{trigger(obj,key),trigger(obj,iterateKey)}),result},has(obj,key){return typeof key!=`symbol`&&track(obj,key),Reflect.has(obj,key)},ownKeys(obj){return track(obj,iterateKey),Reflect.ownKeys(obj)}});return proxyCache.set(target,proxy),proxies.add(proxy),proxy}function isRef(value){return typeof value==`object`&&!!value&&value[REF]===!0}function unref(value){return isRef(value)?value.value:value}function toRef(obj,key){return{[REF]:!0,get value(){return obj[key]},set value(value){obj[key]=value},subscribe(fn){return watch(()=>obj[key],fn)},toJSON(){return obj[key]}}}function toRefs(obj){let result={};for(let key of Object.keys(obj))result[key]=toRef(obj,key);return result}export{batch,computed,isRef,reactive,ref,toRef,toRefs,unref,watch};
12
12
  //# sourceMappingURL=reactivity.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"reactivity.mjs","names":[],"sources":["../../src/core/reactivity.ts"],"sourcesContent":["/**\n * Lightweight reactivity system inspired by Vue 3's composition API.\n * Provides ref(), computed(), watch(), and reactive() for observable\n * backend state — config, metrics, health, circuit breakers.\n */\n\n// ── Dependency Tracking ─────────────────────────────────────────────────\n//\n// Effects carry back-references to every dep Set they were added to, so\n// stopping a watcher / disposing a computed — or simply re-running an\n// effect whose getter reads different keys this time — removes it from the\n// old Sets instead of leaving dead subscriptions to accumulate (and be\n// invoked!) forever. Same cleanup discipline as Vue 3's ReactiveEffect.\n\ninterface Effect {\n (): void\n /** Dep Sets this effect is currently registered in (for cleanup). */\n deps: Set<Set<Effect>>\n}\n\nlet activeEffect: Effect | null = null\nconst targetMap = new WeakMap<object, Map<string | symbol, Set<Effect>>>()\n\nfunction createEffect(fn: () => void): Effect {\n const effect = fn as Effect\n effect.deps = new Set()\n return effect\n}\n\n/** Remove the effect from every dep Set it was tracked into. */\nfunction cleanupEffect(effect: Effect): void {\n for (const depSet of effect.deps) depSet.delete(effect)\n effect.deps.clear()\n}\n\n/**\n * Run `fn` with `effect` as the active tracking target, first clearing the\n * effect's previous subscriptions so conditional reads don't leave stale deps.\n */\nfunction runTracked<T>(effect: Effect, fn: () => T): T {\n cleanupEffect(effect)\n const prev = activeEffect\n activeEffect = effect\n try {\n return fn()\n } finally {\n activeEffect = prev\n }\n}\n\nfunction track(target: object, key: string | symbol): void {\n if (!activeEffect) return\n let depsMap = targetMap.get(target)\n if (!depsMap) {\n depsMap = new Map()\n targetMap.set(target, depsMap)\n }\n let deps = depsMap.get(key)\n if (!deps) {\n deps = new Set()\n depsMap.set(key, deps)\n }\n deps.add(activeEffect)\n activeEffect.deps.add(deps)\n}\n\nfunction trigger(target: object, key: string | symbol): void {\n const depsMap = targetMap.get(target)\n if (!depsMap) return\n const deps = depsMap.get(key)\n if (!deps || deps.size === 0) return\n // Iterate a snapshot — a triggered effect re-tracks (mutating `deps`)\n // during its run, which would otherwise corrupt this iteration.\n for (const effect of Array.from(deps)) {\n effect()\n }\n}\n\n// ── ref() ────────────────────────────────────────────────────────────────\n\nexport interface Ref<T = any> {\n value: T\n /** Subscribe to changes. Returns unsubscribe function. */\n subscribe(fn: (newValue: T, oldValue: T) => void): () => void\n /**\n * Auto-unwrap on `JSON.stringify` — returns the underlying value\n * so refs serialize transparently inside larger payloads (introspect\n * snapshots, devtools state, request responses). Equivalent to\n * `unref(ref)` but invoked implicitly by the JSON pipeline.\n */\n toJSON(): T\n}\n\n/**\n * Create a reactive reference. Reading `.value` tracks the dependency,\n * writing `.value` triggers watchers and computed recalculations.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * count.value++ // triggers watchers\n * ```\n */\nexport function ref<T>(initialValue: T): Ref<T> {\n const subscribers = new Set<(newValue: T, oldValue: T) => void>()\n const wrapper = { _value: initialValue }\n\n return {\n get value(): T {\n track(wrapper, '_value')\n return wrapper._value\n },\n set value(newValue: T) {\n const oldValue = wrapper._value\n if (Object.is(oldValue, newValue)) return\n wrapper._value = newValue\n trigger(wrapper, '_value')\n for (const fn of subscribers) {\n fn(newValue, oldValue)\n }\n },\n subscribe(fn: (newValue: T, oldValue: T) => void): () => void {\n subscribers.add(fn)\n return () => subscribers.delete(fn)\n },\n /**\n * Auto-unwrap on `JSON.stringify`. Without this, serializing a ref\n * leaks the wrapper shape (`{\"value\": …, \"subscribe\": …}`) instead\n * of the underlying value — particularly painful for adopters who\n * keep adapter / plugin state in refs and surface it through\n * `introspect()`. Returning `value` here means\n * `JSON.stringify({ count: ref(0) })` produces `{\"count\":0}` as\n * expected, without callers having to `.value`-unwrap by hand.\n */\n toJSON(): T {\n return wrapper._value\n },\n }\n}\n\n// ── computed() ───────────────────────────────────────────────────────────\n\nexport interface ComputedRef<T = any> {\n readonly value: T\n /**\n * Auto-unwrap on `JSON.stringify` — see {@link Ref.toJSON} for the\n * motivation. Triggers a recompute when the cached value is stale,\n * same as reading `.value`.\n */\n toJSON(): T\n /**\n * Unsubscribe this computed from its reactive sources. Call when the\n * computed's lifetime is shorter than its sources' (e.g. created\n * per-request/per-tenant against app-lifetime refs) — without it the\n * internal effect stays pinned in the sources' dep Sets forever.\n * After disposal, reading `.value` still works but recomputes on every\n * access and no longer tracks.\n */\n dispose(): void\n}\n\n/**\n * Create a computed value that auto-recalculates when its reactive\n * dependencies change. Cached until a dependency triggers.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * const doubled = computed(() => count.value * 2)\n * count.value = 5\n * console.log(doubled.value) // 10\n * ```\n */\nexport function computed<T>(getter: () => T): ComputedRef<T> {\n let cached: T\n let dirty = true\n let disposed = false\n const wrapper = { _value: undefined as T }\n\n const effect = createEffect(() => {\n dirty = true\n trigger(wrapper, '_value')\n })\n\n const recompute = (): T => {\n // Disposed: plain evaluation with tracking SUSPENDED — neither this\n // computed's effect nor any OUTER active effect (a watcher reading\n // `.value`) may attach to the sources through a disposed computed;\n // otherwise disposal wouldn't actually sever the subscription chain.\n if (disposed) {\n const prev = activeEffect\n activeEffect = null\n try {\n return getter()\n } finally {\n activeEffect = prev\n }\n }\n if (dirty) {\n cached = runTracked(effect, getter)\n wrapper._value = cached\n dirty = false\n }\n return cached\n }\n\n return {\n get value(): T {\n track(wrapper, '_value')\n return recompute()\n },\n dispose(): void {\n disposed = true\n cleanupEffect(effect)\n },\n /**\n * Auto-unwrap on `JSON.stringify`, matching {@link ref}'s behavior\n * so adopters can drop a computed straight into a JSON-bound\n * payload (introspect snapshot, devtools state) and get the value\n * rather than the wrapper shape.\n *\n * Computed values cache through the same dirty-flag the getter\n * uses, so calling `toJSON` is at worst one recompute when stale —\n * identical cost to reading `.value`.\n */\n toJSON(): T {\n return recompute()\n },\n }\n}\n\n// ── watch() ──────────────────────────────────────────────────────────────\n\nexport interface WatchOptions {\n /** Run the callback immediately with the current value (default: false) */\n immediate?: boolean\n}\n\ntype WatchSource<T> = Ref<T> | ComputedRef<T> | (() => T)\n\n/**\n * Watch a reactive source and run a callback when it changes.\n * Returns a stop function to unsubscribe.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * const stop = watch(count, (newVal, oldVal) => {\n * console.log(`Changed from ${oldVal} to ${newVal}`)\n * })\n * count.value = 1 // logs: \"Changed from 0 to 1\"\n * stop() // no more callbacks\n * ```\n */\nexport function watch<T>(\n source: WatchSource<T>,\n callback: (newValue: T, oldValue: T) => void,\n options?: WatchOptions,\n): () => void {\n let oldValue: T\n let stopped = false\n\n const getter = typeof source === 'function' ? source : () => source.value\n\n const job = createEffect(() => {\n if (stopped) return\n // Re-run the getter UNDER tracking so deps are refreshed each run —\n // a conditional getter (`cond ? a.value : b.value`) drops the branch\n // it no longer reads instead of staying subscribed to it forever.\n const newValue = runTracked(job, getter)\n if (!Object.is(newValue, oldValue)) {\n callback(newValue, oldValue)\n oldValue = newValue\n }\n })\n\n // Initial run to establish tracking\n oldValue = runTracked(job, getter)\n\n if (options?.immediate) {\n callback(oldValue, undefined as T)\n }\n\n return () => {\n // Detach from every dep Set — a flag alone would leave the dead effect\n // referenced (and invoked) by its sources for their entire lifetime.\n stopped = true\n cleanupEffect(job)\n }\n}\n\n// ── reactive() ───────────────────────────────────────────────────────────\n\n/**\n * Create a deeply reactive proxy around a plain object. Property reads\n * are tracked, property writes trigger watchers and computed recalculations.\n *\n * @example\n * ```ts\n * const state = reactive({ users: 0, errors: 0 })\n * const errorRate = computed(() =>\n * state.users > 0 ? state.errors / state.users : 0\n * )\n * state.users = 100\n * state.errors = 5\n * console.log(errorRate.value) // 0.05\n * ```\n */\n// Memoize proxies per target: repeated reads of the same nested object must\n// return the SAME proxy — otherwise every access allocates a fresh Proxy and\n// referential identity breaks (`state.nested !== state.nested`).\nconst proxyCache = new WeakMap<object, any>()\n\nexport function reactive<T extends Record<string, any>>(target: T): T {\n const existing = proxyCache.get(target)\n if (existing) return existing as T\n const proxy = new Proxy(target, {\n get(obj, key, receiver) {\n const value = Reflect.get(obj, key, receiver)\n if (typeof key === 'symbol') return value\n track(obj, key)\n // Deep reactivity for nested objects\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n return reactive(value)\n }\n return value\n },\n set(obj, key, value, receiver) {\n const oldValue = Reflect.get(obj, key, receiver)\n const result = Reflect.set(obj, key, value, receiver)\n if (!Object.is(oldValue, value) && typeof key !== 'symbol') {\n trigger(obj, key)\n }\n return result\n },\n })\n proxyCache.set(target, proxy)\n return proxy\n}\n\n// ── Utility ──────────────────────────────────────────────────────────────\n\n/** Check if a value is a Ref */\nexport function isRef(value: any): value is Ref {\n return value !== null && typeof value === 'object' && 'subscribe' in value && 'value' in value\n}\n\n/** Unwrap a ref or return the value as-is */\nexport function unref<T>(value: Ref<T> | T): T {\n return isRef(value) ? value.value : value\n}\n\n/** Convert all properties of an object to refs */\nexport function toRefs<T extends Record<string, any>>(obj: T): { [K in keyof T]: Ref<T[K]> } {\n const result = {} as any\n for (const key in obj) {\n result[key] = ref(obj[key])\n }\n return result\n}\n"],"mappings":";;;;;;;;;;AAoBA,IAAI,aAA8B,KAClC,MAA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,SAAU,CACtB,IAAM,MAAQ,QAAQ,IAAI,IAAK,IAAK,QAAQ,EAO5C,OANI,OAAO,KAAQ,SAAiB,OACpC,MAAM,IAAK,GAAG,EAEQ,OAAO,OAAU,UAAnC,OAA+C,CAAC,MAAM,QAAQ,KAAK,EAC9D,SAAS,KAAK,EAEhB,MACT,EACA,IAAI,IAAK,IAAK,MAAO,SAAU,CAC7B,IAAM,SAAW,QAAQ,IAAI,IAAK,IAAK,QAAQ,EACzC,OAAS,QAAQ,IAAI,IAAK,IAAK,MAAO,QAAQ,EAIpD,MAHI,CAAC,OAAO,GAAG,SAAU,KAAK,GAAK,OAAO,KAAQ,UAChD,QAAQ,IAAK,GAAG,EAEX,MACT,CACF,CAAC,EAED,OADA,WAAW,IAAI,OAAQ,KAAK,EACrB,KACT,CAKA,SAAgB,MAAM,MAA0B,CAC9C,OAAyB,OAAO,OAAU,YAAnC,OAA+C,cAAe,OAAS,UAAW,KAC3F,CAGA,SAAgB,MAAS,MAAsB,CAC7C,OAAO,MAAM,KAAK,EAAI,MAAM,MAAQ,KACtC,CAGA,SAAgB,OAAsC,IAAuC,CAC3F,IAAM,OAAS,CAAC,EAChB,IAAK,IAAM,OAAO,IAChB,OAAO,KAAO,IAAI,IAAI,IAAI,EAE5B,OAAO,MACT"}
1
+ {"version":3,"file":"reactivity.mjs","names":[],"sources":["../../src/core/reactivity.ts"],"sourcesContent":["/**\n * Lightweight reactivity system inspired by Vue 3's composition API.\n * Provides ref(), computed(), watch(), reactive() and batch() for observable\n * backend state — config, metrics, health, circuit breakers.\n */\nimport { createLogger } from './logger'\nimport { reportError } from './observers'\n\n// ── Dependency Tracking ─────────────────────────────────────────────────\n//\n// Effects carry back-references to every dep Set they were added to, so\n// stopping a watcher / disposing a computed — or simply re-running an\n// effect whose getter reads different keys this time — removes it from the\n// old Sets instead of leaving dead subscriptions to accumulate (and be\n// invoked!) forever. Same cleanup discipline as Vue 3's ReactiveEffect.\n\ninterface Effect {\n (): void\n /** Dep Sets this effect is currently registered in (for cleanup). */\n deps: Set<Set<Effect>>\n /**\n * A computed's effect: it only marks the computed stale and passes the\n * change on, so it runs at once even inside batch(). Watchers and ref\n * subscribers wait for the batch to end.\n */\n computed?: boolean\n}\n\nlet activeEffect: Effect | null = null\nconst targetMap = new WeakMap<object, Map<string | symbol, Set<Effect>>>()\n\n/** Tracks key iteration (`Object.keys`, `for…in`) and key additions/removals on an object. */\nconst ITERATE_KEY = Symbol('iterate')\n\nfunction createEffect(fn: () => void, computed = false): Effect {\n const effect = fn as Effect\n effect.deps = new Set()\n if (computed) effect.computed = true\n return effect\n}\n\n/** Remove the effect from every dep Set it was tracked into. */\nfunction cleanupEffect(effect: Effect): void {\n for (const depSet of effect.deps) depSet.delete(effect)\n effect.deps.clear()\n}\n\n/**\n * Run `fn` with `effect` as the active tracking target, first clearing the\n * effect's previous subscriptions so conditional reads don't leave stale deps.\n */\nfunction runTracked<T>(effect: Effect, fn: () => T): T {\n cleanupEffect(effect)\n const prev = activeEffect\n activeEffect = effect\n try {\n return fn()\n } finally {\n activeEffect = prev\n }\n}\n\n/** Run `fn` without tracking — what an array mutator reads isn't a dependency. */\nfunction untracked<T>(fn: () => T): T {\n const prev = activeEffect\n activeEffect = null\n try {\n return fn()\n } finally {\n activeEffect = prev\n }\n}\n\nfunction track(target: object, key: string | symbol): void {\n if (!activeEffect) return\n let depsMap = targetMap.get(target)\n if (!depsMap) {\n depsMap = new Map()\n targetMap.set(target, depsMap)\n }\n let deps = depsMap.get(key)\n if (!deps) {\n deps = new Set()\n depsMap.set(key, deps)\n }\n deps.add(activeEffect)\n activeEffect.deps.add(deps)\n}\n\nfunction trigger(target: object, key: string | symbol): void {\n const deps = targetMap.get(target)?.get(key)\n if (!deps || deps.size === 0) return\n for (const effect of Array.from(deps)) schedule(effect)\n}\n\n// ── Scheduling: batch, error isolation, loop detection ──────────────────\n\nlet batchDepth = 0\nconst queue = new Set<Effect>()\n\nfunction schedule(effect: Effect): void {\n if (batchDepth > 0 && !effect.computed) queue.add(effect)\n else runEffect(effect)\n}\n\n/**\n * How deep one effect may re-enter itself — triggered again while it is still\n * running, as a watcher that writes to what it watches does, or two that write\n * to each other — before it is stopped as a loop. Runs one after another\n * (a watcher pushing 1000 items, each re-running another watcher) never nest,\n * so they don't count.\n */\nconst MAX_REENTRY = 100\n/** Effects running right now, by how many times each is on the stack. */\nconst running = new Map<Effect, number>()\n\nconst log = createLogger('Reactivity')\n\nfunction report(err: unknown): void {\n try {\n log.error({ err }, 'A watcher threw. The change still applied, and the other watchers ran.')\n } catch {\n // A failing logger must not turn a watcher error back into a throw.\n }\n reportError(err, { source: 'watch' })\n}\n\n/**\n * Run one effect. Its error is reported, never thrown: the write that\n * triggered it, and every other effect it triggered, carry on regardless.\n */\nfunction runEffect(effect: Effect): void {\n const depth = (running.get(effect) ?? 0) + 1\n if (depth > MAX_REENTRY) {\n report(\n new Error(\n `Reactivity loop: an effect re-triggered itself ${MAX_REENTRY} levels deep — ` +\n 'a watcher that writes to what it watches, or two that write to each other. Stopped it.',\n ),\n )\n return\n }\n running.set(effect, depth)\n try {\n effect()\n } catch (err) {\n report(err)\n } finally {\n if (depth === 1) running.delete(effect)\n else running.set(effect, depth - 1)\n }\n}\n\n/**\n * Apply several writes as one update: watchers and ref subscribers run once,\n * after `fn` returns, with the final values — never with a half-applied state.\n * Computed values stay current inside the batch. Batches nest; the outermost\n * one flushes. Returns what `fn` returns.\n *\n * @example\n * ```ts\n * const total = computed(() => a.value + b.value)\n * watch(total, (v) => console.log(v))\n * batch(() => {\n * a.value = 2\n * b.value = 2\n * }) // logs 4 once, not 3 then 4\n * ```\n */\nexport function batch<T>(fn: () => T): T {\n batchDepth++\n try {\n return fn()\n } finally {\n if (--batchDepth === 0) {\n while (queue.size > 0) {\n const pending = [...queue]\n queue.clear()\n for (const effect of pending) runEffect(effect)\n }\n }\n }\n}\n\n// ── ref() ────────────────────────────────────────────────────────────────\n\n/** Marks refs, computed refs and `toRef()` views, for {@link isRef}. */\nconst REF = Symbol.for('kickjs.ref')\n\nexport interface Ref<T = any> {\n value: T\n /**\n * Subscribe to changes. Returns unsubscribe function. Inside {@link batch},\n * called once when the batch ends, if the value differs from before it.\n */\n subscribe(fn: (newValue: T, oldValue: T) => void): () => void\n /**\n * Auto-unwrap on `JSON.stringify` — returns the underlying value\n * so refs serialize transparently inside larger payloads (introspect\n * snapshots, devtools state, request responses). Equivalent to\n * `unref(ref)` but invoked implicitly by the JSON pipeline.\n */\n toJSON(): T\n}\n\nexport interface RefOptions {\n /**\n * Make an object value deeply reactive: `r.value.count++` and\n * `r.value.items.push(x)` notify too, not only replacing `r.value`.\n * Default: false — only assigning `.value` notifies.\n */\n deep?: boolean\n}\n\n/**\n * Create a reactive reference. Reading `.value` tracks the dependency,\n * writing `.value` triggers watchers and computed recalculations.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * count.value++ // triggers watchers\n *\n * const config = ref({ retries: 3 }, { deep: true })\n * config.value.retries = 5 // triggers watchers too\n * ```\n */\nexport function ref<T>(initialValue: T, options: RefOptions = {}): Ref<T> {\n const subscribers = new Set<(newValue: T, oldValue: T) => void>()\n const wrapper = { _value: initialValue }\n const deep = options.deep === true\n\n const notify = (newValue: T, oldValue: T) => {\n // A copy: a subscriber may unsubscribe while being notified.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(newValue, oldValue)\n } catch (err) {\n report(err)\n }\n }\n }\n // Inside a batch, subscribers hear once, with the value from before the\n // batch and the one after it.\n let batchedFrom: { value: T } | null = null\n const flush = createEffect(() => {\n const from = batchedFrom!\n batchedFrom = null\n if (!Object.is(from.value, wrapper._value)) notify(wrapper._value, from.value)\n })\n\n return {\n [REF]: true,\n get value(): T {\n track(wrapper, '_value')\n const value = wrapper._value\n return deep && value !== null && typeof value === 'object'\n ? (reactive(value as object) as T)\n : value\n },\n set value(newValue: T) {\n const oldValue = wrapper._value\n if (Object.is(oldValue, newValue)) return\n wrapper._value = newValue\n trigger(wrapper, '_value')\n if (subscribers.size === 0) return\n if (batchDepth > 0) {\n batchedFrom ??= { value: oldValue }\n queue.add(flush)\n } else {\n notify(newValue, oldValue)\n }\n },\n subscribe(fn: (newValue: T, oldValue: T) => void): () => void {\n subscribers.add(fn)\n return () => subscribers.delete(fn)\n },\n toJSON(): T {\n return wrapper._value\n },\n } as Ref<T>\n}\n\n// ── computed() ───────────────────────────────────────────────────────────\n\nexport interface ComputedRef<T = any> {\n readonly value: T\n /**\n * Auto-unwrap on `JSON.stringify` — see {@link Ref.toJSON} for the\n * motivation. Triggers a recompute when the cached value is stale,\n * same as reading `.value`.\n */\n toJSON(): T\n /**\n * Unsubscribe this computed from its reactive sources. Call when the\n * computed's lifetime is shorter than its sources' (e.g. created\n * per-request/per-tenant against app-lifetime refs) — without it the\n * internal effect stays pinned in the sources' dep Sets forever.\n * After disposal, reading `.value` still works but recomputes on every\n * access and no longer tracks.\n */\n dispose(): void\n}\n\n/**\n * Create a computed value that auto-recalculates when its reactive\n * dependencies change. Cached until a dependency triggers.\n * @example\n * ```ts\n * const count = ref(0)\n * const doubled = computed(() => count.value * 2)\n * count.value = 5\n * console.log(doubled.value) // 10\n * ```\n */\nexport function computed<T>(getter: () => T): ComputedRef<T> {\n let cached: T\n let dirty = true\n let disposed = false\n const wrapper = { _value: undefined as T }\n\n const effect = createEffect(() => {\n dirty = true\n trigger(wrapper, '_value')\n }, true)\n\n const recompute = (): T => {\n // Disposed: plain evaluation with tracking SUSPENDED — neither this\n // computed's effect nor any OUTER active effect (a watcher reading\n // `.value`) may attach to the sources through a disposed computed;\n // otherwise disposal wouldn't actually sever the subscription chain.\n if (disposed) return untracked(getter)\n if (dirty) {\n cached = runTracked(effect, getter)\n wrapper._value = cached\n dirty = false\n }\n return cached\n }\n\n return {\n [REF]: true,\n get value(): T {\n track(wrapper, '_value')\n return recompute()\n },\n dispose(): void {\n disposed = true\n cleanupEffect(effect)\n },\n /**\n * Auto-unwrap on `JSON.stringify`, matching {@link ref}'s behavior\n * so adopters can drop a computed straight into a JSON-bound\n * payload (introspect snapshot, devtools state) and get the value\n * rather than the wrapper shape.\n *\n * Computed values cache through the same dirty-flag the getter\n * uses, so calling `toJSON` is at worst one recompute when stale —\n * identical cost to reading `.value`.\n */\n toJSON(): T {\n return recompute()\n },\n } as ComputedRef<T>\n}\n\n// ── watch() ──────────────────────────────────────────────────────────────\n\nexport interface WatchOptions {\n /** Run the callback immediately with the current value (default: false) */\n immediate?: boolean\n}\n\ntype WatchSource<T> = Ref<T> | ComputedRef<T> | (() => T)\n\n/**\n * Watch a reactive source and run a callback when it changes.\n * Returns a stop function to unsubscribe.\n *\n * A callback that throws is reported (logged, and passed to `onError`\n * observers) instead of thrown: the write that triggered it, and every other\n * watcher, carry on. Inside {@link batch}, the callback runs once, after the\n * batch.\n *\n * @example\n * ```ts\n * const count = ref(0)\n * const stop = watch(count, (newVal, oldVal) => {\n * console.log(`Changed from ${oldVal} to ${newVal}`)\n * })\n * count.value = 1 // logs: \"Changed from 0 to 1\"\n * stop() // no more callbacks\n * ```\n */\nexport function watch<T>(\n source: WatchSource<T>,\n callback: (newValue: T, oldValue: T) => void,\n options?: WatchOptions,\n): () => void {\n let oldValue: T\n let stopped = false\n\n const getter = typeof source === 'function' ? source : () => source.value\n\n const job = createEffect(() => {\n if (stopped) return\n // Re-run the getter UNDER tracking so deps are refreshed each run —\n // a conditional getter (`cond ? a.value : b.value`) drops the branch\n // it no longer reads instead of staying subscribed to it forever.\n const newValue = runTracked(job, getter)\n if (!Object.is(newValue, oldValue)) {\n const previous = oldValue\n // Advanced before the callback, so one that throws isn't re-called\n // with the same change on the next run.\n oldValue = newValue\n callback(newValue, previous)\n }\n })\n\n // Initial run to establish tracking\n oldValue = runTracked(job, getter)\n\n if (options?.immediate) {\n // Reported like any other run: watch() still returns its stop function.\n try {\n callback(oldValue, undefined as T)\n } catch (err) {\n report(err)\n }\n }\n\n return () => {\n // Detach from every dep Set — a flag alone would leave the dead effect\n // referenced (and invoked) by its sources for their entire lifetime.\n stopped = true\n queue.delete(job)\n cleanupEffect(job)\n }\n}\n\n// ── reactive() ───────────────────────────────────────────────────────────\n\n/**\n * Create a deeply reactive proxy around an object or array. Property reads\n * are tracked, writes and deletes trigger watchers and computed\n * recalculations, and so do key additions and removals for code that\n * iterates the keys (`Object.keys`, `for…in`, `in`). Nested objects and\n * arrays are reactive too.\n * @example\n * ```ts\n * const state = reactive({ users: 0, errors: 0 })\n * const errorRate = computed(() =>\n * state.users > 0 ? state.errors / state.users : 0\n * )\n * state.users = 100\n * state.errors = 5\n * console.log(errorRate.value) // 0.05\n * ```\n */\n// Memoize proxies per target: repeated reads of the same nested object must\n// return the SAME proxy — otherwise every access allocates a fresh Proxy and\n// referential identity breaks (`state.nested !== state.nested`).\nconst proxyCache = new WeakMap<object, any>()\n/** Proxies this module made — `reactive(proxy)` returns it rather than wrapping it again. */\nconst proxies = new WeakSet<object>()\n\n/** Array methods that change the array: run untracked and as one update. */\nconst ARRAY_MUTATORS = new Set([\n 'push',\n 'pop',\n 'shift',\n 'unshift',\n 'splice',\n 'sort',\n 'reverse',\n 'fill',\n 'copyWithin',\n])\n\nexport function reactive<T extends object>(target: T): T {\n if (proxies.has(target)) return target\n const existing = proxyCache.get(target)\n if (existing) return existing as T\n const isArray = Array.isArray(target)\n // What iterating this target depends on: an array's length, an object's key set.\n const iterateKey = isArray ? 'length' : ITERATE_KEY\n const proxy: T = new Proxy(target, {\n get(obj, key, receiver) {\n if (isArray && typeof key === 'string' && ARRAY_MUTATORS.has(key)) {\n const method = Reflect.get(obj, key, receiver) as (...args: unknown[]) => unknown\n return (...args: unknown[]) => batch(() => untracked(() => method.apply(proxy, args)))\n }\n const value = Reflect.get(obj, key, receiver)\n if (typeof key === 'symbol') return value\n track(obj, key)\n // Deep reactivity for nested objects and arrays\n if (value !== null && typeof value === 'object') return reactive(value)\n return value\n },\n set(obj, key, value, receiver) {\n const hadKey =\n isArray && typeof key === 'string' && /^\\d+$/.test(key)\n ? Number(key) < (obj as unknown[]).length\n : Object.hasOwn(obj, key)\n const oldValue = Reflect.get(obj, key, receiver)\n const result = Reflect.set(obj, key, value, receiver)\n if (typeof key === 'symbol') return result\n if (!hadKey) {\n batch(() => {\n trigger(obj, key)\n // A new array index grows the array, but its `length` write that\n // follows sees the length already updated — so it's triggered here.\n trigger(obj, iterateKey)\n })\n } else if (!Object.is(oldValue, value)) {\n trigger(obj, key)\n }\n return result\n },\n deleteProperty(obj, key) {\n const hadKey = Object.hasOwn(obj, key)\n const result = Reflect.deleteProperty(obj, key)\n if (result && hadKey && typeof key !== 'symbol') {\n batch(() => {\n trigger(obj, key)\n trigger(obj, iterateKey)\n })\n }\n return result\n },\n has(obj, key) {\n if (typeof key !== 'symbol') track(obj, key)\n return Reflect.has(obj, key)\n },\n ownKeys(obj) {\n track(obj, iterateKey)\n return Reflect.ownKeys(obj)\n },\n })\n proxyCache.set(target, proxy)\n proxies.add(proxy)\n return proxy\n}\n\n// ── Utility ──────────────────────────────────────────────────────────────\n\n/** Check if a value is a ref — from {@link ref}, {@link computed} or {@link toRef}. */\nexport function isRef<T = any>(value: unknown): value is Ref<T> | ComputedRef<T> {\n return value !== null && typeof value === 'object' && (value as any)[REF] === true\n}\n\n/** Unwrap a ref or computed ref, or return the value as-is */\nexport function unref<T>(value: Ref<T> | ComputedRef<T> | T): T {\n return isRef(value) ? (value.value as T) : (value as T)\n}\n\n/**\n * A ref that reads and writes `obj[key]`: a live view, not a copy. On a\n * {@link reactive} object, watching it follows changes made either way.\n */\nexport function toRef<T extends object, K extends keyof T>(obj: T, key: K): Ref<T[K]> {\n return {\n [REF]: true,\n get value(): T[K] {\n return obj[key]\n },\n set value(value: T[K]) {\n obj[key] = value\n },\n subscribe(fn: (newValue: T[K], oldValue: T[K]) => void): () => void {\n return watch(() => obj[key], fn)\n },\n toJSON(): T[K] {\n return obj[key]\n },\n } as Ref<T[K]>\n}\n\n/** {@link toRef} for every property: live views onto the object, not copies. */\nexport function toRefs<T extends object>(obj: T): { [K in keyof T]: Ref<T[K]> } {\n const result = {} as { [K in keyof T]: Ref<T[K]> }\n for (const key of Object.keys(obj) as Array<keyof T>) {\n result[key] = toRef(obj, key)\n }\n return result\n}\n"],"mappings":";;;;;;;;;;+FA4BA,IAAI,aAA8B,KAClC,MAAM,0BAAY,IAAI,QAGhB,YAAc,OAAO,SAAS,EAEpC,SAAS,aAAa,GAAgB,SAAW,GAAe,CAC9D,IAAM,OAAS,GAGf,MAFA,QAAO,qBAAO,IAAI,IACd,WAAU,OAAO,SAAW,IACzB,MACT,CAGA,SAAS,cAAc,OAAsB,CAC3C,IAAK,IAAM,UAAU,OAAO,KAAM,OAAO,OAAO,MAAM,EACtD,OAAO,KAAK,MAAM,CACpB,CAMA,SAAS,WAAc,OAAgB,GAAgB,CACrD,cAAc,MAAM,EACpB,IAAM,KAAO,aACb,aAAe,OACf,GAAI,CACF,OAAO,GAAG,CACZ,QAAU,CACR,aAAe,IACjB,CACF,CAGA,SAAS,UAAa,GAAgB,CACpC,IAAM,KAAO,aACb,aAAe,KACf,GAAI,CACF,OAAO,GAAG,CACZ,QAAU,CACR,aAAe,IACjB,CACF,CAEA,SAAS,MAAM,OAAgB,IAA4B,CACzD,GAAI,CAAC,aAAc,OACnB,IAAI,QAAU,UAAU,IAAI,MAAM,EAC7B,UACH,wBAAU,IAAI,IACd,UAAU,IAAI,OAAQ,OAAO,GAE/B,IAAI,KAAO,QAAQ,IAAI,GAAG,EACrB,OACH,qBAAO,IAAI,IACX,QAAQ,IAAI,IAAK,IAAI,GAEvB,KAAK,IAAI,YAAY,EACrB,aAAa,KAAK,IAAI,IAAI,CAC5B,CAEA,SAAS,QAAQ,OAAgB,IAA4B,CAC3D,IAAM,KAAO,UAAU,IAAI,MAAM,CAAC,EAAE,IAAI,GAAG,EAC3C,GAAK,MAAQ,KAAK,OAAS,EAC3B,IAAK,IAAM,UAAU,MAAM,KAAK,IAAI,EAAG,SAAS,MAAM,CACxD,CAIA,IAAI,WAAa,EACjB,MAAM,sBAAQ,IAA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