@forinda/kickjs 10.1.0 → 10.2.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 (210) hide show
  1. package/dist/adapter-C5I5e_-i.d.mts +4866 -0
  2. package/dist/adapter-C5I5e_-i.d.mts.map +1 -0
  3. package/dist/allowed-hosts-D6qcuK5I.d.mts +46 -0
  4. package/dist/allowed-hosts-D6qcuK5I.d.mts.map +1 -0
  5. package/dist/{app-module-DCA65GZZ.d.mts → app-module-Ftz6m7SO.d.mts} +8 -2
  6. package/dist/app-module-Ftz6m7SO.d.mts.map +1 -0
  7. package/dist/application-Ch5jT4fj.mjs +14 -0
  8. package/dist/application-Ch5jT4fj.mjs.map +1 -0
  9. package/dist/bootstrap-D56HIq1N.mjs +12 -0
  10. package/dist/{bootstrap-BdyBlBMe.mjs.map → bootstrap-D56HIq1N.mjs.map} +1 -1
  11. package/dist/bounded-counters-B9dzk5o_.mjs +12 -0
  12. package/dist/bounded-counters-B9dzk5o_.mjs.map +1 -0
  13. package/dist/breach-padding-C-Dnq8CS.d.mts +39 -0
  14. package/dist/breach-padding-C-Dnq8CS.d.mts.map +1 -0
  15. package/dist/{client-ip-BbLDp03S.mjs → client-ip-lYnBU2PR.mjs} +2 -2
  16. package/dist/{client-ip-BbLDp03S.mjs.map → client-ip-lYnBU2PR.mjs.map} +1 -1
  17. package/dist/config/index.d.mts +1 -1
  18. package/dist/config/index.mjs +2 -2
  19. package/dist/config-BfImCyaG.mjs +12 -0
  20. package/dist/{config-CJiGeOca.mjs.map → config-BfImCyaG.mjs.map} +1 -1
  21. package/dist/{container-CS9v9UFU.mjs → container-C2aTj8Cb.mjs} +3 -3
  22. package/dist/{container-CS9v9UFU.mjs.map → container-C2aTj8Cb.mjs.map} +1 -1
  23. package/dist/context-C6iKf9hN.mjs +12 -0
  24. package/dist/context-C6iKf9hN.mjs.map +1 -0
  25. package/dist/{context-errors-7C5TBYn7.mjs → context-errors-6psUheqc.mjs} +2 -2
  26. package/dist/{context-errors-7C5TBYn7.mjs.map → context-errors-6psUheqc.mjs.map} +1 -1
  27. package/dist/{contributor-runner-DBpRR5dl.mjs → contributor-runner-Bn-ipSS5.mjs} +3 -3
  28. package/dist/{contributor-runner-DBpRR5dl.mjs.map → contributor-runner-Bn-ipSS5.mjs.map} +1 -1
  29. package/dist/core/adapter.d.mts +1 -1
  30. package/dist/core/adapter.mjs +1 -1
  31. package/dist/core/app-module.d.mts +1 -1
  32. package/dist/core/app-module.mjs +1 -1
  33. package/dist/core/cache.mjs +1 -1
  34. package/dist/core/container.mjs +2 -2
  35. package/dist/core/cron.mjs +2 -2
  36. package/dist/core/decorators.d.mts +1 -1
  37. package/dist/core/decorators.mjs +2 -2
  38. package/dist/core/errors.mjs +2 -2
  39. package/dist/core/errors.mjs.map +1 -1
  40. package/dist/core/interfaces.mjs +1 -1
  41. package/dist/core/logger.mjs +1 -1
  42. package/dist/core/path.mjs +1 -1
  43. package/dist/core/plugin.d.mts +1 -1
  44. package/dist/core/plugin.mjs +1 -1
  45. package/dist/core/reactivity.mjs +1 -1
  46. package/dist/core-CFXpwc7m.mjs +12 -0
  47. package/dist/{core-B0JmdBvX.mjs.map → core-CFXpwc7m.mjs.map} +1 -1
  48. package/dist/{cors-CsibNTQ6.d.mts → cors-2Bwhyhpt.d.mts} +4 -1
  49. package/dist/{cors-CsibNTQ6.d.mts.map → cors-2Bwhyhpt.d.mts.map} +1 -1
  50. package/dist/csrf-C3RRSCMs.mjs +12 -0
  51. package/dist/csrf-C3RRSCMs.mjs.map +1 -0
  52. package/dist/{csrf-C73UkRgc.d.mts → csrf-Cy1meSpf.d.mts} +27 -3
  53. package/dist/csrf-Cy1meSpf.d.mts.map +1 -0
  54. package/dist/decorate-DkxaoRo5.mjs +13 -0
  55. package/dist/decorate-DkxaoRo5.mjs.map +1 -0
  56. package/dist/{decorators-BxNSz9Qt.d.mts → decorators-DaQUNXOn.d.mts} +2 -2
  57. package/dist/{decorators-BxNSz9Qt.d.mts.map → decorators-DaQUNXOn.d.mts.map} +1 -1
  58. package/dist/{define-adapter-BLKlUbSL.mjs → define-adapter-BRJ6lXkV.mjs} +2 -2
  59. package/dist/{define-adapter-BLKlUbSL.mjs.map → define-adapter-BRJ6lXkV.mjs.map} +1 -1
  60. package/dist/{disposables-CuY2S3bw.mjs → disposables-5nFqc1aC.mjs} +2 -2
  61. package/dist/{disposables-CuY2S3bw.mjs.map → disposables-5nFqc1aC.mjs.map} +1 -1
  62. package/dist/errors-By6UueCm.d.mts.map +1 -1
  63. package/dist/handler-Dl_1fGxE.mjs +12 -0
  64. package/dist/handler-Dl_1fGxE.mjs.map +1 -0
  65. package/dist/{helmet-C2QEU6S-.d.mts → helmet-CEOmo516.d.mts} +4 -1
  66. package/dist/helmet-CEOmo516.d.mts.map +1 -0
  67. package/dist/host-DTQ5pZgg.mjs +12 -0
  68. package/dist/host-DTQ5pZgg.mjs.map +1 -0
  69. package/dist/http/application.d.mts +2 -2
  70. package/dist/http/application.mjs +2 -2
  71. package/dist/http/bootstrap.d.mts +1 -1
  72. package/dist/http/bootstrap.mjs +2 -2
  73. package/dist/http/context.d.mts +2 -2
  74. package/dist/http/context.mjs +2 -2
  75. package/dist/http/middleware/allowed-hosts.d.mts +3 -0
  76. package/dist/http/middleware/allowed-hosts.mjs +12 -0
  77. package/dist/http/middleware/allowed-hosts.mjs.map +1 -0
  78. package/dist/http/middleware/breach-padding.d.mts +3 -0
  79. package/dist/http/middleware/breach-padding.mjs +12 -0
  80. package/dist/http/middleware/breach-padding.mjs.map +1 -0
  81. package/dist/http/middleware/cors.d.mts +1 -1
  82. package/dist/http/middleware/cors.mjs +2 -2
  83. package/dist/http/middleware/cors.mjs.map +1 -1
  84. package/dist/http/middleware/csrf.d.mts +2 -2
  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/error-handler.mjs.map +1 -1
  89. package/dist/http/middleware/helmet.d.mts +1 -1
  90. package/dist/http/middleware/helmet.mjs +2 -2
  91. package/dist/http/middleware/helmet.mjs.map +1 -1
  92. package/dist/http/middleware/rate-limit.d.mts +2 -2
  93. package/dist/http/middleware/rate-limit.mjs +2 -2
  94. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  95. package/dist/http/middleware/request-id.mjs +2 -2
  96. package/dist/http/middleware/request-id.mjs.map +1 -1
  97. package/dist/http/middleware/request-logger.mjs +2 -2
  98. package/dist/http/middleware/session.d.mts +2 -2
  99. package/dist/http/middleware/session.mjs +2 -2
  100. package/dist/http/middleware/session.mjs.map +1 -1
  101. package/dist/http/middleware/spa.d.mts +1 -1
  102. package/dist/http/middleware/spa.mjs +2 -2
  103. package/dist/http/middleware/upload.d.mts +1 -1
  104. package/dist/http/middleware/upload.mjs +2 -2
  105. package/dist/http/middleware/validate.d.mts +2 -2
  106. package/dist/http/middleware/validate.mjs +2 -2
  107. package/dist/http/middleware/validate.mjs.map +1 -1
  108. package/dist/http/middleware/views.d.mts +1 -1
  109. package/dist/http/middleware/views.mjs +2 -2
  110. package/dist/http/query/index.mjs +2 -2
  111. package/dist/http/router-builder.d.mts +1 -1
  112. package/dist/http/router-builder.mjs +2 -2
  113. package/dist/http/runtimes/fastify.d.mts +5 -1
  114. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  115. package/dist/http/runtimes/fastify.mjs +3 -3
  116. package/dist/http/runtimes/fastify.mjs.map +1 -1
  117. package/dist/http/runtimes/h3-web.mjs +1 -1
  118. package/dist/http/runtimes/h3.d.mts +1 -1
  119. package/dist/http/runtimes/h3.d.mts.map +1 -1
  120. package/dist/http/runtimes/h3.mjs +2 -2
  121. package/dist/http/runtimes/h3.mjs.map +1 -1
  122. package/dist/{index-CNHSbZTE.d.mts → index-CuiWSnZL.d.mts} +3 -2
  123. package/dist/index-CuiWSnZL.d.mts.map +1 -0
  124. package/dist/index.d.mts +16 -18
  125. package/dist/index.mjs +6 -2
  126. package/dist/index.mjs.map +1 -1
  127. package/dist/is-production-tnFh6NCj.mjs +12 -0
  128. package/dist/is-production-tnFh6NCj.mjs.map +1 -0
  129. package/dist/{jobs-BQ4t3TAb.mjs → jobs-lLcPhIqq.mjs} +3 -3
  130. package/dist/{jobs-BQ4t3TAb.mjs.map → jobs-lLcPhIqq.mjs.map} +1 -1
  131. package/dist/kv-stores-_wz4DEiw.mjs +12 -0
  132. package/dist/kv-stores-_wz4DEiw.mjs.map +1 -0
  133. package/dist/{metadata-zvd6AWkE.mjs → metadata-Tc6jhIBi.mjs} +2 -2
  134. package/dist/{metadata-zvd6AWkE.mjs.map → metadata-Tc6jhIBi.mjs.map} +1 -1
  135. package/dist/{observers-DZgs48UM.mjs → observers-IGga6yut.mjs} +2 -2
  136. package/dist/{observers-DZgs48UM.mjs.map → observers-IGga6yut.mjs.map} +1 -1
  137. package/dist/{query-B_k9qn0R.mjs → query-AnbWMCd6.mjs} +2 -2
  138. package/dist/{query-B_k9qn0R.mjs.map → query-AnbWMCd6.mjs.map} +1 -1
  139. package/dist/{rate-limit-Bwed3jOV.d.mts → rate-limit-BgoeahE5.d.mts} +17 -2
  140. package/dist/rate-limit-BgoeahE5.d.mts.map +1 -0
  141. package/dist/reply-DjysdCPI.mjs +12 -0
  142. package/dist/reply-DjysdCPI.mjs.map +1 -0
  143. package/dist/respond-vPZlRnZR.mjs +12 -0
  144. package/dist/respond-vPZlRnZR.mjs.map +1 -0
  145. package/dist/{route-flag-BWuvJsGZ.mjs → route-flag-BjRpxryx.mjs} +3 -3
  146. package/dist/{route-flag-BWuvJsGZ.mjs.map → route-flag-BjRpxryx.mjs.map} +1 -1
  147. package/dist/{route-policy-B3vM6bSf.mjs → route-policy-Pffte5M1.mjs} +2 -2
  148. package/dist/{route-policy-B3vM6bSf.mjs.map → route-policy-Pffte5M1.mjs.map} +1 -1
  149. package/dist/{router-builder-JvMTp50k.mjs → router-builder-CrWKq6O2.mjs} +3 -3
  150. package/dist/router-builder-CrWKq6O2.mjs.map +1 -0
  151. package/dist/{session-B4hOZj90.d.mts → session-ChXx7jG5.d.mts} +31 -4
  152. package/dist/session-ChXx7jG5.d.mts.map +1 -0
  153. package/dist/settings-C8VKewNS.d.mts +119 -0
  154. package/dist/settings-C8VKewNS.d.mts.map +1 -0
  155. package/dist/settings-CFtEAQUs.mjs +14 -0
  156. package/dist/settings-CFtEAQUs.mjs.map +1 -0
  157. package/dist/{upload-config-Dz2INCaa.mjs → upload-config-DLgt4l7F.mjs} +2 -2
  158. package/dist/{upload-config-Dz2INCaa.mjs.map → upload-config-DLgt4l7F.mjs.map} +1 -1
  159. package/dist/url-for-Cyh7pJCb.mjs +12 -0
  160. package/dist/url-for-Cyh7pJCb.mjs.map +1 -0
  161. package/dist/validate-CzjCbRUn.d.mts +53 -0
  162. package/dist/validate-CzjCbRUn.d.mts.map +1 -0
  163. package/dist/web.d.mts +19 -19
  164. package/dist/web.d.mts.map +1 -1
  165. package/dist/web.mjs +2 -2
  166. package/dist/web.mjs.map +1 -1
  167. package/package.json +14 -1
  168. package/dist/adapter-ClEh-Oos.d.mts +0 -2134
  169. package/dist/adapter-ClEh-Oos.d.mts.map +0 -1
  170. package/dist/app-module-DCA65GZZ.d.mts.map +0 -1
  171. package/dist/application-Dv514EeR.mjs +0 -12
  172. package/dist/application-Dv514EeR.mjs.map +0 -1
  173. package/dist/application-oIPzgjfk.d.mts +0 -1589
  174. package/dist/application-oIPzgjfk.d.mts.map +0 -1
  175. package/dist/bootstrap-BdyBlBMe.mjs +0 -12
  176. package/dist/config-CJiGeOca.mjs +0 -12
  177. package/dist/context-CtL9RxXp.mjs +0 -12
  178. package/dist/context-CtL9RxXp.mjs.map +0 -1
  179. package/dist/core-B0JmdBvX.mjs +0 -12
  180. package/dist/csrf--1t4qDov.mjs +0 -12
  181. package/dist/csrf--1t4qDov.mjs.map +0 -1
  182. package/dist/csrf-C73UkRgc.d.mts.map +0 -1
  183. package/dist/decorate-BHkdkV4l.mjs +0 -11
  184. package/dist/env-BwzF9MkZ.mjs +0 -13
  185. package/dist/env-BwzF9MkZ.mjs.map +0 -1
  186. package/dist/error-handler-BB9wAElm.d.mts +0 -63
  187. package/dist/error-handler-BB9wAElm.d.mts.map +0 -1
  188. package/dist/handler-zKfIgNo4.mjs +0 -13
  189. package/dist/handler-zKfIgNo4.mjs.map +0 -1
  190. package/dist/helmet-C2QEU6S-.d.mts.map +0 -1
  191. package/dist/index-CNHSbZTE.d.mts.map +0 -1
  192. package/dist/kv-stores-Co5k2PYA.d.mts +0 -367
  193. package/dist/kv-stores-Co5k2PYA.d.mts.map +0 -1
  194. package/dist/kv-stores-DsfVy2fk.mjs +0 -12
  195. package/dist/kv-stores-DsfVy2fk.mjs.map +0 -1
  196. package/dist/module-registry-Daf_P2oD.mjs +0 -12
  197. package/dist/module-registry-Daf_P2oD.mjs.map +0 -1
  198. package/dist/rate-limit-Bwed3jOV.d.mts.map +0 -1
  199. package/dist/reply-BDK9xt7Z.mjs +0 -12
  200. package/dist/reply-BDK9xt7Z.mjs.map +0 -1
  201. package/dist/respond-DFRj2-7q.mjs +0 -12
  202. package/dist/respond-DFRj2-7q.mjs.map +0 -1
  203. package/dist/router-builder-JvMTp50k.mjs.map +0 -1
  204. package/dist/router-builder-zWuVIOmd.d.mts +0 -56
  205. package/dist/router-builder-zWuVIOmd.d.mts.map +0 -1
  206. package/dist/session-B4hOZj90.d.mts.map +0 -1
  207. package/dist/upload-CiMtdXWD.d.mts +0 -104
  208. package/dist/upload-CiMtdXWD.d.mts.map +0 -1
  209. package/dist/validate-DMYpUnrf.d.mts +0 -25
  210. package/dist/validate-DMYpUnrf.d.mts.map +0 -1
@@ -1,1589 +0,0 @@
1
-
2
- import { s as InjectionToken, t as Container } from "./container-Dpvd66Yt.mjs";
3
- import "./index-CNHSbZTE.mjs";
4
- import { D as RequestContext, M as AdapterFactory, S as RuntimeResponse, a as KickServer, c as ActiveRuntime, dt as KickPlugin, ft as ModuleRegistry, g as RouteEntry, it as ModuleFactory, p as HttpRuntime, r as AppAdapter, x as RuntimeCapabilities } from "./adapter-ClEh-Oos.mjs";
5
- import { p as RouteFlags, s as RouteFlagDeclarations } from "./route-flag-B1lQht6v.mjs";
6
- import { C as MetaValue, c as ContextDecorator, h as DepValue, m as ContributorRegistrations, r as AppModuleEntry, u as ContextDecoratorSpec, x as ContextMetaKey } from "./app-module-DCA65GZZ.mjs";
7
- import { g as PlatformContext, u as Reply } from "./kv-stores-Co5k2PYA.mjs";
8
- import "./session-B4hOZj90.mjs";
9
- import { t as BuildRoutesOptions } from "./router-builder-zWuVIOmd.mjs";
10
- import "./request-id-CVzJ1uHD.mjs";
11
- import "./validate-DMYpUnrf.mjs";
12
- import "./error-handler-BB9wAElm.mjs";
13
- import "./csrf-C73UkRgc.mjs";
14
- import "./helmet-C2QEU6S-.mjs";
15
- import "./cors-CsibNTQ6.mjs";
16
- import "./rate-limit-Bwed3jOV.mjs";
17
- import "./upload-CiMtdXWD.mjs";
18
- import http, { IncomingMessage, ServerResponse } from "node:http";
19
- import tls from "node:tls";
20
- import { Express, NextFunction, Request as Request$1, RequestHandler, Response as Response$1, Router } from "express";
21
- import { AsyncLocalStorage } from "node:async_hooks";
22
- //#region src/core/disposables.d.ts
23
- /**
24
- * Registry for framework-owned resources that hold timers or other handles
25
- * outside the adapter/plugin lifecycle — e.g. the in-memory session and
26
- * rate-limit stores' cleanup intervals. `Application.shutdown()` drains it so
27
- * startup and shutdown stay symmetric even for resources created lazily by
28
- * middleware factories.
29
- *
30
- * Intervals are `.unref()`'d so they never wedge process exit — this registry
31
- * exists for IN-PROCESS teardown (test suites, HMR, multi-app hosts) where
32
- * each un-disposed store would otherwise leak a live interval + backing Map
33
- * per app instance.
34
- */
35
- type Disposable = () => void | Promise<void>;
36
- /** Register a cleanup callback. Returns an unregister function. */
37
- declare function registerDisposable(fn: Disposable): () => void;
38
- /** Run and clear all registered disposables. Errors are swallowed per-entry. */
39
- declare function disposeAll(): Promise<void>;
40
- //#endregion
41
- //#region src/core/kick-error.d.ts
42
- /**
43
- * Structured framework error with code, cause, and actionable fix hint.
44
- *
45
- * The goal is "the developer who hits this knows what to do next." A
46
- * cryptic `Error('No binding found for: UserService')` becomes a
47
- * multi-line explanation pointing at the likely cause, the exact code
48
- * change to apply, and a docs link.
49
- *
50
- * `.message` carries the full multi-line plain-text body so Node's
51
- * default `Error.toString()` and unhandled-exception printing still
52
- * surface the helpful version. Call {@link formatKickError} to render a
53
- * colorized version for terminals.
54
- *
55
- * Per-error factories live in `kick-errors.ts` — those are the public
56
- * entry points framework code uses. `KickError` is exported so adopters
57
- * can build their own structured errors using the same shape.
58
- */
59
- interface KickErrorInit {
60
- /** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */
61
- code: string;
62
- /** One-line headline. */
63
- summary: string;
64
- /** Multi-line explanation of why this happened. */
65
- cause?: string;
66
- /** Multi-line actionable fix — show exact code if possible. */
67
- fix?: string;
68
- /** Absolute URL to the docs page that covers this error. */
69
- docsUrl?: string;
70
- /** Arbitrary structured fields for log consumers / debug tooling. */
71
- context?: Record<string, unknown>;
72
- }
73
- declare class KickError extends Error {
74
- readonly code: string;
75
- readonly summary: string;
76
- readonly cause?: string;
77
- readonly fix?: string;
78
- readonly docsUrl?: string;
79
- readonly context?: Record<string, unknown>;
80
- constructor(init: KickErrorInit);
81
- }
82
- interface FormatKickErrorOptions {
83
- /**
84
- * Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /
85
- * `FORCE_COLOR` env vars honoured). Pass `false` for log files,
86
- * structured loggers, or HTTP response bodies.
87
- */
88
- color?: boolean;
89
- }
90
- /**
91
- * Render a {@link KickErrorInit} (or {@link KickError} instance) into a
92
- * multi-line human-readable string. Identical layout regardless of
93
- * colour — the colour flag only toggles ANSI codes.
94
- */
95
- declare function formatKickError(err: KickErrorInit | KickError, options?: FormatKickErrorOptions): string;
96
- //#endregion
97
- //#region src/core/circuit-breaker.d.ts
98
- /**
99
- * Circuit Breaker pattern for external service calls.
100
- *
101
- * Protects your application from cascading failures when downstream
102
- * services are unhealthy by short-circuiting requests after a
103
- * configurable failure threshold.
104
- *
105
- * @example
106
- * ```ts
107
- * const breaker = new CircuitBreaker('payment-api', {
108
- * failureThreshold: 5,
109
- * resetTimeout: 30_000,
110
- * })
111
- *
112
- * const result = await breaker.execute(() => fetch('https://payment.example.com/charge'))
113
- * ```
114
- */
115
- type CircuitBreakerState = 'closed' | 'open' | 'half_open';
116
- interface CircuitBreakerOptions {
117
- /** Number of consecutive failures before the circuit opens. */
118
- failureThreshold: number;
119
- /** Milliseconds to wait before transitioning from OPEN to HALF_OPEN. */
120
- resetTimeout: number;
121
- /** Max requests allowed in HALF_OPEN state before deciding (default 1). */
122
- halfOpenMax?: number;
123
- }
124
- interface CircuitBreakerStats {
125
- failures: number;
126
- successes: number;
127
- state: CircuitBreakerState;
128
- lastFailure?: Date;
129
- }
130
- /**
131
- * Error thrown when the circuit is open and calls are being rejected.
132
- */
133
- declare class CircuitOpenError extends Error {
134
- readonly breakerName: string;
135
- constructor(breakerName: string);
136
- }
137
- declare class CircuitBreaker {
138
- readonly name: string;
139
- private state;
140
- private failures;
141
- private successes;
142
- private halfOpenAttempts;
143
- private lastFailure?;
144
- private openedAt?;
145
- private readonly failureThreshold;
146
- private readonly resetTimeout;
147
- private readonly halfOpenMax;
148
- constructor(name: string, options: CircuitBreakerOptions);
149
- /**
150
- * Execute an async function through the circuit breaker.
151
- * Throws `CircuitOpenError` if the circuit is open.
152
- */
153
- execute<T>(fn: () => Promise<T>): Promise<T>;
154
- /** Returns the current circuit state. */
155
- getState(): CircuitBreakerState;
156
- /** Returns current statistics. */
157
- getStats(): CircuitBreakerStats;
158
- /** Manually reset the circuit breaker to CLOSED state. */
159
- reset(): void;
160
- private onSuccess;
161
- private onFailure;
162
- private maybeTransitionToHalfOpen;
163
- }
164
- //#endregion
165
- //#region src/core/context-errors.d.ts
166
- /**
167
- * Errors thrown by the Context Contributor pipeline.
168
- *
169
- * `MissingContributorError`, `ContributorCycleError`, and
170
- * `DuplicateContributorError` are startup-time errors raised during
171
- * pipeline build (topo-sort + validation), not per-request — a
172
- * misconfigured app fails to boot rather than fails a request. Per the
173
- * locked design in `architecture.md` §20.4, the pipeline is validated
174
- * once when each route is mounted and the resolved order is cached on
175
- * the route.
176
- *
177
- * `MissingContextValueError` is the one request-time error here: it is
178
- * raised by `ctx.require(key)` when a value a handler declared it needs
179
- * is absent. See its doc comment for why that case can't be caught at
180
- * startup today.
181
- */
182
- /**
183
- * A contributor declared `dependsOn: ['<key>']` but no other contributor
184
- * (at any precedence level) produces that key for the same route.
185
- *
186
- * @example
187
- * ```text
188
- * MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id
189
- * declared at src/contributors/load-project.ts:42:18
190
- * ```
191
- */
192
- declare class MissingContributorError extends Error {
193
- readonly key: string;
194
- readonly dependent: string;
195
- readonly route?: string;
196
- readonly dependentDefinedAt?: string;
197
- constructor(key: string, dependent: string, route?: string, dependentDefinedAt?: string);
198
- }
199
- /**
200
- * `ctx.require(key)` found no value under `key` in the per-request
201
- * metadata store.
202
- *
203
- * Thrown at request time, by design. `ctx.get(key)` returns
204
- * `T | undefined` for every key, so the usual workaround is a
205
- * non-null assertion — `ctx.get('tenant')!` — which compiles whether or
206
- * not the route actually carries the contributor that produces it. On
207
- * an authorization value that is the worst possible thing to leave
208
- * untypeable: dropping the decorator produces no diagnostic anywhere,
209
- * and the handler reads `undefined` as though it were a real value.
210
- *
211
- * `ctx.require()` converts that silent hole into a loud, named failure
212
- * that points at the missing contributor.
213
- *
214
- * A handler typed with a generated route type (`Ctx<KickRoutes…>`) also
215
- * gets compile-time narrowing, so a dropped decorator fails `tsc` rather
216
- * than reaching this error at all. This error remains the backstop for
217
- * routes typegen couldn't prove (module/adapter/bootstrap registrations),
218
- * handlers typed as plain `RequestContext`, and contributors that ran but
219
- * resolved to `undefined`. See `architecture.md` §20.14.
220
- *
221
- * @example
222
- * ```text
223
- * MissingContextValueError: No context value for 'tenantPerm' on GET /projects/:id
224
- * Nothing wrote this key before the handler ran. Either the contributor
225
- * that produces it isn't applied to this route, or it ran and resolved
226
- * to undefined (check `optional: true` contributors).
227
- * ```
228
- */
229
- declare class MissingContextValueError extends Error {
230
- readonly key: string;
231
- readonly route?: string;
232
- constructor(key: string, route?: string);
233
- }
234
- /**
235
- * Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field
236
- * lists the keys in the order they form the loop, with the first key
237
- * repeated at the end so the path reads naturally.
238
- *
239
- * @example
240
- * ```text
241
- * ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant
242
- * ```
243
- */
244
- declare class ContributorCycleError extends Error {
245
- readonly cycle: readonly string[];
246
- readonly route?: string;
247
- constructor(cycle: readonly string[], route?: string);
248
- }
249
- /**
250
- * Two contributors at the same precedence level both produce the same key
251
- * for the same route. Precedence resolution (method > class > module >
252
- * adapter > global, per architecture.md §20.4) silently drops
253
- * lower-precedence duplicates; this error fires only when ties occur
254
- * within a single level — e.g., two method-level decorators declaring
255
- * `key: 'tenant'`.
256
- *
257
- * `sources` is best-effort identifying labels for each conflicting
258
- * registration (typically the decorator's call site or registering
259
- * module/adapter name).
260
- *
261
- * @example
262
- * ```text
263
- * DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain
264
- * ```
265
- */
266
- declare class DuplicateContributorError extends Error {
267
- readonly key: string;
268
- readonly sources: readonly string[];
269
- constructor(key: string, sources: readonly string[]);
270
- }
271
- //#endregion
272
- //#region src/core/mount-sort.d.ts
273
- /**
274
- * Topological sort for plugins and adapters with `dependsOn` declarations.
275
- *
276
- * Mirrors the algorithm used by the Context Contributor pipeline
277
- * (`contributor-pipeline.ts:topoSort`) but operates on a name-keyed
278
- * `MountSortItem` shape rather than a `ContributorRegistration`. Kept
279
- * standalone instead of factored generic so that:
280
- *
281
- * 1. The contributor pipeline doesn't need refactoring (risk reduction).
282
- * 2. The error classes can carry plugin/adapter-specific diagnostic
283
- * fields (`kind`, `dependent`) without bending the contributor types.
284
- */
285
- /**
286
- * A plugin or adapter that participates in dependency-ordered mounting.
287
- * Both `KickPlugin` and `AppAdapter` satisfy this shape via their `name`
288
- * and `dependsOn` fields.
289
- */
290
- interface MountSortItem {
291
- /** Unique mount name within the plugin/adapter set being sorted. */
292
- name: string;
293
- /**
294
- * Other plugin/adapter names that must mount before this one. Cycles
295
- * and missing names fail at boot — same fail-fast contract as the
296
- * Context Contributor pipeline (architecture.md §20.4).
297
- */
298
- dependsOn?: readonly string[];
299
- }
300
- /** What kind of mount set the sort is operating on — surfaces in error messages. */
301
- type MountKind = 'plugin' | 'adapter';
302
- /**
303
- * Two items in the same mount set declared the same `name`. Plugin/adapter
304
- * names must be unique so `dependsOn` references resolve unambiguously.
305
- */
306
- declare class DuplicateMountNameError extends Error {
307
- readonly kind: MountKind;
308
- readonly mountName: string;
309
- constructor(kind: MountKind, mountName: string);
310
- }
311
- /**
312
- * A `dependsOn` entry references a plugin/adapter that isn't in the
313
- * current set. The dependency might not be installed, might be misspelled,
314
- * or might live in a different mount set (plugin referencing an adapter,
315
- * or vice versa — they sort independently).
316
- */
317
- declare class MissingMountDepError extends Error {
318
- readonly kind: MountKind;
319
- readonly missing: string;
320
- readonly dependent: string;
321
- constructor(kind: MountKind, missing: string, dependent: string);
322
- }
323
- /**
324
- * The `dependsOn` declarations form a cycle. Boot fails so the cycle
325
- * can't poison live traffic. The `cycle` field reports one path through
326
- * the offending nodes for diagnostics — formatted `A → B → C → A`.
327
- */
328
- declare class MountCycleError extends Error {
329
- readonly kind: MountKind;
330
- readonly cycle: readonly string[];
331
- constructor(kind: MountKind, cycle: readonly string[]);
332
- }
333
- /**
334
- * Topologically sort `items` so every item with `dependsOn: ['X']` mounts
335
- * after `X`. Items without `dependsOn` keep their input order via Kahn's
336
- * algorithm with a FIFO queue seeded in input order — preserves the
337
- * historical "plugins/adapters mount in declaration order" behaviour for
338
- * any set that doesn't use `dependsOn`.
339
- *
340
- * @param items - mountable items, e.g. plugins or adapters
341
- * @param kind - 'plugin' | 'adapter', used in error messages
342
- * @returns a new array in valid mount order
343
- * @throws {DuplicateMountNameError} two items share a name
344
- * @throws {MissingMountDepError} a `dependsOn` references an unknown name
345
- * @throws {MountCycleError} the dep graph contains a cycle
346
- */
347
- declare function mountSort<T extends MountSortItem>(items: readonly T[], kind: MountKind): T[];
348
- //#endregion
349
- //#region src/core/asset-keys.d.ts
350
- type AssetKeyStrategy = 'auto' | 'strip' | 'with-extension';
351
- interface AssetKeyPair {
352
- /** Source-relative path the file was discovered at. */
353
- rel: string;
354
- /** Final logical key for the manifest, including the namespace prefix. */
355
- key: string;
356
- }
357
- interface GroupAssetKeysOptions {
358
- /**
359
- * Strategy applied to this namespace. Default `'auto'`.
360
- *
361
- * Adopters override per-namespace via `assetMap.<ns>.keys` in
362
- * kick.config.ts when they want uniform behaviour (e.g. always
363
- * include the extension regardless of collisions).
364
- */
365
- strategy?: AssetKeyStrategy;
366
- }
367
- interface GroupAssetKeysResult {
368
- pairs: AssetKeyPair[];
369
- /**
370
- * Number of collision groups resolved by keeping extensions.
371
- * Surfaces as an informational log ("auto-resolved N collisions")
372
- * so adopters know whether they're relying on auto-mode or not.
373
- * Always 0 for `'strip'` (overwrites) and `'with-extension'`
374
- * (extensions always preserved, no collision possible).
375
- */
376
- collisionGroupsResolved: number;
377
- }
378
- /**
379
- * Compute final manifest keys for a namespace's discovered paths,
380
- * given the chosen strategy. Pure function — no fs / config / globals
381
- * involved.
382
- *
383
- * @param namespace assetMap key — e.g. `'mails'`, `'pages'`.
384
- * @param paths source-relative file paths (POSIX separators) discovered
385
- * under the namespace's `src` directory.
386
- * @param opts grouping options.
387
- */
388
- declare function groupAssetKeys(namespace: string, paths: readonly string[], opts?: GroupAssetKeysOptions): GroupAssetKeysResult;
389
- /** Strip the final extension from a path. `'mails/welcome.ejs'` → `'mails/welcome'`. */
390
- declare function stripExt(path: string): string;
391
- //#endregion
392
- //#region src/core/route-policy.d.ts
393
- declare class RoutePolicyTable {
394
- /** Bucketed by method: an incoming request only scans its own verb. */
395
- private readonly byMethod;
396
- add(method: string, path: string, flags: RouteFlags | undefined): void;
397
- /**
398
- * Flags that apply to `method pathname`, or an empty map when the path
399
- * matches no flagged route — including when it matches no route at all,
400
- * which is exactly the traffic this exists to keep visible.
401
- */
402
- lookup(method: string, pathname: string): RouteFlags;
403
- /** Drop everything — the Application rebuilds on every HMR reload. */
404
- clear(): void;
405
- get size(): number;
406
- }
407
- /**
408
- * Declare that `handler` wants the policy table.
409
- *
410
- * Explicit hand-off rather than a module-level singleton, so the table a
411
- * middleware reads is always the one belonging to the app that mounted it.
412
- */
413
- declare function bindRoutePolicy<T extends object>(handler: T, receive: (table: RoutePolicyTable) => void): T;
414
- /** Hand the table to a middleware if it declared the slot. */
415
- declare function offerRoutePolicy(handler: unknown, table: RoutePolicyTable): void;
416
- //#endregion
417
- //#region src/http/cron-adapter.d.ts
418
- /** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */
419
- declare const CRON_WORKER_ENV = "KICK_CRON_WORKER";
420
- interface CronAdapterOptions {
421
- /** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */
422
- enabled?: boolean;
423
- }
424
- declare const KickCronAdapter: AdapterFactory<CronAdapterOptions, unknown>;
425
- //#endregion
426
- //#region src/http/tracing.d.ts
427
- declare const HANDLER_CHANNEL = "kickjs:handler";
428
- declare const ERROR_CHANNEL = "kickjs:error";
429
- declare const RESPONSE_CHANNEL = "kickjs:response";
430
- /** What subscribers to `kickjs:handler` receive. */
431
- interface HandlerTraceContext {
432
- method: string;
433
- /** The route pattern, e.g. `/api/v1/users/:id` — the span name APMs want. */
434
- route: string;
435
- controller?: string;
436
- handler?: string;
437
- requestId?: string;
438
- ctx: RequestContext;
439
- }
440
- //#endregion
441
- //#region src/http/bootstrap.d.ts
442
- /**
443
- * Bootstrap a KickJS application.
444
- *
445
- * Creates the Express app, registers modules and adapters, and starts
446
- * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages
447
- * the server and HMR — source changes are picked up instantly without
448
- * losing database connections or WebSocket state.
449
- *
450
- * @returns The {@link Application} instance.
451
- *
452
- * @example
453
- * ```ts
454
- * // src/index.ts
455
- * import 'reflect-metadata'
456
- * import { bootstrap } from '@forinda/kickjs'
457
- * import { modules } from './modules'
458
- *
459
- * export const app = await bootstrap({ modules })
460
- * ```
461
- */
462
- declare function bootstrap(options: ApplicationOptions): Promise<Application>;
463
- //#endregion
464
- //#region src/http/handler.d.ts
465
- /** A KickJS app exposed as request handlers. See {@link createHandler}. */
466
- interface KickHandler {
467
- /**
468
- * Web-standard handler: `fetch(Request) → Response`. Netlify Functions,
469
- * Vercel's fetch export, and anything else that speaks `Request`.
470
- *
471
- * Pass the platform context (Netlify's `context`, `{ waitUntil }` from
472
- * `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after
473
- * the response instead of being frozen with the instance.
474
- */
475
- fetch(request: Request, platform?: PlatformContext): Promise<Response>;
476
- /** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */
477
- node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>;
478
- /** Set the app up now instead of on the first request (warm-up). */
479
- ready(): Promise<Application>;
480
- /** Shut adapters down and stop the internal forwarding server, if one started. */
481
- close(): Promise<void>;
482
- }
483
- /**
484
- * Build a KickJS app as request handlers instead of a listening server.
485
- *
486
- * Takes the same options as `bootstrap()`, or a function that imports the
487
- * app's entry — the file that calls `bootstrap()`. With the entry, the app
488
- * is built from that one `bootstrap({ ... })` call, so the server and the
489
- * function never drift apart:
490
- *
491
- * ```ts
492
- * // src/serverless.ts
493
- * export const handler = createHandler(() => import('./index'))
494
- * ```
495
- *
496
- * While the entry loads, its `bootstrap()` call builds the app without
497
- * starting it — no port, no process signal handlers, no cluster. The app is set up once per process
498
- * (per function instance), lazily on the first request, and reused after that.
499
- * Nothing listens on a port, `afterStart` does not run, and no process signal
500
- * handlers are registered — the platform owns the process.
501
- *
502
- * `fetch` uses the runtime's own fetch when it has one (the h3 v2 runtime).
503
- * Runtimes built on Node request/response objects — Express, the default —
504
- * are served through a server bound to `127.0.0.1` on a random port inside the
505
- * same process, started on first use: the `Request` is forwarded to it and its
506
- * response returned. Request bodies are buffered on that path; response bodies
507
- * stream. Adapters that rewrite the `res` prototype (Express does) make a
508
- * direct Request→`res` bridge unreliable, which is why this forwards instead.
509
- *
510
- * One handler per process: the DI container is process-wide.
511
- *
512
- * @example
513
- * ```ts
514
- * // server/src/serverless.ts
515
- * import 'reflect-metadata'
516
- * import './config'
517
- * import { createHandler } from '@forinda/kickjs'
518
- * import { modules } from './modules'
519
- *
520
- * export const handler = createHandler({ modules })
521
- *
522
- * // netlify/functions/api.mjs
523
- * export default (request, context) => handler.fetch(request, context)
524
- * export const config = { path: '/api/*' }
525
- * ```
526
- */
527
- declare function createHandler(options: ApplicationOptions | (() => Promise<unknown>)): KickHandler;
528
- //#endregion
529
- //#region src/http/cluster.d.ts
530
- interface ClusterOptions {
531
- /** Number of worker processes (default: os.cpus().length) */
532
- workers?: number;
533
- /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */
534
- gracefulShutdownTimeout?: number;
535
- /** Delay between worker restarts (ms), default: 1000 */
536
- restartDelay?: number;
537
- /** Max failures in restartWindow before refusing to restart, default: 5 */
538
- maxFailures?: number;
539
- /** Time window for counting failures (ms), default: 30000 */
540
- restartWindow?: number;
541
- }
542
- /** Returns true if the current process is the cluster primary */
543
- declare function isClusterPrimary(): boolean;
544
- //#endregion
545
- //#region src/http/define-http-context-decorator.d.ts
546
- /**
547
- * Curried form returned by {@link DefineHttpContextDecoratorFn.withParams}.
548
- * Spell only the per-call params shape `P`; `K` and `D` are inferred
549
- * from the spec, and `Ctx` is locked to `RequestContext`.
550
- */
551
- interface DefineHttpContextDecoratorWithParams<P extends Record<string, unknown>> {
552
- <K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>>(spec: ContextDecoratorSpec<K, D, P, RequestContext>): ContextDecorator<K, D, P, RequestContext>;
553
- }
554
- /**
555
- * Public shape of {@link defineHttpContextDecorator} — the positional
556
- * call signature plus the curried `.withParams<P>()` helper that fixes
557
- * partial-inference for the parameterised case.
558
- */
559
- interface DefineHttpContextDecoratorFn {
560
- <K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>, P extends Record<string, unknown> = Record<string, never>>(spec: ContextDecoratorSpec<K, D, P, RequestContext>): ContextDecorator<K, D, P, RequestContext>;
561
- /**
562
- * Curried entry point. Spell only `P`; `K` and `D` infer from the
563
- * spec. `Ctx` is locked to `RequestContext`.
564
- *
565
- * ```ts
566
- * const LoadTenant = defineHttpContextDecorator.withParams<{
567
- * source: 'header' | 'subdomain'
568
- * }>()({
569
- * key: 'tenant',
570
- * deps: { repo: TENANT_REPO }, // D inferred
571
- * paramDefaults: { source: 'header' },
572
- * resolve: (ctx, { repo }, params) => repo.findFor(ctx, params),
573
- * })
574
- * ```
575
- */
576
- withParams<P extends Record<string, unknown>>(): DefineHttpContextDecoratorWithParams<P>;
577
- }
578
- declare const defineHttpContextDecorator: DefineHttpContextDecoratorFn;
579
- //#endregion
580
- //#region src/http/runtimes/express.d.ts
581
- /**
582
- * Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.
583
- * Reproduces the legacy handler ordering precisely: validation → upload →
584
- * `(ctx, next)` middleware → contributor runner → terminal handler, with
585
- * `beforeValidation` contributors ahead of validation. Each step
586
- * constructs its own `RequestContext` over the same `req`/`res` — request-scoped
587
- * state lives in the AsyncLocalStorage store, not on the ctx instance, so the
588
- * per-step instances share state exactly as before.
589
- */
590
- declare function materializeRouter(entries: RouteEntry[]): Router;
591
- /**
592
- * Build an Express Router from a controller class decorated with @Get, @Post,
593
- * etc. The public, back-compatible entry point: a thin shim over
594
- * {@link buildRouteTable} + {@link materializeRouter}. Returns an
595
- * `express.Router` exactly as before — modules pass it to `app.use(path, router)`.
596
- *
597
- * @see buildRouteTable for the engine-neutral route-table form.
598
- */
599
- declare function buildRoutes(controllerClass: any, options?: BuildRoutesOptions): Router;
600
- /**
601
- * The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;
602
- * apps that pass no `runtime` get this and behave exactly as before.
603
- */
604
- declare function expressRuntime(): HttpRuntime<Express>;
605
- //#endregion
606
- //#region src/http/request-store.d.ts
607
- /** Per-request storage for REQUEST-scoped DI and request context propagation */
608
- interface RequestStore {
609
- /** Unique request identifier */
610
- requestId: string;
611
- /**
612
- * Per-request singleton cache for REQUEST-scoped services. Keys are
613
- * heterogeneous (class constructors, `InjectionToken` objects, raw
614
- * strings), so the map type stays `Map<any, any>`.
615
- */
616
- instances: Map<any, any>;
617
- /**
618
- * Per-request key/value bag. Canonical backing store for
619
- * `RequestContext.set/get` and the Context Contributor pipeline (#107)
620
- * since Phase 3. Anything written here is visible to every concrete
621
- * execution context constructed for the same request, regardless of
622
- * which middleware/contributor wrote it.
623
- *
624
- * Keys are constrained to `string` per the locked decision in
625
- * `architecture.md` §20.12 (#4); the value type is `unknown` because
626
- * the concrete shape at each key is determined by the consumer's
627
- * `ContextMeta` augmentation, not by the store itself.
628
- *
629
- * Prefer the {@link getRequestValue} helper over reaching into this
630
- * map directly — it threads the augmented `ContextMeta` shape through
631
- * `MetaValue<K>` so consumers get typed reads without an `as` cast.
632
- * Writes should flow through `ctx.set(key, value)` or a Context
633
- * Contributor's return value — see the `setRequestValue` note below
634
- * for why this package intentionally does NOT ship a service-level
635
- * write helper.
636
- */
637
- values: Map<string, unknown>;
638
- /** Set once {@link disposeRequestStore} has run — guards double-dispose. */
639
- disposed?: boolean;
640
- }
641
- /** AsyncLocalStorage instance shared across the framework */
642
- declare const requestStore: AsyncLocalStorage<RequestStore>;
643
- /**
644
- * Get the current request store. Throws if called outside a request context.
645
- * Used by the Container to resolve REQUEST-scoped dependencies.
646
- */
647
- declare function getRequestStore(): RequestStore;
648
- /**
649
- * Read a per-request `ContextMeta`-keyed value from outside a controller
650
- * (services, repositories, anywhere with no `ctx` reference). Returns
651
- * the augmented type for the key — `MetaValue<K>` — so consumers get the
652
- * same static safety as `ctx.get(key)` without holding the context.
653
- *
654
- * Returns `undefined` outside an active request frame (background jobs,
655
- * startup code, tests without `requestScopeMiddleware()`) — the helper
656
- * is intentionally null-tolerant so calling it from a service that
657
- * runs in both request and non-request paths doesn't throw.
658
- *
659
- * @example
660
- * ```ts
661
- * declare module '@forinda/kickjs' {
662
- * interface ContextMeta { tenant: { id: string; name: string } }
663
- * }
664
- *
665
- * @Service()
666
- * class AuditService {
667
- * log(action: string) {
668
- * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined
669
- * db.audit.insert({ action, tenantId: tenant?.id })
670
- * }
671
- * }
672
- * ```
673
- */
674
- declare function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined;
675
- //#endregion
676
- //#region src/http/middleware/request-scope.d.ts
677
- /**
678
- * Wraps each request in an AsyncLocalStorage context.
679
- * Enables REQUEST-scoped DI and automatic requestId propagation to logs.
680
- *
681
- * Should be mounted early in the middleware pipeline (before route handlers).
682
- * `Application` mounts this automatically unless `contextStore: 'manual'` is set
683
- * or the user already includes one in their middleware list.
684
- */
685
- declare function requestScopeMiddleware(): (req: Request$1, res: Response$1, next: NextFunction) => void;
686
- //#endregion
687
- //#region src/http/middleware/trace-context.d.ts
688
- /**
689
- * W3C Trace Context header name.
690
- * @see https://www.w3.org/TR/trace-context/#traceparent-header
691
- */
692
- declare const TRACEPARENT_HEADER = "traceparent";
693
- interface TraceContextOptions {
694
- /**
695
- * When true, respond with a `traceresponse` header containing the trace ID.
696
- * Useful for debugging. Default: false.
697
- */
698
- propagateResponse?: boolean;
699
- }
700
- /**
701
- * Parsed W3C trace context fields.
702
- */
703
- interface TraceContext {
704
- /** W3C traceparent version (usually '00') */
705
- version: string;
706
- /** 32-hex-char distributed trace ID */
707
- traceId: string;
708
- /** 16-hex-char parent span ID */
709
- parentSpanId: string;
710
- /** 2-hex-char trace flags */
711
- flags: string;
712
- }
713
- /**
714
- * Parse a W3C traceparent header value.
715
- * Returns null if the format is invalid.
716
- */
717
- declare function parseTraceparent(header: string): TraceContext | null;
718
- /**
719
- * Middleware that extracts W3C `traceparent` header and stores trace context
720
- * in the request's AsyncLocalStorage store.
721
- *
722
- * If no valid `traceparent` header is present, a new traceId is generated
723
- * so that every request always has a trace ID available for correlation.
724
- *
725
- * Must be mounted **after** `requestScopeMiddleware()` (which creates the store).
726
- *
727
- * @example
728
- * ```ts
729
- * bootstrap({
730
- * middlewares: [
731
- * requestScopeMiddleware(),
732
- * traceContext(), // extracts or generates traceId
733
- * requestLogger(),
734
- * express.json(),
735
- * ],
736
- * })
737
- * ```
738
- */
739
- declare function traceContext(options?: TraceContextOptions): (req: Request$1, res: Response$1, next: NextFunction) => void;
740
- //#endregion
741
- //#region src/http/middleware/views.d.ts
742
- interface ViewAdapterOptions {
743
- /**
744
- * Template engine — pass the engine module or a render function.
745
- * Supported engines: ejs, pug, handlebars, nunjucks, or any
746
- * Express-compatible engine with a __express property.
747
- *
748
- * @example
749
- * ```ts
750
- * import ejs from 'ejs'
751
- * ViewAdapter({ engine: ejs, ext: 'ejs' })
752
- *
753
- * import pug from 'pug'
754
- * ViewAdapter({ engine: pug, ext: 'pug' })
755
- * ```
756
- */
757
- engine: any;
758
- /** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */
759
- ext: string;
760
- /** Directory containing template files (default: 'src/views') */
761
- viewsDir?: string;
762
- /** Default layout template (optional — depends on engine) */
763
- layout?: string;
764
- }
765
- /**
766
- * View/template adapter — pluggable template engine support for KickJS.
767
- *
768
- * Registers an Express view engine and sets the views directory.
769
- * Use `ctx.render()` in controllers to render templates.
770
- *
771
- * Migrated to the `defineAdapter()` factory in v4 — call without `new`.
772
- * The pre-v4 `new ViewAdapter({...})` form is gone; see
773
- * `docs/guide/migration-v3-to-v4.md` for the rename.
774
- *
775
- * @example
776
- * ```ts
777
- * import ejs from 'ejs'
778
- * import { ViewAdapter } from '@forinda/kickjs'
779
- *
780
- * bootstrap({
781
- * modules,
782
- * adapters: [
783
- * ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),
784
- * ],
785
- * })
786
- *
787
- * // In a controller:
788
- * @Get('/dashboard')
789
- * async dashboard(ctx: RequestContext) {
790
- * ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })
791
- * }
792
- * ```
793
- */
794
- declare const ViewAdapter: AdapterFactory<ViewAdapterOptions, unknown>;
795
- //#endregion
796
- //#region src/http/middleware/spa.d.ts
797
- interface SpaAdapterOptions {
798
- /**
799
- * Directory containing the built SPA files (index.html, assets, etc.)
800
- * Default: 'dist/client'
801
- *
802
- * @example
803
- * ```ts
804
- * // Vue: 'dist'
805
- * // React (Vite): 'dist'
806
- * // React (CRA): 'build'
807
- * // Svelte: 'build'
808
- * // Angular: 'dist/my-app/browser'
809
- * ```
810
- */
811
- clientDir?: string;
812
- /**
813
- * URL prefix for API routes. SPA fallback only applies to
814
- * non-API routes (routes NOT starting with this prefix).
815
- * Default: '/api'
816
- *
817
- * Matching is segment-aware: `/api` excludes `/api` and `/api/users`, but
818
- * NOT `/apidocs` — a plain `startsWith` swallowed any path that merely
819
- * began with the same letters.
820
- *
821
- * Set to an array for multiple prefixes:
822
- * ```ts
823
- * apiPrefix: ['/api', '/graphql', '/_debug']
824
- * ```
825
- */
826
- apiPrefix?: string | string[];
827
- /**
828
- * Additional paths to exclude from SPA fallback.
829
- * These paths will NOT serve index.html. Segment-aware, like `apiPrefix`.
830
- *
831
- * @example
832
- * ```ts
833
- * exclude: ['/health', '/metrics', '/ws']
834
- * ```
835
- */
836
- exclude?: string[];
837
- /**
838
- * Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')
839
- * Set to false to disable caching headers.
840
- */
841
- cacheControl?: string | false;
842
- /**
843
- * Cache-Control for index.html (default: 'no-cache')
844
- * index.html should not be cached to ensure clients get fresh builds.
845
- */
846
- indexCacheControl?: string;
847
- /**
848
- * Serve index.html even when the client did not ask for HTML.
849
- * Default: false.
850
- *
851
- * By default the fallback only fires for requests whose `Accept` header
852
- * includes `text/html` — the rule `connect-history-api-fallback` uses. That
853
- * keeps a missing `/assets/app.js` a 404 instead of handing back an HTML
854
- * document that the browser then fails to parse as JavaScript, which is a
855
- * confusing way to discover a broken build.
856
- *
857
- * Turn this on if you have non-browser clients that deep-link into SPA
858
- * routes without an `Accept` header.
859
- */
860
- alwaysFallback?: boolean;
861
- }
862
- /**
863
- * Where to look for the built SPA.
864
- *
865
- * `process.cwd()` is the framework's convention (assets and env files resolve
866
- * the same way) and stays the primary base. But a relative `clientDir` then
867
- * only works when the process happens to be started from the app directory —
868
- * `node server/dist/index.js` run from a monorepo root resolved `../web/dist`
869
- * against the root and found nothing, serving no SPA with only a warning.
870
- *
871
- * So: try cwd first, and only if that misses, retry against the package root
872
- * of the entry script. Both are checked for existence before being chosen, so
873
- * this can never silently pick a directory that is not there — a genuinely
874
- * missing build still lands on the cwd path, which is what the warning names.
875
- *
876
- * Deliberately not entry-relative FIRST: under `kick dev` the entry is the CLI
877
- * binary, whose package root is the CLI itself.
878
- *
879
- * Exported for tests only — not re-exported from the package index.
880
- */
881
- declare function resolveClientDir(clientDir: string, cwd?: string, entry?: string | undefined): string;
882
- /**
883
- * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside
884
- * your KickJS API. API routes are handled by controllers; everything else
885
- * falls back to index.html for client-side routing.
886
- *
887
- * Written against the engine-agnostic `http` surface (`serveStatic` / `use`),
888
- * so it runs under Express, Fastify, and h3 alike. The previous version
889
- * reached for `express.static`, `req.path`, and `res.send`, all of which are
890
- * Express-only — it silently served nothing on the other runtimes.
891
- *
892
- * Migrated to the `defineAdapter()` factory — call without `new`, as
893
- * `ViewAdapter` has since v4.
894
- *
895
- * @example
896
- * ```ts
897
- * import { SpaAdapter } from '@forinda/kickjs/spa'
898
- *
899
- * bootstrap({
900
- * modules,
901
- * adapters: [
902
- * SpaAdapter({
903
- * clientDir: 'dist/client', // or 'build', 'dist', etc.
904
- * apiPrefix: '/api',
905
- * }),
906
- * ],
907
- * })
908
- * ```
909
- *
910
- * File structure:
911
- * ```
912
- * dist/
913
- * client/ ← SPA build output
914
- * index.html
915
- * assets/
916
- * app.js
917
- * style.css
918
- * server/ ← KickJS server
919
- * ```
920
- */
921
- declare const SpaAdapter: AdapterFactory<SpaAdapterOptions, unknown>;
922
- //#endregion
923
- //#region src/http/health-module.d.ts
924
- /** One adapter's answer to `onHealthCheck()`. */
925
- interface HealthCheckResult {
926
- name: string;
927
- status: 'up' | 'down';
928
- }
929
- /**
930
- * What the health routes need from the running Application.
931
- *
932
- * A controller cannot reach `Application` internals, and should not: this is
933
- * the whole surface the endpoints depend on, so a replacement module can
934
- * satisfy it without knowing anything else.
935
- */
936
- interface HealthProbe {
937
- /** True once shutdown has begun and traffic should drain away. */
938
- isDraining(): boolean;
939
- /** Aggregated `onHealthCheck()` results from every adapter that has one. */
940
- checks(): Promise<HealthCheckResult[]>;
941
- }
942
- declare const HEALTH_PROBE: InjectionToken<HealthProbe>;
943
- /** Config for {@link healthModule}. */
944
- interface HealthModuleConfig {
945
- /**
946
- * Route flags to put on `GET /health/live` and `GET /health/ready`.
947
- *
948
- * The framework names no flags, so it cannot decide these probes are
949
- * "public" on your behalf — the name is yours, and every consumer that
950
- * already reads it (an auth contributor's `skipWhen`, a guard's
951
- * `exemptWhen`, `SwaggerAdapter({ publicFlag })`) then covers health with no
952
- * further wiring:
953
- *
954
- * ```ts
955
- * bootstrap({ health: { flags: ['auth.public'] } })
956
- * ```
957
- *
958
- * This replaces exempting `/health/live` and `/health/ready` by pathname,
959
- * which silently stops matching if the probe paths ever move.
960
- */
961
- flags?: RouteFlagDeclarations;
962
- }
963
- declare class HealthController {
964
- private readonly probe;
965
- constructor(probe: HealthProbe);
966
- /** Liveness: is the process up and not shutting down. */
967
- live(): Reply<200, {
968
- status: string;
969
- uptime: number;
970
- }> | Reply<503, {
971
- status: string;
972
- uptime: number;
973
- }>;
974
- /** Readiness: is every adapter's dependency answering. */
975
- ready(): Promise<Reply<200 | 503, {
976
- status: string;
977
- checks: HealthCheckResult[];
978
- }>>;
979
- }
980
- /**
981
- * `GET /health/live` and `GET /health/ready`, mounted at the root.
982
- *
983
- * A `defineModule` factory like any other module — the framework's own routes
984
- * should be declared the way it asks adopters to declare theirs, not through a
985
- * shape only the framework can produce.
986
- *
987
- * Registered automatically unless the app passes `health: false` or supplies a
988
- * module of its own. Pass `health: { flags: [...] }` to `bootstrap()` to flag
989
- * both probes — see {@link HealthModuleConfig}.
990
- */
991
- declare const healthModule: ModuleFactory<HealthModuleConfig, unknown>;
992
- //#endregion
993
- //#region src/http/application.d.ts
994
- /**
995
- * A middleware entry in the declarative pipeline.
996
- * Can be a bare handler or an object with path scoping.
997
- */
998
- type MiddlewareEntry = RequestHandler | {
999
- path: string;
1000
- handler: RequestHandler;
1001
- };
1002
- /** Options for {@link Application.shutdown}. */
1003
- interface ShutdownOptions {
1004
- /**
1005
- * Close the HTTP server and drain in-flight requests. Default `true`.
1006
- *
1007
- * Set `false` for a dev HMR rebuild, where the server is shared across
1008
- * reloads — adapters, plugins, and disposables are still torn down, which is
1009
- * the part a reload needs.
1010
- */
1011
- closeServer?: boolean;
1012
- }
1013
- /** See {@link ApplicationOptions.server}. */
1014
- interface ServerOptions {
1015
- /** TLS credentials and options (`key`, `cert`, `ca`, `pfx`, `passphrase`, …). */
1016
- tls?: tls.SecureContextOptions & tls.TlsOptions;
1017
- /** Serve HTTP/2 with HTTP/1.1 fallback. Requires `tls` and an HTTP/2-capable runtime. */
1018
- http2?: boolean;
1019
- }
1020
- interface ApplicationOptions {
1021
- /**
1022
- * Feature modules to load. Accepts both class form
1023
- * (`SomeModule extends AppModule`, instantiated via `new`) and
1024
- * instance form (output of {@link defineModule}'s factory call,
1025
- * e.g. `TasksModule({ scope: 'admin' })`) — the loader discriminates
1026
- * and either `new`-s the class or uses the instance directly.
1027
- *
1028
- * Static path — for conditional / dynamic registration, use the
1029
- * {@link ApplicationOptions.setup} callback instead.
1030
- */
1031
- modules: AppModuleEntry[];
1032
- /**
1033
- * Imperative module registration callback. Receives a
1034
- * {@link ModuleRegistry} you call `.mount(module)` on to register
1035
- * modules conditionally — based on env flags, runtime config, a
1036
- * tenant list, etc. Runs after every plugin's `setup()` hook and
1037
- * after the static `modules: [...]` array is collected.
1038
- *
1039
- * @example
1040
- * ```ts
1041
- * bootstrap({
1042
- * modules: [HelloModule()],
1043
- * setup(registry) {
1044
- * if (env.ENABLE_ADMIN) registry.mount(AdminModule())
1045
- * },
1046
- * })
1047
- * ```
1048
- */
1049
- setup?(registry: ModuleRegistry): void;
1050
- /** Adapters that hook into the lifecycle (DB, Redis, Swagger, etc.) */
1051
- adapters?: AppAdapter[];
1052
- /** Server port (falls back to PORT env var, then 3000) */
1053
- port?: number;
1054
- /**
1055
- * The Node server `start()` creates in production. Omit for plain HTTP.
1056
- *
1057
- * - `{ tls }` — HTTPS on every runtime.
1058
- * - `{ tls, http2: true }` — HTTP/2 (ALPN `h2`) with HTTP/1.1 fallback, so
1059
- * HTTP/1.1 clients and WebSocket upgrades keep working. Fastify and h3
1060
- * only; Express fails at boot with KICK007, and `http2` without `tls`
1061
- * with KICK008.
1062
- *
1063
- * Ignored in dev mode, where Vite owns the server. Most deploys terminate
1064
- * TLS / HTTP/2 at a proxy and need none of this.
1065
- *
1066
- * @example
1067
- * ```ts
1068
- * bootstrap({
1069
- * modules,
1070
- * runtime: fastifyRuntime(),
1071
- * server: {
1072
- * tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
1073
- * http2: true,
1074
- * },
1075
- * })
1076
- * ```
1077
- */
1078
- server?: ServerOptions;
1079
- /** Global API prefix (default: '/api'). Pass `''` to mount at the root. */
1080
- apiPrefix?: string;
1081
- /**
1082
- * Default API version (default: 1) — routes become /{prefix}/v{version}/{path}.
1083
- *
1084
- * `false` opts out of URL versioning: routes mount at /{prefix}/{path}.
1085
- * A module can still version itself by setting `version` on its
1086
- * `ModuleRoutes` — the per-mount value always wins over this default, in
1087
- * either direction.
1088
- */
1089
- defaultVersion?: number | false;
1090
- /**
1091
- * Global middleware pipeline. Declared in order.
1092
- * Replaces the hardcoded middleware stack — you control exactly what runs.
1093
- *
1094
- * @example
1095
- * ```ts
1096
- * bootstrap({
1097
- * modules,
1098
- * middlewares: [
1099
- * helmet(),
1100
- * cors(),
1101
- * compression(),
1102
- * morgan('dev'),
1103
- * express.json({ limit: '1mb' }),
1104
- * ],
1105
- * })
1106
- * ```
1107
- *
1108
- * If omitted, a sensible default is applied:
1109
- * requestId(), express.json({ limit: '100kb' })
1110
- */
1111
- middlewares?: MiddlewareEntry[];
1112
- /** Plugins that bundle modules, adapters, middleware, and DI bindings */
1113
- plugins?: KickPlugin[];
1114
- /**
1115
- * Global Context Contributors (#107) that apply to every route in the
1116
- * application. Merge into the per-route pipeline at the `'global'`
1117
- * precedence level — they lose to module, adapter, class, and method
1118
- * contributors with the same key, providing app-wide defaults that any
1119
- * narrower scope can override.
1120
- *
1121
- * @example
1122
- * ```ts
1123
- * const StartedAt = defineContextDecorator({
1124
- * key: 'requestStartedAt',
1125
- * resolve: () => Date.now(),
1126
- * })
1127
- *
1128
- * bootstrap({
1129
- * modules,
1130
- * contributors: [StartedAt.registration],
1131
- * })
1132
- * ```
1133
- */
1134
- contributors?: ContributorRegistrations;
1135
- /**
1136
- * Backing store strategy for {@link RequestContext} `set/get` and the
1137
- * Context Contributor pipeline (#107).
1138
- *
1139
- * - `'auto'` (default) — Application mounts {@link requestScopeMiddleware}
1140
- * automatically before any user middleware. If the user-supplied
1141
- * `middleware` list already includes `requestScopeMiddleware()`,
1142
- * detection skips the auto-mount so adopters can control its position.
1143
- * - `'manual'` — Application never mounts the wrapper. The Context
1144
- * Contributor pipeline still runs on every route — the runner is
1145
- * inserted by `router-builder` regardless of ALS state. What
1146
- * degrades without an ALS frame is the *backing store*:
1147
- * REQUEST-scoped DI throws (no `requestStore.getStore()` to read
1148
- * from) and `RequestContext.set/get` throws. Use `'manual'` only when you
1149
- * genuinely intend to wrap requests in your own ALS frame (rare —
1150
- * multi-tenant adapters used to do this; post-Phase 3 they share
1151
- * the framework's frame instead).
1152
- */
1153
- contextStore?: 'auto' | 'manual';
1154
- /**
1155
- * Controls whether KickJS registers process-level handlers at bootstrap.
1156
- *
1157
- * - `'auto'` (default) — register `uncaughtException` /
1158
- * `unhandledRejection` loggers AND `SIGINT` / `SIGTERM` →
1159
- * `app.shutdown()` → `process.exit(0)`.
1160
- * - `'errors-only'` — register the error loggers; skip the signal
1161
- * handlers. Use this when you have your own shutdown choreographer
1162
- * (OpenTelemetry SDK, Sentry, custom orchestrator) that calls
1163
- * `app.shutdown()` itself and you don't want two listeners racing
1164
- * to call `process.exit`.
1165
- * - `'manual'` — skip everything. Adopter is responsible for both
1166
- * error logging and signal-driven shutdown.
1167
- *
1168
- * Background: many observability SDKs install their own SIGTERM
1169
- * handler to flush spans/metrics before the process exits. Two
1170
- * separate handlers calling `process.exit(0)` race each other and
1171
- * can truncate the in-flight flush. Setting this to `'errors-only'`
1172
- * or `'manual'` lets the SDK own the lifecycle while still letting
1173
- * KickJS surface uncaught exceptions / rejections via the logger.
1174
- *
1175
- * The dev mode auto-detect (`__kickjs_httpServer` set by the Vite
1176
- * plugin) suppresses signal registration regardless of this option,
1177
- * since Vite owns the lifecycle in development.
1178
- */
1179
- processHooks?: 'auto' | 'errors-only' | 'manual';
1180
- /**
1181
- * The HTTP engine driver. Defaults to {@link expressRuntime} — Express stays
1182
- * the zero-config default, so existing apps are unaffected.
1183
- *
1184
- * Any `HttpRuntime` is accepted — pass `fastifyRuntime()` (from
1185
- * `@forinda/kickjs/fastify`) or a custom engine driver. Defaults to
1186
- * {@link expressRuntime}. The engine-native escape hatches
1187
- * (`getRuntimeApp()`, `AdapterContext.app`) follow the active runtime via the
1188
- * registry (`ActiveRuntime`, spec §4.3b) — Express by default, or the augmented
1189
- * engine once the `kick/runtime` typegen output is present.
1190
- */
1191
- /**
1192
- * Mount the built-in `GET /health/live` and `GET /health/ready`.
1193
- *
1194
- * On by default. Set `false` to take them over completely — supply your own
1195
- * module at `/health` and nothing collides. The built-in is registered last,
1196
- * so an app module claiming the same path already wins without this.
1197
- *
1198
- * They mount as an ordinary module, which means they sit inside the
1199
- * middleware chain: whatever guards the rest of the app guards these too.
1200
- * Pass `{ flags: [...] }` to put your own route flags on both probes — the
1201
- * way to make them reachable unauthenticated without exempting a pathname
1202
- * that can move:
1203
- *
1204
- * ```ts
1205
- * bootstrap({ health: { flags: ['auth.public'] } })
1206
- * ```
1207
- */
1208
- health?: boolean | HealthModuleConfig;
1209
- runtime?: HttpRuntime;
1210
- /**
1211
- * Requests no route matched, when the app runs inside another handler —
1212
- * `kick dev`'s Vite server, or `app.handle(req, res, next)` in a host server.
1213
- *
1214
- * - `true` (default): Fastify and h3 hand them back to that handler.
1215
- * - `false`: they are answered here — `onNotFound`, or the built-in 404 /
1216
- * 405 — the same as in production. Express always answers.
1217
- *
1218
- * Set `false` when the app owns its URLs, e.g. pages with an error page,
1219
- * so dev answers unknown URLs the way production does.
1220
- */
1221
- notFoundFallthrough?: boolean;
1222
- /** Express `trust proxy` setting */
1223
- trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean);
1224
- /** Maximum JSON body size (only used when middleware is not provided) */
1225
- jsonLimit?: string | number;
1226
- /**
1227
- * Print the route table on startup. Default: `false`. Set to `true`
1228
- * to log a per-controller summary (method counts + mount paths) once
1229
- * the app has mounted. Emitted at `info` level, so it is still subject
1230
- * to `LOG_LEVEL` filtering (visible at the default `info`; hidden at
1231
- * `warn`/`error`/`silent`).
1232
- */
1233
- logRouteTable?: boolean;
1234
- /**
1235
- * @deprecated Use {@link ApplicationOptions.logRouteTable}. Kept as an
1236
- * alias for back-compat; `logRouteTable` wins when both are set.
1237
- */
1238
- logRoutesTable?: boolean;
1239
- /**
1240
- * Maximum time (ms) to wait for graceful shutdown before forcing exit.
1241
- * Default: 30000 (30 seconds). Set to 0 to disable forced exit.
1242
- */
1243
- shutdownTimeout?: number;
1244
- /**
1245
- * Enable cluster mode for multi-core utilization.
1246
- *
1247
- * When enabled, the primary process forks worker processes that share the
1248
- * same port via Node's built-in `cluster` module (OS load balancing).
1249
- *
1250
- * - `true` — use all available CPU cores
1251
- * - `{ workers: N }` — use exactly N workers
1252
- *
1253
- * Workers are auto-restarted on crash. SIGTERM/SIGINT on the primary is
1254
- * forwarded to all workers.
1255
- *
1256
- * @example
1257
- * ```ts
1258
- * bootstrap({ modules, cluster: true })
1259
- * bootstrap({ modules, cluster: { workers: 4 } })
1260
- * ```
1261
- */
1262
- cluster?: boolean | {
1263
- workers?: number;
1264
- };
1265
- /**
1266
- * Custom 404 handler for unmatched routes. When omitted, the built-in
1267
- * handler returns `{ message: 'Not Found' }` with status 404.
1268
- *
1269
- * Connect-**shaped**, not Express-**semantic** — see {@link onError} for the
1270
- * per-runtime table. The same two caveats apply: `next()` is inert on
1271
- * Fastify and h3, and Express-only request members (`req.originalUrl`,
1272
- * `req.path`, `req.ip`) are `undefined` there, so read `req.url`.
1273
- *
1274
- * @example
1275
- * ```ts
1276
- * bootstrap({
1277
- * modules,
1278
- * onNotFound: (req, res) => {
1279
- * // `req.originalUrl` is Express-only — use `req.url` for portability.
1280
- * res.status(404).json({ error: 'Route not found', path: req.url })
1281
- * },
1282
- * })
1283
- * ```
1284
- *
1285
- * Calling `next()` hands the request to the built-in handler — the usual
1286
- * 404, or the 405 with `Allow` when the path exists under another method —
1287
- * so a custom handler can answer some requests and leave the rest.
1288
- */
1289
- onNotFound?: (req: any, res: RuntimeResponse, next: (err?: unknown) => void) => void;
1290
- /**
1291
- * Custom global error handler, receiving `(err, req, res, next)`. When
1292
- * omitted, the built-in handler formats ZodError, HttpException, and
1293
- * unexpected errors.
1294
- *
1295
- * The shape is connect-style, but it is NOT "the standard Express error
1296
- * handler" on every engine — what you actually receive differs, and the
1297
- * differences bite:
1298
- *
1299
- * | | `req` | `res` | `next` |
1300
- * | --- | --- | --- | --- |
1301
- * | Express | native `Request` | native `Response` | real `next` |
1302
- * | Fastify | `request.raw` | reply driver | **no-op** |
1303
- * | h3 | `event.node.req` | response driver | no-op (or dev fall-through) |
1304
- *
1305
- * Two consequences worth knowing before you write one:
1306
- *
1307
- * - **`next(err)` does nothing on Fastify and h3.** It is a no-op function
1308
- * there, so delegating to the default handler silently drops the error.
1309
- * Send a response yourself rather than passing it on.
1310
- * - **Express-only request members are `undefined` elsewhere.**
1311
- * `req.originalUrl`, `req.path`, and `req.ip` do not exist on the raw node
1312
- * request — use `req.url` and the `x-forwarded-*` headers, or reach for
1313
- * `ctx.ip` in a contributor / guard where a `RequestContext` is available.
1314
- *
1315
- * `res` is typed {@link RuntimeResponse} because that is what every engine
1316
- * genuinely provides: `status`, `json`, `send`, `setHeader`, `render`,
1317
- * `writeHead`, `end`. Express's own `Response` satisfies it.
1318
- *
1319
- * @example
1320
- * ```ts
1321
- * bootstrap({
1322
- * modules,
1323
- * onError: (err, req, res) => {
1324
- * logger.error(err, `${req.method} ${req.url}`) // not `originalUrl`
1325
- * res.status(err.status ?? 500).json({ error: err.message })
1326
- * },
1327
- * })
1328
- * ```
1329
- */
1330
- onError?: (err: any, req: any, res: RuntimeResponse, next: (err?: unknown) => void) => void;
1331
- /**
1332
- * Security defaults applied automatically unless opted out.
1333
- *
1334
- * When not specified, secure defaults are applied:
1335
- * - Helmet security headers are auto-injected
1336
- * - JSON body limit defaults to 1MB
1337
- *
1338
- * @example
1339
- * ```ts
1340
- * bootstrap({
1341
- * modules,
1342
- * security: {
1343
- * helmet: false, // disable auto-helmet
1344
- * },
1345
- * })
1346
- * ```
1347
- */
1348
- security?: {
1349
- /** Auto-inject helmet security headers. Default: true */
1350
- helmet?: boolean;
1351
- };
1352
- }
1353
- declare class Application {
1354
- private readonly options;
1355
- private app;
1356
- /** The HTTP engine driver. Defaults to {@link expressRuntime}. */
1357
- private readonly runtime;
1358
- private container;
1359
- private httpServer;
1360
- /** Set by startWithoutServer() — the serverless path, where cron runs over HTTP. */
1361
- private handlerMode;
1362
- /** The observer set this app installed — released on shutdown only if still current. */
1363
- private observers;
1364
- /**
1365
- * Open HTTP/2 sessions. `server.close()` stops new sessions, but on older
1366
- * Node (22 and earlier) existing ones keep accepting new streams — so
1367
- * shutdown closes them itself.
1368
- */
1369
- private readonly http2Sessions;
1370
- /** Forwarding server behind {@link fetch} on Node-based runtimes. */
1371
- private loopback?;
1372
- private readonly adapters;
1373
- /**
1374
- * Flags of every mounted route, for middleware that runs before routing and
1375
- * therefore cannot read `ctx.route` (the connect-style rate limiter). Handed
1376
- * to middleware that declares the slot — see `core/route-policy.ts`.
1377
- */
1378
- private readonly routePolicy;
1379
- private readonly plugins;
1380
- /**
1381
- * Snapshot of every module-level Context Contributor registration
1382
- * captured during `setup()`. The registrations themselves are
1383
- * frozen by `defineContextDecorator`, so storing references is
1384
- * safe — they outlive the module instances they came from.
1385
- *
1386
- * Used by {@link getContributors} so DevTools and adopter tooling
1387
- * can render the module-level contributors alongside the adapter /
1388
- * plugin / global ones. Populated once per `setup()` call; cleared
1389
- * at the start of each invocation so a re-setup (test harnesses,
1390
- * dev-server restarts) doesn't accumulate stale entries.
1391
- */
1392
- private _moduleContributors;
1393
- /** Number of HTTP requests currently being processed */
1394
- private _inFlightRequests;
1395
- /** Whether the application is draining (shutting down gracefully) */
1396
- private _draining;
1397
- /** Whether shutdown has already been initiated (prevents double-shutdown) */
1398
- private _shutdownInitiated;
1399
- /** Resolvers waiting for in-flight requests to reach zero */
1400
- private _drainResolvers;
1401
- constructor(options: ApplicationOptions);
1402
- /** Whether the application is currently draining in-flight requests */
1403
- get isDraining(): boolean;
1404
- /** Number of HTTP requests currently being processed */
1405
- get inFlightRequests(): number;
1406
- /** Get the DI container instance */
1407
- getContainer(): Container;
1408
- /**
1409
- * Express request handler — delegates to the internal Express app.
1410
- *
1411
- * Used by the Vite dev-server plugin to route requests through KickJS:
1412
- * ```ts
1413
- * const mod = await ssrLoadModule('virtual:kickjs/app')
1414
- * mod.app.handle(req, res, next)
1415
- * ```
1416
- *
1417
- * Also works as a standard Node.js request handler for production:
1418
- * ```ts
1419
- * http.createServer(app.handle.bind(app))
1420
- * ```
1421
- */
1422
- /**
1423
- * Run a web `Request` through the app — routing, middleware, validation,
1424
- * contributors, error handling — and return its `Response`, with no
1425
- * listening server required.
1426
- *
1427
- * Runtimes with a native fetch (h3) are called directly.
1428
- * Node-based runtimes (Express, Fastify) are served by forwarding to
1429
- * a server bound to `127.0.0.1` inside this process, started on first use
1430
- * and closed by {@link shutdown}; request bodies are buffered on that path.
1431
- *
1432
- * Used by `createHandler()` and by adapters (`AdapterContext.fetch`) that
1433
- * call the app's own routes, such as MCP and AI tool dispatch.
1434
- */
1435
- fetch(request: Request): Promise<Response>;
1436
- handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void;
1437
- /**
1438
- * Full setup pipeline:
1439
- * 1. Adapter beforeMount hooks (early routes — e.g. docs UI)
1440
- * 2. Adapter middleware (phase: beforeGlobal)
1441
- * 3. Global middleware (user-declared or defaults)
1442
- * 4. Adapter middleware (phase: afterGlobal)
1443
- * 5. Module registration + DI bootstrap (the built-in health module mounts
1444
- * here with everything else — it is NOT an early route)
1445
- * 6. Adapter middleware (phase: beforeRoutes)
1446
- * 7. Module route mounting
1447
- * 8. Adapter middleware (phase: afterRoutes)
1448
- * 9. Adapter beforeStart hooks
1449
- * 10. Error handlers (notFound + global)
1450
- */
1451
- /** Build the adapter context object (shared across all hooks) */
1452
- private adapterCtx;
1453
- /**
1454
- * The engine-agnostic HTTP surface handed to adapters as `ctx.http`. Each
1455
- * call routes through the active runtime over the current `this.app`, so an
1456
- * adapter written against this works under any runtime.
1457
- */
1458
- private adapterHttp;
1459
- /**
1460
- * Call an adapter hook, awaiting async hooks.
1461
- *
1462
- * A setup hook (`beforeMount`, `beforeStart`) that throws aborts boot: the
1463
- * adapter didn't finish wiring itself — a database adapter refusing to
1464
- * start with pending migrations, say — and serving anyway runs on a
1465
- * half-built app. `afterStart` runs once the server is already listening,
1466
- * so its failure is logged and the server keeps going.
1467
- */
1468
- private callHook;
1469
- setup(): Promise<void>;
1470
- /** Register modules and DI without starting the HTTP server (used by kick tinker) */
1471
- registerOnly(): Promise<void>;
1472
- /**
1473
- * Make the app ready to serve requests handed to it, with no server of its
1474
- * own — the serverless path behind {@link createHandler}.
1475
- *
1476
- * Runs the same `setup()` as {@link start} and the plugins' `onReady`, but
1477
- * nothing that needs a listening server: there is no port, no `afterStart`
1478
- * (it receives the `http.Server`), and no process signal handlers.
1479
- */
1480
- startWithoutServer(): Promise<void>;
1481
- /**
1482
- * Start the HTTP server.
1483
- *
1484
- * In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`
1485
- * created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real
1486
- * `http.Server` through `afterStart({ server })` — zero adapter changes needed.
1487
- *
1488
- * In **production**: creates its own `http.Server` and binds to the port.
1489
- */
1490
- start(): Promise<void>;
1491
- /** The production server for {@link ApplicationOptions.server}. */
1492
- private createNodeServer;
1493
- /** HMR rebuild: swap Express handler without restarting the server */
1494
- rebuild(): Promise<void>;
1495
- /**
1496
- * Graceful shutdown with request draining.
1497
- *
1498
- * 1. Stops accepting new connections (server.close())
1499
- * 2. Waits for in-flight requests to complete (up to shutdownTimeout)
1500
- * 3. Calls adapter.shutdown() for all registered adapters
1501
- * 4. Force-closes after timeout
1502
- *
1503
- * Safe to call multiple times — subsequent calls return the same promise.
1504
- */
1505
- shutdown(options?: ShutdownOptions): Promise<void>;
1506
- /**
1507
- * The engine-native app instance, typed from the active runtime
1508
- * ({@link ActiveRuntime} — Express by default). Prefer this over
1509
- * {@link getExpressApp}; under a non-Express runtime the type follows the
1510
- * augmented registry.
1511
- */
1512
- getRuntimeApp(): ActiveRuntime['app'];
1513
- /**
1514
- * The active HTTP runtime's identity + capabilities — `name` is `'express'`
1515
- * (default), `'fastify'`, or `'h3'`; `capabilities` reports what the engine
1516
- * supports (render / uploads / connectMiddleware / nativeBodyParsing).
1517
- * Surfaced by DevTools and the VS Code extension so tooling can show which
1518
- * engine the app is running on. Cheap, side-effect free.
1519
- */
1520
- getActiveRuntime(): {
1521
- name: string;
1522
- capabilities: RuntimeCapabilities;
1523
- };
1524
- /** @deprecated Use {@link getRuntimeApp}. Returns the engine-native app. */
1525
- getExpressApp(): Express;
1526
- /** Get registered adapters — used by DevToolsAdapter for peer discovery */
1527
- getAdapters(): AppAdapter[];
1528
- /**
1529
- * Get registered plugins — used by DevToolsAdapter for topology
1530
- * introspection (architecture.md §23). Read-only; returns the
1531
- * already-sorted plugin list (post-`dependsOn` topo-sort).
1532
- */
1533
- getPlugins(): readonly KickPlugin[];
1534
- /**
1535
- * Snapshot of every Context Contributor reachable from this app —
1536
- * walks **four** registration sites: adapters, plugins, modules,
1537
- * and the bootstrap `contributors` option. The devtools Topology
1538
- * tab consumes this for the Contributors panel; tests + adopters
1539
- * can call it for diagnostics.
1540
- *
1541
- * Per-route (method/class-decorator) registrations are NOT included
1542
- * here — they live on the route registry rather than on any of
1543
- * the four collection sites this method walks. A future RPC will
1544
- * surface them separately.
1545
- *
1546
- * Result shape stays minimal — `{ key, source, label, dependsOn }`
1547
- * — so we don't leak `resolve` closures or other internal fields.
1548
- * `source` matches the five-level precedence union from
1549
- * `ContributorSource` (minus `'method'` / `'class'` which require
1550
- * the per-route walk noted above).
1551
- */
1552
- getContributors(): ReadonlyArray<{
1553
- key: string;
1554
- source: 'module' | 'adapter' | 'plugin' | 'global';
1555
- label: string;
1556
- dependsOn: readonly string[];
1557
- }>;
1558
- getHttpServer(): KickServer | null;
1559
- /**
1560
- * Decide whether {@link Application} should auto-mount the
1561
- * {@link requestScopeMiddleware} ALS wrapper.
1562
- *
1563
- * Returns `false` when:
1564
- * - `contextStore: 'manual'` was set (caller manages ALS frames), or
1565
- * - the user-supplied `middleware` list already includes a
1566
- * `requestScopeMiddleware()` (detected via the symbol marker stamped
1567
- * in `middleware/request-scope.ts`).
1568
- *
1569
- * Otherwise `true` — preserves the historical default of "always wrap
1570
- * requests in an ALS frame" so existing apps see no behavior change.
1571
- */
1572
- private shouldAutoMountRequestScope;
1573
- private collectAdapterMiddleware;
1574
- private mountMiddlewareList;
1575
- private mountMiddlewareEntry;
1576
- /**
1577
- * `GET /_kick/cron/:scheduleId` — how a serverless platform
1578
- * (Vercel crons) runs `@Cron` jobs: `kick build:vercel` emits one cron entry
1579
- * per schedule pointing here. Mounted only in handler mode and only when
1580
- * `CRON_SECRET` is set; the request must carry `Authorization: Bearer
1581
- * $CRON_SECRET` (Vercel sends it). Runs every job on that schedule.
1582
- */
1583
- private mountCronTrigger;
1584
- /** Middleware that tracks in-flight requests for graceful draining */
1585
- private requestTrackingMiddleware;
1586
- }
1587
- //#endregion
1588
- export { MissingMountDepError as $, defineHttpContextDecorator as A, CRON_WORKER_ENV as B, RequestStore as C, buildRoutes as D, requestStore as E, bootstrap as F, offerRoutePolicy as G, KickCronAdapter as H, ERROR_CHANNEL as I, GroupAssetKeysOptions as J, AssetKeyPair as K, HANDLER_CHANNEL as L, isClusterPrimary as M, KickHandler as N, expressRuntime as O, createHandler as P, DuplicateMountNameError as Q, HandlerTraceContext as R, requestScopeMiddleware as S, getRequestValue as T, RoutePolicyTable as U, CronAdapterOptions as V, bindRoutePolicy as W, groupAssetKeys as X, GroupAssetKeysResult as Y, stripExt as Z, TRACEPARENT_HEADER as _, Disposable as _t, ShutdownOptions as a, DuplicateContributorError as at, parseTraceparent as b, HealthController as c, CircuitBreaker as ct, healthModule as d, CircuitBreakerStats as dt, MountCycleError as et, SpaAdapter as f, CircuitOpenError as ft, ViewAdapterOptions as g, formatKickError as gt, ViewAdapter as h, KickErrorInit as ht, ServerOptions as i, ContributorCycleError as it, ClusterOptions as j, materializeRouter as k, HealthModuleConfig as l, CircuitBreakerOptions as lt, resolveClientDir as m, KickError as mt, ApplicationOptions as n, MountSortItem as nt, HEALTH_PROBE as o, MissingContextValueError as ot, SpaAdapterOptions as p, FormatKickErrorOptions as pt, AssetKeyStrategy as q, MiddlewareEntry as r, mountSort as rt, HealthCheckResult as s, MissingContributorError as st, Application as t, MountKind as tt, HealthProbe as u, CircuitBreakerState as ut, TraceContext as v, disposeAll as vt, getRequestStore as w, traceContext as x, TraceContextOptions as y, registerDisposable as yt, RESPONSE_CHANNEL as z };
1589
- //# sourceMappingURL=application-oIPzgjfk.d.mts.map