@forinda/kickjs 10.1.0 → 10.3.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 (214) hide show
  1. package/dist/adapter-BYdxuKiM.d.mts +4916 -0
  2. package/dist/adapter-BYdxuKiM.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-B2e5XYHm.mjs +14 -0
  8. package/dist/application-B2e5XYHm.mjs.map +1 -0
  9. package/dist/bootstrap-BmALF-1Y.mjs +12 -0
  10. package/dist/{bootstrap-BdyBlBMe.mjs.map → bootstrap-BmALF-1Y.mjs.map} +1 -1
  11. package/dist/bounded-counters-aA3iI_Ei.mjs +12 -0
  12. package/dist/bounded-counters-aA3iI_Ei.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-D2dsx8RG.mjs} +2 -2
  16. package/dist/{client-ip-BbLDp03S.mjs.map → client-ip-D2dsx8RG.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-B77LTW_E.mjs +12 -0
  20. package/dist/{config-CJiGeOca.mjs.map → config-B77LTW_E.mjs.map} +1 -1
  21. package/dist/{container-CS9v9UFU.mjs → container-mvaAYThX.mjs} +3 -3
  22. package/dist/{container-CS9v9UFU.mjs.map → container-mvaAYThX.mjs.map} +1 -1
  23. package/dist/context-GbQnJB-L.mjs +12 -0
  24. package/dist/context-GbQnJB-L.mjs.map +1 -0
  25. package/dist/{context-errors-7C5TBYn7.mjs → context-errors-CPqYYhl0.mjs} +2 -2
  26. package/dist/{context-errors-7C5TBYn7.mjs.map → context-errors-CPqYYhl0.mjs.map} +1 -1
  27. package/dist/{contributor-runner-DBpRR5dl.mjs → contributor-runner-Cl5yZZy1.mjs} +3 -3
  28. package/dist/{contributor-runner-DBpRR5dl.mjs.map → contributor-runner-Cl5yZZy1.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-D1AV-Tvd.mjs +12 -0
  47. package/dist/{core-B0JmdBvX.mjs.map → core-D1AV-Tvd.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-C73UkRgc.d.mts → csrf-Cy1meSpf.d.mts} +27 -3
  51. package/dist/csrf-Cy1meSpf.d.mts.map +1 -0
  52. package/dist/csrf-D3prC4FK.mjs +12 -0
  53. package/dist/csrf-D3prC4FK.mjs.map +1 -0
  54. package/dist/decorate-BiXL-9e9.mjs +13 -0
  55. package/dist/decorate-BiXL-9e9.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-D22SDe0U.mjs} +2 -2
  59. package/dist/{define-adapter-BLKlUbSL.mjs.map → define-adapter-D22SDe0U.mjs.map} +1 -1
  60. package/dist/{disposables-CuY2S3bw.mjs → disposables-CJD_gWlA.mjs} +2 -2
  61. package/dist/{disposables-CuY2S3bw.mjs.map → disposables-CJD_gWlA.mjs.map} +1 -1
  62. package/dist/errors-By6UueCm.d.mts.map +1 -1
  63. package/dist/handler-gW_h2miq.mjs +12 -0
  64. package/dist/handler-gW_h2miq.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-D__uZPyz.mjs +12 -0
  68. package/dist/host-D__uZPyz.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 -3
  105. package/dist/http/middleware/upload.mjs.map +1 -1
  106. package/dist/http/middleware/validate.d.mts +2 -2
  107. package/dist/http/middleware/validate.mjs +2 -2
  108. package/dist/http/middleware/validate.mjs.map +1 -1
  109. package/dist/http/middleware/views.d.mts +2 -2
  110. package/dist/http/middleware/views.mjs +2 -2
  111. package/dist/http/middleware/views.mjs.map +1 -1
  112. package/dist/http/query/index.mjs +2 -2
  113. package/dist/http/router-builder.d.mts +1 -1
  114. package/dist/http/router-builder.mjs +2 -2
  115. package/dist/http/runtimes/fastify.d.mts +5 -1
  116. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  117. package/dist/http/runtimes/fastify.mjs +3 -3
  118. package/dist/http/runtimes/fastify.mjs.map +1 -1
  119. package/dist/http/runtimes/h3-web.mjs +1 -1
  120. package/dist/http/runtimes/h3.d.mts +5 -4
  121. package/dist/http/runtimes/h3.d.mts.map +1 -1
  122. package/dist/http/runtimes/h3.mjs +2 -2
  123. package/dist/http/runtimes/h3.mjs.map +1 -1
  124. package/dist/{index-CNHSbZTE.d.mts → index-CuiWSnZL.d.mts} +3 -2
  125. package/dist/index-CuiWSnZL.d.mts.map +1 -0
  126. package/dist/index.d.mts +16 -18
  127. package/dist/index.mjs +6 -2
  128. package/dist/index.mjs.map +1 -1
  129. package/dist/is-production-Dbm13WNL.mjs +12 -0
  130. package/dist/is-production-Dbm13WNL.mjs.map +1 -0
  131. package/dist/{jobs-BQ4t3TAb.mjs → jobs-s4__kZLr.mjs} +3 -3
  132. package/dist/{jobs-BQ4t3TAb.mjs.map → jobs-s4__kZLr.mjs.map} +1 -1
  133. package/dist/kv-stores-Cjel_Dkc.mjs +12 -0
  134. package/dist/kv-stores-Cjel_Dkc.mjs.map +1 -0
  135. package/dist/lazy-serve-static-w94Xs3wQ.mjs +12 -0
  136. package/dist/lazy-serve-static-w94Xs3wQ.mjs.map +1 -0
  137. package/dist/{metadata-zvd6AWkE.mjs → metadata-C2GK_17k.mjs} +2 -2
  138. package/dist/{metadata-zvd6AWkE.mjs.map → metadata-C2GK_17k.mjs.map} +1 -1
  139. package/dist/{observers-DZgs48UM.mjs → observers-boPE9XGi.mjs} +2 -2
  140. package/dist/{observers-DZgs48UM.mjs.map → observers-boPE9XGi.mjs.map} +1 -1
  141. package/dist/{query-B_k9qn0R.mjs → query-DjTeF1d4.mjs} +2 -2
  142. package/dist/{query-B_k9qn0R.mjs.map → query-DjTeF1d4.mjs.map} +1 -1
  143. package/dist/{rate-limit-Bwed3jOV.d.mts → rate-limit-BgoeahE5.d.mts} +17 -2
  144. package/dist/rate-limit-BgoeahE5.d.mts.map +1 -0
  145. package/dist/reply-CYY_CzRf.mjs +12 -0
  146. package/dist/reply-CYY_CzRf.mjs.map +1 -0
  147. package/dist/respond-Dc18G0X7.mjs +12 -0
  148. package/dist/respond-Dc18G0X7.mjs.map +1 -0
  149. package/dist/{route-flag-BWuvJsGZ.mjs → route-flag-BOQZs2Wn.mjs} +3 -3
  150. package/dist/{route-flag-BWuvJsGZ.mjs.map → route-flag-BOQZs2Wn.mjs.map} +1 -1
  151. package/dist/{route-policy-B3vM6bSf.mjs → route-policy-B8c6QfiU.mjs} +2 -2
  152. package/dist/{route-policy-B3vM6bSf.mjs.map → route-policy-B8c6QfiU.mjs.map} +1 -1
  153. package/dist/{router-builder-JvMTp50k.mjs → router-builder-DoWOIGmG.mjs} +3 -3
  154. package/dist/router-builder-DoWOIGmG.mjs.map +1 -0
  155. package/dist/{session-B4hOZj90.d.mts → session-ChXx7jG5.d.mts} +31 -4
  156. package/dist/session-ChXx7jG5.d.mts.map +1 -0
  157. package/dist/settings-C8VKewNS.d.mts +119 -0
  158. package/dist/settings-C8VKewNS.d.mts.map +1 -0
  159. package/dist/settings-DcytOCC6.mjs +14 -0
  160. package/dist/settings-DcytOCC6.mjs.map +1 -0
  161. package/dist/{upload-config-Dz2INCaa.mjs → upload-config-CzxbJALL.mjs} +2 -2
  162. package/dist/{upload-config-Dz2INCaa.mjs.map → upload-config-CzxbJALL.mjs.map} +1 -1
  163. package/dist/url-for-DGSrVfdD.mjs +12 -0
  164. package/dist/url-for-DGSrVfdD.mjs.map +1 -0
  165. package/dist/validate-CzjCbRUn.d.mts +53 -0
  166. package/dist/validate-CzjCbRUn.d.mts.map +1 -0
  167. package/dist/web.d.mts +19 -19
  168. package/dist/web.d.mts.map +1 -1
  169. package/dist/web.mjs +2 -2
  170. package/dist/web.mjs.map +1 -1
  171. package/package.json +18 -1
  172. package/dist/adapter-ClEh-Oos.d.mts +0 -2134
  173. package/dist/adapter-ClEh-Oos.d.mts.map +0 -1
  174. package/dist/app-module-DCA65GZZ.d.mts.map +0 -1
  175. package/dist/application-Dv514EeR.mjs +0 -12
  176. package/dist/application-Dv514EeR.mjs.map +0 -1
  177. package/dist/application-oIPzgjfk.d.mts +0 -1589
  178. package/dist/application-oIPzgjfk.d.mts.map +0 -1
  179. package/dist/bootstrap-BdyBlBMe.mjs +0 -12
  180. package/dist/config-CJiGeOca.mjs +0 -12
  181. package/dist/context-CtL9RxXp.mjs +0 -12
  182. package/dist/context-CtL9RxXp.mjs.map +0 -1
  183. package/dist/core-B0JmdBvX.mjs +0 -12
  184. package/dist/csrf--1t4qDov.mjs +0 -12
  185. package/dist/csrf--1t4qDov.mjs.map +0 -1
  186. package/dist/csrf-C73UkRgc.d.mts.map +0 -1
  187. package/dist/decorate-BHkdkV4l.mjs +0 -11
  188. package/dist/env-BwzF9MkZ.mjs +0 -13
  189. package/dist/env-BwzF9MkZ.mjs.map +0 -1
  190. package/dist/error-handler-BB9wAElm.d.mts +0 -63
  191. package/dist/error-handler-BB9wAElm.d.mts.map +0 -1
  192. package/dist/handler-zKfIgNo4.mjs +0 -13
  193. package/dist/handler-zKfIgNo4.mjs.map +0 -1
  194. package/dist/helmet-C2QEU6S-.d.mts.map +0 -1
  195. package/dist/index-CNHSbZTE.d.mts.map +0 -1
  196. package/dist/kv-stores-Co5k2PYA.d.mts +0 -367
  197. package/dist/kv-stores-Co5k2PYA.d.mts.map +0 -1
  198. package/dist/kv-stores-DsfVy2fk.mjs +0 -12
  199. package/dist/kv-stores-DsfVy2fk.mjs.map +0 -1
  200. package/dist/module-registry-Daf_P2oD.mjs +0 -12
  201. package/dist/module-registry-Daf_P2oD.mjs.map +0 -1
  202. package/dist/rate-limit-Bwed3jOV.d.mts.map +0 -1
  203. package/dist/reply-BDK9xt7Z.mjs +0 -12
  204. package/dist/reply-BDK9xt7Z.mjs.map +0 -1
  205. package/dist/respond-DFRj2-7q.mjs +0 -12
  206. package/dist/respond-DFRj2-7q.mjs.map +0 -1
  207. package/dist/router-builder-JvMTp50k.mjs.map +0 -1
  208. package/dist/router-builder-zWuVIOmd.d.mts +0 -56
  209. package/dist/router-builder-zWuVIOmd.d.mts.map +0 -1
  210. package/dist/session-B4hOZj90.d.mts.map +0 -1
  211. package/dist/upload-CiMtdXWD.d.mts +0 -104
  212. package/dist/upload-CiMtdXWD.d.mts.map +0 -1
  213. package/dist/validate-DMYpUnrf.d.mts +0 -25
  214. package/dist/validate-DMYpUnrf.d.mts.map +0 -1
@@ -1,2134 +0,0 @@
1
-
2
- import { i as Constructor, o as MaybePromise } from "./interfaces-C1hCSoLD.mjs";
3
- import { s as InjectionToken, t as Container } from "./container-Dpvd66Yt.mjs";
4
- import { g as FileUploadConfig, k as RouteDefinition, x as MiddlewareHandler } from "./decorators-BxNSz9Qt.mjs";
5
- import { p as RouteFlags } from "./route-flag-B1lQht6v.mjs";
6
- import { C as MetaValue, S as ExecutionContext, m as ContributorRegistrations, o as AnyContributorRegistration, r as AppModuleEntry, t as AppModule, x as ContextMetaKey } from "./app-module-DCA65GZZ.mjs";
7
- import "./cache-C0qL0NSD.mjs";
8
- import { i as ProblemDetails } from "./errors-By6UueCm.mjs";
9
- import { t as Session } from "./session-B4hOZj90.mjs";
10
- import { S as QueryFieldConfig, T as TypedParsedQuery, t as ParseQueryOptions, v as PaginatedResponse } from "./index-BfT5KZ-M.mjs";
11
- import "reflect-metadata";
12
- import http, { IncomingMessage, ServerResponse } from "node:http";
13
- import https from "node:https";
14
- import http2 from "node:http2";
15
- import { ErrorRequestHandler, Express as Express$1, NextFunction, Request as Request$1, RequestHandler, Response as Response$1 } from "express";
16
- //#region src/core/observers.d.ts
17
- /** Where an error came from. Integrations may report their own sources. */
18
- type ErrorSource = 'request' | 'uncaught' | 'unhandled-rejection' | 'background' | 'job' | (string & {});
19
- interface ErrorInfo {
20
- source: ErrorSource;
21
- requestId?: string;
22
- method?: string;
23
- /** The request URL path, as received. */
24
- path?: string;
25
- /** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */
26
- route?: string;
27
- /** The status the error was answered with, for request errors. */
28
- status?: number;
29
- /** Anything else the reporter knows — a queue and job name, a cron schedule. */
30
- context?: Record<string, unknown>;
31
- }
32
- interface ResponseInfo {
33
- method: string;
34
- path: string;
35
- /** The matched route pattern, or undefined when no route matched (404s). */
36
- route?: string;
37
- status: number;
38
- durationMs: number;
39
- requestId?: string;
40
- }
41
- /**
42
- * Report an error to every observer. The framework calls this for request
43
- * errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and
44
- * queue job failures; call it from your own integrations too (a cron runner,
45
- * a message consumer). Never throws.
46
- */
47
- declare function reportError(error: unknown, info: ErrorInfo): void;
48
- /** Report a finished response to every observer. Never throws. */
49
- declare function reportResponse(info: ResponseInfo): void;
50
- //#endregion
51
- //#region src/core/introspect.d.ts
52
- /**
53
- * Per-primitive introspection snapshot — the JSON shape an adapter or
54
- * plugin's optional `introspect()` hook returns for DevTools.
55
- *
56
- * Lives in `@forinda/kickjs` (not `@forinda/kickjs-devtools-kit`) so
57
- * adopters can type their `introspect()` return without taking on a
58
- * dep on the kit just to satisfy the contract. The kit's own
59
- * `IntrospectionSnapshot` type is structurally identical and continues
60
- * to be the canonical doc location for DevTools-side consumers; the
61
- * two stay in lockstep — if a field is added on one side it MUST be
62
- * added on the other (covered by the type-equivalence test in the
63
- * devtools-kit package).
64
- *
65
- * Cheap-by-default principle: `state` and `metrics` should be O(1) to
66
- * compute (counters, flags, recent samples). Anything that requires a
67
- * DB round trip or a full DI graph walk belongs behind a separate
68
- * explicit RPC — DevTools polls topology aggressively.
69
- */
70
- interface IntrospectionSnapshot {
71
- /**
72
- * Wire-protocol version this snapshot conforms to. The kit ships a
73
- * `PROTOCOL_VERSION` constant typed as the literal `1`; we mirror
74
- * that literal here so structural parity is enforced both ways —
75
- * an adopter who writes `protocolVersion: 1` satisfies both this
76
- * type and the kit's `IntrospectionSnapshot`. Bumping is a
77
- * coordinated kit + framework release; widen this literal in
78
- * lockstep.
79
- */
80
- protocolVersion: 1;
81
- /** Stable identity matching the `name` from `definePlugin` / `defineAdapter`. */
82
- name: string;
83
- /** Discriminator for what kind of primitive this is. */
84
- kind: IntrospectionKind;
85
- /** Optional version string from the plugin / adapter metadata. */
86
- version?: string;
87
- /**
88
- * Reactive state surface — JSON-serialisable snapshot. Keep small
89
- * (under a few KB) so polling stays cheap.
90
- */
91
- state?: Record<string, unknown>;
92
- /** DI tokens this primitive registers (`provides`) or consumes (`requires`). */
93
- tokens?: {
94
- provides: readonly string[];
95
- requires: readonly string[];
96
- };
97
- /**
98
- * Per-instance counters — active connections, in-flight jobs, cached
99
- * items, etc. Numbers only so the DevTools panel can chart trends.
100
- */
101
- metrics?: Record<string, number>;
102
- /** Self-reported memory footprint estimate, in bytes. Optional. */
103
- memoryBytes?: number;
104
- }
105
- /**
106
- * What kind of primitive an introspection snapshot describes. Matches
107
- * the kit's `IntrospectionKind` and the routing the topology aggregator
108
- * does when bucketing adapters vs plugins vs middleware vs contributor
109
- * primitives.
110
- */
111
- type IntrospectionKind = 'plugin' | 'adapter' | 'middleware' | 'contributor';
112
- /**
113
- * Convenience function signature for adopter-side helpers that return
114
- * a complete snapshot. Used by the optional `introspect?()` hook on
115
- * `AppAdapter` and `KickPlugin`.
116
- */
117
- type IntrospectFn = () => IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
118
- //#endregion
119
- //#region src/core/augmentation.d.ts
120
- /**
121
- * The canonical `KickJsPluginRegistry` interface that `kick typegen`
122
- * augments, for typed `dependsOn` between plugins and adapters.
123
- *
124
- * See `architecture.md` §21.2.1 (typegen for `dependsOn`) and §21.3.3
125
- * (standardized augmentation registry) for the design rationale.
126
- *
127
- * @module @forinda/kickjs/core/augmentation
128
- */
129
- /**
130
- * Marker interface that lists every plugin/adapter in the project. The
131
- * keys are the literal `name` field passed to `defineAdapter` /
132
- * `definePlugin` (or declared on a `class implements AppAdapter`); the
133
- * values are the kind tag (`'plugin' | 'adapter'`).
134
- *
135
- * The framework ships this empty. `kick typegen` augments it from
136
- * source so `keyof KickJsPluginRegistry` resolves to a string-literal
137
- * union of every name in scope — and therefore so do `dependsOn`
138
- * declarations on plugins/adapters.
139
- */
140
- interface KickJsPluginRegistry {}
141
- /**
142
- * Resolves to a string-literal union of every registered plugin/adapter
143
- * name when the project's typegen has populated `KickJsPluginRegistry`,
144
- * or to `string` when the registry is empty (no typegen pass yet).
145
- *
146
- * Falling back to `string` keeps fresh projects compiling — the typegen
147
- * narrowing is a progressive enhancement, not a hard prerequisite.
148
- */
149
- type KickJsPluginName = keyof KickJsPluginRegistry extends never ? string : keyof KickJsPluginRegistry & string;
150
- //#endregion
151
- //#region src/core/module-registry.d.ts
152
- /**
153
- * Imperative receiver passed to {@link KickPlugin.setup} and the
154
- * top-level `bootstrap({ setup })` callback so adopters can register
155
- * modules conditionally — based on env flags, runtime config,
156
- * tenant lists, etc. — instead of being limited to the static
157
- * `modules: [...]` array.
158
- *
159
- * @example
160
- * ```ts
161
- * bootstrap({
162
- * modules: [HelloModule()], // static — always mounted
163
- * setup(registry) {
164
- * if (env.ENABLE_ADMIN) registry.mount(AdminModule())
165
- * for (const tenant of env.TENANTS) {
166
- * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))
167
- * }
168
- * },
169
- * })
170
- * ```
171
- *
172
- * **Currently exposes only `.mount(module)` — the HTTP-feature path.**
173
- * A future `.use(module)` for non-HTTP modules (queues, cron, workers,
174
- * DI-only seeds) is planned but not yet implemented; existing non-HTTP
175
- * modules continue returning `null` from `routes()` and registering
176
- * via `.mount()`.
177
- *
178
- * Same dispatch rules as the static `modules: [...]` array — class
179
- * entries get `new`-ed at boot, `defineModule` factory output is used
180
- * directly. The registry doesn't validate the entry shape itself; the
181
- * Application loader does the typeof discrimination at mount time.
182
- */
183
- interface ModuleRegistry {
184
- /**
185
- * Register a module for the full HTTP lifecycle: `register()` runs,
186
- * `import.meta.glob` decorator side-effects fire, `routes()` is
187
- * called and its result mounted, `contributors()` are merged at
188
- * `'module'` precedence and applied to the mounted routes.
189
- *
190
- * Modules are mounted in registration order (first call → first
191
- * mount). Order across sources is: plugin static modules → plugin
192
- * `setup()` calls → user static modules → user `setup()` callback.
193
- */
194
- mount(module: AppModuleEntry): void;
195
- }
196
- /**
197
- * Internal collector implementing {@link ModuleRegistry}. Application
198
- * passes one of these to every `setup()` callback during bootstrap;
199
- * the collected `entries` array is then run through the same
200
- * class-vs-instance dispatch as the static `modules: [...]` array.
201
- *
202
- * Not exported from the public surface — adopters interact only
203
- * through the {@link ModuleRegistry} interface.
204
- */
205
- declare class MutableModuleRegistry implements ModuleRegistry {
206
- readonly entries: AppModuleEntry[];
207
- mount(module: AppModuleEntry): void;
208
- }
209
- //#endregion
210
- //#region src/core/plugin.d.ts
211
- /**
212
- * Plugin interface for extending KickJS applications.
213
- *
214
- * Plugins bundle modules, adapters, middleware, and DI bindings into a single
215
- * reusable unit. They run before the application bootstraps, so they can
216
- * register services and configure the app before any module loads.
217
- *
218
- * @example
219
- * ```ts
220
- * import type { KickPlugin } from '@forinda/kickjs'
221
- *
222
- * export class CorsPlugin implements KickPlugin {
223
- * name = 'CorsPlugin'
224
- *
225
- * middleware() {
226
- * return [cors({ origin: '*' })]
227
- * }
228
- * }
229
- *
230
- * // Usage:
231
- * bootstrap({
232
- * modules,
233
- * plugins: [new CorsPlugin()],
234
- * })
235
- * ```
236
- *
237
- * @example
238
- * ```ts
239
- * // A more complex plugin that bundles modules and adapters
240
- * export class AuthPlugin implements KickPlugin {
241
- * name = 'AuthPlugin'
242
- *
243
- * constructor(private config: AuthConfig) {}
244
- *
245
- * register(container: Container) {
246
- * container.registerFactory(AUTH_SERVICE, () => new JwtAuthService(this.config))
247
- * }
248
- *
249
- * modules() {
250
- * return [AuthModule]
251
- * }
252
- *
253
- * adapters() {
254
- * return [new AuthGuardAdapter(this.config)]
255
- * }
256
- *
257
- * middleware() {
258
- * return [passport.initialize()]
259
- * }
260
- * }
261
- * ```
262
- */
263
- interface KickPlugin {
264
- /** Human-readable name for logging, debugging, and `dependsOn` resolution. */
265
- name: string;
266
- /**
267
- * Other plugin names that must mount before this one. The framework
268
- * topologically sorts plugins at boot — cycles or unknown names throw
269
- * via {@link MountCycleError} / {@link MissingMountDepError} so bad
270
- * configurations fail boot rather than corrupt live traffic.
271
- *
272
- * Plugins with no `dependsOn` retain their declaration order, so
273
- * existing apps that don't use this field see no behaviour change.
274
- *
275
- * @example
276
- * ```ts
277
- * class MonitoringPlugin implements KickPlugin {
278
- * name = 'MonitoringPlugin'
279
- * // OTel must initialize traces before request logger reads them
280
- * dependsOn = ['OtelPlugin']
281
- * }
282
- * ```
283
- */
284
- dependsOn?: readonly KickJsPluginName[];
285
- /**
286
- * Register DI bindings before modules load.
287
- * Use this to provide services that modules depend on.
288
- */
289
- register?(container: Container): void;
290
- /**
291
- * Return modules to be loaded alongside user modules. Plugin
292
- * modules are loaded before user modules.
293
- *
294
- * Accepts both class form (`SomeModule extends AppModule`) and
295
- * instance form (output of {@link defineModule}'s factory call,
296
- * e.g. `TasksModule({ scope: 'admin' })`) — the bootstrap loader
297
- * discriminates and either `new`-s the class or uses the instance
298
- * directly.
299
- *
300
- * Static path — for conditional / dynamic registration, use
301
- * {@link KickPlugin.setup} instead.
302
- */
303
- modules?(): AppModuleEntry[];
304
- /**
305
- * Imperative module registration hook. Receives a {@link ModuleRegistry}
306
- * the plugin can call `.mount(module)` on to register modules
307
- * conditionally — e.g. based on injected config, env flags, or a
308
- * tenant list resolved at boot.
309
- *
310
- * Runs after the static {@link KickPlugin.modules} array is collected
311
- * but before user modules and the user-level `setup()` callback. The
312
- * plugin sees the same dispatch rules as everything else: class
313
- * entries get `new`-ed, factory output is used directly.
314
- *
315
- * @example
316
- * ```ts
317
- * definePlugin<{ tenants: string[] }>({
318
- * name: 'MultiTenantPlugin',
319
- * build: (config) => ({
320
- * setup(registry) {
321
- * for (const tenant of config.tenants) {
322
- * registry.mount(TenantModule.scoped(tenant, { id: tenant }))
323
- * }
324
- * },
325
- * }),
326
- * })
327
- * ```
328
- */
329
- setup?(registry: ModuleRegistry): void;
330
- /**
331
- * Return adapter instances to be added to the application.
332
- * Plugin adapters are added before user adapters.
333
- */
334
- adapters?(): AppAdapter[];
335
- /**
336
- * Return connect-style handlers — `(req, res, next)` — for the global
337
- * pipeline. Each is mounted through the runtime's `useConnect` seam, so
338
- * these work on Express, Fastify and h3 alike; only the `req` / `res`
339
- * shapes differ per engine. Plugin middleware runs before user-defined
340
- * middleware, and carries no `phase` / `path` — use an adapter's
341
- * {@link AppAdapter.middleware} for scoped or phased entries.
342
- */
343
- middleware?(): any[];
344
- /**
345
- * Return Context Contributors (#107) the plugin ships. Contributors
346
- * returned here merge into the per-route pipeline at the **`'adapter'`
347
- * precedence level** — same as those returned by adapters the plugin
348
- * ships via {@link KickPlugin.adapters}, and for the same reason: a
349
- * plugin is a cross-cutting bundle, narrower than the global default
350
- * but broader than a per-module hook.
351
- *
352
- * Use when a plugin wants to ship a typed contributor without standing
353
- * up an accompanying adapter. For full coverage of the precedence
354
- * matrix (method > class > module > adapter > global) see
355
- * `docs/guide/context-decorators.md`.
356
- *
357
- * @example
358
- * ```ts
359
- * import { defineContextDecorator, type KickPlugin } from '@forinda/kickjs'
360
- *
361
- * const LoadFlags = defineContextDecorator({
362
- * key: 'flags',
363
- * resolve: (ctx) => fetchFlags(ctx.requestId!),
364
- * })
365
- *
366
- * export class FlagsPlugin implements KickPlugin {
367
- * name = 'FlagsPlugin'
368
- * contributors() {
369
- * return [LoadFlags.registration]
370
- * }
371
- * }
372
- * ```
373
- */
374
- contributors?(): ContributorRegistrations;
375
- /**
376
- * Called after the application has fully bootstrapped.
377
- * Use for post-startup logic like logging, health registration, etc.
378
- */
379
- onReady?(container: Container): void | Promise<void>;
380
- /**
381
- * Observe every error the app reports — request errors (any status; filter
382
- * on `info.status`), uncaught exceptions, unhandled rejections, failed
383
- * `waitUntil` work, failed queue jobs, and anything passed to
384
- * `reportError()`. Observe-only: the response is not yours to change, and a
385
- * throw here is logged and skipped. The place to wire Sentry & co.
386
- */
387
- onError?(error: unknown, info: ErrorInfo): void | Promise<void>;
388
- /**
389
- * Observe every finished response — method, path, the matched route
390
- * pattern, status, duration. Only timed while something listens.
391
- */
392
- onResponse?(info: ResponseInfo): void | Promise<void>;
393
- /**
394
- * Called during application shutdown — release what this plugin owns
395
- * (connections, intervals, subscriptions).
396
- *
397
- * Runs on a real shutdown AND on **every HMR reload**, so it is a hot path
398
- * in dev, not an exit-only courtesy.
399
- *
400
- * Close only what you own. Never close the shared HTTP server: in dev it is
401
- * Vite's listener, and closing it leaves the port dead with no rebind. The
402
- * framework closes it itself on a real shutdown.
403
- *
404
- * Time-boxed: `shutdownTimeout` on a real shutdown, `min(shutdownTimeout,
405
- * 5s)` on a reload. Overruns are logged by name and skipped.
406
- */
407
- shutdown?(): void | Promise<void>;
408
- /**
409
- * Optional DevTools introspection hook (architecture.md §23). Returns
410
- * a snapshot describing this plugin's current state, metrics, and DI
411
- * tokens. DevTools awaits the result, so async work is fine — but keep
412
- * the implementation cheap (counters + flags, no DB round trips) since
413
- * the topology endpoint polls on a short interval.
414
- *
415
- * The return type lives in `@forinda/kickjs` itself
416
- * ({@link IntrospectionSnapshot}) so adopters can author `introspect()`
417
- * without importing the kit just to satisfy the contract. The kit's
418
- * own `IntrospectionSnapshot` type stays structurally identical;
419
- * either import works.
420
- */
421
- introspect?(): IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
422
- /**
423
- * Optional DevTools tabs this plugin contributes (architecture.md §23).
424
- * Same shape as {@link AppAdapter.devtoolsTabs}; the kit's
425
- * `DevtoolsTabDescriptor` types it for plugin authors.
426
- */
427
- devtoolsTabs?(): readonly unknown[];
428
- }
429
- //#endregion
430
- //#region src/core/define-plugin.d.ts
431
- /**
432
- * Options passed to {@link definePlugin}. Mirrors the spec in
433
- * `architecture.md` §21.3.1 + §21.2.2 (Phase A "lite").
434
- */
435
- interface DefinePluginOptions<TConfig> {
436
- /** Stable identity used for logging, `dependsOn` lookups, and `.scoped()` namespacing. */
437
- name: string;
438
- /** Optional plugin version — surfaced to DevTools and `kick add` compatibility checks (Phase B). */
439
- version?: string;
440
- /**
441
- * Peer-version ranges this plugin needs from the framework or other
442
- * plugins. Recorded as metadata; runtime enforcement lands in §21.4.4.
443
- */
444
- requires?: {
445
- kickjs?: string;
446
- };
447
- /** Default config merged under any caller overrides. */
448
- defaults?: Partial<TConfig>;
449
- /** Builds the underlying {@link KickPlugin} from the resolved config. */
450
- build(config: TConfig, ctx: BuildContext): Omit<KickPlugin, 'name'>;
451
- }
452
- /**
453
- * Hook context handed to a plugin/adapter `build` function. `name` is the
454
- * resolved instance name (the bare definition name for the bare call,
455
- * or `${defName}:${scope}` for `.scoped()`). `scoped` is the discriminator
456
- * authors use to namespace DI tokens or resource keys.
457
- */
458
- interface BuildContext {
459
- name: string;
460
- scoped: boolean;
461
- }
462
- /**
463
- * Async-config form of a plugin or adapter — `inject` lists DI tokens to
464
- * resolve from the container, then `useFactory` produces the config.
465
- *
466
- * Plugins resolve this lazily inside `onReady`, so any module/adapter/
467
- * middleware/contributor a plugin contributes via `build` is **not
468
- * available** when `.async()` is used. Use the bare/`.scoped()` form for
469
- * plugins that need to register modules or middleware.
470
- */
471
- interface PluginAsyncOptions<TConfig> {
472
- inject?: ReadonlyArray<unknown>;
473
- useFactory(...deps: any[]): TConfig | Promise<TConfig>;
474
- }
475
- /**
476
- * Factory returned by {@link definePlugin}. Callable form is the singleton
477
- * (`AuthPlugin(config)`); `.scoped()` and `.async()` are the multi-instance
478
- * and deferred-config forms.
479
- */
480
- interface PluginFactory<TConfig> {
481
- (config?: Partial<TConfig>): KickPlugin;
482
- scoped(scopeName: string, config?: Partial<TConfig>): KickPlugin;
483
- async(opts: PluginAsyncOptions<TConfig>): KickPlugin;
484
- /** Read-only access to the original definition — useful for DevTools introspection. */
485
- readonly definition: Readonly<DefinePluginOptions<TConfig>>;
486
- }
487
- /**
488
- * Build a {@link KickPlugin} factory from a typed definition. See
489
- * `architecture.md` §21.2.2 for the design rationale.
490
- *
491
- * @example
492
- * ```ts
493
- * const FlagsPlugin = definePlugin<FlagsConfig>({
494
- * name: 'FlagsPlugin',
495
- * defaults: { defaultTtl: 60_000 },
496
- * build(config) {
497
- * return {
498
- * register(container) {
499
- * container.registerInstance(FLAGS, makeProvider(config))
500
- * },
501
- * }
502
- * },
503
- * })
504
- *
505
- * bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })
506
- * ```
507
- */
508
- declare function definePlugin<TConfig = Record<string, unknown>>(options: DefinePluginOptions<TConfig>): PluginFactory<TConfig>;
509
- //#endregion
510
- //#region src/core/define-module.d.ts
511
- /**
512
- * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}
513
- * and {@link DefinePluginOptions} so adopters learn one mental model
514
- * across all three primitives.
515
- *
516
- * The optional `TExtra` generic lets a module ship public methods
517
- * beyond the standard {@link AppModule} contract — they're preserved
518
- * on the returned module instance so external callers (tests, sibling
519
- * modules) can invoke them directly.
520
- */
521
- interface DefineModuleOptions<TConfig, TExtra = unknown> {
522
- /**
523
- * Stable identity surfaced in diagnostics, route logs, and
524
- * `.scoped()` namespacing. Required because boot-time error
525
- * messages reference modules by name — anonymous modules make
526
- * cycles + missing-dep errors hard to localize.
527
- */
528
- name: string;
529
- /** Optional version string surfaced in diagnostics. */
530
- version?: string;
531
- /**
532
- * Optional kickjs version constraint. Enforced by the framework
533
- * when implemented; today it lives on the definition for
534
- * documentation and forward compatibility.
535
- */
536
- requires?: {
537
- kickjs?: string;
538
- };
539
- /**
540
- * Default config merged with overrides at instantiation time
541
- * (`MyModule({ field: x })`). Call-site overrides win.
542
- */
543
- defaults?: Partial<TConfig>;
544
- /**
545
- * Build the AppModule shape from the resolved config and context.
546
- * `ctx.name` is the resolved instance name (the bare definition
547
- * name for the default call, or `${name}:${scope}` for
548
- * `.scoped()`); `ctx.scoped` discriminates so the build function
549
- * can branch on namespacing if needed.
550
- *
551
- * Return any extension methods alongside the standard
552
- * {@link AppModule} surface — they're typed via `TExtra` and stay
553
- * accessible on the resulting instance.
554
- */
555
- build(config: TConfig, ctx: BuildContext): AppModule & TExtra;
556
- }
557
- /**
558
- * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}
559
- * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),
560
- * inspect (`MyModule.definition`).
561
- *
562
- * `.async()` is intentionally **not** part of the module factory
563
- * surface. Module config has no async-resolution window: `register()`
564
- * and `routes()` both run synchronously during bootstrap, before any
565
- * adapter `beforeStart` hook fires. Adopters that need async-resolved
566
- * config push it into an adapter (which has `beforeStart`), then
567
- * inject the resolved value into the module via DI tokens.
568
- */
569
- interface ModuleFactory<TConfig, TExtra = unknown> {
570
- (config?: Partial<TConfig>): AppModule & TExtra;
571
- scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra;
572
- readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>;
573
- }
574
- /**
575
- * Build an {@link AppModule} factory from a typed definition. Pairs
576
- * with {@link defineAdapter}, {@link definePlugin}, and
577
- * {@link defineContextDecorator} as the fourth `define*` primitive
578
- * — adopters write modules the same way they write adapters and
579
- * plugins.
580
- *
581
- * The returned factory produces real {@link AppModule} instances
582
- * that drop into `bootstrap({ modules })` directly. The legacy
583
- * class form (`class TasksModule implements AppModule { ... }`) keeps
584
- * working — `bootstrap` accepts either shape.
585
- *
586
- * @example
587
- * ```ts
588
- * interface TasksConfig {
589
- * scope: 'public' | 'admin'
590
- * }
591
- *
592
- * const TasksModule = defineModule<TasksConfig>({
593
- * name: 'TasksModule',
594
- * defaults: { scope: 'public' },
595
- * build: (config, { name }) => ({
596
- * register(container) {
597
- * container.registerInstance(`tasks:scope:${name}`, config.scope)
598
- * },
599
- * routes() {
600
- * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }
601
- * },
602
- * contributors() {
603
- * return [LoadTenant.registration]
604
- * },
605
- * }),
606
- * })
607
- *
608
- * bootstrap({
609
- * modules: [
610
- * TasksModule(), // public scope (defaults)
611
- * TasksModule.scoped('admin', { scope: 'admin' }),
612
- * ],
613
- * })
614
- * ```
615
- */
616
- declare function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(options: DefineModuleOptions<TConfig, TExtra>): ModuleFactory<TConfig, TExtra>;
617
- //#endregion
618
- //#region src/core/define-modules.d.ts
619
- /**
620
- * Chainable registry returned by {@link defineModules}. Extends
621
- * `Array<AppModuleEntry>` so it drops into `bootstrap({ modules })`
622
- * unchanged — the framework loader already iterates the array, so a
623
- * `ModuleList` IS a valid `modules` value with no special handling.
624
- *
625
- * The added affordance is `.mount(module)` returning `this` so
626
- * adopters can build the list fluently:
627
- *
628
- * ```ts
629
- * const modules = defineModules()
630
- * .mount(HelloModule())
631
- * .mount(AdminModule())
632
- *
633
- * bootstrap({ modules })
634
- * ```
635
- *
636
- * **Why not just use a plain array?** Two reasons. First, the
637
- * fluent shape reads more naturally for module-list construction —
638
- * adopters used to `definePlugin().scoped(...)` / `defineAdapter(...)`
639
- * see the same call-then-call pattern. Second, the registry is the
640
- * stable extension point: a future `.use(module)` for non-HTTP
641
- * modules (queues, cron, workers) lands as a method on `ModuleList`
642
- * without breaking the `Array<AppModuleEntry>` superclass contract.
643
- */
644
- declare class ModuleList extends Array<AppModuleEntry> {
645
- /**
646
- * Append a module to the list. Returns `this` for chaining.
647
- *
648
- * Accepts both class form (`SomeModule extends AppModule`) and
649
- * `defineModule` factory output — same as the underlying
650
- * `bootstrap({ modules })` array. The framework loader
651
- * discriminates `typeof entry === 'function'` at boot.
652
- */
653
- mount(module: AppModuleEntry): this;
654
- }
655
- /**
656
- * Build a {@link ModuleList} for the application. Optional vararg
657
- * lets adopters seed the list inline; subsequent `.mount()` calls
658
- * append.
659
- *
660
- * @example
661
- * ```ts
662
- * import { bootstrap, defineModules } from '@forinda/kickjs'
663
- * import { HelloModule } from './modules/hello/hello.module'
664
- * import { AdminModule } from './modules/admin/admin.module'
665
- *
666
- * // Fluent — most common
667
- * const modules = defineModules()
668
- * .mount(HelloModule())
669
- * .mount(AdminModule())
670
- *
671
- * // Or seeded inline + chained
672
- * const modules2 = defineModules(HelloModule()).mount(AdminModule())
673
- *
674
- * await bootstrap({ modules })
675
- * ```
676
- *
677
- * The returned value is an `AppModuleEntry[]` subclass — `bootstrap`
678
- * accepts it directly without any special-casing. For conditional /
679
- * dynamic registration at bootstrap time (env flags, runtime config,
680
- * tenant lists), use the `setup(registry)` callback on `bootstrap`
681
- * instead — both surfaces compose.
682
- */
683
- declare function defineModules(...initial: AppModuleEntry[]): ModuleList;
684
- //#endregion
685
- //#region src/core/metadata.d.ts
686
- /**
687
- * Typed utilities for reflect-metadata operations.
688
- *
689
- * Replaces scattered Reflect.defineMetadata/getMetadata calls with a single
690
- * source of truth. If we later move to Stage 3 decorators or a WeakMap-based
691
- * store, only this file changes — all 24+ consumer files stay untouched.
692
- *
693
- * Keys may be symbols, strings, or `InjectionToken<T>` objects produced by
694
- * `createToken()`. Using `createToken` is the preferred pattern because the
695
- * token's phantom type flows through the helpers, enabling type-safe reads.
696
- */
697
- type MetaKey = symbol | string | InjectionToken<unknown>;
698
- /** Set metadata on a class (or prototype for property decorators) */
699
- declare function setClassMeta<T>(key: MetaKey, value: T, target: object): void;
700
- /** Set metadata on a specific method */
701
- declare function setMethodMeta<T>(key: MetaKey, value: T, target: object, method: string): void;
702
- /** Get metadata from a class, returning `fallback` if not set */
703
- declare function getClassMeta<T>(key: MetaKey, target: object, fallback: T): T;
704
- /** Get metadata from a specific method, returning `fallback` if not set */
705
- declare function getMethodMeta<T>(key: MetaKey, target: object, method: string, fallback: T): T;
706
- /** Check if metadata exists on a class */
707
- declare function hasClassMeta(key: MetaKey, target: object): boolean;
708
- /** Get metadata from a class with no default (returns undefined if absent) */
709
- declare function getClassMetaOrUndefined<T>(key: MetaKey, target: object): T | undefined;
710
- /** Get metadata from a method with no default (returns undefined if absent) */
711
- declare function getMethodMetaOrUndefined<T>(key: MetaKey, target: object, method: string): T | undefined;
712
- /** Append items to an array stored in class metadata */
713
- declare function pushClassMeta<T>(key: MetaKey, target: object, ...items: T[]): void;
714
- /** Append items to an array stored in method metadata */
715
- declare function pushMethodMeta<T>(key: MetaKey, target: object, method: string, ...items: T[]): void;
716
- /** Set a key/value in a Map stored in class metadata */
717
- declare function setInMetaMap<K, V>(key: MetaKey, target: object, mapKey: K, mapValue: V): void;
718
- /** Get a Map from class metadata (returns empty Map if absent) */
719
- declare function getMetaMap<K, V>(key: MetaKey, target: object): Map<K, V>;
720
- /** Set a key/value in a Record stored in class metadata */
721
- declare function setInMetaRecord<V>(key: MetaKey, target: object, recKey: string | number, recValue: V): void;
722
- /** Get a Record from class metadata (returns empty object if absent) */
723
- declare function getMetaRecord<V>(key: MetaKey, target: object): Record<string | number, V>;
724
- //#endregion
725
- //#region src/core/contributor-pipeline.d.ts
726
- /**
727
- * Where a contributor was registered, ordered by precedence
728
- * (lower index wins). Mirrors `architecture.md` §20.4.
729
- *
730
- * Levels (highest → lowest precedence):
731
- * - `'method'` — `@LoadX` on a controller method.
732
- * - `'class'` — `@LoadX` on a controller class.
733
- * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.
734
- * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies
735
- * to every module's routes.
736
- * - `'global'` — `ApplicationOptions.contributors`. App-wide default.
737
- */
738
- type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global';
739
- /**
740
- * Input row to {@link buildPipeline}. Pairs a registration with its origin
741
- * so dedup can apply the precedence rule and diagnostic errors can name
742
- * the offending site.
743
- *
744
- * `registration` is the type-erased {@link AnyContributorRegistration}
745
- * — the runner doesn't care about each registration's narrow `D` /
746
- * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic
747
- * contributors in the same `externalSources` / `contributors()`
748
- * array. The narrow generics from `defineContextDecorator` survive
749
- * at the *definition* site (where `resolve` is typed); they're erased
750
- * here so collections compose without `as any` casts.
751
- */
752
- interface SourcedRegistration {
753
- registration: AnyContributorRegistration;
754
- source: ContributorSource;
755
- /** Human label surfaced in DuplicateContributorError messages. */
756
- label?: string;
757
- }
758
- /**
759
- * Resolved, validated, topo-sorted pipeline ready for execution.
760
- *
761
- * `contributors` is in execution order — every entry's `dependsOn`
762
- * keys appear earlier. `keys` is the set of all keys this pipeline
763
- * produces; the runner uses it for fast existence checks and the
764
- * builder uses it for missing-dep validation.
765
- */
766
- interface ContributorPipeline {
767
- readonly contributors: readonly AnyContributorRegistration[];
768
- readonly keys: ReadonlySet<string>;
769
- }
770
- interface BuildPipelineOptions {
771
- /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */
772
- route?: string;
773
- }
774
- /**
775
- * Build, validate, and topo-sort a contributor pipeline.
776
- *
777
- * Pipeline:
778
- *
779
- * 1. Group sources by precedence (method > class > module > adapter > global).
780
- * 2. Within each precedence level, two contributors with the same `key`
781
- * raise {@link DuplicateContributorError}.
782
- * 3. Across levels, the highest-precedence contributor wins each key
783
- * (lower-precedence duplicates are silently dropped — that is the
784
- * documented override mechanism, not an error).
785
- * 4. Every key referenced by `dependsOn` must be produced by the
786
- * surviving set, otherwise {@link MissingContributorError}.
787
- * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after
788
- * the queue drains form a cycle → {@link ContributorCycleError}
789
- * with a reconstructed path.
790
- *
791
- * Pure function — no DI, no I/O. Safe to call once at startup per
792
- * route and cache the result.
793
- */
794
- declare function buildPipeline(sources: readonly SourcedRegistration[], options?: BuildPipelineOptions): ContributorPipeline;
795
- //#endregion
796
- //#region src/core/contributor-runner.d.ts
797
- interface RunContributorsOptions {
798
- /** Pre-built, validated, topo-sorted pipeline. */
799
- pipeline: ContributorPipeline;
800
- /** The execution context contributors read from and write into. */
801
- ctx: ExecutionContext;
802
- /** DI container used to resolve declared `deps`. */
803
- container: Container;
804
- /**
805
- * Route flags in force for the matched route, used to honour a
806
- * registration's `skipWhen` / `onlyWhen`. Omitted outside a route (the
807
- * pipeline then runs every contributor, as before).
808
- */
809
- flags?: RouteFlags;
810
- }
811
- /**
812
- * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.
813
- *
814
- * Sequential — one contributor at a time, in the topo order chosen at
815
- * pipeline-build time. Per `architecture.md` §20.10, V1 does not run
816
- * contributors in parallel even within the same topo level; that is a
817
- * V2 follow-up gated on profiling.
818
- *
819
- * ## Error matrix (architecture.md §20.9)
820
- *
821
- * | resolve outcome | optional | onError defined | runner behaviour |
822
- * |-----------------|----------|-----------------|--------------------------------------------------|
823
- * | throws | true | — | skip; `ctx.get(key)` remains undefined |
824
- * | throws | false | yes | call hook; returned value (if any) stored |
825
- * | throws | false | no | propagate the original error |
826
- * | hook throws | — | yes | propagate the new error |
827
- * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |
828
- * | resolves | — | — | `ctx.set(key, value)` |
829
- *
830
- * Container.resolve() throwing while building `deps` is treated as a
831
- * resolve-side throw and flows through the same matrix — adopters who
832
- * need different behaviour for missing-DI vs. data-lookup failures can
833
- * wrap the container access inside their own `resolve()`.
834
- */
835
- declare function runContributors(options: RunContributorsOptions): Promise<void>;
836
- //#endregion
837
- //#region src/core/define-adapter.d.ts
838
- /**
839
- * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}
840
- * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter
841
- * symmetry rationale.
842
- *
843
- * The optional `TExtra` generic lets an adapter ship public methods
844
- * beyond the standard {@link AppAdapter} contract — they're preserved
845
- * on the returned adapter instance so external callers (tests, peer
846
- * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`
847
- * for the canonical use case.
848
- */
849
- interface DefineAdapterOptions<TConfig, TExtra = unknown> {
850
- /**
851
- * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`
852
- * namespacing. Required for adapters that participate in `dependsOn`
853
- * sort — error messages reference adapters by name.
854
- */
855
- name: string;
856
- version?: string;
857
- requires?: {
858
- kickjs?: string;
859
- };
860
- defaults?: Partial<TConfig>;
861
- build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra;
862
- }
863
- /**
864
- * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`
865
- * but resolved during `beforeStart` (the earliest async hook in
866
- * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner
867
- * adapter are **not** picked up. Use the bare/`.scoped()` form when you need
868
- * those.
869
- */
870
- interface AdapterAsyncOptions<TConfig> {
871
- inject?: ReadonlyArray<unknown>;
872
- useFactory(...deps: any[]): TConfig | Promise<TConfig>;
873
- }
874
- /**
875
- * Factory returned by {@link defineAdapter}. Same surface as
876
- * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn
877
- * one mental model for both primitives. Returned instances carry both
878
- * the standard {@link AppAdapter} contract and any `TExtra` extension
879
- * methods the `build` function exposed.
880
- */
881
- interface AdapterFactory<TConfig, TExtra = unknown> {
882
- (config?: Partial<TConfig>): AppAdapter & TExtra;
883
- scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra;
884
- async(opts: AdapterAsyncOptions<TConfig>): AppAdapter;
885
- readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>;
886
- }
887
- /**
888
- * Build an {@link AppAdapter} factory from a typed definition. See
889
- * `architecture.md` §21.3.4 for migration guidance — most first-party
890
- * adapter packages collapse to a single `defineAdapter()` call after this
891
- * lands.
892
- *
893
- * @example
894
- * ```ts
895
- * const TenantAdapter = defineAdapter<TenantConfig>({
896
- * name: 'TenantAdapter',
897
- * defaults: { strategy: 'header', required: true },
898
- * build: (config) => ({
899
- * middleware: () => [tenantResolverMiddleware(config)],
900
- * beforeStart: ({ container }) => registerTenantFactory(container, config),
901
- * }),
902
- * })
903
- *
904
- * bootstrap({
905
- * adapters: [
906
- * TenantAdapter({ strategy: 'subdomain' }),
907
- * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),
908
- * ],
909
- * })
910
- * ```
911
- */
912
- declare function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(options: DefineAdapterOptions<TConfig, TExtra>): AdapterFactory<TConfig, TExtra>;
913
- //#endregion
914
- //#region src/http/context.d.ts
915
- /**
916
- * Input shape for the typed problem-detail convenience methods on
917
- * {@link ProblemSender} (`ctx.problem.notFound`, `.badRequest`, etc.) —
918
- * RFC 9457 details minus the `status`, which each method pre-fills.
919
- */
920
- type ProblemInput = Omit<ProblemDetails, 'status'>;
921
- /**
922
- * Callable response helper for RFC 9457 — Problem Details responses.
923
- * Returned by `ctx.problem`. Invoke directly for a fully-specified
924
- * payload, or use the named convenience methods to pre-fill `status` +
925
- * `title` for the common codes.
926
- *
927
- * Each call sets `Content-Type: application/problem+json` and serializes
928
- * the canonical shape (defaulting `type` to `about:blank` and `title` to
929
- * the IANA reason phrase per RFC 9457 §3.1.1 / §3.1.4).
930
- *
931
- * @example
932
- * ```ts
933
- * ctx.problem({
934
- * type: 'https://api.example.com/problems/out-of-credit',
935
- * status: 403,
936
- * detail: 'Your balance is 30, but that costs 50.',
937
- * balance: 30, // extension per §3.2
938
- * })
939
- *
940
- * ctx.problem.notFound({ detail: 'User abc not found' })
941
- * ctx.problem.validation(zodResult.error.issues)
942
- * ```
943
- */
944
- interface ProblemSender {
945
- (input: ProblemDetails): RuntimeResponse;
946
- /** 400 Bad Request — RFC 9457. */
947
- badRequest(input?: ProblemInput): RuntimeResponse;
948
- /** 401 Unauthorized — RFC 9457. */
949
- unauthorized(input?: ProblemInput): RuntimeResponse;
950
- /** 403 Forbidden — RFC 9457. */
951
- forbidden(input?: ProblemInput): RuntimeResponse;
952
- /** 404 Not Found — RFC 9457. */
953
- notFound(input?: ProblemInput): RuntimeResponse;
954
- /** 409 Conflict — RFC 9457. */
955
- conflict(input?: ProblemInput): RuntimeResponse;
956
- /** 422 Unprocessable Entity — RFC 9457. */
957
- unprocessable(input?: ProblemInput): RuntimeResponse;
958
- /** 429 Too Many Requests — RFC 9457. */
959
- tooManyRequests(input?: ProblemInput): RuntimeResponse;
960
- /** 500 Internal Server Error — RFC 9457. */
961
- internal(input?: ProblemInput): RuntimeResponse;
962
- /**
963
- * 422 with Zod issues serialized into the `errors` extension per
964
- * RFC 9457 §3.2's array convention. Pass `error.issues` from a Zod
965
- * `safeParse` failure or `error.issues` from a thrown ZodError.
966
- */
967
- validation(issues: any[], input?: ProblemInput): RuntimeResponse;
968
- }
969
- /**
970
- * Recursively marks every property of `T` as `readonly`. Preserves
971
- * `Function`, `Date`, and `RegExp` unchanged, and converts `Map` / `Set`
972
- * to `ReadonlyMap` / `ReadonlySet` so their mutating methods (`set`,
973
- * `delete`, `add`, `clear`) are removed from the public surface.
974
- * Tuples keep their positional element types — only their per-element
975
- * mutability is locked.
976
- *
977
- * Exposed as a utility for adopters who want to opt into compile-time
978
- * sealing of their own shapes. **No longer applied to
979
- * `RequestContext.{body,params,query,headers,file,files}`** — that
980
- * broke TS narrowing / discriminated-union drilldowns on typed request
981
- * payloads. Runtime read-only enforcement now lives in
982
- * {@link makeReadOnlyProxy} (dev-only Proxy that warns on writes,
983
- * no-op in production).
984
- *
985
- * Type-only. No runtime cost. `DeepReadonly<any>` is `any` (TS
986
- * distributes conditional types over `any`).
987
- */
988
- type DeepReadonly<T> = T extends ((...args: never[]) => unknown) ? T : T extends Date | RegExp ? T : T extends Map<infer K, infer V> ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>> : T extends Set<infer V> ? ReadonlySet<DeepReadonly<V>> : T extends readonly (infer U)[] ? number extends T['length'] ? ReadonlyArray<DeepReadonly<U>> : { readonly [K in keyof T]: DeepReadonly<T[K]>; } : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]>; } : T;
989
- /**
990
- * The shape of a single route entry in `KickRoutes`. Generated by
991
- * `kick typegen` and consumed via the `Ctx<T>` helper. Each field is
992
- * `unknown` by default and is filled in as the typegen learns more
993
- * about the route (URL params from the path, body/query from validation
994
- * schemas, etc.).
995
- */
996
- interface RouteShape {
997
- params?: unknown;
998
- body?: unknown;
999
- query?: unknown;
1000
- response?: unknown;
1001
- /**
1002
- * Union of context keys `kick typegen` proved are populated for this
1003
- * route — the keys of every context contributor applied at method or
1004
- * class level. Drives {@link RequestContext.require} narrowing, so
1005
- * calling `ctx.require()` for a key this route doesn't carry is a
1006
- * compile error instead of a request-time throw.
1007
- *
1008
- * `string` (the default) means "not proven", not "no keys". Typegen
1009
- * emits `string` whenever it cannot see the full picture — a
1010
- * contributor registered at module / adapter / bootstrap level, or an
1011
- * unrecognised decorator that might bundle contributors of its own.
1012
- * Narrowing an unprovable route would produce compile errors for keys
1013
- * that really are present.
1014
- */
1015
- contextKeys?: string;
1016
- }
1017
- /**
1018
- * Unified request/response abstraction passed to every controller method.
1019
- * Shields handlers from raw Express objects and provides convenience methods.
1020
- *
1021
- * Implements {@link ExecutionContext} so the transport-agnostic Context
1022
- * Contributor pipeline (#107) can run against this concrete HTTP context
1023
- * the same way it will run against future WS / queue / cron contexts.
1024
- */
1025
- declare class RequestContext<TBody = any, TParams = any, TQuery = any,
1026
- /**
1027
- * Context keys proven present for this route. Defaults to
1028
- * {@link ContextMetaKey} — every key the project has registered — which
1029
- * collapses to `string` when neither registry has been augmented, so a
1030
- * handler typed as plain `RequestContext` keeps today's behaviour. That
1031
- * default is also the deliberate escape hatch when typegen's view of a
1032
- * route is incomplete.
1033
- */
1034
- TKeys extends ContextMetaKey = ContextMetaKey> implements ExecutionContext<TKeys> {
1035
- readonly req: ActiveRuntime['request'];
1036
- readonly res: ActiveRuntime['response'];
1037
- readonly next: NextFunction;
1038
- /**
1039
- * Engine-agnostic response driver the response helpers write through. Under
1040
- * the Express runtime it IS `res` (Express's Response satisfies
1041
- * {@link RuntimeResponse} structurally); other runtimes pass a thin wrapper
1042
- * over their native reply as the optional fourth argument.
1043
- */
1044
- private readonly _response;
1045
- /**
1046
- * The route this request matched: its method, path, controller, handler name
1047
- * and resolved {@link MatchedRoute.flags}.
1048
- *
1049
- * Available to anything running inside the matched route — route middleware,
1050
- * contributors, guards, the handler. Global middleware runs before route
1051
- * matching, so it sees `undefined` there.
1052
- *
1053
- * ```ts
1054
- * if (ctx.route?.flags.has('auth.public')) return next()
1055
- * ```
1056
- */
1057
- get route(): MatchedRoute | undefined;
1058
- constructor(req: ActiveRuntime['request'], res: ActiveRuntime['response'], next: NextFunction, responseDriver?: RuntimeResponse);
1059
- /**
1060
- * Memo of the most recent {@link qs} call this request. The query
1061
- * object is immutable for a request's lifetime, so a repeat call with
1062
- * the same `(fieldConfig, options)` references returns the cached
1063
- * parse instead of re-walking the filter/sort strings.
1064
- */
1065
- private _qsMemo?;
1066
- /** Memoized {@link problem} sender — built lazily on first access. */
1067
- private _problem?;
1068
- /**
1069
- * Read-side accessor for the per-request metadata map.
1070
- *
1071
- * Returns the AsyncLocalStorage map (`requestStore.getStore().values`)
1072
- * shared with the Context Contributor pipeline when an ALS frame is
1073
- * active. Returns `null` outside any frame — read-side callers
1074
- * (`ctx.get`, `ctx.user`, `ctx.tenantId`, `ctx.roles`) treat that as
1075
- * "no metadata" and fall through to their `req.*` defaults. Reads
1076
- * never throw because outside an ALS frame nobody could have written
1077
- * via `ctx.set` anyway, so an empty answer is the truthful one.
1078
- */
1079
- private metadataReadOnly;
1080
- /**
1081
- * Write-side accessor for the per-request metadata map.
1082
- *
1083
- * Returns the same map as {@link metadataReadOnly} when an ALS frame
1084
- * is active. Throws otherwise — writing to a fallback map outside
1085
- * the ALS frame would silently lose data because other call sites
1086
- * (downstream contributors, request-logger, etc.) read from the
1087
- * canonical store and would never see it. Mount
1088
- * `requestScopeMiddleware()` (Application does this for you in
1089
- * `'auto'` mode) or wrap your test setup in
1090
- * `requestStore.run({...}, () => …)` to fix.
1091
- */
1092
- private metadataForWrite;
1093
- /**
1094
- * Parsed request body. Wrapped in a dev-only Proxy that warns when
1095
- * adopters try to mutate Zod-validated payloads in place — compute
1096
- * new values and stash them via `ctx.set('key', value)` or a Context
1097
- * Contributor instead. Reach for `ctx.req.body` if you genuinely
1098
- * need the raw, mutable Express handle (rare).
1099
- *
1100
- * In production the Proxy is bypassed and `this.req.body` is
1101
- * returned as-is — no runtime cost on the hot path.
1102
- */
1103
- get body(): TBody;
1104
- /** Path parameters parsed from the route — read-only, see {@link body}. */
1105
- get params(): TParams;
1106
- /** Parsed query string — read-only, see {@link body}. */
1107
- get query(): TQuery;
1108
- /** Inbound HTTP headers — read-only, see {@link body}. */
1109
- get headers(): Request$1['headers'];
1110
- get requestId(): string | undefined;
1111
- /**
1112
- * `AbortSignal` that fires when the underlying HTTP request is
1113
- * closed — either because the client disconnected before the
1114
- * response was sent, or because Node's socket-close event ran
1115
- * after a normal response. Multiple `RequestContext` wrappers for
1116
- * the same request (router-builder constructs one per
1117
- * middleware/contributor pipeline / main handler) share a single
1118
- * `AbortController` cached on the underlying `req` object, so the
1119
- * signal is stable across the request lifecycle.
1120
- *
1121
- * Thread it through anything that takes an `AbortSignal` so the
1122
- * work cancels as soon as the client gives up — e.g. a kickjs-db
1123
- * relational query:
1124
- *
1125
- * ```ts
1126
- * @Get('/:id/full')
1127
- * async show(ctx: RequestContext) {
1128
- * const row = await this.repo.findFullById(ctx.params.id, ctx.signal)
1129
- * if (!row) return ctx.notFound()
1130
- * ctx.json(row)
1131
- * }
1132
- * ```
1133
- *
1134
- * The repo passes `signal` to `db.query.<table>.findUnique({ signal })`;
1135
- * if the client disconnects mid-flight, the in-flight query rejects
1136
- * with `RelationalQueryCancelledError` instead of consuming the
1137
- * connection until completion.
1138
- *
1139
- * Implementation note — both `req.on('close')` and `res.on('close')`
1140
- * are wired so the signal aborts regardless of whether the close
1141
- * event lands on the request stream or the response stream first.
1142
- * Subsequent fires are no-ops (`AbortController.abort()` is
1143
- * idempotent).
1144
- */
1145
- get signal(): AbortSignal;
1146
- /**
1147
- * The request's session — set by the `session()` middleware, which must be
1148
- * installed. Type your keys once by augmenting `SessionData`:
1149
- *
1150
- * ```ts
1151
- * declare module '@forinda/kickjs' {
1152
- * interface SessionData { userId?: string }
1153
- * }
1154
- * ```
1155
- */
1156
- get session(): Session;
1157
- /**
1158
- * The authenticated user set by AuthAdapter.
1159
- * Reads from the per-request metadata store first (`ctx.set('user', ...)`),
1160
- * then falls back to `req.user` (set directly by AuthAdapter middleware).
1161
- *
1162
- * Extend the `AuthUser` interface via module augmentation in your own auth
1163
- * module — see the BYO Auth recipe in the docs
1164
- * to get full typing.
1165
- *
1166
- * @example
1167
- * ```ts
1168
- * @Get('/me')
1169
- * @Authenticated()
1170
- * getProfile(ctx: RequestContext) {
1171
- * const user = ctx.user
1172
- * if (!user) return ctx.notFound()
1173
- * return ctx.json({ user })
1174
- * }
1175
- * ```
1176
- */
1177
- get user(): MetaValue<'user', Record<string, any>> | undefined;
1178
- /**
1179
- * Tenant identifier for multi-tenant apps. Reads `user.tenantId` —
1180
- * populated either by `AuthAdapter.testMode({ tenantId })`, a tenant
1181
- * resolver middleware, or manually on the strategy's `mapPayload`.
1182
- *
1183
- * Augment `AuthUser` (or `ContextMeta['user']`) to widen the return
1184
- * type if your user shape guarantees a non-`string | undefined` id.
1185
- */
1186
- get tenantId(): string | undefined;
1187
- /**
1188
- * Effective role list for the current user. Prefers `user.tenantRoles`
1189
- * (populated by `AuthAdapterOptions.roleResolver` under a tenant) and
1190
- * falls back to `user.roles`. Returns an empty array when the user is
1191
- * absent or the shape has neither field.
1192
- */
1193
- get roles(): string[];
1194
- /**
1195
- * Parse the request query string into structured filters, sort, pagination, and search.
1196
- * Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).
1197
- *
1198
- * Generic over the field config: when passed an inline literal (or
1199
- * `as const`), `filters[].field` and `sort[].field` are narrowed to
1200
- * the exact whitelisted field names. Pass nothing or a non-literal
1201
- * config and you get the loose `string` fallback.
1202
- *
1203
- * @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
1204
- * @param options - Limits (`maxLimit`, `defaultLimit`, `maxSearchLength`) and an
1205
- * `onReject` hook. By default a rejected/over-broad field is logged via
1206
- * `console.warn` with the request id; pass an explicit `onReject` to override
1207
- * (e.g. throw to return a 400), or `onReject: () => {}` to silence.
1208
- *
1209
- * @example
1210
- * ```ts
1211
- * @Get('/')
1212
- * async list(ctx: RequestContext) {
1213
- * const parsed = ctx.qs({
1214
- * filterable: ['status', 'priority'],
1215
- * sortable: ['createdAt', 'title'],
1216
- * } as const)
1217
- * parsed.filters[0].field // typed as 'status' | 'priority'
1218
- * parsed.sort[0].field // typed as 'createdAt' | 'title'
1219
- * }
1220
- * ```
1221
- */
1222
- qs<TConfig extends QueryFieldConfig | undefined = undefined>(fieldConfig?: TConfig, options?: ParseQueryOptions): TypedParsedQuery<TConfig>;
1223
- /**
1224
- * Single uploaded file (requires `@FileUpload({ mode: 'single' })`).
1225
- * Wrapped in a dev-only Proxy that warns on mutation — see {@link body}.
1226
- * File metadata is set by the upload middleware and shouldn't be
1227
- * mutated downstream.
1228
- */
1229
- get file(): Express.Multer.File | undefined;
1230
- /**
1231
- * Array of uploaded files (requires `@FileUpload({ mode: 'array' })`).
1232
- * The array (and each entry in dev) is wrapped in a read-only Proxy
1233
- * that warns on `push`/`pop` and per-file mutation. Use
1234
- * `ctx.req.files` if you genuinely need the mutable Express handle.
1235
- */
1236
- get files(): Express.Multer.File[] | undefined;
1237
- /**
1238
- * Read a value from the per-request metadata store.
1239
- *
1240
- * The key is constrained to {@link ContextMetaKey} — the keys registered in
1241
- * `ContextMeta` / `ContextKeys` — so a typo is a compile error rather than a
1242
- * permanent `undefined`. Projects that have augmented neither registry get
1243
- * `string`, exactly as before.
1244
- *
1245
- * Constrained by `ContextMetaKey` and deliberately NOT by `TKeys`: "does this
1246
- * key exist in the app" is a different question from "does this route carry
1247
- * it", and narrowing by the latter would turn an incomplete typegen view into
1248
- * false errors for keys written by middleware. Presence is `require`'s job;
1249
- * this always returns `| undefined`.
1250
- *
1251
- * When `ContextMeta` has a matching key the return type is inferred
1252
- * automatically. For ad-hoc keys, pass a generic: `ctx.get<MyType>('custom')`.
1253
- */
1254
- get<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined;
1255
- /**
1256
- * Read a value that a contributor is expected to have produced, and
1257
- * throw {@link MissingContextValueError} when it hasn't.
1258
- *
1259
- * Use this instead of `ctx.get(key)!` anywhere the value is a
1260
- * precondition rather than an optional extra — permissions, tenants,
1261
- * the resolved subject of the route. The non-null assertion compiles
1262
- * whether or not the producing contributor is actually applied to the
1263
- * route, so a dropped `@LoadTenant` turns into `undefined` flowing
1264
- * silently into an auth check. `require()` fails loudly at that point
1265
- * instead, naming the key.
1266
- *
1267
- * ```ts
1268
- * // before — compiles even if @OperatorPerm was never applied
1269
- * const perm = ctx.get('operatorPerm')!
1270
- *
1271
- * // after — throws MissingContextValueError naming the key + route
1272
- * const perm = ctx.require('operatorPerm')
1273
- * ```
1274
- *
1275
- * When `TKeys` is narrowed — which it is for a handler typed as
1276
- * `Ctx<KickRoutes…>`, from typegen's per-route `contextKeys` — asking
1277
- * for a key the route doesn't carry is a compile error, so a dropped
1278
- * decorator fails the build. `TKeys` stays `string` (no narrowing) for
1279
- * a plain `RequestContext` and for any route typegen couldn't prove
1280
- * complete; there this is a runtime guarantee only.
1281
- * See `architecture.md` §20.14.
1282
- *
1283
- * `null` counts as present; only `undefined` (or a missing entry)
1284
- * throws. A contributor that deliberately resolves to `null` is
1285
- * expressing "looked, found nothing", which is a real value — which
1286
- * is why the return type is `Exclude<…, undefined>` and NOT
1287
- * `NonNullable<…>`. The latter would strip `null` from the type while
1288
- * the runtime still hands it back, so a caller would be told a value
1289
- * is non-null and then get `null`.
1290
- */
1291
- require<K extends TKeys>(key: K): Exclude<MetaValue<K>, undefined>;
1292
- /**
1293
- * Best-effort `"GET /path"` label for error messages. Runtime-agnostic:
1294
- * express/fastify requests and web-standard `Request` all expose
1295
- * `method` + `url`, but none of them are guaranteed here, so every
1296
- * access is defensive and the whole thing is optional.
1297
- */
1298
- private routeLabel;
1299
- /**
1300
- * Write a value to the per-request metadata store. Throws when no
1301
- * AsyncLocalStorage frame is active — see {@link metadataForWrite}
1302
- * for why a silent fallback is the wrong default.
1303
- */
1304
- set<K extends ContextMetaKey>(key: K, value: MetaValue<K>): void;
1305
- /**
1306
- * Set a response header. Runtime-neutral — works on every engine and on
1307
- * the web/edge entry. No-op guards are the runtime's job (headers set
1308
- * after the response settles are ignored or throw per engine).
1309
- */
1310
- setHeader(name: string, value: string | number | readonly string[]): this;
1311
- json(data: any, status?: number): RuntimeResponse;
1312
- created(data: any): RuntimeResponse;
1313
- private sendJson;
1314
- noContent(): unknown;
1315
- /**
1316
- * @deprecated Prefer {@link ProblemSender.notFound | ctx.problem.notFound()},
1317
- * which emits an RFC 9457 — Problem Details response. This helper stays
1318
- * for backward compatibility and will not be removed.
1319
- */
1320
- notFound(message?: string): RuntimeResponse;
1321
- /**
1322
- * @deprecated Prefer {@link ProblemSender.badRequest | ctx.problem.badRequest()},
1323
- * which emits an RFC 9457 — Problem Details response. This helper stays
1324
- * for backward compatibility and will not be removed.
1325
- */
1326
- badRequest(message: string): RuntimeResponse;
1327
- /**
1328
- * RFC 9457 — Problem Details for HTTP APIs response helper.
1329
- * https://datatracker.ietf.org/doc/html/rfc9457
1330
- *
1331
- * `ctx.problem(...)` sends a canonical problem-detail response with
1332
- * `Content-Type: application/problem+json`. The convenience methods
1333
- * (`ctx.problem.notFound`, `.badRequest`, etc.) pre-fill `status` +
1334
- * `title` for the common codes.
1335
- *
1336
- * `type` defaults to `about:blank` (§3.1.1); `title` defaults to the
1337
- * IANA reason phrase for `status` (§3.1.4). Extension members per §3.2
1338
- * pass through unchanged.
1339
- *
1340
- * @example
1341
- * ```ts
1342
- * ctx.problem({
1343
- * type: 'https://api.example.com/problems/out-of-credit',
1344
- * status: 403,
1345
- * detail: 'Your balance is 30, but that costs 50.',
1346
- * instance: `/account/${ctx.user.id}/messages/${ctx.params.id}`,
1347
- * balance: 30,
1348
- * })
1349
- *
1350
- * ctx.problem.notFound({ detail: 'User abc not found' })
1351
- * ctx.problem.validation(zodResult.error.issues)
1352
- * ```
1353
- *
1354
- * @see {@link ProblemException} for the exception-throwing equivalent
1355
- * (use it from services where `ctx` isn't in scope).
1356
- */
1357
- get problem(): ProblemSender;
1358
- private sendProblem;
1359
- /**
1360
- * Send an HTML response.
1361
- *
1362
- * Passes the full MIME type rather than the `'html'` shorthand. The
1363
- * shorthand is an Express affordance — `res.type()` runs it through a MIME
1364
- * lookup — but the Fastify and h3 drivers forward the string to their own
1365
- * `type()` / `setHeader()` verbatim, so `'html'` reached the wire as a
1366
- * malformed `Content-Type: html` on those engines. Fastify 5.10 started
1367
- * normalising that invalid value to `text/plain`, which is what surfaced it.
1368
- *
1369
- * Express produces `text/html; charset=utf-8` for `.type('html')`, so
1370
- * spelling it out here is byte-identical there and correct everywhere else.
1371
- */
1372
- /**
1373
- * The client's IP address, or `undefined` when it cannot be determined.
1374
- *
1375
- * Prefers the value the runtime computed (Express derives `req.ip` from the
1376
- * app's `trust proxy` setting; Fastify from `trustProxy`), because raw
1377
- * forwarded headers are client-SPOOFABLE on deployments that do not
1378
- * normalize them. The header fallbacks exist for runtimes with no `ip`
1379
- * field at all — notably the web/edge entry.
1380
- *
1381
- * `ctx.req.ip` is Express-only, so reaching for it directly broke on
1382
- * Fastify and h3.
1383
- */
1384
- get ip(): string | undefined;
1385
- /**
1386
- * Redirect the client. Works on every runtime.
1387
- *
1388
- * Every engine spells this differently — Express and Fastify have
1389
- * `res.redirect()`, h3 has `sendRedirect(event, location, code)` — and none
1390
- * of them is shared, so this writes the status and `Location` header through
1391
- * the runtime response surface, which all four expose.
1392
- *
1393
- * The response carries no body. Express sends a short text line and h3 an
1394
- * HTML meta-refresh fallback; a bare `Location` with a 3xx is sufficient per
1395
- * RFC 9110, and interpolating the URL into an HTML body would add an
1396
- * injection surface to a value this method already warns is dangerous.
1397
- *
1398
- * ::: warning
1399
- * Never pass an unvalidated user-supplied `url`. An attacker-controlled
1400
- * destination turns this into an open redirect, which is a common phishing
1401
- * primitive. Allow-list the target or keep it relative.
1402
- * :::
1403
- */
1404
- redirect(url: string, status?: number): unknown;
1405
- html(content: string, status?: number): RuntimeResponse;
1406
- /**
1407
- * Send a body with its content type — XML, plain text, CSV, an image.
1408
- * Runtime-neutral, like `json()` and `html()`. `type` defaults to
1409
- * `text/plain; charset=utf-8`.
1410
- *
1411
- * @example
1412
- * ```ts
1413
- * ctx.send(sitemapXml, { type: 'application/xml' })
1414
- * ctx.send(csv, { type: 'text/csv; charset=utf-8', status: 200 })
1415
- * ```
1416
- */
1417
- send(body: string | Uint8Array, options?: {
1418
- type?: string;
1419
- status?: number;
1420
- }): RuntimeResponse;
1421
- /**
1422
- * Send `buffer` as a file download named `filename`. The name is written
1423
- * per RFC 6266 — an ASCII fallback plus `filename*` in UTF-8 — so a name
1424
- * from an upload (quotes, line breaks, non-Latin text) can't break the header.
1425
- */
1426
- download(buffer: Buffer, filename: string, contentType?: string): RuntimeResponse;
1427
- /**
1428
- * Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).
1429
- * Requires a ViewAdapter to be configured in bootstrap().
1430
- *
1431
- * @param template - Template name (without extension, relative to viewsDir)
1432
- * @param data - Data to pass to the template
1433
- *
1434
- * @example
1435
- * ```ts
1436
- * ctx.render('dashboard', { user, title: 'Dashboard' })
1437
- * ctx.render('emails/welcome', { name: 'Alice' })
1438
- * ```
1439
- */
1440
- render(template: string, data?: Record<string, any>): unknown;
1441
- /**
1442
- * Parse query params and return a standardized paginated response.
1443
- * Calls `ctx.qs()` internally, then wraps your data with pagination meta.
1444
- *
1445
- * @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`
1446
- * @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields
1447
- *
1448
- * @example
1449
- * ```ts
1450
- * @Get('/')
1451
- * async list(ctx: RequestContext) {
1452
- * return ctx.paginate(
1453
- * async (parsed) => {
1454
- * const data = await db.select().from(users)
1455
- * .where(query.where).limit(parsed.pagination.limit)
1456
- * .offset(parsed.pagination.offset).all()
1457
- * const total = await db.select({ count: count() }).from(users).get()
1458
- * return { data, total: total?.count ?? 0 }
1459
- * },
1460
- * { filterable: ['name', 'role'], sortable: ['createdAt'] },
1461
- * )
1462
- * }
1463
- * ```
1464
- */
1465
- paginate<T, TConfig extends QueryFieldConfig | undefined = undefined>(fetcher: (parsed: TypedParsedQuery<TConfig>) => Promise<{
1466
- data: T[];
1467
- total: number;
1468
- }>, fieldConfig?: TConfig): Promise<PaginatedResponse<T>>;
1469
- /**
1470
- * Start an SSE (Server-Sent Events) stream.
1471
- * Sets the correct headers and returns helpers to send events.
1472
- *
1473
- * Pass a payload type to get typed sends — and `return sse` from the
1474
- * handler so `kick typegen` carries the event type into
1475
- * `KickRoutes.Api`, where `@forinda/kickjs-client`'s `api.stream()`
1476
- * picks it up (the returned handler is ignored at runtime — the
1477
- * response is already streaming).
1478
- *
1479
- * @example
1480
- * ```ts
1481
- * interface Tick { time: string }
1482
- *
1483
- * @Get('/events')
1484
- * async stream(ctx: RequestContext) {
1485
- * const sse = ctx.sse<Tick>()
1486
- *
1487
- * const interval = setInterval(() => {
1488
- * sse.send({ time: new Date().toISOString() }, 'tick')
1489
- * }, 1000)
1490
- *
1491
- * sse.onClose(() => clearInterval(interval))
1492
- * return sse // typed as SseHandler<Tick> → response inference
1493
- * }
1494
- * ```
1495
- */
1496
- /**
1497
- * Send a web-standard `Response` — status, headers (every `Set-Cookie`
1498
- * kept) and body, streamed chunk by chunk — on any runtime. For handing off
1499
- * to libraries that speak `Request`/`Response`, such as the MCP SDK's
1500
- * web-standard transport.
1501
- *
1502
- * Resolves once the body is fully written. Stops reading the body when the
1503
- * client disconnects.
1504
- *
1505
- * @example
1506
- * ```ts
1507
- * @Post('/mcp')
1508
- * async mcp(ctx: RequestContext) {
1509
- * await ctx.sendResponse(await transport.handleRequest(webRequest))
1510
- * }
1511
- * ```
1512
- */
1513
- sendResponse(response: Response): Promise<void>;
1514
- /**
1515
- * Keep `promise` running after the response is sent — an audit log, an
1516
- * email, an analytics call. The Node server's `shutdown()` waits for it;
1517
- * `createHandler()` and the web entry hand it to the platform's
1518
- * `waitUntil` when you pass the platform context in. A rejection is
1519
- * logged, never unhandled. Same as the standalone `waitUntil()` export.
1520
- */
1521
- waitUntil(promise: Promise<unknown>): void;
1522
- sse<T = unknown>(): SseHandler<T>;
1523
- }
1524
- /**
1525
- * The handle {@link RequestContext.sse} returns. The optional phantom
1526
- * `__sse` property carries the event payload type STRUCTURALLY — never set
1527
- * at runtime — so `kick typegen`'s response inference (handler `return sse`)
1528
- * flows it into `KickRoutes.Api`, and `@forinda/kickjs-client` detects SSE
1529
- * routes without importing any server types.
1530
- */
1531
- interface SseHandler<T = unknown> {
1532
- /** Phantom event-payload type marker — never assigned at runtime. */
1533
- readonly __sse?: T;
1534
- /** Send an SSE event with optional event name and id. */
1535
- send(data: T, event?: string, id?: string): void;
1536
- /** Send a comment line (keeps the connection alive through proxies). */
1537
- comment(text: string): void;
1538
- /** Register a callback for client disconnect. */
1539
- onClose(fn: () => void): void;
1540
- /** End the SSE stream. */
1541
- close(): void;
1542
- }
1543
- /**
1544
- * Short alias for `RequestContext` parameterised by a route shape.
1545
- *
1546
- * Use with `kick typegen`'s generated `KickRoutes` namespace for
1547
- * fully-typed `ctx.params`, `ctx.body`, and `ctx.query`. Metadata
1548
- * typing (`ctx.get()`, `ctx.set()`, `ctx.user`) comes from
1549
- * `ContextMeta` augmentation and works on all `RequestContext` instances.
1550
- *
1551
- * @example
1552
- * ```ts
1553
- * @Get('/:id')
1554
- * getUser(ctx: Ctx<KickRoutes.UserController['getUser']>) {
1555
- * ctx.params.id // typed from RouteShape
1556
- * ctx.body // typed from RouteShape
1557
- * ctx.user // typed from ContextMeta
1558
- * ctx.get('tenant') // typed from ContextMeta
1559
- * }
1560
- * ```
1561
- */
1562
- type Ctx<TRoute extends RouteShape = RouteShape> = RequestContext<TRoute extends {
1563
- body: infer B;
1564
- } ? B : any, TRoute extends {
1565
- params: infer P;
1566
- } ? P : any, TRoute extends {
1567
- query: infer Q;
1568
- } ? Q : any, TRoute extends {
1569
- contextKeys: infer K;
1570
- } ? K extends ContextMetaKey ? K : ContextMetaKey : ContextMetaKey>;
1571
- /**
1572
- * Global ambient registry of typed routes, populated by `kick typegen`.
1573
- *
1574
- * Interfaces inside `KickRoutes` correspond to controller classes (each
1575
- * property one route method, conforming to `RouteShape`) — plus the
1576
- * reserved `KickRoutes.Api`: a flat `'METHOD /mounted/path'` map over the
1577
- * same shapes, consumed by `@forinda/kickjs-client`. Don't name a
1578
- * controller class `Api` — it would declaration-merge into that map.
1579
- *
1580
- * Empty by default — declarations come from `.kickjs/types/kick__routes.ts`
1581
- * generated alongside the rest of the typegen output.
1582
- */
1583
- declare global {
1584
- namespace KickRoutes {}
1585
- }
1586
- /** `attachment; filename="…"; filename*=UTF-8''…` for any file name (RFC 6266 / RFC 8187). */
1587
- declare function contentDisposition(filename: string): string;
1588
- //#endregion
1589
- //#region src/http/runtime.d.ts
1590
- /** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */
1591
- type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
1592
- /**
1593
- * A context-based handler: the runtime-neutral unit of the request pipeline.
1594
- * Contributors, route middleware (via {@link MiddlewareHandler}), and the
1595
- * terminal controller call all reduce to this shape. The runtime owns how a
1596
- * `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,
1597
- * next)`; Fastify in its own handler).
1598
- */
1599
- type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>;
1600
- /**
1601
- * Connect-style middleware — the portable middleware format. Built-in
1602
- * middleware and adopter-supplied Express middleware are this shape. The
1603
- * Express runtime hands them straight to `app.use`; later runtimes bridge
1604
- * them (Fastify via `@fastify/middie`, h3 via its node adapter).
1605
- *
1606
- * Typed as the Express handler union for M1 (Express is the only runtime);
1607
- * a future milestone narrows this to bare node `(req, res, next)` primitives
1608
- * once the driver layer lands.
1609
- */
1610
- type ConnectMiddleware = RequestHandler | ErrorRequestHandler;
1611
- /**
1612
- * One materialized route, as plain data. Produced by {@link buildRouteTable}
1613
- * from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.
1614
- *
1615
- * The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`
1616
- * keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),
1617
- * `contributorRunner` is a closure over the pre-built pipeline + container (the
1618
- * pipeline is built — and any cycle / missing-dep error thrown — at table-build
1619
- * time, i.e. boot), and `validation` / `upload` stay as metadata the runtime
1620
- * materializes its own way. Faithfully reproducing the legacy Express chain —
1621
- * not collapsing it — is what keeps M1 behavior-neutral.
1622
- */
1623
- interface RouteEntry {
1624
- method: RouteMethod;
1625
- /** Path with `:param` segments — the portable subset all engines accept. */
1626
- path: string;
1627
- /** Class + method middleware, in execution order; each receives `(ctx, next)`. */
1628
- middlewares: MiddlewareHandler[];
1629
- /**
1630
- * Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),
1631
- * or `null` when no contributors apply. Closes over the built pipeline and
1632
- * the DI container so it stays engine-neutral; the runtime advances the
1633
- * chain (Express: call `next()`) once it resolves.
1634
- */
1635
- contributorRunner: CtxHandler | null;
1636
- /**
1637
- * Contributors registered with `beforeValidation: true`. Runtimes run this
1638
- * right after publishing the matched route — before validation, upload and
1639
- * middleware — so a rejection (401) lands before a malformed body's 422.
1640
- * Absent or `null` when no contributor asks for it.
1641
- */
1642
- earlyContributorRunner?: CtxHandler | null;
1643
- /** Terminal handler: resolves the controller per-request and invokes it. */
1644
- handler: CtxHandler;
1645
- /** Introspection + runtime-materialized concerns (swagger/typegen read this). */
1646
- meta: RouteMeta;
1647
- }
1648
- /** Per-route metadata: introspection refs plus runtime-materialized concerns. */
1649
- interface RouteMeta {
1650
- /**
1651
- * Owning controller class — for DI resolution and adapter introspection.
1652
- * Absent for ad-hoc routes registered through {@link AdapterHttp.route},
1653
- * which have no controller class behind them.
1654
- */
1655
- controller?: Constructor;
1656
- /** Handler method name on the controller, when there is one. */
1657
- handlerName?: string;
1658
- /** Zod/JSON-schema validation config from the route decorator, if any. */
1659
- validation?: RouteDefinition['validation'];
1660
- /** `@FileUpload` config, if present — the runtime supplies the backend. */
1661
- upload?: FileUploadConfig;
1662
- /**
1663
- * Route flags in force here, resolved at build time (method over class).
1664
- * Enabled flags only: a flag declared `false` at a higher-precedence site is
1665
- * absent rather than present-and-false, so `has()` is always the right
1666
- * question. See `core/route-flag.ts`.
1667
- */
1668
- flags?: RouteFlags;
1669
- /**
1670
- * The full mounted pattern (`/api/v1/users/:id`) — set by the Application
1671
- * for controller routes. `path` is relative to the module mount.
1672
- */
1673
- pattern?: string;
1674
- }
1675
- interface MatchedRoute {
1676
- method: RouteMethod;
1677
- /** Path as declared on the handler, e.g. `/:id`. */
1678
- path: string;
1679
- /**
1680
- * The full route pattern including the mount prefix and version, e.g.
1681
- * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls
1682
- * back to `path` for routes registered without a mount.
1683
- */
1684
- pattern: string;
1685
- controller?: Constructor;
1686
- handlerName?: string;
1687
- /** Enabled flags only — see {@link RouteMeta.flags}. */
1688
- flags: RouteFlags;
1689
- }
1690
- /** A controller's routes grouped under the module mount prefix. */
1691
- type RouteTable = {
1692
- mountPath: string;
1693
- routes: RouteEntry[];
1694
- }[];
1695
- interface RuntimeResponse {
1696
- status(code: number): RuntimeResponse;
1697
- json(data: unknown): RuntimeResponse;
1698
- send(data: unknown): RuntimeResponse;
1699
- type(contentType: string): RuntimeResponse;
1700
- setHeader(name: string, value: string | number | readonly string[]): unknown;
1701
- render(view: string, data?: Record<string, unknown>): unknown;
1702
- writeHead(statusCode: number, headers?: Record<string, string>): unknown;
1703
- flushHeaders(): unknown;
1704
- write(chunk: string | Buffer): boolean;
1705
- end(data?: unknown): unknown;
1706
- once(event: 'close' | 'drain', listener: () => void): unknown;
1707
- readonly headersSent: boolean;
1708
- }
1709
- /**
1710
- * Per-runtime type map: the engine-native request / response / app types an
1711
- * `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.
1712
- */
1713
- interface RuntimeTypeMap {
1714
- request: unknown;
1715
- response: unknown;
1716
- app: unknown;
1717
- }
1718
- /** The Express runtime's native types — the default when nothing is augmented. */
1719
- interface ExpressRuntimeTypes {
1720
- request: Request$1;
1721
- response: Response$1;
1722
- app: Express$1;
1723
- }
1724
- /**
1725
- * Augmentable runtime registry. Empty by default; the `kick/runtime` typegen
1726
- * plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured
1727
- * runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,
1728
- * `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`
1729
- * — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is
1730
- * uniform with `kick/db` and env typing.
1731
- *
1732
- * @example
1733
- * ```ts
1734
- * // .kickjs/types/kick__runtime.d.ts — generated by typegen
1735
- * declare module '@forinda/kickjs' {
1736
- * interface KickRuntimeRegister {
1737
- * runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes
1738
- * }
1739
- * }
1740
- * ```
1741
- */
1742
- interface KickRuntimeRegister {}
1743
- /** The active runtime's type map — the augmented one, or Express by default. */
1744
- type ActiveRuntime = KickRuntimeRegister extends {
1745
- runtime: infer R extends RuntimeTypeMap;
1746
- } ? R : ExpressRuntimeTypes;
1747
- /** Options passed to {@link HttpRuntime.createApp}. */
1748
- interface RuntimeAppOptions {
1749
- /**
1750
- * Express `trust proxy` setting (and the equivalent on other engines). The
1751
- * function form is Express-specific; other runtimes interpret the simpler
1752
- * shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).
1753
- */
1754
- trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean);
1755
- /**
1756
- * When the app is mounted inside another handler (`kick dev`'s Vite server,
1757
- * `app.handle(req, res, next)` in a host server), hand requests no route
1758
- * matched back to it — `true`, the default — or answer them here with the
1759
- * app's not-found handling — `false`. Express always answers.
1760
- */
1761
- notFoundFallthrough?: boolean;
1762
- }
1763
- /** Where a connect middleware sits and what it scopes to. */
1764
- interface UseConnectOptions {
1765
- path?: string | RegExp | ReadonlyArray<string | RegExp>;
1766
- }
1767
- /**
1768
- * Optional engine capabilities. Absence means the corresponding `ctx` feature
1769
- * raises a clear error on that runtime rather than failing obscurely.
1770
- */
1771
- interface RuntimeCapabilities {
1772
- /** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */
1773
- render: boolean;
1774
- /** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */
1775
- uploads: boolean;
1776
- /** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */
1777
- connectMiddleware: boolean;
1778
- /**
1779
- * The engine parses request bodies itself (Fastify, h3). When true, the
1780
- * Application skips its default `express.json()` so the body stream isn't
1781
- * consumed twice (which would deadlock the engine's own parser). Express:
1782
- * false — it relies on the `express.json()` connect middleware.
1783
- */
1784
- nativeBodyParsing: boolean;
1785
- /**
1786
- * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2
1787
- * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:
1788
- * true. Express: false — it does not run on that layer. Absent = false, so
1789
- * custom runtimes opt in explicitly.
1790
- */
1791
- http2?: boolean;
1792
- }
1793
- /**
1794
- * The engine driver. KickJS owns decorators → {@link RouteTable}, the
1795
- * contributor pipeline, the `RequestContext` surface, and error mapping. The
1796
- * runtime owns app/server creation, route materialization, connect-middleware
1797
- * registration, static serving, and the terminal not-found / error handlers.
1798
- *
1799
- * `expressRuntime()` is the default and the M1 reference implementation.
1800
- */
1801
- interface HttpRuntime<TApp = unknown> {
1802
- readonly name: 'express' | 'fastify' | 'h3' | (string & {});
1803
- /** Create the engine app. Called once per Application (and per HMR rebuild). */
1804
- createApp(options?: RuntimeAppOptions): TApp;
1805
- /**
1806
- * Node-compatible request listener — the transport contract.
1807
- * `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST
1808
- * invoke `next` (when given) instead of 404-ing if no route matched — the
1809
- * Vite dev chain depends on fall-through.
1810
- */
1811
- nodeHandler(app: TApp): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void;
1812
- /** Materialize the framework-built route table onto the engine. */
1813
- mountRoutes(app: TApp, table: RouteTable): void;
1814
- /** Register a connect-style middleware (built-ins + adopter middleware). */
1815
- useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void;
1816
- /** Serve a static directory (swagger-ui assets, devtools SPA). */
1817
- serveStatic(app: TApp, prefix: string, dir: string): void;
1818
- /** Terminal not-found handler. */
1819
- setNotFound(app: TApp, mw: ConnectMiddleware): void;
1820
- /** Terminal error handler. */
1821
- setErrorHandler(app: TApp, mw: ConnectMiddleware): void;
1822
- readonly capabilities: RuntimeCapabilities;
1823
- }
1824
- /**
1825
- * The supported surface adapters use to add HTTP routes, mounts, static dirs,
1826
- * and middleware — engine-agnostic, in place of reaching for the raw Express
1827
- * `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the
1828
- * Application over the active {@link HttpRuntime}, so an adapter written against
1829
- * this works under any runtime; the raw `app` escape hatch stays available for
1830
- * the rare engine-specific need.
1831
- */
1832
- interface AdapterHttp {
1833
- /** Register a single context-handler route (e.g. a docs or transport endpoint). */
1834
- route(method: RouteMethod, path: string, handler: CtxHandler): void;
1835
- /** Mount a pre-built route table under a path prefix. */
1836
- mount(prefix: string, routes: RouteEntry[]): void;
1837
- /** Serve a static directory under a path prefix. */
1838
- serveStatic(prefix: string, dir: string): void;
1839
- /** Register a connect-style middleware (optionally path-scoped). */
1840
- use(mw: ConnectMiddleware, opts?: UseConnectOptions): void;
1841
- }
1842
- //#endregion
1843
- //#region src/core/adapter.d.ts
1844
- /**
1845
- * Where in the middleware pipeline an adapter's middleware should be inserted.
1846
- *
1847
- * - `beforeGlobal` — runs **before** any user-defined global middleware.
1848
- * Suitable for transport-level concerns (request tagging, low-level
1849
- * request rewriting). Fires on every request.
1850
- * - `afterGlobal` — runs **after** global middleware, **before** module
1851
- * routes are matched. Default for most adapter middleware (auth pre-checks,
1852
- * tenant resolution, body shaping). Fires on every request.
1853
- * - `beforeRoutes` — runs just before module routes are mounted. Functionally
1854
- * equivalent to `afterGlobal` for most cases; the explicit phase exists so
1855
- * adapters that *must* sit at the very end of the pre-route stack can
1856
- * declare intent. Fires on every request.
1857
- * - `afterRoutes` — sits **after** module routes but **before** error
1858
- * handlers. **Fires only on fall-through** — when no route matched (404
1859
- * path) or a route handler called `next()` without ending the response.
1860
- * Controllers that respond with `ctx.json(...)` end the chain and skip
1861
- * this phase, so it is *not* a "post-response" hook. For per-response
1862
- * work (logging, metrics) use `res.on('finish', ...)` from inside an
1863
- * earlier-phase middleware instead.
1864
- */
1865
- type MiddlewarePhase = 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes';
1866
- /**
1867
- * Path scope for an {@link AdapterMiddleware} entry. Mirrors what
1868
- * Express's `app.use(path, handler)` accepts so adapters get the full
1869
- * range without learning a new mini-language:
1870
- *
1871
- * - A `string` prefix — `'/api'` matches `/api`, `/api/v1`, `/api/v1/x`.
1872
- * - A `RegExp` — `/^\/api\/v\d+/` matches `/api/v1`, `/api/v42`.
1873
- * - An array of either — `['/api', '/admin']` matches either prefix;
1874
- * `['/api', /^\/internal\//]` mixes shapes.
1875
- *
1876
- * Omit to apply the middleware unconditionally (Express `app.use(handler)`).
1877
- */
1878
- type MiddlewarePath = string | RegExp | ReadonlyArray<string | RegExp>;
1879
- /** A middleware entry contributed by an adapter */
1880
- interface AdapterMiddleware {
1881
- /**
1882
- * Express handler: either a `RequestHandler` (`(req, res, next) => …`)
1883
- * or an `ErrorRequestHandler` (`(err, req, res, next) => …`).
1884
- * Express dispatches based on arity, so the same field accepts both
1885
- * without a discriminant.
1886
- */
1887
- handler: RequestHandler | ErrorRequestHandler;
1888
- /** Which phase to insert into (default: 'afterGlobal') */
1889
- phase?: MiddlewarePhase;
1890
- /**
1891
- * Optional path scope. See {@link MiddlewarePath} for the accepted
1892
- * shapes (string prefix, RegExp, or an array mixing both). Omit to
1893
- * apply the middleware to every request that reaches this phase.
1894
- */
1895
- path?: MiddlewarePath;
1896
- }
1897
- /**
1898
- * Context passed to adapter lifecycle hooks.
1899
- * Populated by the Application — provides the engine-agnostic HTTP surface,
1900
- * the engine-native app instance, the DI container, the http.Server, and
1901
- * environment info without requiring external type imports.
1902
- *
1903
- * Prefer `http` over `app`: `http` is the same on every runtime, while `app`
1904
- * is whatever the active engine's instance happens to be (Express, Fastify,
1905
- * h3), so an adapter that reaches for it only runs on that engine.
1906
- *
1907
- * @example
1908
- * ```ts
1909
- * beforeMount({ http, container }: AdapterContext) {
1910
- * http.use(myConnectMiddleware())
1911
- * http.route('GET', '/status', (ctx) => ctx.json({ ok: true }))
1912
- * }
1913
- * ```
1914
- */
1915
- /** The Node server behind the app — see `ApplicationOptions.server`. */
1916
- type KickServer = http.Server | https.Server | http2.Http2SecureServer;
1917
- interface AdapterContext {
1918
- /**
1919
- * Engine-agnostic HTTP surface — the supported way to add routes, mounts,
1920
- * static dirs, and middleware (spec §4.4). Prefer this over {@link app}:
1921
- * an adapter written against `http` works under any runtime.
1922
- */
1923
- http: AdapterHttp;
1924
- /**
1925
- * Engine-native application instance — Express under the default runtime,
1926
- * typed from the active runtime via {@link ActiveRuntime} (spec §4.3b).
1927
- * Escape hatch for genuinely engine-specific needs; for everything else use
1928
- * {@link http}.
1929
- */
1930
- app: ActiveRuntime['app'];
1931
- /**
1932
- * Run a web `Request` through this app's pipeline and return the
1933
- * `Response` — routing, middleware, validation, contributors, errors —
1934
- * without a listening server (`createHandler()`, tests), so an adapter that
1935
- * calls the app's own routes (MCP and AI tool dispatch) never needs the
1936
- * server address. See `Application.fetch`.
1937
- *
1938
- * The full pipeline exists once setup completes: from `beforeStart` on,
1939
- * and in request handlers after that. In `beforeMount` module routes and
1940
- * error handlers are not mounted yet.
1941
- */
1942
- fetch(request: Request): Promise<Response>;
1943
- /** DI container */
1944
- container: Container;
1945
- /**
1946
- * The Node server the app listens on — only available in afterStart. An
1947
- * `http.Server` by default; an `https.Server` or `Http2SecureServer` when
1948
- * `bootstrap({ server })` sets `tls` / `http2`. All three emit `upgrade`
1949
- * for HTTP/1.1 clients, which is what WebSocket libraries attach to.
1950
- */
1951
- server?: KickServer;
1952
- /** Current NODE_ENV value (default: 'development') */
1953
- env: string;
1954
- /** true when NODE_ENV === 'production' */
1955
- isProduction: boolean;
1956
- }
1957
- /**
1958
- * Adapters plug into the Application lifecycle.
1959
- * Implement this to add WebSocket, database, rate limiting, docs, etc.
1960
- *
1961
- * All hooks receive an `AdapterContext` populated by the framework.
1962
- * No external type imports needed — the context is fully typed from KickJS internals.
1963
- *
1964
- * @example
1965
- * ```ts
1966
- * import type { AppAdapter, AdapterContext } from '@forinda/kickjs/adapter'
1967
- *
1968
- * class SentryAdapter implements AppAdapter {
1969
- * name = 'SentryAdapter'
1970
- *
1971
- * beforeMount({ http, container }: AdapterContext) {
1972
- * // `http.use` takes any connect-style middleware and mounts it on
1973
- * // whichever engine is active. Reach for `app` only when the thing you
1974
- * // are wiring is engine-specific — and accept the engine lock-in.
1975
- * http.use(Sentry.expressRequestHandler())
1976
- * }
1977
- *
1978
- * afterStart({ server }: AdapterContext) {
1979
- * // server is the http.Server — available after listen()
1980
- * }
1981
- *
1982
- * async shutdown() {
1983
- * await Sentry.close(2000)
1984
- * }
1985
- * }
1986
- * ```
1987
- */
1988
- interface AppAdapter {
1989
- /**
1990
- * Human-readable name for logging and `dependsOn` resolution.
1991
- * Required when the adapter (or any other in the same set) declares
1992
- * `dependsOn` — sort errors will reference adapters by name.
1993
- */
1994
- name?: string;
1995
- /**
1996
- * Other adapter names that must mount before this one. The framework
1997
- * topologically sorts adapters at boot — cycles or unknown names throw
1998
- * via `MountCycleError` / `MissingMountDepError` so bad configurations
1999
- * fail boot rather than corrupt live traffic.
2000
- *
2001
- * Common pattern: `TenantAdapter` populates `req.tenant` and
2002
- * `AuthAdapter` reads it for tenant-scoped RBAC, so AuthAdapter
2003
- * declares `dependsOn = ['TenantAdapter']`. Adapters without
2004
- * `dependsOn` retain their declaration order.
2005
- *
2006
- * @example
2007
- * ```ts
2008
- * class AuthAdapter implements AppAdapter {
2009
- * name = 'AuthAdapter'
2010
- * dependsOn = ['TenantAdapter']
2011
- * }
2012
- * ```
2013
- */
2014
- dependsOn?: readonly KickJsPluginName[];
2015
- /**
2016
- * Return middleware entries to be inserted into the pipeline.
2017
- * The `phase` controls ordering relative to global middleware and routes.
2018
- */
2019
- middleware?(): AdapterMiddleware[];
2020
- /**
2021
- * Return Context Contributors (#107) that apply to every route in the
2022
- * application. Adapter-level contributors merge into the per-route
2023
- * pipeline at the `'adapter'` precedence level — they win over global
2024
- * contributors but lose to module, class, and method decorators.
2025
- *
2026
- * Useful for cross-cutting concerns: an auth adapter contributing
2027
- * `user`, a multi-tenant adapter contributing `tenant`, etc. Optional.
2028
- */
2029
- contributors?(): ContributorRegistrations;
2030
- /**
2031
- * Called before global middleware — register early routes (docs UI, health).
2032
- * May return a Promise — async rejections are caught and logged.
2033
- */
2034
- beforeMount?(ctx: AdapterContext): void | Promise<void>;
2035
- /**
2036
- * Called for each module route that gets mounted.
2037
- * Use this to collect route metadata (e.g. for OpenAPI spec generation).
2038
- */
2039
- onRouteMount?(controllerClass: Constructor, mountPath: string): void;
2040
- /**
2041
- * Called after modules are registered and the DI container is bootstrapped,
2042
- * before the HTTP server starts listening. **This is the correct hook for
2043
- * adapters that register DI bindings, resolve services, or otherwise prepare
2044
- * container-side state** (e.g. `container.registerInstance(MAILER, ...)`).
2045
- *
2046
- * `beforeStart` runs inside `app.setup()`, which means it also fires under
2047
- * `createTestApp` — adapters using this hook work in unit tests without
2048
- * needing a live HTTP server. See {@link afterStart} for the contrast.
2049
- *
2050
- * May return a Promise — async rejections are caught and logged.
2051
- */
2052
- beforeStart?(ctx: AdapterContext): void | Promise<void>;
2053
- /**
2054
- * Called after the HTTP server is listening — `ctx.server` is the live
2055
- * `http.Server`. **Use this hook only for work that genuinely needs a
2056
- * listening server**: attaching Socket.IO / WS upgrades, reading the bound
2057
- * port via `server.address()`, dispatching to the local server over HTTP,
2058
- * etc.
2059
- *
2060
- * `afterStart` does NOT fire under `createTestApp`, since tests call
2061
- * `app.setup()` and never `app.start()`. If your adapter only registers DI
2062
- * bindings or resolves services, use {@link beforeStart} — that hook runs
2063
- * in both production (`start()`) and tests (`setup()`).
2064
- *
2065
- * May return a Promise — async rejections are caught and logged.
2066
- */
2067
- afterStart?(ctx: AdapterContext): void | Promise<void>;
2068
- /**
2069
- * Called by the /health/ready endpoint. Return the health status of your adapter's
2070
- * backing service (database, Redis, queue, etc.).
2071
- */
2072
- onHealthCheck?(): Promise<{
2073
- name: string;
2074
- status: 'up' | 'down';
2075
- }>;
2076
- /**
2077
- * Observe every error the app reports — request errors (any status; filter
2078
- * on `info.status`), uncaught exceptions, unhandled rejections, failed
2079
- * `waitUntil` work, failed queue jobs, and anything passed to
2080
- * `reportError()`. Observe-only: the response is not yours to change, and a
2081
- * throw here is logged and skipped. The place to wire Sentry & co.
2082
- */
2083
- onError?(error: unknown, info: ErrorInfo): void | Promise<void>;
2084
- /**
2085
- * Observe every finished response — method, path, the matched route
2086
- * pattern, status, duration. Only timed while something listens.
2087
- */
2088
- onResponse?(info: ResponseInfo): void | Promise<void>;
2089
- /**
2090
- * Called on shutdown — release what this adapter owns.
2091
- *
2092
- * Runs on a real shutdown AND on **every HMR reload**, so treat it as a hot
2093
- * path in dev, not an exit-only courtesy.
2094
- *
2095
- * Close only what you own. The `server` from {@link AdapterContext} is
2096
- * SHARED — in dev it is Vite's listener — and closing it takes the dev
2097
- * server down with no way to rebind. `io.close()` on a socket.io server
2098
- * does exactly that; detach with `io.engine.close()` instead. The framework
2099
- * closes the shared server itself on a real shutdown.
2100
- *
2101
- * Time-boxed: `shutdownTimeout` on a real shutdown, `min(shutdownTimeout,
2102
- * 5s)` on a reload. Overruns are logged by name and skipped.
2103
- */
2104
- shutdown?(): MaybePromise;
2105
- /**
2106
- * Optional DevTools introspection hook (architecture.md §23). Returns
2107
- * a snapshot describing this adapter's current state, metrics, and DI
2108
- * tokens. DevTools awaits the result, so async work is fine — but keep
2109
- * the implementation cheap (counters + flags, no DB round trips) since
2110
- * the topology endpoint polls on a short interval.
2111
- *
2112
- * The return type lives in `@forinda/kickjs` itself ({@link IntrospectionSnapshot})
2113
- * so adopters can author `introspect()` without importing the kit just
2114
- * to satisfy the contract. The kit's own `IntrospectionSnapshot` type
2115
- * stays structurally identical; either import works.
2116
- */
2117
- introspect?(): IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
2118
- /**
2119
- * Optional DevTools tabs this adapter contributes (architecture.md §23).
2120
- * Returns an array of `DevtoolsTabDescriptor` shapes — typically one
2121
- * entry per adapter-owned panel (iframe / launch / html view).
2122
- *
2123
- * Same untyped-at-this-layer convention as {@link introspect}: adapter
2124
- * authors import `defineDevtoolsTab` (or the bare type) from
2125
- * `@forinda/kickjs-devtools-kit` so `@forinda/kickjs` doesn't take on
2126
- * a runtime dep on the kit.
2127
- */
2128
- devtoolsTabs?(): readonly unknown[];
2129
- }
2130
- /** Constructor type for AppAdapter classes */
2131
- type AppAdapterClass = new () => AppAdapter;
2132
- //#endregion
2133
- export { setInMetaRecord as $, contentDisposition as A, SourcedRegistration as B, RuntimeTypeMap as C, reportResponse as Ct, RequestContext as D, DeepReadonly as E, RunContributorsOptions as F, getMetaRecord as G, getClassMeta as H, runContributors as I, hasClassMeta as J, getMethodMeta as K, BuildPipelineOptions as L, AdapterFactory as M, DefineAdapterOptions as N, RouteShape as O, defineAdapter as P, setInMetaMap as Q, ContributorPipeline as R, RuntimeResponse as S, reportError as St, Ctx as T, getClassMetaOrUndefined as U, buildPipeline as V, getMetaMap as W, pushMethodMeta as X, pushClassMeta as Y, setClassMeta as Z, RouteMeta as _, IntrospectionKind as _t, KickServer as a, defineModule as at, RuntimeAppOptions as b, ErrorSource as bt, ActiveRuntime as c, PluginAsyncOptions as ct, CtxHandler as d, KickPlugin as dt, setMethodMeta as et, ExpressRuntimeTypes as f, ModuleRegistry as ft, RouteEntry as g, IntrospectFn as gt, MatchedRoute as h, KickJsPluginRegistry as ht, AppAdapterClass as i, ModuleFactory as it, AdapterAsyncOptions as j, SseHandler as k, AdapterHttp as l, PluginFactory as lt, KickRuntimeRegister as m, KickJsPluginName as mt, AdapterMiddleware as n, defineModules as nt, MiddlewarePath as o, BuildContext as ot, HttpRuntime as p, MutableModuleRegistry as pt, getMethodMetaOrUndefined as q, AppAdapter as r, DefineModuleOptions as rt, MiddlewarePhase as s, DefinePluginOptions as st, AdapterContext as t, ModuleList as tt, ConnectMiddleware as u, definePlugin as ut, RouteMethod as v, IntrospectionSnapshot as vt, UseConnectOptions as w, RuntimeCapabilities as x, ResponseInfo as xt, RouteTable as y, ErrorInfo as yt, ContributorSource as z };
2134
- //# sourceMappingURL=adapter-ClEh-Oos.d.mts.map