@forinda/kickjs 5.3.0 → 5.4.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 (90) hide show
  1. package/dist/application-mir5CSWO.mjs +12 -0
  2. package/dist/{application-Cna_2gex.mjs.map → application-mir5CSWO.mjs.map} +1 -1
  3. package/dist/bootstrap-B7j_-dOg.mjs +12 -0
  4. package/dist/{bootstrap-kPcmbbWe.mjs.map → bootstrap-B7j_-dOg.mjs.map} +1 -1
  5. package/dist/config/index.mjs +2 -4
  6. package/dist/config-Dk5RVTnD.mjs +12 -0
  7. package/dist/{config-DxEREQmR.mjs.map → config-Dk5RVTnD.mjs.map} +1 -1
  8. package/dist/container-DArhTDQQ.mjs +12 -0
  9. package/dist/{container-SMnB5yeT.mjs.map → container-DArhTDQQ.mjs.map} +1 -1
  10. package/dist/{context-Ymvv-85x.d.mts → context-BAdAV-zO.d.mts} +48 -11
  11. package/dist/context-BAdAV-zO.d.mts.map +1 -0
  12. package/dist/context-CIoXqpAX.mjs +12 -0
  13. package/dist/context-CIoXqpAX.mjs.map +1 -0
  14. package/dist/core/adapter.mjs +2 -2
  15. package/dist/core/app-module.mjs +2 -2
  16. package/dist/core/cache.mjs +2 -103
  17. package/dist/core/cache.mjs.map +1 -1
  18. package/dist/core/container.mjs +2 -3
  19. package/dist/core/cron.mjs +2 -32
  20. package/dist/core/cron.mjs.map +1 -1
  21. package/dist/core/decorators.mjs +2 -285
  22. package/dist/core/decorators.mjs.map +1 -1
  23. package/dist/core/errors.mjs +2 -110
  24. package/dist/core/errors.mjs.map +1 -1
  25. package/dist/core/interfaces.mjs +2 -53
  26. package/dist/core/interfaces.mjs.map +1 -1
  27. package/dist/core/logger.mjs +2 -207
  28. package/dist/core/logger.mjs.map +1 -1
  29. package/dist/core/path.mjs +2 -35
  30. package/dist/core/path.mjs.map +1 -1
  31. package/dist/core/plugin.mjs +2 -2
  32. package/dist/core/reactivity.mjs +2 -179
  33. package/dist/core/reactivity.mjs.map +1 -1
  34. package/dist/core-BQZyB8Wv.mjs +12 -0
  35. package/dist/{core--a4XflX7.mjs.map → core-BQZyB8Wv.mjs.map} +1 -1
  36. package/dist/env-BL0xOTyi.mjs +12 -0
  37. package/dist/{env-C4Yr6nN8.mjs.map → env-BL0xOTyi.mjs.map} +1 -1
  38. package/dist/http/application.mjs +2 -3
  39. package/dist/http/bootstrap.mjs +2 -3
  40. package/dist/http/context.d.mts +2 -2
  41. package/dist/http/context.mjs +2 -3
  42. package/dist/http/middleware/cors.mjs +2 -73
  43. package/dist/http/middleware/cors.mjs.map +1 -1
  44. package/dist/http/middleware/csrf.mjs +2 -62
  45. package/dist/http/middleware/csrf.mjs.map +1 -1
  46. package/dist/http/middleware/error-handler.mjs +2 -54
  47. package/dist/http/middleware/error-handler.mjs.map +1 -1
  48. package/dist/http/middleware/helmet.mjs +2 -41
  49. package/dist/http/middleware/helmet.mjs.map +1 -1
  50. package/dist/http/middleware/rate-limit.mjs +2 -91
  51. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  52. package/dist/http/middleware/request-id.mjs +2 -25
  53. package/dist/http/middleware/request-id.mjs.map +1 -1
  54. package/dist/http/middleware/request-logger.mjs +2 -39
  55. package/dist/http/middleware/request-logger.mjs.map +1 -1
  56. package/dist/http/middleware/session.mjs +2 -167
  57. package/dist/http/middleware/session.mjs.map +1 -1
  58. package/dist/http/middleware/spa.mjs +2 -98
  59. package/dist/http/middleware/spa.mjs.map +1 -1
  60. package/dist/http/middleware/upload.mjs +2 -181
  61. package/dist/http/middleware/upload.mjs.map +1 -1
  62. package/dist/http/middleware/validate.mjs +2 -68
  63. package/dist/http/middleware/validate.mjs.map +1 -1
  64. package/dist/http/middleware/views.d.mts +1 -1
  65. package/dist/http/middleware/views.mjs +2 -56
  66. package/dist/http/middleware/views.mjs.map +1 -1
  67. package/dist/http/query/index.mjs +2 -3
  68. package/dist/http/router-builder.mjs +2 -105
  69. package/dist/http/router-builder.mjs.map +1 -1
  70. package/dist/index.d.mts +3 -3
  71. package/dist/index.mjs +2 -171
  72. package/dist/index.mjs.map +1 -1
  73. package/dist/metadata-Dn6kNT82.mjs +12 -0
  74. package/dist/{metadata-CdYaU-XM.mjs.map → metadata-Dn6kNT82.mjs.map} +1 -1
  75. package/dist/query-B7n5isk_.mjs +12 -0
  76. package/dist/{query-nAYUgagU.mjs.map → query-B7n5isk_.mjs.map} +1 -1
  77. package/dist/{views-DkNp9JJs.d.mts → views-oKRSw0Op.d.mts} +2 -2
  78. package/dist/{views-DkNp9JJs.d.mts.map → views-oKRSw0Op.d.mts.map} +1 -1
  79. package/package.json +1 -1
  80. package/dist/application-Cna_2gex.mjs +0 -574
  81. package/dist/bootstrap-kPcmbbWe.mjs +0 -195
  82. package/dist/config-DxEREQmR.mjs +0 -135
  83. package/dist/container-SMnB5yeT.mjs +0 -897
  84. package/dist/context-B0B3WQft.mjs +0 -348
  85. package/dist/context-B0B3WQft.mjs.map +0 -1
  86. package/dist/context-Ymvv-85x.d.mts.map +0 -1
  87. package/dist/core--a4XflX7.mjs +0 -820
  88. package/dist/env-C4Yr6nN8.mjs +0 -137
  89. package/dist/metadata-CdYaU-XM.mjs +0 -76
  90. package/dist/query-nAYUgagU.mjs +0 -164
@@ -1,574 +0,0 @@
1
- /**
2
- * @forinda/kickjs v5.3.0
3
- *
4
- * Copyright (c) Felix Orinda
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import { n as tokenName, t as Container } from "./container-SMnB5yeT.mjs";
12
- import { METADATA } from "./core/interfaces.mjs";
13
- import { Logger, createLogger } from "./core/logger.mjs";
14
- import { t as getClassMeta } from "./metadata-CdYaU-XM.mjs";
15
- import { normalizePath } from "./core/path.mjs";
16
- import { s as mountSort } from "./core--a4XflX7.mjs";
17
- import { requestId } from "./http/middleware/request-id.mjs";
18
- import { errorHandler, notFoundHandler } from "./http/middleware/error-handler.mjs";
19
- import { i as requestStore } from "./context-B0B3WQft.mjs";
20
- import { _setExternalContributorSources } from "./http/router-builder.mjs";
21
- import http from "node:http";
22
- import express from "express";
23
- import crypto from "node:crypto";
24
- //#region src/http/middleware/request-scope.ts
25
- /**
26
- * Marker symbol stamped on the function returned by {@link requestScopeMiddleware}.
27
- *
28
- * `Application.setup()` uses {@link isRequestScopeMiddleware} to detect whether
29
- * the user-supplied middleware list already contains the request-scope wrapper,
30
- * and skips its automatic auto-mount when one is found. Lets adopters control
31
- * the exact position of the ALS frame in their pipeline (e.g., after a custom
32
- * tracing wrapper) without ending up with two nested frames.
33
- */
34
- const REQUEST_SCOPE_MIDDLEWARE_MARKER = Symbol.for("@kickjs/requestScopeMiddleware");
35
- /**
36
- * Wraps each request in an AsyncLocalStorage context.
37
- * Enables REQUEST-scoped DI and automatic requestId propagation to logs.
38
- *
39
- * Should be mounted early in the middleware pipeline (before route handlers).
40
- * `Application` mounts this automatically unless `contextStore: 'manual'` is set
41
- * or the user already includes one in their middleware list.
42
- */
43
- function requestScopeMiddleware() {
44
- const mw = (req, _res, next) => {
45
- const requestIdHeader = req.headers["x-request-id"];
46
- const requestId = (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID();
47
- const store = {
48
- requestId,
49
- instances: /* @__PURE__ */ new Map(),
50
- values: /* @__PURE__ */ new Map()
51
- };
52
- req.requestId = requestId;
53
- requestStore.run(store, () => next());
54
- };
55
- mw[REQUEST_SCOPE_MIDDLEWARE_MARKER] = true;
56
- return mw;
57
- }
58
- /**
59
- * Returns `true` when `value` is the function produced by {@link requestScopeMiddleware}.
60
- *
61
- * Detection uses a `Symbol.for(...)` marker so the check survives different
62
- * copies of `@forinda/kickjs` loaded under different module identities (e.g.,
63
- * a published package alongside a workspace-linked one during local dev).
64
- */
65
- function isRequestScopeMiddleware(value) {
66
- if (typeof value !== "function") return false;
67
- return value[REQUEST_SCOPE_MIDDLEWARE_MARKER] === true;
68
- }
69
- //#endregion
70
- //#region src/http/application.ts
71
- const log = createLogger("Application");
72
- /**
73
- * The main application class. Wires together Express, the DI container,
74
- * feature modules, adapters, and the middleware pipeline.
75
- */
76
- var Application = class {
77
- app;
78
- container;
79
- httpServer = null;
80
- adapters;
81
- plugins;
82
- /** Number of HTTP requests currently being processed */
83
- _inFlightRequests = 0;
84
- /** Whether the application is draining (shutting down gracefully) */
85
- _draining = false;
86
- /** Whether shutdown has already been initiated (prevents double-shutdown) */
87
- _shutdownInitiated = false;
88
- /** Resolvers waiting for in-flight requests to reach zero */
89
- _drainResolvers = [];
90
- constructor(options) {
91
- this.options = options;
92
- this.app = express();
93
- this.container = Container.getInstance();
94
- this.plugins = mountSort(options.plugins ?? [], "plugin");
95
- const allAdapters = [...this.plugins.flatMap((p) => p.adapters?.() ?? []), ...options.adapters ?? []];
96
- let anonAdapterCount = 0;
97
- this.adapters = mountSort(allAdapters.map((adapter) => {
98
- if (!adapter.name) {
99
- const ctorName = adapter.constructor?.name;
100
- const fallback = ctorName && ctorName !== "Object" ? ctorName : `AnonymousAdapter#${anonAdapterCount++}`;
101
- return Object.assign(adapter, { name: fallback });
102
- }
103
- return adapter;
104
- }), "adapter");
105
- Container._requestStoreProvider = () => requestStore.getStore() ?? null;
106
- Logger._contextProvider = () => {
107
- const store = requestStore.getStore();
108
- if (!store) return null;
109
- const ctx = { requestId: store.requestId };
110
- const traceId = store.values.get("traceId");
111
- if (traceId) ctx.traceId = traceId;
112
- const spanId = store.values.get("spanId");
113
- if (spanId) ctx.spanId = spanId;
114
- return ctx;
115
- };
116
- }
117
- /** Whether the application is currently draining in-flight requests */
118
- get isDraining() {
119
- return this._draining;
120
- }
121
- /** Number of HTTP requests currently being processed */
122
- get inFlightRequests() {
123
- return this._inFlightRequests;
124
- }
125
- /** Get the DI container instance */
126
- getContainer() {
127
- return this.container;
128
- }
129
- /**
130
- * Express request handler — delegates to the internal Express app.
131
- *
132
- * Used by the Vite dev-server plugin to route requests through KickJS:
133
- * ```ts
134
- * const mod = await ssrLoadModule('virtual:kickjs/app')
135
- * mod.app.handle(req, res, next)
136
- * ```
137
- *
138
- * Also works as a standard Node.js request handler for production:
139
- * ```ts
140
- * http.createServer(app.handle.bind(app))
141
- * ```
142
- */
143
- handle(req, res, next) {
144
- if (next) this.app(req, res, next);
145
- else this.app(req, res);
146
- }
147
- /**
148
- * Full setup pipeline:
149
- * 1. Adapter beforeMount hooks (early routes — docs, health)
150
- * 2. Adapter middleware (phase: beforeGlobal)
151
- * 3. Global middleware (user-declared or defaults)
152
- * 4. Adapter middleware (phase: afterGlobal)
153
- * 5. Module registration + DI bootstrap
154
- * 6. Adapter middleware (phase: beforeRoutes)
155
- * 7. Module route mounting
156
- * 8. Adapter middleware (phase: afterRoutes)
157
- * 9. Error handlers (notFound + global)
158
- * 10. Adapter beforeStart hooks
159
- */
160
- /** Build the adapter context object (shared across all hooks) */
161
- adapterCtx(server) {
162
- const env = process.env.NODE_ENV ?? "development";
163
- return {
164
- app: this.app,
165
- container: this.container,
166
- server,
167
- env,
168
- isProduction: env === "production"
169
- };
170
- }
171
- /** Call an adapter hook, awaiting async hooks and catching errors */
172
- async callHook(hook, ctx) {
173
- if (!hook) return;
174
- try {
175
- const result = hook(ctx);
176
- if (result && typeof result.then === "function") await result;
177
- } catch (err) {
178
- log.error(err, "Adapter hook failed");
179
- }
180
- }
181
- async setup() {
182
- log.debug("Bootstrapping application...");
183
- const adapterMw = this.collectAdapterMiddleware();
184
- this.app.__kickApp = this;
185
- const ctx = this.adapterCtx();
186
- for (const adapter of this.adapters) await this.callHook(adapter.beforeMount?.bind(adapter), ctx);
187
- this.app.disable("x-powered-by");
188
- this.app.set("trust proxy", this.options.trustProxy ?? false);
189
- this.app.use(this.requestTrackingMiddleware());
190
- this.mountHealthEndpoints();
191
- if (this.shouldAutoMountRequestScope()) this.app.use(requestScopeMiddleware());
192
- this.mountMiddlewareList(adapterMw.beforeGlobal);
193
- for (const plugin of this.plugins) plugin.register?.(this.container);
194
- for (const plugin of this.plugins) try {
195
- const mw = plugin.middleware?.() ?? [];
196
- for (const handler of mw) this.app.use(handler);
197
- } catch (err) {
198
- log.error(err, `Plugin middleware failed: ${plugin.name ?? "unknown"}`);
199
- }
200
- if (this.options.security?.helmet !== false) try {
201
- const { helmet: helmetFn } = await import("./http/middleware/helmet.mjs");
202
- this.app.use(helmetFn());
203
- } catch {}
204
- if (this.options.middleware) for (const entry of this.options.middleware) this.mountMiddlewareEntry(entry);
205
- else {
206
- this.app.use(requestId());
207
- this.app.use(express.json({ limit: this.options.jsonLimit ?? "1mb" }));
208
- }
209
- this.mountMiddlewareList(adapterMw.afterGlobal);
210
- const modules = [...this.plugins.flatMap((p) => p.modules?.() ?? []), ...this.options.modules].map((ModuleClass) => {
211
- const mod = new ModuleClass();
212
- mod.register?.(this.container);
213
- return mod;
214
- });
215
- this.container.bootstrap();
216
- this.mountMiddlewareList(adapterMw.beforeRoutes);
217
- const apiPrefix = this.options.apiPrefix ?? "/api";
218
- const defaultVersion = this.options.defaultVersion ?? 1;
219
- const shouldLogRoutes = this.options.logRoutesTable ?? process.env.NODE_ENV !== "production";
220
- const mountedRoutes = [];
221
- const adapterSources = [];
222
- for (const adapter of this.adapters) {
223
- const adapterContribs = adapter.contributors?.() ?? [];
224
- const adapterLabel = adapter.name ?? adapter.constructor.name ?? "adapter";
225
- for (const registration of adapterContribs) adapterSources.push({
226
- source: "adapter",
227
- registration,
228
- label: adapterLabel
229
- });
230
- }
231
- for (const plugin of this.plugins) {
232
- const pluginContribs = plugin.contributors?.() ?? [];
233
- const pluginLabel = plugin.name ?? plugin.constructor?.name ?? "plugin";
234
- for (const registration of pluginContribs) adapterSources.push({
235
- source: "adapter",
236
- registration,
237
- label: pluginLabel
238
- });
239
- }
240
- const globalSources = (this.options.contributors ?? []).map((registration) => ({
241
- source: "global",
242
- registration,
243
- label: "bootstrap"
244
- }));
245
- for (const mod of modules) {
246
- _setExternalContributorSources([
247
- ...(mod.contributors?.() ?? []).map((registration) => ({
248
- source: "module",
249
- registration,
250
- label: mod.constructor?.name ?? "module"
251
- })),
252
- ...adapterSources,
253
- ...globalSources
254
- ]);
255
- let result;
256
- try {
257
- result = mod.routes();
258
- } finally {
259
- _setExternalContributorSources([]);
260
- }
261
- if (!result) continue;
262
- const routeSets = Array.isArray(result) ? result : [result];
263
- for (const route of routeSets) {
264
- const mountPath = `${apiPrefix}/v${route.version ?? defaultVersion}${normalizePath(route.path)}`;
265
- this.app.use(mountPath, route.router);
266
- if (route.controller) {
267
- for (const adapter of this.adapters) try {
268
- adapter.onRouteMount?.(route.controller, mountPath);
269
- } catch (err) {
270
- log.error(err, `adapter.onRouteMount() failed for ${mountPath}`);
271
- }
272
- if (shouldLogRoutes) mountedRoutes.push({
273
- controller: route.controller,
274
- mountPath
275
- });
276
- }
277
- }
278
- }
279
- if (shouldLogRoutes && mountedRoutes.length > 0) {
280
- const methodOrder = [
281
- "GET",
282
- "POST",
283
- "PUT",
284
- "PATCH",
285
- "DELETE",
286
- "HEAD",
287
- "OPTIONS"
288
- ];
289
- const methodRank = (m) => {
290
- const i = methodOrder.indexOf(m);
291
- return i === -1 ? 99 : i;
292
- };
293
- let totalRoutes = 0;
294
- log.debug("Routes:");
295
- for (const { controller, mountPath } of mountedRoutes) {
296
- const defs = getClassMeta(METADATA.ROUTES, controller, []);
297
- if (defs.length === 0) continue;
298
- const counts = {};
299
- for (const def of defs) {
300
- const m = def.method.toUpperCase();
301
- counts[m] = (counts[m] || 0) + 1;
302
- }
303
- totalRoutes += defs.length;
304
- const methods = Object.entries(counts).toSorted(([a], [b]) => methodRank(a) - methodRank(b)).map(([m, n]) => `${n} ${m}`).join(", ");
305
- const name = controller.name || "Controller";
306
- log.debug(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})`);
307
- }
308
- log.debug(` Total: ${totalRoutes} routes`);
309
- }
310
- this.mountMiddlewareList(adapterMw.afterRoutes);
311
- this.app.use(this.options.onNotFound ?? notFoundHandler());
312
- this.app.use(this.options.onError ?? errorHandler());
313
- for (const adapter of this.adapters) await this.callHook(adapter.beforeStart?.bind(adapter), ctx);
314
- }
315
- /** Register modules and DI without starting the HTTP server (used by kick tinker) */
316
- async registerOnly() {
317
- await this.setup();
318
- }
319
- /**
320
- * Start the HTTP server.
321
- *
322
- * In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`
323
- * created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real
324
- * `http.Server` through `afterStart({ server })` — zero adapter changes needed.
325
- *
326
- * In **production**: creates its own `http.Server` and binds to the port.
327
- */
328
- async start() {
329
- await this.setup();
330
- const g = globalThis;
331
- if (g.__kickjs_httpServer) {
332
- this.httpServer = g.__kickjs_httpServer;
333
- log.debug("Attached to Vite dev server");
334
- for (const adapter of this.adapters) {
335
- const ctx = this.adapterCtx(this.httpServer);
336
- await this.callHook(adapter.afterStart?.bind(adapter), ctx);
337
- }
338
- for (const plugin of this.plugins) await plugin.onReady?.(this.container);
339
- return;
340
- }
341
- const port = this.options.port ?? parseInt(process.env.PORT || "3000", 10);
342
- this.httpServer = http.createServer(this.app);
343
- this.httpServer.on("error", (err) => {
344
- if (err.code === "EADDRINUSE") {
345
- log.error(`Port ${port} is already in use. Kill the existing process or use a different port:\n PORT=${port + 1} kick dev\n lsof -i :${port} # find what's using it\n kill <PID> # stop it`);
346
- process.exit(1);
347
- }
348
- throw err;
349
- });
350
- await new Promise((resolve, reject) => {
351
- this.httpServer.listen(port, async () => {
352
- try {
353
- log.info(`Server running on http://localhost:${port}`);
354
- for (const adapter of this.adapters) {
355
- const afterCtx = this.adapterCtx(this.httpServer);
356
- await this.callHook(adapter.afterStart?.bind(adapter), afterCtx);
357
- }
358
- for (const plugin of this.plugins) await plugin.onReady?.(this.container);
359
- resolve();
360
- } catch (err) {
361
- reject(err);
362
- }
363
- });
364
- });
365
- }
366
- /** HMR rebuild: swap Express handler without restarting the server */
367
- async rebuild() {
368
- const prevApp = this.app;
369
- const prevContainer = this.container;
370
- try {
371
- Container.reset();
372
- this.container = Container.getInstance();
373
- this.app = express();
374
- await this.setup();
375
- } catch (err) {
376
- log.error(err, "HMR rebuild failed, keeping previous app");
377
- this.app = prevApp;
378
- this.container = prevContainer;
379
- return;
380
- }
381
- if (this.httpServer) {
382
- this.httpServer.removeAllListeners("request");
383
- this.httpServer.on("request", this.app);
384
- log.debug("HMR: Express app rebuilt and swapped");
385
- }
386
- }
387
- /**
388
- * Graceful shutdown with request draining.
389
- *
390
- * 1. Stops accepting new connections (server.close())
391
- * 2. Waits for in-flight requests to complete (up to shutdownTimeout)
392
- * 3. Calls adapter.shutdown() for all registered adapters
393
- * 4. Force-closes after timeout
394
- *
395
- * Safe to call multiple times — subsequent calls return the same promise.
396
- */
397
- async shutdown() {
398
- if (this._shutdownInitiated) {
399
- log.debug("Shutdown already in progress, skipping duplicate call");
400
- return;
401
- }
402
- this._shutdownInitiated = true;
403
- this._draining = true;
404
- log.debug("Shutting down — draining in-flight requests...");
405
- const timeoutMs = this.options.shutdownTimeout ?? 3e4;
406
- let timer;
407
- const forceExitPromise = timeoutMs > 0 ? new Promise((resolve) => {
408
- timer = setTimeout(() => resolve("timeout"), timeoutMs);
409
- timer.unref();
410
- }) : new Promise(() => {});
411
- try {
412
- if (this.httpServer) this.httpServer.close(() => {});
413
- if (this._inFlightRequests > 0) {
414
- log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`);
415
- const drainPromise = new Promise((resolve) => {
416
- this._drainResolvers.push(() => resolve("drained"));
417
- });
418
- if (await Promise.race([drainPromise, forceExitPromise]) === "timeout") log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`);
419
- else log.debug("All in-flight requests completed");
420
- }
421
- const results = await Promise.allSettled([...this.plugins.map((plugin) => Promise.resolve(plugin.shutdown?.())), ...this.adapters.map((adapter) => Promise.resolve(adapter.shutdown?.()))]);
422
- for (const result of results) if (result.status === "rejected") log.error({ err: result.reason }, "Adapter shutdown failed");
423
- } finally {
424
- if (timer) clearTimeout(timer);
425
- }
426
- }
427
- getExpressApp() {
428
- return this.app;
429
- }
430
- /** Get registered adapters — used by DevToolsAdapter for peer discovery */
431
- getAdapters() {
432
- return this.adapters;
433
- }
434
- /**
435
- * Get registered plugins — used by DevToolsAdapter for topology
436
- * introspection (architecture.md §23). Read-only; returns the
437
- * already-sorted plugin list (post-`dependsOn` topo-sort).
438
- */
439
- getPlugins() {
440
- return this.plugins;
441
- }
442
- /**
443
- * Snapshot of every Context Contributor reachable from this app —
444
- * walks the four registration sites (adapters, plugins, global, and
445
- * the bootstrap `contributors` option). Module-level contributors
446
- * are NOT included; module instances aren't retained post-bootstrap.
447
- * The devtools Topology tab consumes this for the Contributors
448
- * panel; tests + adopters can call it for diagnostics.
449
- *
450
- * Result shape stays minimal — `{ key, source, label, dependsOn }`
451
- * — so we don't leak `resolve` closures or other internal fields.
452
- */
453
- getContributors() {
454
- const out = [];
455
- const ingest = (list, source, label) => {
456
- if (!list) return;
457
- for (const reg of list) {
458
- const r = reg;
459
- if (r.key === void 0 || r.key === null) continue;
460
- const key = typeof r.key === "string" ? r.key : tokenName(r.key);
461
- out.push({
462
- key,
463
- source,
464
- label,
465
- dependsOn: Array.isArray(r.dependsOn) ? r.dependsOn : []
466
- });
467
- }
468
- };
469
- for (const adapter of this.adapters) ingest(adapter.contributors?.(), "adapter", adapter.name ?? "adapter");
470
- for (const plugin of this.plugins) ingest(plugin.contributors?.(), "plugin", plugin.name ?? "plugin");
471
- ingest(this.options.contributors, "global", "bootstrap");
472
- return out;
473
- }
474
- getHttpServer() {
475
- return this.httpServer;
476
- }
477
- /**
478
- * Decide whether {@link Application} should auto-mount the
479
- * {@link requestScopeMiddleware} ALS wrapper.
480
- *
481
- * Returns `false` when:
482
- * - `contextStore: 'manual'` was set (caller manages ALS frames), or
483
- * - the user-supplied `middleware` list already includes a
484
- * `requestScopeMiddleware()` (detected via the symbol marker stamped
485
- * in `middleware/request-scope.ts`).
486
- *
487
- * Otherwise `true` — preserves the historical default of "always wrap
488
- * requests in an ALS frame" so existing apps see no behavior change.
489
- */
490
- shouldAutoMountRequestScope() {
491
- if (this.options.contextStore === "manual") return false;
492
- const userEntries = this.options.middleware ?? [];
493
- for (const entry of userEntries) if (isRequestScopeMiddleware(typeof entry === "function" ? entry : entry.handler)) return false;
494
- return true;
495
- }
496
- collectAdapterMiddleware() {
497
- const result = {
498
- beforeGlobal: [],
499
- afterGlobal: [],
500
- beforeRoutes: [],
501
- afterRoutes: []
502
- };
503
- for (const adapter of this.adapters) {
504
- const entries = adapter.middleware?.() ?? [];
505
- for (const entry of entries) result[entry.phase ?? "afterGlobal"].push(entry);
506
- }
507
- return result;
508
- }
509
- mountMiddlewareList(entries) {
510
- for (const entry of entries) if (entry.path) this.app.use(entry.path, entry.handler);
511
- else this.app.use(entry.handler);
512
- }
513
- mountMiddlewareEntry(entry) {
514
- if (typeof entry === "function") this.app.use(entry);
515
- else this.app.use(entry.path, entry.handler);
516
- }
517
- /** Middleware that tracks in-flight requests for graceful draining */
518
- requestTrackingMiddleware() {
519
- return (_req, res, next) => {
520
- this._inFlightRequests++;
521
- const onFinish = () => {
522
- res.removeListener("finish", onFinish);
523
- res.removeListener("close", onFinish);
524
- this._inFlightRequests--;
525
- if (this._draining && this._inFlightRequests === 0) {
526
- for (const resolve of this._drainResolvers) resolve();
527
- this._drainResolvers = [];
528
- }
529
- };
530
- res.on("finish", onFinish);
531
- res.on("close", onFinish);
532
- next();
533
- };
534
- }
535
- /** Mount /health/live and /health/ready endpoints at the root (no API prefix) */
536
- mountHealthEndpoints() {
537
- this.app.get("/health/live", (_req, res) => {
538
- if (this._draining) res.status(503).json({
539
- status: "draining",
540
- uptime: process.uptime()
541
- });
542
- else res.json({
543
- status: "ok",
544
- uptime: process.uptime()
545
- });
546
- });
547
- this.app.get("/health/ready", async (_req, res) => {
548
- if (this._draining) {
549
- res.status(503).json({
550
- status: "draining",
551
- checks: []
552
- });
553
- return;
554
- }
555
- const adaptersWithHealth = this.adapters.filter((a) => a.onHealthCheck);
556
- const results = (await Promise.allSettled(adaptersWithHealth.map((a) => a.onHealthCheck()))).map((c, i) => {
557
- if (c.status === "fulfilled") return c.value;
558
- return {
559
- name: adaptersWithHealth[i].name ?? "unknown",
560
- status: "down"
561
- };
562
- });
563
- const healthy = results.every((r) => r.status === "up");
564
- res.status(healthy ? 200 : 503).json({
565
- status: healthy ? "ready" : "degraded",
566
- checks: results
567
- });
568
- });
569
- }
570
- };
571
- //#endregion
572
- export { requestScopeMiddleware as n, Application as t };
573
-
574
- //# sourceMappingURL=application-Cna_2gex.mjs.map