@forinda/kickjs 3.1.3 → 4.0.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 (192) hide show
  1. package/README.md +13 -212
  2. package/dist/adapter-BNw2pGbg.d.mts +261 -0
  3. package/dist/adapter-BNw2pGbg.d.mts.map +1 -0
  4. package/dist/{app-module-Cotu9TIC.d.mts → app-module-CO0ksPCm.d.mts} +12 -2
  5. package/dist/app-module-CO0ksPCm.d.mts.map +1 -0
  6. package/dist/{application-BVl6L8xo.mjs → application-Ce4DQN6m.mjs} +114 -25
  7. package/dist/application-Ce4DQN6m.mjs.map +1 -0
  8. package/dist/application-Czwm7Gty.d.mts +302 -0
  9. package/dist/application-Czwm7Gty.d.mts.map +1 -0
  10. package/dist/{bootstrap-D6leYXz2.mjs → bootstrap-CB7bJeJG.mjs} +6 -6
  11. package/dist/{bootstrap-D6leYXz2.mjs.map → bootstrap-CB7bJeJG.mjs.map} +1 -1
  12. package/dist/bootstrap-NxFRaNTh.d.mts +28 -0
  13. package/dist/bootstrap-NxFRaNTh.d.mts.map +1 -0
  14. package/dist/{cache-CcTzzNdr.d.mts → cache-BStrqXSZ.d.mts} +2 -2
  15. package/dist/{cache-CcTzzNdr.d.mts.map → cache-BStrqXSZ.d.mts.map} +1 -1
  16. package/dist/config/index.d.mts +1 -1
  17. package/dist/config/index.mjs +3 -3
  18. package/dist/{config-gkVEnxVm.mjs → config-wZ_TgBfs.mjs} +4 -4
  19. package/dist/{config-gkVEnxVm.mjs.map → config-wZ_TgBfs.mjs.map} +1 -1
  20. package/dist/{container-BJb34faa.d.mts → container-CnWDsxi-.d.mts} +9 -7
  21. package/dist/container-CnWDsxi-.d.mts.map +1 -0
  22. package/dist/{container-BBZLlK6y.mjs → container-DYYSu58w.mjs} +313 -9
  23. package/dist/container-DYYSu58w.mjs.map +1 -0
  24. package/dist/context-BAGzqT7-.mjs +319 -0
  25. package/dist/context-BAGzqT7-.mjs.map +1 -0
  26. package/dist/context-Ymvv-85x.d.mts +260 -0
  27. package/dist/context-Ymvv-85x.d.mts.map +1 -0
  28. package/dist/context-decorator-B5v3VQCN.d.mts +111 -0
  29. package/dist/context-decorator-B5v3VQCN.d.mts.map +1 -0
  30. package/dist/core/adapter.d.mts +1 -1
  31. package/dist/core/adapter.mjs +1 -1
  32. package/dist/core/app-module.d.mts +1 -1
  33. package/dist/core/app-module.mjs +1 -1
  34. package/dist/core/cache.d.mts +1 -1
  35. package/dist/core/cache.mjs +2 -2
  36. package/dist/core/cache.mjs.map +1 -1
  37. package/dist/core/container.d.mts +1 -1
  38. package/dist/core/container.mjs +2 -2
  39. package/dist/core/cron.d.mts +1 -1
  40. package/dist/core/cron.mjs +2 -2
  41. package/dist/core/decorators.d.mts +2 -2
  42. package/dist/core/decorators.mjs +48 -16
  43. package/dist/core/decorators.mjs.map +1 -1
  44. package/dist/core/errors.d.mts +1 -1
  45. package/dist/core/errors.mjs +1 -1
  46. package/dist/core/interfaces.d.mts +1 -1
  47. package/dist/core/interfaces.mjs +35 -16
  48. package/dist/core/interfaces.mjs.map +1 -1
  49. package/dist/core/logger.d.mts +2 -2
  50. package/dist/core/logger.mjs +2 -4
  51. package/dist/core/logger.mjs.map +1 -1
  52. package/dist/core/path.d.mts +1 -1
  53. package/dist/core/path.mjs +1 -1
  54. package/dist/core/plugin.d.mts +1 -1
  55. package/dist/core/plugin.mjs +1 -1
  56. package/dist/core/reactivity.d.mts +1 -1
  57. package/dist/core/reactivity.mjs +1 -1
  58. package/dist/core-DBcoqPHM.mjs +709 -0
  59. package/dist/core-DBcoqPHM.mjs.map +1 -0
  60. package/dist/cors-BfgqfLPd.d.mts +48 -0
  61. package/dist/cors-BfgqfLPd.d.mts.map +1 -0
  62. package/dist/{cron-H-IyLcOr.d.mts → cron-7zqvsmMI.d.mts} +1 -1
  63. package/dist/{cron-H-IyLcOr.d.mts.map → cron-7zqvsmMI.d.mts.map} +1 -1
  64. package/dist/csrf-DiK9zept.d.mts +52 -0
  65. package/dist/csrf-DiK9zept.d.mts.map +1 -0
  66. package/dist/{decorators-C9_SN7ge.d.mts → decorators-BMvaLliz.d.mts} +147 -12
  67. package/dist/decorators-BMvaLliz.d.mts.map +1 -0
  68. package/dist/{env-Cu5hWsuE.mjs → env-CdH5-dM_.mjs} +3 -4
  69. package/dist/{env-Cu5hWsuE.mjs.map → env-CdH5-dM_.mjs.map} +1 -1
  70. package/dist/error-handler-Xud_3Lah.d.mts +20 -0
  71. package/dist/error-handler-Xud_3Lah.d.mts.map +1 -0
  72. package/dist/{errors-BOUCRl-p.d.mts → errors-uaHCeXRz.d.mts} +1 -1
  73. package/dist/{errors-BOUCRl-p.d.mts.map → errors-uaHCeXRz.d.mts.map} +1 -1
  74. package/dist/execution-context-DKnt61pY.d.mts +57 -0
  75. package/dist/execution-context-DKnt61pY.d.mts.map +1 -0
  76. package/dist/helmet-CaMbjzBG.d.mts +41 -0
  77. package/dist/helmet-CaMbjzBG.d.mts.map +1 -0
  78. package/dist/http/application.d.mts +2 -239
  79. package/dist/http/application.mjs +2 -2
  80. package/dist/http/bootstrap.d.mts +2 -27
  81. package/dist/http/bootstrap.mjs +2 -2
  82. package/dist/http/context.d.mts +3 -262
  83. package/dist/http/context.mjs +2 -271
  84. package/dist/http/middleware/cors.d.mts +2 -47
  85. package/dist/http/middleware/cors.mjs +1 -1
  86. package/dist/http/middleware/csrf.d.mts +2 -51
  87. package/dist/http/middleware/csrf.mjs +2 -2
  88. package/dist/http/middleware/csrf.mjs.map +1 -1
  89. package/dist/http/middleware/error-handler.d.mts +2 -19
  90. package/dist/http/middleware/error-handler.mjs +2 -2
  91. package/dist/http/middleware/helmet.d.mts +2 -40
  92. package/dist/http/middleware/helmet.mjs +1 -1
  93. package/dist/http/middleware/rate-limit.d.mts +2 -55
  94. package/dist/http/middleware/rate-limit.mjs +2 -2
  95. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  96. package/dist/http/middleware/request-id.d.mts +2 -9
  97. package/dist/http/middleware/request-id.mjs +12 -3
  98. package/dist/http/middleware/request-id.mjs.map +1 -1
  99. package/dist/http/middleware/request-logger.d.mts +2 -31
  100. package/dist/http/middleware/request-logger.mjs +2 -2
  101. package/dist/http/middleware/session.d.mts +2 -69
  102. package/dist/http/middleware/session.mjs +1 -1
  103. package/dist/http/middleware/spa.d.mts +2 -100
  104. package/dist/http/middleware/spa.mjs +5 -5
  105. package/dist/http/middleware/spa.mjs.map +1 -1
  106. package/dist/http/middleware/upload.d.mts +2 -78
  107. package/dist/http/middleware/upload.mjs +1 -1
  108. package/dist/http/middleware/validate.d.mts +2 -22
  109. package/dist/http/middleware/validate.mjs +2 -2
  110. package/dist/http/middleware/views.d.mts +2 -61
  111. package/dist/http/middleware/views.mjs +16 -15
  112. package/dist/http/middleware/views.mjs.map +1 -1
  113. package/dist/http/query/index.d.mts +1 -1
  114. package/dist/http/query/index.mjs +2 -2
  115. package/dist/http/router-builder.d.mts +2 -20
  116. package/dist/http/router-builder.mjs +58 -10
  117. package/dist/http/router-builder.mjs.map +1 -1
  118. package/dist/{index-Co7a3Zat.d.mts → index-B9cyOQAe.d.mts} +1 -1
  119. package/dist/{index-Co7a3Zat.d.mts.map → index-B9cyOQAe.d.mts.map} +1 -1
  120. package/dist/{index-DNVfGjF9.d.mts → index-D-qhXg9M.d.mts} +3 -3
  121. package/dist/{index-DNVfGjF9.d.mts.map → index-D-qhXg9M.d.mts.map} +1 -1
  122. package/dist/index-DQyWtyp0.d.mts +511 -0
  123. package/dist/index-DQyWtyp0.d.mts.map +1 -0
  124. package/dist/index.d.mts +34 -133
  125. package/dist/index.mjs +14 -14
  126. package/dist/interfaces-B50n7dwl.d.mts +71 -0
  127. package/dist/{interfaces-DXjE8Re1.d.mts.map → interfaces-B50n7dwl.d.mts.map} +1 -1
  128. package/dist/{logger-CW6FHtvU.d.mts → logger-CLVRZf2N.d.mts} +2 -4
  129. package/dist/{logger-CW6FHtvU.d.mts.map → logger-CLVRZf2N.d.mts.map} +1 -1
  130. package/dist/{metadata-BwRJ69bC.mjs → metadata-VQM9wChy.mjs} +2 -2
  131. package/dist/{metadata-BwRJ69bC.mjs.map → metadata-VQM9wChy.mjs.map} +1 -1
  132. package/dist/{path-B4JcbwKX.d.mts → path-Diviu6hv.d.mts} +1 -1
  133. package/dist/path-Diviu6hv.d.mts.map +1 -0
  134. package/dist/plugin-WdrDgNzk.d.mts +165 -0
  135. package/dist/plugin-WdrDgNzk.d.mts.map +1 -0
  136. package/dist/{query-BQ2UT3oi.mjs → query-DJMxdx5r.mjs} +2 -2
  137. package/dist/{query-BQ2UT3oi.mjs.map → query-DJMxdx5r.mjs.map} +1 -1
  138. package/dist/rate-limit-DUwoICtI.d.mts +56 -0
  139. package/dist/rate-limit-DUwoICtI.d.mts.map +1 -0
  140. package/dist/{reactivity-I8nDlg4c.d.mts → reactivity-CfJceo4H.d.mts} +1 -1
  141. package/dist/{reactivity-I8nDlg4c.d.mts.map → reactivity-CfJceo4H.d.mts.map} +1 -1
  142. package/dist/request-id-BgglvZHN.d.mts +19 -0
  143. package/dist/request-id-BgglvZHN.d.mts.map +1 -0
  144. package/dist/request-logger-CWHbAzTE.d.mts +32 -0
  145. package/dist/request-logger-CWHbAzTE.d.mts.map +1 -0
  146. package/dist/router-builder-C799BAf0.d.mts +31 -0
  147. package/dist/router-builder-C799BAf0.d.mts.map +1 -0
  148. package/dist/session-N0hActOO.d.mts +70 -0
  149. package/dist/session-N0hActOO.d.mts.map +1 -0
  150. package/dist/spa-CrFR2_cz.d.mts +101 -0
  151. package/dist/spa-CrFR2_cz.d.mts.map +1 -0
  152. package/dist/upload-BueOnnLw.d.mts +79 -0
  153. package/dist/upload-BueOnnLw.d.mts.map +1 -0
  154. package/dist/validate-HwAyWTwH.d.mts +23 -0
  155. package/dist/validate-HwAyWTwH.d.mts.map +1 -0
  156. package/dist/views-DhQSXV2P.d.mts +176 -0
  157. package/dist/views-DhQSXV2P.d.mts.map +1 -0
  158. package/package.json +6 -9
  159. package/dist/adapter-DjL8ql5d.d.mts +0 -140
  160. package/dist/adapter-DjL8ql5d.d.mts.map +0 -1
  161. package/dist/app-module-Cotu9TIC.d.mts.map +0 -1
  162. package/dist/application-BVl6L8xo.mjs.map +0 -1
  163. package/dist/chunk-CVPG7JJl.mjs +0 -15
  164. package/dist/container-BBZLlK6y.mjs.map +0 -1
  165. package/dist/container-BJb34faa.d.mts.map +0 -1
  166. package/dist/core-qyPNtpKp.mjs +0 -121
  167. package/dist/core-qyPNtpKp.mjs.map +0 -1
  168. package/dist/decorators-C9_SN7ge.d.mts.map +0 -1
  169. package/dist/http/application.d.mts.map +0 -1
  170. package/dist/http/bootstrap.d.mts.map +0 -1
  171. package/dist/http/context.d.mts.map +0 -1
  172. package/dist/http/context.mjs.map +0 -1
  173. package/dist/http/middleware/cors.d.mts.map +0 -1
  174. package/dist/http/middleware/csrf.d.mts.map +0 -1
  175. package/dist/http/middleware/error-handler.d.mts.map +0 -1
  176. package/dist/http/middleware/helmet.d.mts.map +0 -1
  177. package/dist/http/middleware/rate-limit.d.mts.map +0 -1
  178. package/dist/http/middleware/request-id.d.mts.map +0 -1
  179. package/dist/http/middleware/request-logger.d.mts.map +0 -1
  180. package/dist/http/middleware/session.d.mts.map +0 -1
  181. package/dist/http/middleware/spa.d.mts.map +0 -1
  182. package/dist/http/middleware/upload.d.mts.map +0 -1
  183. package/dist/http/middleware/validate.d.mts.map +0 -1
  184. package/dist/http/middleware/views.d.mts.map +0 -1
  185. package/dist/http/router-builder.d.mts.map +0 -1
  186. package/dist/index-CwqjAF6I.d.mts +0 -112
  187. package/dist/index-CwqjAF6I.d.mts.map +0 -1
  188. package/dist/index.d.mts.map +0 -1
  189. package/dist/interfaces-DXjE8Re1.d.mts +0 -52
  190. package/dist/path-B4JcbwKX.d.mts.map +0 -1
  191. package/dist/plugin-Cvacmm7N.d.mts +0 -95
  192. package/dist/plugin-Cvacmm7N.d.mts.map +0 -1
@@ -0,0 +1,709 @@
1
+ /**
2
+ * @forinda/kickjs v4.0.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import "./container-DYYSu58w.mjs";
12
+ import { METADATA } from "./core/interfaces.mjs";
13
+ import "./core/logger.mjs";
14
+ import { c as pushClassMeta, l as pushMethodMeta } from "./metadata-VQM9wChy.mjs";
15
+ import "./core/decorators.mjs";
16
+ import "./core/cron.mjs";
17
+ import "./core/cache.mjs";
18
+ import "reflect-metadata";
19
+ //#region src/core/circuit-breaker.ts
20
+ /**
21
+ * Error thrown when the circuit is open and calls are being rejected.
22
+ */
23
+ var CircuitOpenError = class extends Error {
24
+ constructor(breakerName) {
25
+ super(`Circuit breaker "${breakerName}" is open — request rejected`);
26
+ this.breakerName = breakerName;
27
+ this.name = "CircuitOpenError";
28
+ }
29
+ };
30
+ var CircuitBreaker = class {
31
+ state = "closed";
32
+ failures = 0;
33
+ successes = 0;
34
+ halfOpenAttempts = 0;
35
+ lastFailure;
36
+ openedAt;
37
+ failureThreshold;
38
+ resetTimeout;
39
+ halfOpenMax;
40
+ constructor(name, options) {
41
+ this.name = name;
42
+ this.failureThreshold = options.failureThreshold;
43
+ this.resetTimeout = options.resetTimeout;
44
+ this.halfOpenMax = options.halfOpenMax ?? 1;
45
+ }
46
+ /**
47
+ * Execute an async function through the circuit breaker.
48
+ * Throws `CircuitOpenError` if the circuit is open.
49
+ */
50
+ async execute(fn) {
51
+ this.maybeTransitionToHalfOpen();
52
+ if (this.state === "open") throw new CircuitOpenError(this.name);
53
+ if (this.state === "half_open" && this.halfOpenAttempts >= this.halfOpenMax) throw new CircuitOpenError(this.name);
54
+ if (this.state === "half_open") this.halfOpenAttempts++;
55
+ try {
56
+ const result = await fn();
57
+ this.onSuccess();
58
+ return result;
59
+ } catch (error) {
60
+ this.onFailure();
61
+ throw error;
62
+ }
63
+ }
64
+ /** Returns the current circuit state. */
65
+ getState() {
66
+ this.maybeTransitionToHalfOpen();
67
+ return this.state;
68
+ }
69
+ /** Returns current statistics. */
70
+ getStats() {
71
+ this.maybeTransitionToHalfOpen();
72
+ return {
73
+ failures: this.failures,
74
+ successes: this.successes,
75
+ state: this.state,
76
+ ...this.lastFailure ? { lastFailure: this.lastFailure } : {}
77
+ };
78
+ }
79
+ /** Manually reset the circuit breaker to CLOSED state. */
80
+ reset() {
81
+ this.state = "closed";
82
+ this.failures = 0;
83
+ this.successes = 0;
84
+ this.halfOpenAttempts = 0;
85
+ this.lastFailure = void 0;
86
+ this.openedAt = void 0;
87
+ }
88
+ onSuccess() {
89
+ if (this.state === "half_open") {
90
+ this.state = "closed";
91
+ this.failures = 0;
92
+ this.halfOpenAttempts = 0;
93
+ this.openedAt = void 0;
94
+ }
95
+ this.successes++;
96
+ }
97
+ onFailure() {
98
+ this.failures++;
99
+ this.lastFailure = /* @__PURE__ */ new Date();
100
+ if (this.state === "half_open") {
101
+ this.state = "open";
102
+ this.openedAt = Date.now();
103
+ this.halfOpenAttempts = 0;
104
+ } else if (this.state === "closed" && this.failures >= this.failureThreshold) {
105
+ this.state = "open";
106
+ this.openedAt = Date.now();
107
+ }
108
+ }
109
+ maybeTransitionToHalfOpen() {
110
+ if (this.state === "open" && this.openedAt != null) {
111
+ if (Date.now() - this.openedAt >= this.resetTimeout) {
112
+ this.state = "half_open";
113
+ this.halfOpenAttempts = 0;
114
+ }
115
+ }
116
+ }
117
+ };
118
+ //#endregion
119
+ //#region src/core/context-decorator.ts
120
+ /**
121
+ * Define a typed context contributor.
122
+ *
123
+ * The returned function works as a method or class decorator:
124
+ *
125
+ * ```ts
126
+ * const LoadTenant = defineContextDecorator({
127
+ * key: 'tenant',
128
+ * deps: { tenants: TenantsRepo },
129
+ * resolve: (ctx, { tenants }) => tenants.findByHost(ctx.requestId),
130
+ * })
131
+ *
132
+ * @LoadTenant
133
+ * @Get('/me')
134
+ * me(ctx: RequestContext) {
135
+ * ctx.get('tenant') // typed via ContextMeta
136
+ * }
137
+ * ```
138
+ *
139
+ * For non-decorator registration (module/adapter/bootstrap), pass
140
+ * `LoadTenant.registration` into the appropriate contributors list.
141
+ *
142
+ * **No runtime behaviour is wired in Phase 1.** This factory only writes
143
+ * metadata; the topo-sort, runner, and HTTP integration land in later
144
+ * phases. See `architecture.md` §20 for the full pipeline plan.
145
+ */
146
+ function defineContextDecorator(spec) {
147
+ const registration = Object.freeze({
148
+ key: spec.key,
149
+ deps: Object.freeze({ ...spec.deps ?? {} }),
150
+ dependsOn: Object.freeze([...spec.dependsOn ?? []]),
151
+ optional: spec.optional ?? false,
152
+ onError: spec.onError,
153
+ resolve: spec.resolve
154
+ });
155
+ function decorator(target, propertyKey, _descriptor) {
156
+ if (propertyKey === void 0) pushClassMeta(METADATA.CLASS_CONTRIBUTORS, target, registration);
157
+ else {
158
+ const constructor = target.constructor;
159
+ pushMethodMeta(METADATA.METHOD_CONTRIBUTORS, constructor, String(propertyKey), registration);
160
+ }
161
+ }
162
+ Object.defineProperty(decorator, "registration", {
163
+ value: registration,
164
+ writable: false,
165
+ enumerable: true,
166
+ configurable: false
167
+ });
168
+ return decorator;
169
+ }
170
+ //#endregion
171
+ //#region src/core/context-errors.ts
172
+ /**
173
+ * Errors thrown by the Context Contributor pipeline.
174
+ *
175
+ * All three are startup-time errors raised during pipeline build (topo-sort
176
+ * + validation), not per-request — a misconfigured app fails to boot rather
177
+ * than fails a request. Per the locked design in `architecture.md` §20.4,
178
+ * the pipeline is validated once when each route is mounted and the
179
+ * resolved order is cached on the route.
180
+ */
181
+ /**
182
+ * A contributor declared `dependsOn: ['<key>']` but no other contributor
183
+ * (at any precedence level) produces that key for the same route.
184
+ *
185
+ * @example
186
+ * ```text
187
+ * MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id
188
+ * ```
189
+ */
190
+ var MissingContributorError = class extends Error {
191
+ key;
192
+ dependent;
193
+ route;
194
+ constructor(key, dependent, route) {
195
+ const where = route ? ` on route ${route}` : "";
196
+ super(`Missing context contributor '${key}' required by '${dependent}'${where}`);
197
+ this.name = "MissingContributorError";
198
+ this.key = key;
199
+ this.dependent = dependent;
200
+ this.route = route;
201
+ }
202
+ };
203
+ /**
204
+ * Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field
205
+ * lists the keys in the order they form the loop, with the first key
206
+ * repeated at the end so the path reads naturally.
207
+ *
208
+ * @example
209
+ * ```text
210
+ * ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant
211
+ * ```
212
+ */
213
+ var ContributorCycleError = class extends Error {
214
+ cycle;
215
+ route;
216
+ constructor(cycle, route) {
217
+ const where = route ? ` on route ${route}` : "";
218
+ super(`Cycle in context contributors${where}: ${cycle.join(" → ")}`);
219
+ this.name = "ContributorCycleError";
220
+ this.cycle = Object.freeze([...cycle]);
221
+ this.route = route;
222
+ }
223
+ };
224
+ /**
225
+ * Two contributors at the same precedence level both produce the same key
226
+ * for the same route. Precedence resolution (method > class > module >
227
+ * adapter > global, per architecture.md §20.4) silently drops
228
+ * lower-precedence duplicates; this error fires only when ties occur
229
+ * within a single level — e.g., two method-level decorators declaring
230
+ * `key: 'tenant'`.
231
+ *
232
+ * `sources` is best-effort identifying labels for each conflicting
233
+ * registration (typically the decorator's call site or registering
234
+ * module/adapter name).
235
+ *
236
+ * @example
237
+ * ```text
238
+ * DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain
239
+ * ```
240
+ */
241
+ var DuplicateContributorError = class extends Error {
242
+ key;
243
+ sources;
244
+ constructor(key, sources) {
245
+ super(`Duplicate context contributor for key '${key}' at the same precedence level. Sources: ${sources.join(", ")}`);
246
+ this.name = "DuplicateContributorError";
247
+ this.key = key;
248
+ this.sources = Object.freeze([...sources]);
249
+ }
250
+ };
251
+ //#endregion
252
+ //#region src/core/contributor-pipeline.ts
253
+ /** Precedence-ranked source list. Index = precedence; method (0) wins ties. */
254
+ const PRECEDENCE_ORDER = [
255
+ "method",
256
+ "class",
257
+ "module",
258
+ "adapter",
259
+ "global"
260
+ ];
261
+ /**
262
+ * Build, validate, and topo-sort a contributor pipeline.
263
+ *
264
+ * Pipeline:
265
+ *
266
+ * 1. Group sources by precedence (method > class > module > adapter > global).
267
+ * 2. Within each precedence level, two contributors with the same `key`
268
+ * raise {@link DuplicateContributorError}.
269
+ * 3. Across levels, the highest-precedence contributor wins each key
270
+ * (lower-precedence duplicates are silently dropped — that is the
271
+ * documented override mechanism, not an error).
272
+ * 4. Every key referenced by `dependsOn` must be produced by the
273
+ * surviving set, otherwise {@link MissingContributorError}.
274
+ * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after
275
+ * the queue drains form a cycle → {@link ContributorCycleError}
276
+ * with a reconstructed path.
277
+ *
278
+ * Pure function — no DI, no I/O. Safe to call once at startup per
279
+ * route and cache the result.
280
+ */
281
+ function buildPipeline(sources, options = {}) {
282
+ const route = options.route;
283
+ const bySource = /* @__PURE__ */ new Map();
284
+ for (const src of PRECEDENCE_ORDER) bySource.set(src, []);
285
+ for (const entry of sources) bySource.get(entry.source).push(entry);
286
+ const winners = /* @__PURE__ */ new Map();
287
+ for (const src of PRECEDENCE_ORDER) {
288
+ const rows = bySource.get(src);
289
+ const keysAtThisLevel = /* @__PURE__ */ new Map();
290
+ for (const row of rows) {
291
+ const key = row.registration.key;
292
+ const existing = keysAtThisLevel.get(key) ?? [];
293
+ existing.push(row);
294
+ keysAtThisLevel.set(key, existing);
295
+ }
296
+ for (const [key, rowsForKey] of keysAtThisLevel) {
297
+ if (rowsForKey.length > 1) throw new DuplicateContributorError(key, rowsForKey.map((r, i) => r.label ?? `${src}#${i}`));
298
+ if (!winners.has(key)) winners.set(key, rowsForKey[0]);
299
+ }
300
+ }
301
+ const survivors = [...winners.values()].map((r) => r.registration);
302
+ const allKeys = new Set(survivors.map((r) => r.key));
303
+ for (const reg of survivors) for (const dep of reg.dependsOn) if (!allKeys.has(dep)) throw new MissingContributorError(dep, reg.key, route);
304
+ const sorted = topoSort(survivors, route);
305
+ return Object.freeze({
306
+ contributors: Object.freeze(sorted),
307
+ keys: allKeys
308
+ });
309
+ }
310
+ /**
311
+ * Kahn's algorithm with deterministic ordering on ties.
312
+ *
313
+ * Nodes with no remaining incoming edges enter the queue in input
314
+ * order. Cycles surface as nodes still present after the queue
315
+ * drains; we reconstruct one cycle path for diagnostics.
316
+ */
317
+ function topoSort(registrations, route) {
318
+ const indegree = /* @__PURE__ */ new Map();
319
+ const dependents = /* @__PURE__ */ new Map();
320
+ const byKey = /* @__PURE__ */ new Map();
321
+ for (const reg of registrations) {
322
+ indegree.set(reg.key, reg.dependsOn.length);
323
+ byKey.set(reg.key, reg);
324
+ }
325
+ for (const reg of registrations) for (const dep of reg.dependsOn) {
326
+ const list = dependents.get(dep) ?? [];
327
+ list.push(reg);
328
+ dependents.set(dep, list);
329
+ }
330
+ const queue = [];
331
+ for (const reg of registrations) if (indegree.get(reg.key) === 0) queue.push(reg);
332
+ const sorted = [];
333
+ while (queue.length > 0) {
334
+ const node = queue.shift();
335
+ sorted.push(node);
336
+ for (const dependent of dependents.get(node.key) ?? []) {
337
+ const next = (indegree.get(dependent.key) ?? 0) - 1;
338
+ indegree.set(dependent.key, next);
339
+ if (next === 0) queue.push(dependent);
340
+ }
341
+ }
342
+ if (sorted.length !== registrations.length) throw new ContributorCycleError(reconstructCycle$1(registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0), byKey), route);
343
+ return sorted;
344
+ }
345
+ /**
346
+ * Reconstruct one cycle path from the residual graph.
347
+ *
348
+ * Walks from any remaining node, following its first dependency that's
349
+ * still in the residual set, until we revisit a node. The path returned
350
+ * starts and ends with the same key so the message reads naturally:
351
+ * `tenant → project → tenant`.
352
+ */
353
+ function reconstructCycle$1(residual, byKey) {
354
+ const residualKeys = new Set(residual.map((r) => r.key));
355
+ const start = residual[0].key;
356
+ const path = [start];
357
+ const seen = new Set([start]);
358
+ let cursor = start;
359
+ while (true) {
360
+ const nextDep = byKey.get(cursor).dependsOn.find((d) => residualKeys.has(d));
361
+ if (nextDep === void 0) break;
362
+ if (seen.has(nextDep)) {
363
+ const cycleStart = path.indexOf(nextDep);
364
+ return [...path.slice(cycleStart), nextDep];
365
+ }
366
+ path.push(nextDep);
367
+ seen.add(nextDep);
368
+ cursor = nextDep;
369
+ }
370
+ return path;
371
+ }
372
+ //#endregion
373
+ //#region src/core/contributor-runner.ts
374
+ /**
375
+ * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.
376
+ *
377
+ * Sequential — one contributor at a time, in the topo order chosen at
378
+ * pipeline-build time. Per `architecture.md` §20.10, V1 does not run
379
+ * contributors in parallel even within the same topo level; that is a
380
+ * V2 follow-up gated on profiling.
381
+ *
382
+ * ## Error matrix (architecture.md §20.9)
383
+ *
384
+ * | resolve outcome | optional | onError defined | runner behaviour |
385
+ * |-----------------|----------|-----------------|--------------------------------------------------|
386
+ * | throws | true | — | skip; `ctx.get(key)` remains undefined |
387
+ * | throws | false | yes | call hook; returned value (if any) stored |
388
+ * | throws | false | no | propagate the original error |
389
+ * | hook throws | — | yes | propagate the new error |
390
+ * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |
391
+ * | resolves | — | — | `ctx.set(key, value)` |
392
+ *
393
+ * Container.resolve() throwing while building `deps` is treated as a
394
+ * resolve-side throw and flows through the same matrix — adopters who
395
+ * need different behaviour for missing-DI vs. data-fetch failures can
396
+ * wrap the container access inside their own `resolve()`.
397
+ */
398
+ async function runContributors(options) {
399
+ const { pipeline, ctx, container } = options;
400
+ for (const reg of pipeline.contributors) await runOne(reg, ctx, container);
401
+ }
402
+ async function runOne(reg, ctx, container) {
403
+ let value;
404
+ try {
405
+ const deps = resolveDeps(reg, container);
406
+ value = await reg.resolve(ctx, deps);
407
+ } catch (err) {
408
+ if (reg.optional) return;
409
+ if (reg.onError) {
410
+ const replacement = await reg.onError(err, ctx);
411
+ if (replacement === void 0) return;
412
+ ctx.set(reg.key, replacement);
413
+ return;
414
+ }
415
+ throw err;
416
+ }
417
+ ctx.set(reg.key, value);
418
+ }
419
+ /**
420
+ * Resolve a contributor's declared dependencies through the container,
421
+ * preserving the property names from the spec so `resolve(ctx, deps)`
422
+ * receives exactly the shape the user wrote.
423
+ *
424
+ * Empty `deps` produces an empty object — `resolve()` always sees an
425
+ * object, never `undefined`.
426
+ */
427
+ function resolveDeps(reg, container) {
428
+ const out = {};
429
+ for (const [key, token] of Object.entries(reg.deps)) out[key] = container.resolve(token);
430
+ return out;
431
+ }
432
+ //#endregion
433
+ //#region src/core/mount-sort.ts
434
+ /**
435
+ * Two items in the same mount set declared the same `name`. Plugin/adapter
436
+ * names must be unique so `dependsOn` references resolve unambiguously.
437
+ */
438
+ var DuplicateMountNameError = class extends Error {
439
+ kind;
440
+ mountName;
441
+ constructor(kind, mountName) {
442
+ super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`);
443
+ this.name = "DuplicateMountNameError";
444
+ this.kind = kind;
445
+ this.mountName = mountName;
446
+ }
447
+ };
448
+ /**
449
+ * A `dependsOn` entry references a plugin/adapter that isn't in the
450
+ * current set. The dependency might not be installed, might be misspelled,
451
+ * or might live in a different mount set (plugin referencing an adapter,
452
+ * or vice versa — they sort independently).
453
+ */
454
+ var MissingMountDepError = class extends Error {
455
+ kind;
456
+ missing;
457
+ dependent;
458
+ constructor(kind, missing, dependent) {
459
+ super(`Missing ${kind} dependency '${missing}' required by '${dependent}' — is the ${kind} installed and named correctly?`);
460
+ this.name = "MissingMountDepError";
461
+ this.kind = kind;
462
+ this.missing = missing;
463
+ this.dependent = dependent;
464
+ }
465
+ };
466
+ /**
467
+ * The `dependsOn` declarations form a cycle. Boot fails so the cycle
468
+ * can't poison live traffic. The `cycle` field reports one path through
469
+ * the offending nodes for diagnostics — formatted `A → B → C → A`.
470
+ */
471
+ var MountCycleError = class extends Error {
472
+ kind;
473
+ cycle;
474
+ constructor(kind, cycle) {
475
+ super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(" → ")}`);
476
+ this.name = "MountCycleError";
477
+ this.kind = kind;
478
+ this.cycle = Object.freeze([...cycle]);
479
+ }
480
+ };
481
+ /**
482
+ * Topologically sort `items` so every item with `dependsOn: ['X']` mounts
483
+ * after `X`. Items without `dependsOn` keep their input order via Kahn's
484
+ * algorithm with a FIFO queue seeded in input order — preserves the
485
+ * historical "plugins/adapters mount in declaration order" behaviour for
486
+ * any set that doesn't use `dependsOn`.
487
+ *
488
+ * @param items - mountable items, e.g. plugins or adapters
489
+ * @param kind - 'plugin' | 'adapter', used in error messages
490
+ * @returns a new array in valid mount order
491
+ * @throws {DuplicateMountNameError} two items share a name
492
+ * @throws {MissingMountDepError} a `dependsOn` references an unknown name
493
+ * @throws {MountCycleError} the dep graph contains a cycle
494
+ */
495
+ function mountSort(items, kind) {
496
+ const byName = /* @__PURE__ */ new Map();
497
+ for (const item of items) {
498
+ if (byName.has(item.name)) throw new DuplicateMountNameError(kind, item.name);
499
+ byName.set(item.name, item);
500
+ }
501
+ const indegree = /* @__PURE__ */ new Map();
502
+ const dependents = /* @__PURE__ */ new Map();
503
+ for (const item of items) indegree.set(item.name, item.dependsOn?.length ?? 0);
504
+ for (const item of items) for (const dep of item.dependsOn ?? []) {
505
+ if (!byName.has(dep)) throw new MissingMountDepError(kind, dep, item.name);
506
+ const list = dependents.get(dep) ?? [];
507
+ list.push(item);
508
+ dependents.set(dep, list);
509
+ }
510
+ const queue = [];
511
+ for (const item of items) if (indegree.get(item.name) === 0) queue.push(item);
512
+ const sorted = [];
513
+ while (queue.length > 0) {
514
+ const node = queue.shift();
515
+ sorted.push(node);
516
+ for (const dependent of dependents.get(node.name) ?? []) {
517
+ const next = (indegree.get(dependent.name) ?? 0) - 1;
518
+ indegree.set(dependent.name, next);
519
+ if (next === 0) queue.push(dependent);
520
+ }
521
+ }
522
+ if (sorted.length !== items.length) throw new MountCycleError(kind, reconstructCycle(items.filter((it) => (indegree.get(it.name) ?? 0) > 0), byName));
523
+ return sorted;
524
+ }
525
+ /**
526
+ * Walk the residual graph to find one cycle path for diagnostics.
527
+ * Starts from the first remaining node and follows the first dep that's
528
+ * still in the residual set until we revisit a node. Returns a path
529
+ * starting and ending with the same name so the message reads naturally
530
+ * (`A → B → C → A`).
531
+ */
532
+ function reconstructCycle(residual, byName) {
533
+ const residualNames = new Set(residual.map((r) => r.name));
534
+ const start = residual[0].name;
535
+ const path = [start];
536
+ const seen = new Set([start]);
537
+ let cursor = start;
538
+ while (true) {
539
+ const nextDep = byName.get(cursor).dependsOn?.find((d) => residualNames.has(d));
540
+ if (nextDep === void 0) break;
541
+ if (seen.has(nextDep)) {
542
+ const cycleStart = path.indexOf(nextDep);
543
+ return [...path.slice(cycleStart), nextDep];
544
+ }
545
+ path.push(nextDep);
546
+ seen.add(nextDep);
547
+ cursor = nextDep;
548
+ }
549
+ return path;
550
+ }
551
+ //#endregion
552
+ //#region src/core/define-plugin.ts
553
+ const mergeConfig$1 = (defaults, overrides) => ({
554
+ ...defaults ?? {},
555
+ ...overrides ?? {}
556
+ });
557
+ const composeName$1 = (base, scope) => `${base}:${scope}`;
558
+ /**
559
+ * Build a {@link KickPlugin} factory from a typed definition. See
560
+ * `architecture.md` §21.2.2 for the design rationale.
561
+ *
562
+ * @example
563
+ * ```ts
564
+ * const FlagsPlugin = definePlugin<FlagsConfig>({
565
+ * name: 'FlagsPlugin',
566
+ * defaults: { defaultTtl: 60_000 },
567
+ * build(config) {
568
+ * return {
569
+ * register(container) {
570
+ * container.registerInstance(FLAGS, makeProvider(config))
571
+ * },
572
+ * }
573
+ * },
574
+ * })
575
+ *
576
+ * bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })
577
+ * ```
578
+ */
579
+ function definePlugin(options) {
580
+ const buildSync = (instanceName, scoped, overrides) => {
581
+ const config = mergeConfig$1(options.defaults, overrides);
582
+ const built = options.build(config, {
583
+ name: instanceName,
584
+ scoped
585
+ });
586
+ built.name = instanceName;
587
+ return built;
588
+ };
589
+ const buildAsync = (instanceName, opts) => {
590
+ let inner;
591
+ const ensureInner = async (container) => {
592
+ if (inner) return inner;
593
+ const deps = (opts.inject ?? []).map((tok) => container.resolve(tok));
594
+ inner = buildSync(instanceName, false, await opts.useFactory(...deps));
595
+ return inner;
596
+ };
597
+ return {
598
+ name: instanceName,
599
+ async onReady(container) {
600
+ const built = await ensureInner(container);
601
+ built.register?.(container);
602
+ await built.onReady?.(container);
603
+ },
604
+ async shutdown() {
605
+ await inner?.shutdown?.();
606
+ }
607
+ };
608
+ };
609
+ const factory = ((config) => buildSync(options.name, false, config));
610
+ factory.scoped = (scopeName, config) => buildSync(composeName$1(options.name, scopeName), true, config);
611
+ factory.async = (opts) => buildAsync(options.name, opts);
612
+ Object.defineProperty(factory, "definition", { value: Object.freeze({ ...options }) });
613
+ return factory;
614
+ }
615
+ //#endregion
616
+ //#region src/core/define-adapter.ts
617
+ const mergeConfig = (defaults, overrides) => ({
618
+ ...defaults ?? {},
619
+ ...overrides ?? {}
620
+ });
621
+ const composeName = (base, scope) => `${base}:${scope}`;
622
+ /**
623
+ * Build an {@link AppAdapter} factory from a typed definition. See
624
+ * `architecture.md` §21.3.4 for migration guidance — most first-party
625
+ * adapter packages collapse to a single `defineAdapter()` call after this
626
+ * lands.
627
+ *
628
+ * @example
629
+ * ```ts
630
+ * const TenantAdapter = defineAdapter<TenantConfig>({
631
+ * name: 'TenantAdapter',
632
+ * defaults: { strategy: 'header', required: true },
633
+ * build: (config) => ({
634
+ * middleware: () => [tenantResolverMiddleware(config)],
635
+ * beforeStart: ({ container }) => registerTenantFactory(container, config),
636
+ * }),
637
+ * })
638
+ *
639
+ * bootstrap({
640
+ * adapters: [
641
+ * TenantAdapter({ strategy: 'subdomain' }),
642
+ * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),
643
+ * ],
644
+ * })
645
+ * ```
646
+ */
647
+ function defineAdapter(options) {
648
+ const buildSync = (instanceName, scoped, overrides) => {
649
+ const config = mergeConfig(options.defaults, overrides);
650
+ const built = options.build(config, {
651
+ name: instanceName,
652
+ scoped
653
+ });
654
+ built.name = instanceName;
655
+ return built;
656
+ };
657
+ const buildAsync = (instanceName, opts) => {
658
+ let inner;
659
+ return {
660
+ name: instanceName,
661
+ async beforeStart(ctx) {
662
+ const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok));
663
+ inner = buildSync(instanceName, false, await opts.useFactory(...deps));
664
+ await inner.beforeStart?.(ctx);
665
+ },
666
+ async afterStart(ctx) {
667
+ await inner?.afterStart?.(ctx);
668
+ },
669
+ async shutdown() {
670
+ await inner?.shutdown?.();
671
+ },
672
+ async onHealthCheck() {
673
+ return await inner?.onHealthCheck?.() ?? {
674
+ name: instanceName,
675
+ status: "up"
676
+ };
677
+ }
678
+ };
679
+ };
680
+ const factory = ((config) => buildSync(options.name, false, config));
681
+ factory.scoped = (scopeName, config) => buildSync(composeName(options.name, scopeName), true, config);
682
+ factory.async = (opts) => buildAsync(options.name, opts);
683
+ Object.defineProperty(factory, "definition", { value: Object.freeze({ ...options }) });
684
+ return factory;
685
+ }
686
+ //#endregion
687
+ //#region src/core/augmentation.ts
688
+ /**
689
+ * Advertise an augmentable interface so `kick typegen` can list it in
690
+ * `.kickjs/types/augmentations.d.ts`. Runtime no-op — exists purely as
691
+ * a static marker for the typegen scanner to discover.
692
+ *
693
+ * @example
694
+ * ```ts
695
+ * import { defineAugmentation } from '@forinda/kickjs'
696
+ *
697
+ * export interface FeatureFlags {} // augmentable
698
+ *
699
+ * defineAugmentation('FeatureFlags', {
700
+ * description: 'Flags consumed by FlagsPlugin',
701
+ * example: '{ beta: boolean; rolloutPercentage: number }',
702
+ * })
703
+ * ```
704
+ */
705
+ function defineAugmentation(name, meta) {}
706
+ //#endregion
707
+ export { MissingMountDepError as a, runContributors as c, DuplicateContributorError as d, MissingContributorError as f, CircuitOpenError as h, DuplicateMountNameError as i, buildPipeline as l, CircuitBreaker as m, defineAdapter as n, MountCycleError as o, defineContextDecorator as p, definePlugin as r, mountSort as s, defineAugmentation as t, ContributorCycleError as u };
708
+
709
+ //# sourceMappingURL=core-DBcoqPHM.mjs.map