@forinda/kickjs 3.2.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -212
- package/dist/{adapter-DLEHb0K6.d.mts → adapter-BNw2pGbg.d.mts} +117 -7
- package/dist/adapter-BNw2pGbg.d.mts.map +1 -0
- package/dist/{app-module-ERR9jhow.d.mts → app-module-CO0ksPCm.d.mts} +3 -3
- package/dist/{app-module-ERR9jhow.d.mts.map → app-module-CO0ksPCm.d.mts.map} +1 -1
- package/dist/{application-x8CXLOlv.mjs → application-Ce4DQN6m.mjs} +28 -9
- package/dist/application-Ce4DQN6m.mjs.map +1 -0
- package/dist/application-Czwm7Gty.d.mts +302 -0
- package/dist/application-Czwm7Gty.d.mts.map +1 -0
- package/dist/{bootstrap-CYnxozL_.mjs → bootstrap-CB7bJeJG.mjs} +6 -6
- package/dist/{bootstrap-CYnxozL_.mjs.map → bootstrap-CB7bJeJG.mjs.map} +1 -1
- package/dist/bootstrap-NxFRaNTh.d.mts +28 -0
- package/dist/bootstrap-NxFRaNTh.d.mts.map +1 -0
- package/dist/{cache-V91BNTIM.d.mts → cache-BStrqXSZ.d.mts} +2 -2
- package/dist/{cache-V91BNTIM.d.mts.map → cache-BStrqXSZ.d.mts.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +3 -3
- package/dist/{config-aWxKLk4A.mjs → config-wZ_TgBfs.mjs} +4 -4
- package/dist/{config-aWxKLk4A.mjs.map → config-wZ_TgBfs.mjs.map} +1 -1
- package/dist/{container-fIS1uLx-.d.mts → container-CnWDsxi-.d.mts} +9 -7
- package/dist/container-CnWDsxi-.d.mts.map +1 -0
- package/dist/{container-Dnk43k54.mjs → container-DYYSu58w.mjs} +313 -9
- package/dist/container-DYYSu58w.mjs.map +1 -0
- package/dist/{context-OktlOQBQ.mjs → context-BAGzqT7-.mjs} +33 -41
- package/dist/context-BAGzqT7-.mjs.map +1 -0
- package/dist/context-Ymvv-85x.d.mts +260 -0
- package/dist/context-Ymvv-85x.d.mts.map +1 -0
- package/dist/{context-decorator-GA8-hDLe.d.mts → context-decorator-B5v3VQCN.d.mts} +4 -4
- package/dist/{context-decorator-GA8-hDLe.d.mts.map → context-decorator-B5v3VQCN.d.mts.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.d.mts +1 -1
- package/dist/core/cache.mjs +2 -2
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.d.mts +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.d.mts +1 -1
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +2 -2
- package/dist/core/decorators.mjs +48 -16
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.d.mts +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.d.mts +1 -1
- package/dist/core/interfaces.mjs +35 -18
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.d.mts +2 -2
- package/dist/core/logger.mjs +2 -4
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.d.mts +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.d.mts +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/{core-DANnH5-e.mjs → core-DBcoqPHM.mjs} +282 -8
- package/dist/core-DBcoqPHM.mjs.map +1 -0
- package/dist/cors-BfgqfLPd.d.mts +48 -0
- package/dist/cors-BfgqfLPd.d.mts.map +1 -0
- package/dist/{cron-CfsPdi7R.d.mts → cron-7zqvsmMI.d.mts} +1 -1
- package/dist/{cron-CfsPdi7R.d.mts.map → cron-7zqvsmMI.d.mts.map} +1 -1
- package/dist/csrf-DiK9zept.d.mts +52 -0
- package/dist/csrf-DiK9zept.d.mts.map +1 -0
- package/dist/{decorators-H42oPg0m.d.mts → decorators-BMvaLliz.d.mts} +147 -12
- package/dist/decorators-BMvaLliz.d.mts.map +1 -0
- package/dist/{env-Cs8Wt8A_.mjs → env-CdH5-dM_.mjs} +3 -4
- package/dist/{env-Cs8Wt8A_.mjs.map → env-CdH5-dM_.mjs.map} +1 -1
- package/dist/error-handler-Xud_3Lah.d.mts +20 -0
- package/dist/error-handler-Xud_3Lah.d.mts.map +1 -0
- package/dist/{errors-D_CWI7Bl.d.mts → errors-uaHCeXRz.d.mts} +1 -1
- package/dist/{errors-D_CWI7Bl.d.mts.map → errors-uaHCeXRz.d.mts.map} +1 -1
- package/dist/{execution-context-Dl2CKqSo.d.mts → execution-context-DKnt61pY.d.mts} +1 -1
- package/dist/{execution-context-Dl2CKqSo.d.mts.map → execution-context-DKnt61pY.d.mts.map} +1 -1
- package/dist/helmet-CaMbjzBG.d.mts +41 -0
- package/dist/helmet-CaMbjzBG.d.mts.map +1 -0
- package/dist/http/application.d.mts +2 -293
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +2 -27
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +3 -251
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/cors.d.mts +2 -47
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +2 -51
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +2 -19
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.d.mts +2 -40
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.d.mts +2 -55
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.d.mts +2 -9
- package/dist/http/middleware/request-id.mjs +12 -3
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.d.mts +2 -31
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.d.mts +2 -69
- package/dist/http/middleware/session.mjs +1 -1
- package/dist/http/middleware/spa.d.mts +2 -100
- package/dist/http/middleware/spa.mjs +5 -5
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.d.mts +2 -78
- package/dist/http/middleware/upload.mjs +1 -1
- package/dist/http/middleware/validate.d.mts +2 -22
- package/dist/http/middleware/validate.mjs +2 -2
- package/dist/http/middleware/views.d.mts +2 -61
- package/dist/http/middleware/views.mjs +16 -15
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.d.mts +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +2 -32
- package/dist/http/router-builder.mjs +10 -14
- package/dist/http/router-builder.mjs.map +1 -1
- package/dist/{index-RNK41JPE.d.mts → index-B9cyOQAe.d.mts} +1 -1
- package/dist/{index-RNK41JPE.d.mts.map → index-B9cyOQAe.d.mts.map} +1 -1
- package/dist/{index-Cf-MGrqT.d.mts → index-D-qhXg9M.d.mts} +3 -3
- package/dist/{index-Cf-MGrqT.d.mts.map → index-D-qhXg9M.d.mts.map} +1 -1
- package/dist/{index-BQM9pJrV.d.mts → index-DQyWtyp0.d.mts} +241 -5
- package/dist/index-DQyWtyp0.d.mts.map +1 -0
- package/dist/index.d.mts +34 -152
- package/dist/index.mjs +14 -14
- package/dist/interfaces-B50n7dwl.d.mts +71 -0
- package/dist/{interfaces-CwcdqfNq.d.mts.map → interfaces-B50n7dwl.d.mts.map} +1 -1
- package/dist/{logger-GK8yT0BD.d.mts → logger-CLVRZf2N.d.mts} +2 -4
- package/dist/{logger-GK8yT0BD.d.mts.map → logger-CLVRZf2N.d.mts.map} +1 -1
- package/dist/{metadata-BFuoSEX6.mjs → metadata-VQM9wChy.mjs} +2 -2
- package/dist/{metadata-BFuoSEX6.mjs.map → metadata-VQM9wChy.mjs.map} +1 -1
- package/dist/{path-Bj3vZMUY.d.mts → path-Diviu6hv.d.mts} +1 -1
- package/dist/path-Diviu6hv.d.mts.map +1 -0
- package/dist/{plugin-3rKA0Loy.d.mts → plugin-WdrDgNzk.d.mts} +45 -7
- package/dist/plugin-WdrDgNzk.d.mts.map +1 -0
- package/dist/{query-BcYEjYyX.mjs → query-DJMxdx5r.mjs} +2 -2
- package/dist/{query-BcYEjYyX.mjs.map → query-DJMxdx5r.mjs.map} +1 -1
- package/dist/rate-limit-DUwoICtI.d.mts +56 -0
- package/dist/rate-limit-DUwoICtI.d.mts.map +1 -0
- package/dist/{reactivity-CczHu3R-.d.mts → reactivity-CfJceo4H.d.mts} +1 -1
- package/dist/{reactivity-CczHu3R-.d.mts.map → reactivity-CfJceo4H.d.mts.map} +1 -1
- package/dist/request-id-BgglvZHN.d.mts +19 -0
- package/dist/request-id-BgglvZHN.d.mts.map +1 -0
- package/dist/request-logger-CWHbAzTE.d.mts +32 -0
- package/dist/request-logger-CWHbAzTE.d.mts.map +1 -0
- package/dist/router-builder-C799BAf0.d.mts +31 -0
- package/dist/router-builder-C799BAf0.d.mts.map +1 -0
- package/dist/session-N0hActOO.d.mts +70 -0
- package/dist/session-N0hActOO.d.mts.map +1 -0
- package/dist/spa-CrFR2_cz.d.mts +101 -0
- package/dist/spa-CrFR2_cz.d.mts.map +1 -0
- package/dist/upload-BueOnnLw.d.mts +79 -0
- package/dist/upload-BueOnnLw.d.mts.map +1 -0
- package/dist/validate-HwAyWTwH.d.mts +23 -0
- package/dist/validate-HwAyWTwH.d.mts.map +1 -0
- package/dist/views-DhQSXV2P.d.mts +176 -0
- package/dist/views-DhQSXV2P.d.mts.map +1 -0
- package/package.json +6 -9
- package/dist/adapter-DLEHb0K6.d.mts.map +0 -1
- package/dist/application-x8CXLOlv.mjs.map +0 -1
- package/dist/chunk-Bt-rz0Tp.mjs +0 -15
- package/dist/container-Dnk43k54.mjs.map +0 -1
- package/dist/container-fIS1uLx-.d.mts.map +0 -1
- package/dist/context-OktlOQBQ.mjs.map +0 -1
- package/dist/core-DANnH5-e.mjs.map +0 -1
- package/dist/decorators-H42oPg0m.d.mts.map +0 -1
- package/dist/http/application.d.mts.map +0 -1
- package/dist/http/bootstrap.d.mts.map +0 -1
- package/dist/http/context.d.mts.map +0 -1
- package/dist/http/middleware/cors.d.mts.map +0 -1
- package/dist/http/middleware/csrf.d.mts.map +0 -1
- package/dist/http/middleware/error-handler.d.mts.map +0 -1
- package/dist/http/middleware/helmet.d.mts.map +0 -1
- package/dist/http/middleware/rate-limit.d.mts.map +0 -1
- package/dist/http/middleware/request-id.d.mts.map +0 -1
- package/dist/http/middleware/request-logger.d.mts.map +0 -1
- package/dist/http/middleware/session.d.mts.map +0 -1
- package/dist/http/middleware/spa.d.mts.map +0 -1
- package/dist/http/middleware/upload.d.mts.map +0 -1
- package/dist/http/middleware/validate.d.mts.map +0 -1
- package/dist/http/middleware/views.d.mts.map +0 -1
- package/dist/http/router-builder.d.mts.map +0 -1
- package/dist/index-BQM9pJrV.d.mts.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/interfaces-CwcdqfNq.d.mts +0 -54
- package/dist/path-Bj3vZMUY.d.mts.map +0 -1
- package/dist/plugin-3rKA0Loy.d.mts.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,10 +8,10 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
+
import "./container-DYYSu58w.mjs";
|
|
11
12
|
import { METADATA } from "./core/interfaces.mjs";
|
|
12
13
|
import "./core/logger.mjs";
|
|
13
|
-
import { c as pushClassMeta, l as pushMethodMeta } from "./metadata-
|
|
14
|
-
import "./container-Dnk43k54.mjs";
|
|
14
|
+
import { c as pushClassMeta, l as pushMethodMeta } from "./metadata-VQM9wChy.mjs";
|
|
15
15
|
import "./core/decorators.mjs";
|
|
16
16
|
import "./core/cron.mjs";
|
|
17
17
|
import "./core/cache.mjs";
|
|
@@ -146,7 +146,7 @@ var CircuitBreaker = class {
|
|
|
146
146
|
function defineContextDecorator(spec) {
|
|
147
147
|
const registration = Object.freeze({
|
|
148
148
|
key: spec.key,
|
|
149
|
-
deps: spec.deps ?? {},
|
|
149
|
+
deps: Object.freeze({ ...spec.deps ?? {} }),
|
|
150
150
|
dependsOn: Object.freeze([...spec.dependsOn ?? []]),
|
|
151
151
|
optional: spec.optional ?? false,
|
|
152
152
|
onError: spec.onError,
|
|
@@ -339,7 +339,7 @@ function topoSort(registrations, route) {
|
|
|
339
339
|
if (next === 0) queue.push(dependent);
|
|
340
340
|
}
|
|
341
341
|
}
|
|
342
|
-
if (sorted.length !== registrations.length) throw new ContributorCycleError(reconstructCycle(registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0), byKey), route);
|
|
342
|
+
if (sorted.length !== registrations.length) throw new ContributorCycleError(reconstructCycle$1(registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0), byKey), route);
|
|
343
343
|
return sorted;
|
|
344
344
|
}
|
|
345
345
|
/**
|
|
@@ -350,7 +350,7 @@ function topoSort(registrations, route) {
|
|
|
350
350
|
* starts and ends with the same key so the message reads naturally:
|
|
351
351
|
* `tenant → project → tenant`.
|
|
352
352
|
*/
|
|
353
|
-
function reconstructCycle(residual, byKey) {
|
|
353
|
+
function reconstructCycle$1(residual, byKey) {
|
|
354
354
|
const residualKeys = new Set(residual.map((r) => r.key));
|
|
355
355
|
const start = residual[0].key;
|
|
356
356
|
const path = [start];
|
|
@@ -430,6 +430,280 @@ function resolveDeps(reg, container) {
|
|
|
430
430
|
return out;
|
|
431
431
|
}
|
|
432
432
|
//#endregion
|
|
433
|
-
|
|
433
|
+
//#region src/core/mount-sort.ts
|
|
434
|
+
/**
|
|
435
|
+
* Two items in the same mount set declared the same `name`. Plugin/adapter
|
|
436
|
+
* names must be unique so `dependsOn` references resolve unambiguously.
|
|
437
|
+
*/
|
|
438
|
+
var DuplicateMountNameError = class extends Error {
|
|
439
|
+
kind;
|
|
440
|
+
mountName;
|
|
441
|
+
constructor(kind, mountName) {
|
|
442
|
+
super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`);
|
|
443
|
+
this.name = "DuplicateMountNameError";
|
|
444
|
+
this.kind = kind;
|
|
445
|
+
this.mountName = mountName;
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
/**
|
|
449
|
+
* A `dependsOn` entry references a plugin/adapter that isn't in the
|
|
450
|
+
* current set. The dependency might not be installed, might be misspelled,
|
|
451
|
+
* or might live in a different mount set (plugin referencing an adapter,
|
|
452
|
+
* or vice versa — they sort independently).
|
|
453
|
+
*/
|
|
454
|
+
var MissingMountDepError = class extends Error {
|
|
455
|
+
kind;
|
|
456
|
+
missing;
|
|
457
|
+
dependent;
|
|
458
|
+
constructor(kind, missing, dependent) {
|
|
459
|
+
super(`Missing ${kind} dependency '${missing}' required by '${dependent}' — is the ${kind} installed and named correctly?`);
|
|
460
|
+
this.name = "MissingMountDepError";
|
|
461
|
+
this.kind = kind;
|
|
462
|
+
this.missing = missing;
|
|
463
|
+
this.dependent = dependent;
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
/**
|
|
467
|
+
* The `dependsOn` declarations form a cycle. Boot fails so the cycle
|
|
468
|
+
* can't poison live traffic. The `cycle` field reports one path through
|
|
469
|
+
* the offending nodes for diagnostics — formatted `A → B → C → A`.
|
|
470
|
+
*/
|
|
471
|
+
var MountCycleError = class extends Error {
|
|
472
|
+
kind;
|
|
473
|
+
cycle;
|
|
474
|
+
constructor(kind, cycle) {
|
|
475
|
+
super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(" → ")}`);
|
|
476
|
+
this.name = "MountCycleError";
|
|
477
|
+
this.kind = kind;
|
|
478
|
+
this.cycle = Object.freeze([...cycle]);
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
/**
|
|
482
|
+
* Topologically sort `items` so every item with `dependsOn: ['X']` mounts
|
|
483
|
+
* after `X`. Items without `dependsOn` keep their input order via Kahn's
|
|
484
|
+
* algorithm with a FIFO queue seeded in input order — preserves the
|
|
485
|
+
* historical "plugins/adapters mount in declaration order" behaviour for
|
|
486
|
+
* any set that doesn't use `dependsOn`.
|
|
487
|
+
*
|
|
488
|
+
* @param items - mountable items, e.g. plugins or adapters
|
|
489
|
+
* @param kind - 'plugin' | 'adapter', used in error messages
|
|
490
|
+
* @returns a new array in valid mount order
|
|
491
|
+
* @throws {DuplicateMountNameError} two items share a name
|
|
492
|
+
* @throws {MissingMountDepError} a `dependsOn` references an unknown name
|
|
493
|
+
* @throws {MountCycleError} the dep graph contains a cycle
|
|
494
|
+
*/
|
|
495
|
+
function mountSort(items, kind) {
|
|
496
|
+
const byName = /* @__PURE__ */ new Map();
|
|
497
|
+
for (const item of items) {
|
|
498
|
+
if (byName.has(item.name)) throw new DuplicateMountNameError(kind, item.name);
|
|
499
|
+
byName.set(item.name, item);
|
|
500
|
+
}
|
|
501
|
+
const indegree = /* @__PURE__ */ new Map();
|
|
502
|
+
const dependents = /* @__PURE__ */ new Map();
|
|
503
|
+
for (const item of items) indegree.set(item.name, item.dependsOn?.length ?? 0);
|
|
504
|
+
for (const item of items) for (const dep of item.dependsOn ?? []) {
|
|
505
|
+
if (!byName.has(dep)) throw new MissingMountDepError(kind, dep, item.name);
|
|
506
|
+
const list = dependents.get(dep) ?? [];
|
|
507
|
+
list.push(item);
|
|
508
|
+
dependents.set(dep, list);
|
|
509
|
+
}
|
|
510
|
+
const queue = [];
|
|
511
|
+
for (const item of items) if (indegree.get(item.name) === 0) queue.push(item);
|
|
512
|
+
const sorted = [];
|
|
513
|
+
while (queue.length > 0) {
|
|
514
|
+
const node = queue.shift();
|
|
515
|
+
sorted.push(node);
|
|
516
|
+
for (const dependent of dependents.get(node.name) ?? []) {
|
|
517
|
+
const next = (indegree.get(dependent.name) ?? 0) - 1;
|
|
518
|
+
indegree.set(dependent.name, next);
|
|
519
|
+
if (next === 0) queue.push(dependent);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (sorted.length !== items.length) throw new MountCycleError(kind, reconstructCycle(items.filter((it) => (indegree.get(it.name) ?? 0) > 0), byName));
|
|
523
|
+
return sorted;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Walk the residual graph to find one cycle path for diagnostics.
|
|
527
|
+
* Starts from the first remaining node and follows the first dep that's
|
|
528
|
+
* still in the residual set until we revisit a node. Returns a path
|
|
529
|
+
* starting and ending with the same name so the message reads naturally
|
|
530
|
+
* (`A → B → C → A`).
|
|
531
|
+
*/
|
|
532
|
+
function reconstructCycle(residual, byName) {
|
|
533
|
+
const residualNames = new Set(residual.map((r) => r.name));
|
|
534
|
+
const start = residual[0].name;
|
|
535
|
+
const path = [start];
|
|
536
|
+
const seen = new Set([start]);
|
|
537
|
+
let cursor = start;
|
|
538
|
+
while (true) {
|
|
539
|
+
const nextDep = byName.get(cursor).dependsOn?.find((d) => residualNames.has(d));
|
|
540
|
+
if (nextDep === void 0) break;
|
|
541
|
+
if (seen.has(nextDep)) {
|
|
542
|
+
const cycleStart = path.indexOf(nextDep);
|
|
543
|
+
return [...path.slice(cycleStart), nextDep];
|
|
544
|
+
}
|
|
545
|
+
path.push(nextDep);
|
|
546
|
+
seen.add(nextDep);
|
|
547
|
+
cursor = nextDep;
|
|
548
|
+
}
|
|
549
|
+
return path;
|
|
550
|
+
}
|
|
551
|
+
//#endregion
|
|
552
|
+
//#region src/core/define-plugin.ts
|
|
553
|
+
const mergeConfig$1 = (defaults, overrides) => ({
|
|
554
|
+
...defaults ?? {},
|
|
555
|
+
...overrides ?? {}
|
|
556
|
+
});
|
|
557
|
+
const composeName$1 = (base, scope) => `${base}:${scope}`;
|
|
558
|
+
/**
|
|
559
|
+
* Build a {@link KickPlugin} factory from a typed definition. See
|
|
560
|
+
* `architecture.md` §21.2.2 for the design rationale.
|
|
561
|
+
*
|
|
562
|
+
* @example
|
|
563
|
+
* ```ts
|
|
564
|
+
* const FlagsPlugin = definePlugin<FlagsConfig>({
|
|
565
|
+
* name: 'FlagsPlugin',
|
|
566
|
+
* defaults: { defaultTtl: 60_000 },
|
|
567
|
+
* build(config) {
|
|
568
|
+
* return {
|
|
569
|
+
* register(container) {
|
|
570
|
+
* container.registerInstance(FLAGS, makeProvider(config))
|
|
571
|
+
* },
|
|
572
|
+
* }
|
|
573
|
+
* },
|
|
574
|
+
* })
|
|
575
|
+
*
|
|
576
|
+
* bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })
|
|
577
|
+
* ```
|
|
578
|
+
*/
|
|
579
|
+
function definePlugin(options) {
|
|
580
|
+
const buildSync = (instanceName, scoped, overrides) => {
|
|
581
|
+
const config = mergeConfig$1(options.defaults, overrides);
|
|
582
|
+
const built = options.build(config, {
|
|
583
|
+
name: instanceName,
|
|
584
|
+
scoped
|
|
585
|
+
});
|
|
586
|
+
built.name = instanceName;
|
|
587
|
+
return built;
|
|
588
|
+
};
|
|
589
|
+
const buildAsync = (instanceName, opts) => {
|
|
590
|
+
let inner;
|
|
591
|
+
const ensureInner = async (container) => {
|
|
592
|
+
if (inner) return inner;
|
|
593
|
+
const deps = (opts.inject ?? []).map((tok) => container.resolve(tok));
|
|
594
|
+
inner = buildSync(instanceName, false, await opts.useFactory(...deps));
|
|
595
|
+
return inner;
|
|
596
|
+
};
|
|
597
|
+
return {
|
|
598
|
+
name: instanceName,
|
|
599
|
+
async onReady(container) {
|
|
600
|
+
const built = await ensureInner(container);
|
|
601
|
+
built.register?.(container);
|
|
602
|
+
await built.onReady?.(container);
|
|
603
|
+
},
|
|
604
|
+
async shutdown() {
|
|
605
|
+
await inner?.shutdown?.();
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
};
|
|
609
|
+
const factory = ((config) => buildSync(options.name, false, config));
|
|
610
|
+
factory.scoped = (scopeName, config) => buildSync(composeName$1(options.name, scopeName), true, config);
|
|
611
|
+
factory.async = (opts) => buildAsync(options.name, opts);
|
|
612
|
+
Object.defineProperty(factory, "definition", { value: Object.freeze({ ...options }) });
|
|
613
|
+
return factory;
|
|
614
|
+
}
|
|
615
|
+
//#endregion
|
|
616
|
+
//#region src/core/define-adapter.ts
|
|
617
|
+
const mergeConfig = (defaults, overrides) => ({
|
|
618
|
+
...defaults ?? {},
|
|
619
|
+
...overrides ?? {}
|
|
620
|
+
});
|
|
621
|
+
const composeName = (base, scope) => `${base}:${scope}`;
|
|
622
|
+
/**
|
|
623
|
+
* Build an {@link AppAdapter} factory from a typed definition. See
|
|
624
|
+
* `architecture.md` §21.3.4 for migration guidance — most first-party
|
|
625
|
+
* adapter packages collapse to a single `defineAdapter()` call after this
|
|
626
|
+
* lands.
|
|
627
|
+
*
|
|
628
|
+
* @example
|
|
629
|
+
* ```ts
|
|
630
|
+
* const TenantAdapter = defineAdapter<TenantConfig>({
|
|
631
|
+
* name: 'TenantAdapter',
|
|
632
|
+
* defaults: { strategy: 'header', required: true },
|
|
633
|
+
* build: (config) => ({
|
|
634
|
+
* middleware: () => [tenantResolverMiddleware(config)],
|
|
635
|
+
* beforeStart: ({ container }) => registerTenantFactory(container, config),
|
|
636
|
+
* }),
|
|
637
|
+
* })
|
|
638
|
+
*
|
|
639
|
+
* bootstrap({
|
|
640
|
+
* adapters: [
|
|
641
|
+
* TenantAdapter({ strategy: 'subdomain' }),
|
|
642
|
+
* TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),
|
|
643
|
+
* ],
|
|
644
|
+
* })
|
|
645
|
+
* ```
|
|
646
|
+
*/
|
|
647
|
+
function defineAdapter(options) {
|
|
648
|
+
const buildSync = (instanceName, scoped, overrides) => {
|
|
649
|
+
const config = mergeConfig(options.defaults, overrides);
|
|
650
|
+
const built = options.build(config, {
|
|
651
|
+
name: instanceName,
|
|
652
|
+
scoped
|
|
653
|
+
});
|
|
654
|
+
built.name = instanceName;
|
|
655
|
+
return built;
|
|
656
|
+
};
|
|
657
|
+
const buildAsync = (instanceName, opts) => {
|
|
658
|
+
let inner;
|
|
659
|
+
return {
|
|
660
|
+
name: instanceName,
|
|
661
|
+
async beforeStart(ctx) {
|
|
662
|
+
const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok));
|
|
663
|
+
inner = buildSync(instanceName, false, await opts.useFactory(...deps));
|
|
664
|
+
await inner.beforeStart?.(ctx);
|
|
665
|
+
},
|
|
666
|
+
async afterStart(ctx) {
|
|
667
|
+
await inner?.afterStart?.(ctx);
|
|
668
|
+
},
|
|
669
|
+
async shutdown() {
|
|
670
|
+
await inner?.shutdown?.();
|
|
671
|
+
},
|
|
672
|
+
async onHealthCheck() {
|
|
673
|
+
return await inner?.onHealthCheck?.() ?? {
|
|
674
|
+
name: instanceName,
|
|
675
|
+
status: "up"
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
};
|
|
680
|
+
const factory = ((config) => buildSync(options.name, false, config));
|
|
681
|
+
factory.scoped = (scopeName, config) => buildSync(composeName(options.name, scopeName), true, config);
|
|
682
|
+
factory.async = (opts) => buildAsync(options.name, opts);
|
|
683
|
+
Object.defineProperty(factory, "definition", { value: Object.freeze({ ...options }) });
|
|
684
|
+
return factory;
|
|
685
|
+
}
|
|
686
|
+
//#endregion
|
|
687
|
+
//#region src/core/augmentation.ts
|
|
688
|
+
/**
|
|
689
|
+
* Advertise an augmentable interface so `kick typegen` can list it in
|
|
690
|
+
* `.kickjs/types/augmentations.d.ts`. Runtime no-op — exists purely as
|
|
691
|
+
* a static marker for the typegen scanner to discover.
|
|
692
|
+
*
|
|
693
|
+
* @example
|
|
694
|
+
* ```ts
|
|
695
|
+
* import { defineAugmentation } from '@forinda/kickjs'
|
|
696
|
+
*
|
|
697
|
+
* export interface FeatureFlags {} // augmentable
|
|
698
|
+
*
|
|
699
|
+
* defineAugmentation('FeatureFlags', {
|
|
700
|
+
* description: 'Flags consumed by FlagsPlugin',
|
|
701
|
+
* example: '{ beta: boolean; rolloutPercentage: number }',
|
|
702
|
+
* })
|
|
703
|
+
* ```
|
|
704
|
+
*/
|
|
705
|
+
function defineAugmentation(name, meta) {}
|
|
706
|
+
//#endregion
|
|
707
|
+
export { MissingMountDepError as a, runContributors as c, DuplicateContributorError as d, MissingContributorError as f, CircuitOpenError as h, DuplicateMountNameError as i, buildPipeline as l, CircuitBreaker as m, defineAdapter as n, MountCycleError as o, defineContextDecorator as p, definePlugin as r, mountSort as s, defineAugmentation as t, ContributorCycleError as u };
|
|
434
708
|
|
|
435
|
-
//# sourceMappingURL=core-
|
|
709
|
+
//# sourceMappingURL=core-DBcoqPHM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core-DBcoqPHM.mjs","names":["reconstructCycle","mergeConfig","composeName"],"sources":["../src/core/circuit-breaker.ts","../src/core/context-decorator.ts","../src/core/context-errors.ts","../src/core/contributor-pipeline.ts","../src/core/contributor-runner.ts","../src/core/mount-sort.ts","../src/core/define-plugin.ts","../src/core/define-adapter.ts","../src/core/augmentation.ts"],"sourcesContent":["/**\n * Circuit Breaker pattern for external service calls.\n *\n * Protects your application from cascading failures when downstream\n * services are unhealthy by short-circuiting requests after a\n * configurable failure threshold.\n *\n * @example\n * ```ts\n * const breaker = new CircuitBreaker('payment-api', {\n * failureThreshold: 5,\n * resetTimeout: 30_000,\n * })\n *\n * const result = await breaker.execute(() => fetch('https://payment.example.com/charge'))\n * ```\n */\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half_open'\n\nexport interface CircuitBreakerOptions {\n /** Number of consecutive failures before the circuit opens. */\n failureThreshold: number\n /** Milliseconds to wait before transitioning from OPEN to HALF_OPEN. */\n resetTimeout: number\n /** Max requests allowed in HALF_OPEN state before deciding (default 1). */\n halfOpenMax?: number\n}\n\nexport interface CircuitBreakerStats {\n failures: number\n successes: number\n state: CircuitBreakerState\n lastFailure?: Date\n}\n\n/**\n * Error thrown when the circuit is open and calls are being rejected.\n */\nexport class CircuitOpenError extends Error {\n constructor(public readonly breakerName: string) {\n super(`Circuit breaker \"${breakerName}\" is open — request rejected`)\n this.name = 'CircuitOpenError'\n }\n}\n\nexport class CircuitBreaker {\n private state: CircuitBreakerState = 'closed'\n private failures = 0\n private successes = 0\n private halfOpenAttempts = 0\n private lastFailure?: Date\n private openedAt?: number\n\n private readonly failureThreshold: number\n private readonly resetTimeout: number\n private readonly halfOpenMax: number\n\n constructor(\n public readonly name: string,\n options: CircuitBreakerOptions,\n ) {\n this.failureThreshold = options.failureThreshold\n this.resetTimeout = options.resetTimeout\n this.halfOpenMax = options.halfOpenMax ?? 1\n }\n\n /**\n * Execute an async function through the circuit breaker.\n * Throws `CircuitOpenError` if the circuit is open.\n */\n async execute<T>(fn: () => Promise<T>): Promise<T> {\n this.maybeTransitionToHalfOpen()\n\n if (this.state === 'open') {\n throw new CircuitOpenError(this.name)\n }\n\n if (this.state === 'half_open' && this.halfOpenAttempts >= this.halfOpenMax) {\n throw new CircuitOpenError(this.name)\n }\n\n if (this.state === 'half_open') {\n this.halfOpenAttempts++\n }\n\n try {\n const result = await fn()\n this.onSuccess()\n return result\n } catch (error) {\n this.onFailure()\n throw error\n }\n }\n\n /** Returns the current circuit state. */\n getState(): CircuitBreakerState {\n this.maybeTransitionToHalfOpen()\n return this.state\n }\n\n /** Returns current statistics. */\n getStats(): CircuitBreakerStats {\n this.maybeTransitionToHalfOpen()\n return {\n failures: this.failures,\n successes: this.successes,\n state: this.state,\n ...(this.lastFailure ? { lastFailure: this.lastFailure } : {}),\n }\n }\n\n /** Manually reset the circuit breaker to CLOSED state. */\n reset(): void {\n this.state = 'closed'\n this.failures = 0\n this.successes = 0\n this.halfOpenAttempts = 0\n this.lastFailure = undefined\n this.openedAt = undefined\n }\n\n private onSuccess(): void {\n if (this.state === 'half_open') {\n // Recovery confirmed — close the circuit\n this.state = 'closed'\n this.failures = 0\n this.halfOpenAttempts = 0\n this.openedAt = undefined\n }\n this.successes++\n }\n\n private onFailure(): void {\n this.failures++\n this.lastFailure = new Date()\n\n if (this.state === 'half_open') {\n // Recovery failed — re-open\n this.state = 'open'\n this.openedAt = Date.now()\n this.halfOpenAttempts = 0\n } else if (this.state === 'closed' && this.failures >= this.failureThreshold) {\n this.state = 'open'\n this.openedAt = Date.now()\n }\n }\n\n private maybeTransitionToHalfOpen(): void {\n if (this.state === 'open' && this.openedAt != null) {\n if (Date.now() - this.openedAt >= this.resetTimeout) {\n this.state = 'half_open'\n this.halfOpenAttempts = 0\n }\n }\n }\n}\n","import 'reflect-metadata'\nimport { METADATA, type Constructor, type MaybePromise } from './interfaces'\nimport { pushClassMeta, pushMethodMeta } from './metadata'\nimport type { InjectionToken } from './token'\nimport type { ExecutionContext, MetaValue } from './execution-context'\n\n/**\n * Maps a `deps` declaration object to its resolved-instance shape.\n *\n * `deps: { db: DB_TOKEN, cache: CacheService }` produces\n * `{ db: Db, cache: CacheService }` — the runner resolves each value\n * against the DI container and hands the result to `resolve()`.\n */\nexport type ResolvedDeps<D extends Record<string, unknown>> = {\n [K in keyof D]: D[K] extends InjectionToken<infer T>\n ? T\n : D[K] extends Constructor<infer T>\n ? T\n : unknown\n}\n\n/**\n * Spec passed to {@link defineContextDecorator}. Describes one entry in\n * the per-request contributor pipeline.\n *\n * @typeParam K - The {@link ContextMeta} key this contributor populates.\n * @typeParam D - DI dependency declaration shape (see {@link ResolvedDeps}).\n * @typeParam Ctx - Concrete execution-context type. Defaults to the abstract\n * {@link ExecutionContext}; HTTP contributors typically\n * default to `RequestContext` at the call site.\n */\nexport interface ContextDecoratorSpec<\n K extends string = string,\n D extends Record<string, unknown> = Record<string, never>,\n Ctx extends ExecutionContext = ExecutionContext,\n> {\n /** ContextMeta key the resolved value is written to. */\n key: K\n /**\n * DI dependencies resolved by the runner before `resolve()` runs.\n * Map entry keys become property names on the resolved-deps argument\n * passed to `resolve()`.\n */\n deps?: D\n /**\n * Other contributor keys that must populate before this one runs.\n * Enforced via topo-sort at startup; missing deps and cycles fail boot.\n */\n dependsOn?: readonly string[]\n /**\n * If `true`, a thrown `resolve` skips the contributor instead of\n * forwarding to the request error handler. The key is left unset\n * and downstream consumers see `ctx.get(key) === undefined`.\n */\n optional?: boolean\n /**\n * Hook invoked when `resolve()` throws and `optional` is `false`.\n * Returning a value writes it to `ctx.set(key, …)`; returning\n * `undefined` / `void` skips. Throwing inside the hook forwards\n * the new error to the request error handler.\n *\n * Async-permitted by design — adopters frequently want to\n * `await auditService.log(err)` or `await cache.fallback(...)`.\n */\n onError?: (err: unknown, ctx: Ctx) => MaybePromise<MetaValue<K> | undefined | void>\n /** Compute and return the value to write into `ctx.set(key, …)`. */\n resolve: (ctx: Ctx, deps: ResolvedDeps<D>) => MaybePromise<MetaValue<K>>\n}\n\n/**\n * Internal, normalised registration produced by {@link defineContextDecorator}.\n *\n * Frozen and shared by every use site of the decorator (method, class,\n * module, adapter, global). The pipeline builder dedupes by `key` using\n * the precedence rule defined in §20.4 of `architecture.md`.\n */\nexport interface ContributorRegistration<\n K extends string = string,\n D extends Record<string, unknown> = Record<string, never>,\n Ctx extends ExecutionContext = ExecutionContext,\n> {\n readonly key: K\n readonly deps: D\n readonly dependsOn: readonly string[]\n readonly optional: boolean\n readonly onError?: ContextDecoratorSpec<K, D, Ctx>['onError']\n readonly resolve: ContextDecoratorSpec<K, D, Ctx>['resolve']\n}\n\n/**\n * The value returned by {@link defineContextDecorator}. Callable as either\n * a method or class decorator, and exposes the underlying frozen\n * {@link ContributorRegistration} via `.registration` for non-decorator\n * registration sites (module hooks, adapter hooks, bootstrap option).\n */\nexport interface ContextDecorator<\n K extends string = string,\n D extends Record<string, unknown> = Record<string, never>,\n Ctx extends ExecutionContext = ExecutionContext,\n> {\n (target: object, propertyKey?: string | symbol, descriptor?: PropertyDescriptor): void\n readonly registration: ContributorRegistration<K, D, Ctx>\n}\n\n/**\n * Define a typed context contributor.\n *\n * The returned function works as a method or class decorator:\n *\n * ```ts\n * const LoadTenant = defineContextDecorator({\n * key: 'tenant',\n * deps: { tenants: TenantsRepo },\n * resolve: (ctx, { tenants }) => tenants.findByHost(ctx.requestId),\n * })\n *\n * @LoadTenant\n * @Get('/me')\n * me(ctx: RequestContext) {\n * ctx.get('tenant') // typed via ContextMeta\n * }\n * ```\n *\n * For non-decorator registration (module/adapter/bootstrap), pass\n * `LoadTenant.registration` into the appropriate contributors list.\n *\n * **No runtime behaviour is wired in Phase 1.** This factory only writes\n * metadata; the topo-sort, runner, and HTTP integration land in later\n * phases. See `architecture.md` §20 for the full pipeline plan.\n */\nexport function defineContextDecorator<\n K extends string,\n D extends Record<string, unknown> = Record<string, never>,\n Ctx extends ExecutionContext = ExecutionContext,\n>(spec: ContextDecoratorSpec<K, D, Ctx>): ContextDecorator<K, D, Ctx> {\n // Shallow-clone + freeze `deps` so a caller mutating their original\n // map (e.g. `someDeps.cache = NewCache`) cannot reach into a registration\n // that is documented as frozen and shared across every use site.\n // `Object.freeze` is shallow — the values inside (DI tokens, constructors)\n // are intentionally untouched; freezing them would prevent the container\n // from doing legitimate per-instance bookkeeping.\n const registration: ContributorRegistration<K, D, Ctx> = Object.freeze({\n key: spec.key,\n deps: Object.freeze({ ...(spec.deps ?? ({} as D)) }) as D,\n dependsOn: Object.freeze([...(spec.dependsOn ?? [])]),\n optional: spec.optional ?? false,\n onError: spec.onError,\n resolve: spec.resolve,\n })\n\n function decorator(\n target: object,\n propertyKey?: string | symbol,\n _descriptor?: PropertyDescriptor,\n ): void {\n if (propertyKey === undefined) {\n // Class decorator — `target` is the constructor.\n pushClassMeta(METADATA.CLASS_CONTRIBUTORS, target, registration)\n } else {\n // Method decorator — `target` is the prototype; we write to its\n // constructor so reads can use the controller class as the lookup\n // key, matching the convention used by @Middleware and consumed by\n // router-builder.ts.\n const constructor = (target as { constructor: object }).constructor\n pushMethodMeta(METADATA.METHOD_CONTRIBUTORS, constructor, String(propertyKey), registration)\n }\n }\n\n Object.defineProperty(decorator, 'registration', {\n value: registration,\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return decorator as ContextDecorator<K, D, Ctx>\n}\n","/**\n * Errors thrown by the Context Contributor pipeline.\n *\n * All three are startup-time errors raised during pipeline build (topo-sort\n * + validation), not per-request — a misconfigured app fails to boot rather\n * than fails a request. Per the locked design in `architecture.md` §20.4,\n * the pipeline is validated once when each route is mounted and the\n * resolved order is cached on the route.\n */\n\n/**\n * A contributor declared `dependsOn: ['<key>']` but no other contributor\n * (at any precedence level) produces that key for the same route.\n *\n * @example\n * ```text\n * MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id\n * ```\n */\nexport class MissingContributorError extends Error {\n readonly key: string\n readonly dependent: string\n readonly route?: string\n\n constructor(key: string, dependent: string, route?: string) {\n const where = route ? ` on route ${route}` : ''\n super(`Missing context contributor '${key}' required by '${dependent}'${where}`)\n this.name = 'MissingContributorError'\n this.key = key\n this.dependent = dependent\n this.route = route\n }\n}\n\n/**\n * Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field\n * lists the keys in the order they form the loop, with the first key\n * repeated at the end so the path reads naturally.\n *\n * @example\n * ```text\n * ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant\n * ```\n */\nexport class ContributorCycleError extends Error {\n readonly cycle: readonly string[]\n readonly route?: string\n\n constructor(cycle: readonly string[], route?: string) {\n const where = route ? ` on route ${route}` : ''\n super(`Cycle in context contributors${where}: ${cycle.join(' → ')}`)\n this.name = 'ContributorCycleError'\n this.cycle = Object.freeze([...cycle])\n this.route = route\n }\n}\n\n/**\n * Two contributors at the same precedence level both produce the same key\n * for the same route. Precedence resolution (method > class > module >\n * adapter > global, per architecture.md §20.4) silently drops\n * lower-precedence duplicates; this error fires only when ties occur\n * within a single level — e.g., two method-level decorators declaring\n * `key: 'tenant'`.\n *\n * `sources` is best-effort identifying labels for each conflicting\n * registration (typically the decorator's call site or registering\n * module/adapter name).\n *\n * @example\n * ```text\n * DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain\n * ```\n */\nexport class DuplicateContributorError extends Error {\n readonly key: string\n readonly sources: readonly string[]\n\n constructor(key: string, sources: readonly string[]) {\n super(\n `Duplicate context contributor for key '${key}' at the same precedence level. ` +\n `Sources: ${sources.join(', ')}`,\n )\n this.name = 'DuplicateContributorError'\n this.key = key\n this.sources = Object.freeze([...sources])\n }\n}\n","import type { ContributorRegistration } from './context-decorator'\nimport {\n ContributorCycleError,\n DuplicateContributorError,\n MissingContributorError,\n} from './context-errors'\n\n/**\n * Where a contributor was registered, ordered by precedence\n * (lower index wins). Mirrors `architecture.md` §20.4.\n *\n * Levels (highest → lowest precedence):\n * - `'method'` — `@LoadX` on a controller method.\n * - `'class'` — `@LoadX` on a controller class.\n * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.\n * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies\n * to every module's routes.\n * - `'global'` — `ApplicationOptions.contributors`. App-wide default.\n */\nexport type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global'\n\n/** Precedence-ranked source list. Index = precedence; method (0) wins ties. */\nconst PRECEDENCE_ORDER: readonly ContributorSource[] = [\n 'method',\n 'class',\n 'module',\n 'adapter',\n 'global',\n]\n\n/**\n * Input row to {@link buildPipeline}. Pairs a registration with its origin\n * so dedup can apply the precedence rule and diagnostic errors can name\n * the offending site.\n */\nexport interface SourcedRegistration {\n registration: ContributorRegistration\n source: ContributorSource\n /** Human label surfaced in DuplicateContributorError messages. */\n label?: string\n}\n\n/**\n * Resolved, validated, topo-sorted pipeline ready for execution.\n *\n * `contributors` is in execution order — every entry's `dependsOn`\n * keys appear earlier. `keys` is the set of all keys this pipeline\n * produces; the runner uses it for fast existence checks and the\n * builder uses it for missing-dep validation.\n */\nexport interface ContributorPipeline {\n readonly contributors: readonly ContributorRegistration[]\n readonly keys: ReadonlySet<string>\n}\n\nexport interface BuildPipelineOptions {\n /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */\n route?: string\n}\n\n/**\n * Build, validate, and topo-sort a contributor pipeline.\n *\n * Pipeline:\n *\n * 1. Group sources by precedence (method > class > module > adapter > global).\n * 2. Within each precedence level, two contributors with the same `key`\n * raise {@link DuplicateContributorError}.\n * 3. Across levels, the highest-precedence contributor wins each key\n * (lower-precedence duplicates are silently dropped — that is the\n * documented override mechanism, not an error).\n * 4. Every key referenced by `dependsOn` must be produced by the\n * surviving set, otherwise {@link MissingContributorError}.\n * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after\n * the queue drains form a cycle → {@link ContributorCycleError}\n * with a reconstructed path.\n *\n * Pure function — no DI, no I/O. Safe to call once at startup per\n * route and cache the result.\n */\nexport function buildPipeline(\n sources: readonly SourcedRegistration[],\n options: BuildPipelineOptions = {},\n): ContributorPipeline {\n const route = options.route\n\n // Step 1: group by source.\n const bySource = new Map<ContributorSource, SourcedRegistration[]>()\n for (const src of PRECEDENCE_ORDER) bySource.set(src, [])\n for (const entry of sources) bySource.get(entry.source)!.push(entry)\n\n // Step 2 + 3: dedup with precedence. We walk highest precedence first,\n // claim its keys, and drop lower-precedence rows that conflict.\n const winners = new Map<string, SourcedRegistration>()\n for (const src of PRECEDENCE_ORDER) {\n const rows = bySource.get(src)!\n const keysAtThisLevel = new Map<string, SourcedRegistration[]>()\n for (const row of rows) {\n const key = row.registration.key\n const existing = keysAtThisLevel.get(key) ?? []\n existing.push(row)\n keysAtThisLevel.set(key, existing)\n }\n for (const [key, rowsForKey] of keysAtThisLevel) {\n if (rowsForKey.length > 1) {\n const labels = rowsForKey.map((r, i) => r.label ?? `${src}#${i}`)\n throw new DuplicateContributorError(key, labels)\n }\n if (!winners.has(key)) winners.set(key, rowsForKey[0])\n }\n }\n\n const survivors = [...winners.values()].map((r) => r.registration)\n const allKeys = new Set(survivors.map((r) => r.key))\n\n // Step 4: dependsOn validation.\n for (const reg of survivors) {\n for (const dep of reg.dependsOn) {\n if (!allKeys.has(dep)) {\n throw new MissingContributorError(dep, reg.key, route)\n }\n }\n }\n\n // Step 5: Kahn topo-sort.\n const sorted = topoSort(survivors, route)\n\n return Object.freeze({\n contributors: Object.freeze(sorted),\n keys: allKeys,\n })\n}\n\n/**\n * Kahn's algorithm with deterministic ordering on ties.\n *\n * Nodes with no remaining incoming edges enter the queue in input\n * order. Cycles surface as nodes still present after the queue\n * drains; we reconstruct one cycle path for diagnostics.\n */\nfunction topoSort(\n registrations: readonly ContributorRegistration[],\n route: string | undefined,\n): ContributorRegistration[] {\n // indegree[key] = number of unresolved dependsOn entries for key\n const indegree = new Map<string, number>()\n // dependents[depKey] = list of registrations that depend on depKey\n const dependents = new Map<string, ContributorRegistration[]>()\n const byKey = new Map<string, ContributorRegistration>()\n\n for (const reg of registrations) {\n indegree.set(reg.key, reg.dependsOn.length)\n byKey.set(reg.key, reg)\n }\n for (const reg of registrations) {\n for (const dep of reg.dependsOn) {\n const list = dependents.get(dep) ?? []\n list.push(reg)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: registrations with zero indegree, preserving input order.\n const queue: ContributorRegistration[] = []\n for (const reg of registrations) {\n if (indegree.get(reg.key) === 0) queue.push(reg)\n }\n\n const sorted: ContributorRegistration[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.key) ?? []) {\n const next = (indegree.get(dependent.key) ?? 0) - 1\n indegree.set(dependent.key, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== registrations.length) {\n const remaining = registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0)\n throw new ContributorCycleError(reconstructCycle(remaining, byKey), route)\n }\n\n return sorted\n}\n\n/**\n * Reconstruct one cycle path from the residual graph.\n *\n * Walks from any remaining node, following its first dependency that's\n * still in the residual set, until we revisit a node. The path returned\n * starts and ends with the same key so the message reads naturally:\n * `tenant → project → tenant`.\n */\nfunction reconstructCycle(\n residual: readonly ContributorRegistration[],\n byKey: ReadonlyMap<string, ContributorRegistration>,\n): string[] {\n const residualKeys = new Set(residual.map((r) => r.key))\n const start = residual[0].key\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor: string = start\n\n while (true) {\n const reg = byKey.get(cursor)!\n const nextDep = reg.dependsOn.find((d) => residualKeys.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n // Trim the prefix that isn't part of the cycle.\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n // Fallback — couldn't reconstruct a strict cycle, return what we walked.\n return path\n}\n","import type { Container } from './container'\nimport type { ContributorRegistration } from './context-decorator'\nimport type { ExecutionContext } from './execution-context'\nimport type { ContributorPipeline } from './contributor-pipeline'\n\nexport interface RunContributorsOptions {\n /** Pre-built, validated, topo-sorted pipeline. */\n pipeline: ContributorPipeline\n /** The execution context contributors read from and write into. */\n ctx: ExecutionContext\n /** DI container used to resolve declared `deps`. */\n container: Container\n}\n\n/**\n * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.\n *\n * Sequential — one contributor at a time, in the topo order chosen at\n * pipeline-build time. Per `architecture.md` §20.10, V1 does not run\n * contributors in parallel even within the same topo level; that is a\n * V2 follow-up gated on profiling.\n *\n * ## Error matrix (architecture.md §20.9)\n *\n * | resolve outcome | optional | onError defined | runner behaviour |\n * |-----------------|----------|-----------------|--------------------------------------------------|\n * | throws | true | — | skip; `ctx.get(key)` remains undefined |\n * | throws | false | yes | call hook; returned value (if any) stored |\n * | throws | false | no | propagate the original error |\n * | hook throws | — | yes | propagate the new error |\n * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |\n * | resolves | — | — | `ctx.set(key, value)` |\n *\n * Container.resolve() throwing while building `deps` is treated as a\n * resolve-side throw and flows through the same matrix — adopters who\n * need different behaviour for missing-DI vs. data-fetch failures can\n * wrap the container access inside their own `resolve()`.\n */\nexport async function runContributors(options: RunContributorsOptions): Promise<void> {\n const { pipeline, ctx, container } = options\n\n for (const reg of pipeline.contributors) {\n await runOne(reg, ctx, container)\n }\n}\n\nasync function runOne(\n reg: ContributorRegistration,\n ctx: ExecutionContext,\n container: Container,\n): Promise<void> {\n let value: unknown\n try {\n const deps = resolveDeps(reg, container)\n value = await reg.resolve(ctx, deps)\n } catch (err) {\n if (reg.optional) return\n if (reg.onError) {\n // Hook throws are unconditionally propagated — there is no\n // second-chance hook. Returning undefined/void from the hook\n // means \"skip\"; returning a value means \"use this instead\".\n const replacement = await reg.onError(err, ctx)\n if (replacement === undefined) return\n ctx.set(reg.key, replacement as never)\n return\n }\n throw err\n }\n ctx.set(reg.key, value as never)\n}\n\n/**\n * Resolve a contributor's declared dependencies through the container,\n * preserving the property names from the spec so `resolve(ctx, deps)`\n * receives exactly the shape the user wrote.\n *\n * Empty `deps` produces an empty object — `resolve()` always sees an\n * object, never `undefined`.\n */\nfunction resolveDeps(reg: ContributorRegistration, container: Container): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [key, token] of Object.entries(reg.deps)) {\n out[key] = container.resolve(token as never)\n }\n return out\n}\n","/**\n * Topological sort for plugins and adapters with `dependsOn` declarations.\n *\n * Mirrors the algorithm used by the Context Contributor pipeline\n * (`contributor-pipeline.ts:topoSort`) but operates on a name-keyed\n * `MountSortItem` shape rather than a `ContributorRegistration`. Kept\n * standalone instead of factored generic so that:\n *\n * 1. The contributor pipeline doesn't need refactoring (risk reduction).\n * 2. The error classes can carry plugin/adapter-specific diagnostic\n * fields (`kind`, `dependent`) without bending the contributor types.\n */\n\n/**\n * A plugin or adapter that participates in dependency-ordered mounting.\n * Both `KickPlugin` and `AppAdapter` satisfy this shape via their `name`\n * and `dependsOn` fields.\n */\nexport interface MountSortItem {\n /** Unique mount name within the plugin/adapter set being sorted. */\n name: string\n /**\n * Other plugin/adapter names that must mount before this one. Cycles\n * and missing names fail at boot — same fail-fast contract as the\n * Context Contributor pipeline (architecture.md §20.4).\n */\n dependsOn?: readonly string[]\n}\n\n/** What kind of mount set the sort is operating on — surfaces in error messages. */\nexport type MountKind = 'plugin' | 'adapter'\n\n/**\n * Two items in the same mount set declared the same `name`. Plugin/adapter\n * names must be unique so `dependsOn` references resolve unambiguously.\n */\nexport class DuplicateMountNameError extends Error {\n readonly kind: MountKind\n readonly mountName: string\n\n constructor(kind: MountKind, mountName: string) {\n super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`)\n this.name = 'DuplicateMountNameError'\n this.kind = kind\n this.mountName = mountName\n }\n}\n\n/**\n * A `dependsOn` entry references a plugin/adapter that isn't in the\n * current set. The dependency might not be installed, might be misspelled,\n * or might live in a different mount set (plugin referencing an adapter,\n * or vice versa — they sort independently).\n */\nexport class MissingMountDepError extends Error {\n readonly kind: MountKind\n readonly missing: string\n readonly dependent: string\n\n constructor(kind: MountKind, missing: string, dependent: string) {\n super(\n `Missing ${kind} dependency '${missing}' required by '${dependent}' — ` +\n `is the ${kind} installed and named correctly?`,\n )\n this.name = 'MissingMountDepError'\n this.kind = kind\n this.missing = missing\n this.dependent = dependent\n }\n}\n\n/**\n * The `dependsOn` declarations form a cycle. Boot fails so the cycle\n * can't poison live traffic. The `cycle` field reports one path through\n * the offending nodes for diagnostics — formatted `A → B → C → A`.\n */\nexport class MountCycleError extends Error {\n readonly kind: MountKind\n readonly cycle: readonly string[]\n\n constructor(kind: MountKind, cycle: readonly string[]) {\n super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(' → ')}`)\n this.name = 'MountCycleError'\n this.kind = kind\n this.cycle = Object.freeze([...cycle])\n }\n}\n\n/**\n * Topologically sort `items` so every item with `dependsOn: ['X']` mounts\n * after `X`. Items without `dependsOn` keep their input order via Kahn's\n * algorithm with a FIFO queue seeded in input order — preserves the\n * historical \"plugins/adapters mount in declaration order\" behaviour for\n * any set that doesn't use `dependsOn`.\n *\n * @param items - mountable items, e.g. plugins or adapters\n * @param kind - 'plugin' | 'adapter', used in error messages\n * @returns a new array in valid mount order\n * @throws {DuplicateMountNameError} two items share a name\n * @throws {MissingMountDepError} a `dependsOn` references an unknown name\n * @throws {MountCycleError} the dep graph contains a cycle\n */\nexport function mountSort<T extends MountSortItem>(items: readonly T[], kind: MountKind): T[] {\n const byName = new Map<string, T>()\n for (const item of items) {\n if (byName.has(item.name)) {\n throw new DuplicateMountNameError(kind, item.name)\n }\n byName.set(item.name, item)\n }\n\n // indegree[name] = number of unresolved deps for that item\n const indegree = new Map<string, number>()\n // dependents[depName] = items that depend on depName\n const dependents = new Map<string, T[]>()\n\n for (const item of items) {\n indegree.set(item.name, item.dependsOn?.length ?? 0)\n }\n for (const item of items) {\n for (const dep of item.dependsOn ?? []) {\n if (!byName.has(dep)) {\n throw new MissingMountDepError(kind, dep, item.name)\n }\n const list = dependents.get(dep) ?? []\n list.push(item)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: items with zero indegree, preserving input order.\n const queue: T[] = []\n for (const item of items) {\n if (indegree.get(item.name) === 0) queue.push(item)\n }\n\n const sorted: T[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.name) ?? []) {\n const next = (indegree.get(dependent.name) ?? 0) - 1\n indegree.set(dependent.name, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== items.length) {\n const remaining = items.filter((it) => (indegree.get(it.name) ?? 0) > 0)\n throw new MountCycleError(kind, reconstructCycle(remaining, byName))\n }\n\n return sorted\n}\n\n/**\n * Walk the residual graph to find one cycle path for diagnostics.\n * Starts from the first remaining node and follows the first dep that's\n * still in the residual set until we revisit a node. Returns a path\n * starting and ending with the same name so the message reads naturally\n * (`A → B → C → A`).\n */\nfunction reconstructCycle<T extends MountSortItem>(\n residual: readonly T[],\n byName: ReadonlyMap<string, T>,\n): string[] {\n const residualNames = new Set(residual.map((r) => r.name))\n const start = residual[0].name\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor = start\n\n while (true) {\n const item = byName.get(cursor)!\n const nextDep = item.dependsOn?.find((d) => residualNames.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n return path\n}\n","import type { Container } from './container'\nimport type { KickPlugin } from './plugin'\n\n/**\n * Options passed to {@link definePlugin}. Mirrors the spec in\n * `architecture.md` §21.3.1 + §21.2.2 (Phase A \"lite\").\n */\nexport interface DefinePluginOptions<TConfig> {\n /** Stable identity used for logging, `dependsOn` lookups, and `.scoped()` namespacing. */\n name: string\n\n /** Optional plugin version — surfaced to DevTools and `kick add` compatibility checks (Phase B). */\n version?: string\n\n /**\n * Peer-version ranges this plugin needs from the framework or other\n * plugins. Recorded as metadata; runtime enforcement lands in §21.4.4.\n */\n requires?: { kickjs?: string }\n\n /** Default config merged under any caller overrides. */\n defaults?: Partial<TConfig>\n\n /** Builds the underlying {@link KickPlugin} from the resolved config. */\n build(config: TConfig, ctx: BuildContext): Omit<KickPlugin, 'name'>\n}\n\n/**\n * Hook context handed to a plugin/adapter `build` function. `name` is the\n * resolved instance name (the bare definition name for the bare call,\n * or `${defName}:${scope}` for `.scoped()`). `scoped` is the discriminator\n * authors use to namespace DI tokens or resource keys.\n */\nexport interface BuildContext {\n name: string\n scoped: boolean\n}\n\n/**\n * Async-config form of a plugin or adapter — `inject` lists DI tokens to\n * resolve from the container, then `useFactory` produces the config.\n *\n * Plugins resolve this lazily inside `onReady`, so any module/adapter/\n * middleware/contributor a plugin contributes via `build` is **not\n * available** when `.async()` is used. Use the bare/`.scoped()` form for\n * plugins that need to register modules or middleware.\n */\nexport interface PluginAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link definePlugin}. Callable form is the singleton\n * (`AuthPlugin(config)`); `.scoped()` and `.async()` are the multi-instance\n * and deferred-config forms.\n */\nexport interface PluginFactory<TConfig> {\n (config?: Partial<TConfig>): KickPlugin\n scoped(scopeName: string, config?: Partial<TConfig>): KickPlugin\n async(opts: PluginAsyncOptions<TConfig>): KickPlugin\n /** Read-only access to the original definition — useful for DevTools introspection. */\n readonly definition: Readonly<DefinePluginOptions<TConfig>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> | undefined,\n overrides: Partial<TConfig> | undefined,\n): TConfig => ({ ...(defaults ?? {}), ...(overrides ?? {}) }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build a {@link KickPlugin} factory from a typed definition. See\n * `architecture.md` §21.2.2 for the design rationale.\n *\n * @example\n * ```ts\n * const FlagsPlugin = definePlugin<FlagsConfig>({\n * name: 'FlagsPlugin',\n * defaults: { defaultTtl: 60_000 },\n * build(config) {\n * return {\n * register(container) {\n * container.registerInstance(FLAGS, makeProvider(config))\n * },\n * }\n * },\n * })\n *\n * bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })\n * ```\n */\nexport function definePlugin<TConfig = Record<string, unknown>>(\n options: DefinePluginOptions<TConfig>,\n): PluginFactory<TConfig> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): KickPlugin => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n const built = options.build(config, { name: instanceName, scoped }) as KickPlugin\n built.name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: PluginAsyncOptions<TConfig>): KickPlugin => {\n let inner: KickPlugin | undefined\n\n const ensureInner = async (container: Container): Promise<KickPlugin> => {\n if (inner) return inner\n const deps = (opts.inject ?? []).map((tok) => container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n return inner\n }\n\n return {\n name: instanceName,\n async onReady(container: Container) {\n const built = await ensureInner(container)\n // Run the inner plugin's register() now that we have the config —\n // late but better than never; `.async()` plugins skip the early\n // module/middleware contribution surface by design.\n built.register?.(container)\n await built.onReady?.(container)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as PluginFactory<TConfig>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: PluginAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n","import type { AppAdapter, AdapterContext } from './adapter'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}\n * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter\n * symmetry rationale.\n *\n * The optional `TExtra` generic lets an adapter ship public methods\n * beyond the standard {@link AppAdapter} contract — they're preserved\n * on the returned adapter instance so external callers (tests, peer\n * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`\n * for the canonical use case.\n */\nexport interface DefineAdapterOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`\n * namespacing. Required for adapters that participate in `dependsOn`\n * sort — error messages reference adapters by name.\n */\n name: string\n version?: string\n requires?: { kickjs?: string }\n defaults?: Partial<TConfig>\n build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra\n}\n\n/**\n * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`\n * but resolved during `beforeStart` (the earliest async hook in\n * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner\n * adapter are **not** picked up. Use the bare/`.scoped()` form when you need\n * those.\n */\nexport interface AdapterAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link defineAdapter}. Same surface as\n * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn\n * one mental model for both primitives. Returned instances carry both\n * the standard {@link AppAdapter} contract and any `TExtra` extension\n * methods the `build` function exposed.\n */\nexport interface AdapterFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppAdapter & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra\n async(opts: AdapterAsyncOptions<TConfig>): AppAdapter\n readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> | undefined,\n overrides: Partial<TConfig> | undefined,\n): TConfig => ({ ...(defaults ?? {}), ...(overrides ?? {}) }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppAdapter} factory from a typed definition. See\n * `architecture.md` §21.3.4 for migration guidance — most first-party\n * adapter packages collapse to a single `defineAdapter()` call after this\n * lands.\n *\n * @example\n * ```ts\n * const TenantAdapter = defineAdapter<TenantConfig>({\n * name: 'TenantAdapter',\n * defaults: { strategy: 'header', required: true },\n * build: (config) => ({\n * middleware: () => [tenantResolverMiddleware(config)],\n * beforeStart: ({ container }) => registerTenantFactory(container, config),\n * }),\n * })\n *\n * bootstrap({\n * adapters: [\n * TenantAdapter({ strategy: 'subdomain' }),\n * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),\n * ],\n * })\n * ```\n */\nexport function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineAdapterOptions<TConfig, TExtra>,\n): AdapterFactory<TConfig, TExtra> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppAdapter & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n // Extension methods declared by the build function (`TExtra`) survive\n // the mutation since they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped }) as AppAdapter & TExtra\n ;(built as AppAdapter).name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: AdapterAsyncOptions<TConfig>): AppAdapter => {\n let inner: AppAdapter | undefined\n\n return {\n name: instanceName,\n async beforeStart(ctx: AdapterContext) {\n const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n await inner.beforeStart?.(ctx)\n },\n async afterStart(ctx: AdapterContext) {\n await inner?.afterStart?.(ctx)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n async onHealthCheck() {\n return (await inner?.onHealthCheck?.()) ?? { name: instanceName, status: 'up' }\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as AdapterFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: AdapterAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n","/**\n * Augmentation registry — runtime no-op + the canonical\n * `KickJsPluginRegistry` interface that `kick typegen` augments.\n *\n * See `architecture.md` §21.2.1 (typegen for `dependsOn`) and §21.3.3\n * (standardized augmentation registry) for the design rationale.\n *\n * @module @forinda/kickjs/core/augmentation\n */\n\n/**\n * Marker interface that lists every plugin/adapter in the project. The\n * keys are the literal `name` field passed to `defineAdapter` /\n * `definePlugin` (or declared on a `class implements AppAdapter`); the\n * values are the kind tag (`'plugin' | 'adapter'`).\n *\n * The framework ships this empty. `kick typegen` augments it from\n * source so `keyof KickJsPluginRegistry` resolves to a string-literal\n * union of every name in scope — and therefore so do `dependsOn`\n * declarations on plugins/adapters.\n */\nexport interface KickJsPluginRegistry {}\n\n/**\n * Resolves to a string-literal union of every registered plugin/adapter\n * name when the project's typegen has populated `KickJsPluginRegistry`,\n * or to `string` when the registry is empty (no typegen pass yet).\n *\n * Falling back to `string` keeps fresh projects compiling — the typegen\n * narrowing is a progressive enhancement, not a hard prerequisite.\n */\nexport type KickJsPluginName = keyof KickJsPluginRegistry extends never\n ? string\n : keyof KickJsPluginRegistry & string\n\n/**\n * Metadata attached to a `defineAugmentation` call. The fields are\n * documentation-only — `kick typegen` surfaces them in the generated\n * `.kickjs/types/augmentations.d.ts` so adopters can browse every\n * augmentable interface from one place.\n */\nexport interface AugmentationMeta {\n /** One-line description of what the augmentation customises. */\n description?: string\n /** Tiny TS snippet showing a typical shape (`'{ foo: string }'`). */\n example?: string\n}\n\n/**\n * Advertise an augmentable interface so `kick typegen` can list it in\n * `.kickjs/types/augmentations.d.ts`. Runtime no-op — exists purely as\n * a static marker for the typegen scanner to discover.\n *\n * @example\n * ```ts\n * import { defineAugmentation } from '@forinda/kickjs'\n *\n * export interface FeatureFlags {} // augmentable\n *\n * defineAugmentation('FeatureFlags', {\n * description: 'Flags consumed by FlagsPlugin',\n * example: '{ beta: boolean; rolloutPercentage: number }',\n * })\n * ```\n */\nexport function defineAugmentation(name: string, meta?: AugmentationMeta): void {\n // No-op at runtime — `kick typegen` discovers the call statically and\n // emits the augmentation catalogue. Touch the args so esbuild / tsc\n // don't drop the call as dead code under aggressive minification\n // (the marker has to survive the build for static scanners that look\n // at compiled output, e.g. third-party tools).\n void name\n void meta\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,YAAY,aAAqC;AAC/C,QAAM,oBAAoB,YAAY,8BAA8B;AAD1C,OAAA,cAAA;AAE1B,OAAK,OAAO;;;AAIhB,IAAa,iBAAb,MAA4B;CAC1B,QAAqC;CACrC,WAAmB;CACnB,YAAoB;CACpB,mBAA2B;CAC3B;CACA;CAEA;CACA;CACA;CAEA,YACE,MACA,SACA;AAFgB,OAAA,OAAA;AAGhB,OAAK,mBAAmB,QAAQ;AAChC,OAAK,e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;;ACvET,SAAgB,mBAAmB,MAAc,MAA+B"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
|
|
2
|
+
import { NextFunction, Request, Response } from "express";
|
|
3
|
+
|
|
4
|
+
//#region src/http/middleware/cors.d.ts
|
|
5
|
+
interface CorsOptions {
|
|
6
|
+
/** Allowed origin(s). `true` reflects request origin, `'*'` allows all, `false` rejects all. Default: `false` (restrictive) */
|
|
7
|
+
origin?: boolean | string | RegExp | (string | RegExp)[];
|
|
8
|
+
/** Allowed HTTP methods. Default: `['GET','HEAD','PUT','PATCH','POST','DELETE']` */
|
|
9
|
+
methods?: string[];
|
|
10
|
+
/** Allowed request headers. Default: reflects `Access-Control-Request-Headers` */
|
|
11
|
+
allowedHeaders?: string[];
|
|
12
|
+
/** Headers exposed to the browser. Default: none */
|
|
13
|
+
exposedHeaders?: string[];
|
|
14
|
+
/** Allow credentials (cookies, authorization). Default: false */
|
|
15
|
+
credentials?: boolean;
|
|
16
|
+
/** Preflight cache duration in seconds. Default: 86400 (24h) */
|
|
17
|
+
maxAge?: number;
|
|
18
|
+
/** Handle preflight OPTIONS requests. Default: true */
|
|
19
|
+
preflight?: boolean;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* CORS middleware with correct spec behavior.
|
|
23
|
+
*
|
|
24
|
+
* - Reflects origin from allowlist (sets `Vary: Origin`)
|
|
25
|
+
* - Handles preflight `OPTIONS` with `204 No Content`
|
|
26
|
+
* - Supports string, regex, and array origin matching
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* // Allow all origins
|
|
31
|
+
* bootstrap({ middleware: [cors(), express.json()] })
|
|
32
|
+
*
|
|
33
|
+
* // Allowlist specific origins
|
|
34
|
+
* bootstrap({
|
|
35
|
+
* middleware: [
|
|
36
|
+
* cors({
|
|
37
|
+
* origin: ['https://app.example.com', /\.example\.com$/],
|
|
38
|
+
* credentials: true,
|
|
39
|
+
* }),
|
|
40
|
+
* express.json(),
|
|
41
|
+
* ],
|
|
42
|
+
* })
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
declare function cors(options?: CorsOptions): (req: Request, res: Response, next: NextFunction) => void;
|
|
46
|
+
//#endregion
|
|
47
|
+
export { cors as n, CorsOptions as t };
|
|
48
|
+
//# sourceMappingURL=cors-BfgqfLPd.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cors-BfgqfLPd.d.mts","names":[],"sources":["../src/http/middleware/cors.ts"],"mappings":";;;;UAEiB,WAAA;;EAEf,MAAA,sBAA4B,MAAA,aAAmB,MAAA;EAFrB;EAI1B,OAAA;EAFqD;EAIrD,cAAA;EAJ4B;EAM5B,cAAA;EAJA;EAMA,WAAA;EAFA;EAIA,MAAA;EAAA;EAEA,SAAA;AAAA;;AAyCF;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,IAAA,CAAK,OAAA,GAAS,WAAA,IAWpB,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,YAAA"}
|
|
@@ -27,4 +27,4 @@ declare function Cron(expression: string, options?: {
|
|
|
27
27
|
declare function getCronJobs(target: any): CronJobMeta[];
|
|
28
28
|
//#endregion
|
|
29
29
|
export { getCronJobs as i, Cron as n, CronJobMeta as r, CRON_META as t };
|
|
30
|
-
//# sourceMappingURL=cron-
|
|
30
|
+
//# sourceMappingURL=cron-7zqvsmMI.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cron-
|
|
1
|
+
{"version":3,"file":"cron-7zqvsmMI.d.mts","names":[],"sources":["../src/core/cron.ts"],"mappings":";;cAEM,SAAA;AAAA,UAEW,WAAA;EACf,UAAA;EACA,WAAA;EACA,WAAA;EACA,QAAA;EACA,SAAA;AAAA;;;;;;;;;;AAqBF;iBAAgB,IAAA,CACd,UAAA,UACA,OAAA;EAAY,WAAA;EAAsB,QAAA;EAAmB,SAAA;AAAA,IACpD,eAAA;;iBAaa,WAAA,CAAY,MAAA,QAAc,WAAA"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
|
|
2
|
+
import { NextFunction, Request, Response } from "express";
|
|
3
|
+
|
|
4
|
+
//#region src/http/middleware/csrf.d.ts
|
|
5
|
+
interface CsrfOptions {
|
|
6
|
+
/** Cookie name for the CSRF token (default: '_csrf') */
|
|
7
|
+
cookie?: string;
|
|
8
|
+
/** Header name to check for the token (default: 'x-csrf-token') */
|
|
9
|
+
header?: string;
|
|
10
|
+
/** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */
|
|
11
|
+
methods?: string[];
|
|
12
|
+
/** Paths to exclude from CSRF checks (e.g. webhooks) */
|
|
13
|
+
ignorePaths?: string[];
|
|
14
|
+
/** Token byte length before hex encoding (default: 32 = 64 hex chars) */
|
|
15
|
+
tokenLength?: number;
|
|
16
|
+
/** Cookie options */
|
|
17
|
+
cookieOptions?: {
|
|
18
|
+
httpOnly?: boolean;
|
|
19
|
+
sameSite?: 'strict' | 'lax' | 'none';
|
|
20
|
+
secure?: boolean;
|
|
21
|
+
path?: string;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Double-submit cookie CSRF protection middleware.
|
|
26
|
+
*
|
|
27
|
+
* On every request, sets a CSRF token cookie. For state-changing methods
|
|
28
|
+
* (POST, PUT, PATCH, DELETE), validates that the request header matches
|
|
29
|
+
* the cookie value.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* import { csrf } from '@forinda/kickjs'
|
|
34
|
+
*
|
|
35
|
+
* bootstrap({
|
|
36
|
+
* modules,
|
|
37
|
+
* middleware: [
|
|
38
|
+
* cookieParser(),
|
|
39
|
+
* csrf(),
|
|
40
|
+
* // ... other middleware
|
|
41
|
+
* ],
|
|
42
|
+
* })
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* Client usage:
|
|
46
|
+
* 1. Read the `_csrf` cookie value
|
|
47
|
+
* 2. Send it in the `x-csrf-token` header on every mutating request
|
|
48
|
+
*/
|
|
49
|
+
declare function csrf(options?: CsrfOptions): (req: Request, res: Response, next: NextFunction) => void | Response<any, Record<string, any>>;
|
|
50
|
+
//#endregion
|
|
51
|
+
export { csrf as n, CsrfOptions as t };
|
|
52
|
+
//# sourceMappingURL=csrf-DiK9zept.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"csrf-DiK9zept.d.mts","names":[],"sources":["../src/http/middleware/csrf.ts"],"mappings":";;;;UAGiB,WAAA;;EAEf,MAAA;EAF0B;EAI1B,MAAA;EAJ0B;EAM1B,OAAA;EAFA;EAIA,WAAA;EAAA;EAEA,WAAA;EAEA;EAAA,aAAA;IACE,QAAA;IACA,QAAA;IACA,MAAA;IACA,IAAA;EAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6BY,IAAA,CAAK,OAAA,GAAS,WAAA,IAgBpB,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,YAAA,YAAY,QAAA,MAAA,MAAA"}
|