@forinda/kickjs 5.3.0 → 5.5.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 (122) hide show
  1. package/dist/{adapter-C1w_xt08.d.mts → adapter-0r2uRCD3.d.mts} +2 -2
  2. package/dist/{adapter-C1w_xt08.d.mts.map → adapter-0r2uRCD3.d.mts.map} +1 -1
  3. package/dist/app-module-CzlIIjO3.d.mts +92 -0
  4. package/dist/app-module-CzlIIjO3.d.mts.map +1 -0
  5. package/dist/{application-BTRI4aBd.d.mts → application-CaEYca9E.d.mts} +34 -7
  6. package/dist/application-CaEYca9E.d.mts.map +1 -0
  7. package/dist/application-Zt956jNS.mjs +12 -0
  8. package/dist/application-Zt956jNS.mjs.map +1 -0
  9. package/dist/bootstrap-CmFQq1ar.mjs +12 -0
  10. package/dist/{bootstrap-kPcmbbWe.mjs.map → bootstrap-CmFQq1ar.mjs.map} +1 -1
  11. package/dist/{bootstrap-B4YrBipl.d.mts → bootstrap-Db8k2-21.d.mts} +2 -2
  12. package/dist/{bootstrap-B4YrBipl.d.mts.map → bootstrap-Db8k2-21.d.mts.map} +1 -1
  13. package/dist/config/index.mjs +2 -4
  14. package/dist/config-DDz5LuWw.mjs +12 -0
  15. package/dist/{config-DxEREQmR.mjs.map → config-DDz5LuWw.mjs.map} +1 -1
  16. package/dist/container-DrioVLNv.mjs +12 -0
  17. package/dist/{container-SMnB5yeT.mjs.map → container-DrioVLNv.mjs.map} +1 -1
  18. package/dist/context-B4BeGq1B.mjs +12 -0
  19. package/dist/context-B4BeGq1B.mjs.map +1 -0
  20. package/dist/{context-Ymvv-85x.d.mts → context-BAdAV-zO.d.mts} +48 -11
  21. package/dist/context-BAdAV-zO.d.mts.map +1 -0
  22. package/dist/{context-decorator-Bca_BoRK.d.mts → context-decorator-BgdDd-6X.d.mts} +19 -4
  23. package/dist/{context-decorator-Bca_BoRK.d.mts.map → context-decorator-BgdDd-6X.d.mts.map} +1 -1
  24. package/dist/core/adapter.d.mts +1 -1
  25. package/dist/core/adapter.mjs +2 -2
  26. package/dist/core/app-module.d.mts +2 -2
  27. package/dist/core/app-module.mjs +2 -2
  28. package/dist/core/cache.mjs +2 -103
  29. package/dist/core/cache.mjs.map +1 -1
  30. package/dist/core/container.mjs +2 -3
  31. package/dist/core/cron.mjs +2 -32
  32. package/dist/core/cron.mjs.map +1 -1
  33. package/dist/core/decorators.mjs +2 -285
  34. package/dist/core/decorators.mjs.map +1 -1
  35. package/dist/core/errors.mjs +2 -110
  36. package/dist/core/errors.mjs.map +1 -1
  37. package/dist/core/interfaces.mjs +2 -53
  38. package/dist/core/interfaces.mjs.map +1 -1
  39. package/dist/core/logger.mjs +2 -207
  40. package/dist/core/logger.mjs.map +1 -1
  41. package/dist/core/path.mjs +2 -35
  42. package/dist/core/path.mjs.map +1 -1
  43. package/dist/core/plugin.d.mts +1 -1
  44. package/dist/core/plugin.mjs +2 -2
  45. package/dist/core/reactivity.mjs +2 -179
  46. package/dist/core/reactivity.mjs.map +1 -1
  47. package/dist/core-MvABl8Cl.mjs +13 -0
  48. package/dist/core-MvABl8Cl.mjs.map +1 -0
  49. package/dist/env-CObTuGZ3.mjs +12 -0
  50. package/dist/{env-C4Yr6nN8.mjs.map → env-CObTuGZ3.mjs.map} +1 -1
  51. package/dist/http/application.d.mts +1 -1
  52. package/dist/http/application.mjs +2 -3
  53. package/dist/http/bootstrap.d.mts +1 -1
  54. package/dist/http/bootstrap.mjs +2 -3
  55. package/dist/http/context.d.mts +2 -2
  56. package/dist/http/context.mjs +2 -3
  57. package/dist/http/middleware/cors.mjs +2 -73
  58. package/dist/http/middleware/cors.mjs.map +1 -1
  59. package/dist/http/middleware/csrf.mjs +2 -62
  60. package/dist/http/middleware/csrf.mjs.map +1 -1
  61. package/dist/http/middleware/error-handler.mjs +2 -54
  62. package/dist/http/middleware/error-handler.mjs.map +1 -1
  63. package/dist/http/middleware/helmet.mjs +2 -41
  64. package/dist/http/middleware/helmet.mjs.map +1 -1
  65. package/dist/http/middleware/rate-limit.mjs +2 -91
  66. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  67. package/dist/http/middleware/request-id.mjs +2 -25
  68. package/dist/http/middleware/request-id.mjs.map +1 -1
  69. package/dist/http/middleware/request-logger.mjs +2 -39
  70. package/dist/http/middleware/request-logger.mjs.map +1 -1
  71. package/dist/http/middleware/session.mjs +2 -167
  72. package/dist/http/middleware/session.mjs.map +1 -1
  73. package/dist/http/middleware/spa.d.mts +1 -1
  74. package/dist/http/middleware/spa.mjs +2 -98
  75. package/dist/http/middleware/spa.mjs.map +1 -1
  76. package/dist/http/middleware/upload.mjs +2 -181
  77. package/dist/http/middleware/upload.mjs.map +1 -1
  78. package/dist/http/middleware/validate.mjs +2 -68
  79. package/dist/http/middleware/validate.mjs.map +1 -1
  80. package/dist/http/middleware/views.d.mts +1 -1
  81. package/dist/http/middleware/views.mjs +2 -56
  82. package/dist/http/middleware/views.mjs.map +1 -1
  83. package/dist/http/query/index.mjs +2 -3
  84. package/dist/http/router-builder.d.mts +1 -1
  85. package/dist/http/router-builder.mjs +2 -105
  86. package/dist/http/router-builder.mjs.map +1 -1
  87. package/dist/{index-DvZfBNIf.d.mts → index-D-Wb23e6.d.mts} +264 -86
  88. package/dist/index-D-Wb23e6.d.mts.map +1 -0
  89. package/dist/index.d.mts +12 -12
  90. package/dist/index.mjs +2 -171
  91. package/dist/index.mjs.map +1 -1
  92. package/dist/metadata-WTmSU6Sf.mjs +12 -0
  93. package/dist/{metadata-CdYaU-XM.mjs.map → metadata-WTmSU6Sf.mjs.map} +1 -1
  94. package/dist/{plugin-DF8Xfv9Z.d.mts → plugin-JMkG7soG.d.mts} +102 -8
  95. package/dist/plugin-JMkG7soG.d.mts.map +1 -0
  96. package/dist/query-BmO0aBf6.mjs +12 -0
  97. package/dist/{query-nAYUgagU.mjs.map → query-BmO0aBf6.mjs.map} +1 -1
  98. package/dist/{router-builder-C7sXk_FG.d.mts → router-builder-CaQ629tw.d.mts} +2 -2
  99. package/dist/{router-builder-C7sXk_FG.d.mts.map → router-builder-CaQ629tw.d.mts.map} +1 -1
  100. package/dist/{spa-e4FIS2RB.d.mts → spa-CreyQc4N.d.mts} +2 -2
  101. package/dist/{spa-e4FIS2RB.d.mts.map → spa-CreyQc4N.d.mts.map} +1 -1
  102. package/dist/{views-DkNp9JJs.d.mts → views-1e3jQr5C.d.mts} +4 -4
  103. package/dist/{views-DkNp9JJs.d.mts.map → views-1e3jQr5C.d.mts.map} +1 -1
  104. package/package.json +2 -2
  105. package/dist/app-module-D6zL_V5S.d.mts +0 -50
  106. package/dist/app-module-D6zL_V5S.d.mts.map +0 -1
  107. package/dist/application-BTRI4aBd.d.mts.map +0 -1
  108. package/dist/application-Cna_2gex.mjs +0 -574
  109. package/dist/application-Cna_2gex.mjs.map +0 -1
  110. package/dist/bootstrap-kPcmbbWe.mjs +0 -195
  111. package/dist/config-DxEREQmR.mjs +0 -135
  112. package/dist/container-SMnB5yeT.mjs +0 -897
  113. package/dist/context-B0B3WQft.mjs +0 -348
  114. package/dist/context-B0B3WQft.mjs.map +0 -1
  115. package/dist/context-Ymvv-85x.d.mts.map +0 -1
  116. package/dist/core--a4XflX7.mjs +0 -820
  117. package/dist/core--a4XflX7.mjs.map +0 -1
  118. package/dist/env-C4Yr6nN8.mjs +0 -137
  119. package/dist/index-DvZfBNIf.d.mts.map +0 -1
  120. package/dist/metadata-CdYaU-XM.mjs +0 -76
  121. package/dist/plugin-DF8Xfv9Z.d.mts.map +0 -1
  122. package/dist/query-nAYUgagU.mjs +0 -164
@@ -1 +0,0 @@
1
- {"version":3,"file":"core--a4XflX7.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 { ContextMeta, ExecutionContext, MetaValue } from './execution-context'\n\n/**\n * String-literal union of every key declared on the augmentable\n * {@link ContextMeta} interface. Resolves to `string` when the\n * project hasn't augmented `ContextMeta` yet (so a first-day project\n * keeps compiling), and narrows to the concrete keys once the\n * `declare module '@forinda/kickjs' { interface ContextMeta { ... } }`\n * blocks land.\n *\n * Used as the element type of `dependsOn`, so a typo like\n * `dependsOn: ['tenent']` becomes a TS error instead of a boot-time\n * `MissingContributorError`.\n */\nexport type ContextMetaKey = keyof ContextMeta extends never ? string : keyof ContextMeta & string\n\n/**\n * What a single `deps` entry is allowed to be — the runtime calls\n * `container.resolve(value)`, which accepts an injection token brand\n * or a constructor (decorated class). Anything else (a string literal,\n * an array, a plain object) silently fails at boot when the runner\n * tries to resolve it; constraining at the type level surfaces the\n * mistake in the editor instead.\n */\nexport type DepValue = InjectionToken<unknown> | Constructor<unknown>\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, DepValue>> = {\n [K in keyof D]: D[K] extends InjectionToken<infer T>\n ? T\n : D[K] extends Constructor<infer T>\n ? T\n : never\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, DepValue> = Record<string, never>,\n P 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 * Typed against `keyof ContextMeta` once the project augments it — so\n * `dependsOn: ['tenent']` (typo) is a TS error, not a boot-time\n * `MissingContributorError`. Falls back to plain `string[]` when the\n * registry is empty (no augmentation yet) so first-day projects keep\n * compiling. Cast-as-any escape hatch:\n * `dependsOn: ['custom-key' as keyof ContextMeta]`.\n */\n dependsOn?: readonly ContextMetaKey[]\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 * Default per-call params merged with the call-site params; call-site\n * wins. When omitted, params default to `{}` and the resolver\n * receives an empty object — back-compat with today's zero-arg\n * decorators.\n *\n * Param shape is intentionally unconstrained: plain data, functions,\n * and closures are all valid. Adopters who want runtime validation\n * should perform it inside `resolve()` — keeps the framework\n * validator-agnostic so projects can plug Zod / Valibot / hand-rolled\n * checks without the framework caring.\n *\n * **Required-field caveat.** The factory call signature accepts\n * `Partial<P>` so adopters can override only the fields they care\n * about. If your `P` declares a *required* field that isn't in\n * `paramDefaults`, the merged runtime value can be missing that\n * field even though TypeScript types `params` as `P` inside\n * `resolve()`. Mitigate by either:\n *\n * 1. Marking the field optional in `P` and `if`-checking inside\n * `resolve()`, or\n * 2. Providing a default for every required field in\n * `paramDefaults`.\n *\n * The framework can't enforce option 2 at compile time without\n * giving up the back-compat that lets `paramDefaults` be omitted\n * entirely for `P = Record<string, never>`.\n */\n paramDefaults?: Partial<P>\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 * The third `params` argument carries the resolved per-call params\n * (call-site overrides merged on top of `paramDefaults`).\n */\n onError?: (err: unknown, ctx: Ctx, params: P) => MaybePromise<MetaValue<K> | undefined | void>\n /**\n * Compute and return the value to write into `ctx.set(key, …)`.\n *\n * The third `params` argument carries the resolved per-call params\n * (call-site overrides merged on top of `paramDefaults`). When the\n * decorator is applied zero-arg (`@Foo`), `params` equals\n * `paramDefaults` (or `{}` if defaults are omitted). When applied as\n * a factory (`@Foo({ ... })`), the call-site object is merged on top.\n */\n resolve: (ctx: Ctx, deps: ResolvedDeps<D>, params: P) => 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, DepValue> = Record<string, never>,\n Ctx extends ExecutionContext = ExecutionContext,\n> {\n readonly key: K\n readonly deps: D\n readonly dependsOn: readonly ContextMetaKey[]\n readonly optional: boolean\n /**\n * Per-call params from the spec are baked into the closure at\n * decorator-construction time, so the runner-facing `onError`\n * exposes only `(err, ctx)`.\n */\n readonly onError?: (err: unknown, ctx: Ctx) => MaybePromise<MetaValue<K> | undefined | void>\n /**\n * Per-call params from the spec are baked into the closure at\n * decorator-construction time, so the runner-facing `resolve`\n * exposes only `(ctx, deps)`. Adopters who write their own\n * registrations (without `defineContextDecorator`) match this\n * shape directly — params are an implementation detail of the\n * decorator factory, not of the runtime pipeline.\n */\n readonly resolve: (ctx: Ctx, deps: ResolvedDeps<D>) => MaybePromise<MetaValue<K>>\n}\n\n/**\n * Type-erased registration shape used in the public collection slots\n * (`AppModule.contributors?()`, `AppAdapter.contributors?()`,\n * `KickPlugin.contributors?()`, `bootstrap({ contributors })`).\n *\n * The narrow `ContributorRegistration` carries a `Ctx` parameter so\n * `resolve(ctx, deps)` is typed at the *definition* site, but `Ctx`\n * sits in a contravariant position on `resolve` — meaning a\n * `ContributorRegistration<…, RequestContext>` is *not* assignable to\n * `ContributorRegistration<…, ExecutionContext>` even though every\n * `RequestContext` is-a `ExecutionContext`. That's TS-sound but\n * useless: the runner only ever calls a contributor with the same\n * concrete ctx the route mounts under, so an HTTP-typed contributor\n * never sees a non-HTTP ctx. Erasing `Ctx` to `any` in the collection\n * type lets adopters store contributors typed against `RequestContext`\n * (or any future transport-specific ctx) in the same array without\n * casting.\n */\nexport type AnyContributorRegistration = ContributorRegistration<\n string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>\n\n/** Convenience alias for `AnyContributorRegistration[]` collections. */\nexport type ContributorRegistrations =\n | AnyContributorRegistration[]\n | readonly AnyContributorRegistration[]\n\n/**\n * The decorator function returned by either a zero-arg\n * {@link ContextDecorator} application or a factory call. Overloaded\n * to satisfy both class and method decorator shapes — adopters apply\n * the same decorator to either site without TS rejecting the call.\n */\nexport interface ContextDecoratorTarget {\n /** Class decorator usage. */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n (target: Function): void\n /** Method decorator usage. */\n (target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor): void\n}\n\n/**\n * The value returned by {@link defineContextDecorator}. Callable as\n * either a class or method decorator (with `paramDefaults` applied),\n * as a factory (`@Foo({...})` returning a per-site decorator), or\n * via `.with(params)` for non-decorator registration sites (module\n * hooks, adapter hooks, bootstrap option). `.registration` exposes\n * the underlying frozen {@link ContributorRegistration} for the\n * default-params case.\n */\nexport interface ContextDecorator<\n K extends string = string,\n D extends Record<string, DepValue> = Record<string, never>,\n P extends Record<string, unknown> = Record<string, never>,\n Ctx extends ExecutionContext = ExecutionContext,\n> {\n /**\n * Class decorator usage with `paramDefaults` — `@Foo class C {}`.\n * The class constructor is a `Function`, so this overload only\n * matches actual classes (not plain object literals — which\n * fall through to the factory overload below).\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n (target: Function): void\n /**\n * Method decorator usage with `paramDefaults` — `@Foo` over a\n * method. The required `propertyKey` distinguishes this from the\n * factory overload's single-object-arg call shape.\n */\n (target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor): void\n /**\n * Zero-arg factory usage — `@Foo()` returns a decorator with\n * `paramDefaults` applied. Equivalent in behaviour to the bare\n * `@Foo` form, exposed here so adopters who prefer \"always call the\n * factory\" don't need an `as any` cast.\n */\n (): ContextDecoratorTarget\n /**\n * Factory usage — `@Foo({ ... })` returns the actual decorator with\n * call-site params merged onto `paramDefaults`. Matches a single\n * params object; plain objects don't satisfy the `Function` /\n * 2-arg-minimum constraints above, so TS picks this overload.\n *\n * Accepts `Partial<P>` so adopters can override only the fields\n * they care about — anything missing falls back to `paramDefaults`\n * at runtime. Inside `resolve()`, `params` is the fully merged\n * `P`, never a `Partial<P>`.\n *\n * The returned decorator is overloaded for class AND method usage —\n * `@Foo({...}) class C {}` and `@Foo({...}) m() {}` both type-check.\n */\n (params: Partial<P>): ContextDecoratorTarget\n /**\n * Bare registration — uses `paramDefaults` only. Use this at non-\n * decorator registration sites (module / adapter / bootstrap) when\n * the call site doesn't need to override params.\n */\n readonly registration: ContributorRegistration<K, D, Ctx>\n /**\n * Build a registration with call-site params merged onto\n * `paramDefaults`. Use this at non-decorator registration sites\n * when the call site DOES want to override params:\n *\n * ```ts\n * bootstrap({\n * contributors: [LoadTenant.with({ source: 'subdomain' }).registration],\n * })\n * ```\n *\n * `Partial<P>` for the same reason as the factory overload — the\n * runtime merges with `paramDefaults`, so adopters only specify\n * fields they want to override.\n */\n with(params: Partial<P>): { 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, DepValue> = Record<string, never>,\n P extends Record<string, unknown> = Record<string, never>,\n Ctx extends ExecutionContext = ExecutionContext,\n>(spec: ContextDecoratorSpec<K, D, P, Ctx>): ContextDecorator<K, D, P, Ctx> {\n // Snapshot + freeze paramDefaults so callers can't mutate the spec\n // object post-definition and shift the merged params under our feet.\n // Same immutability boundary applied to `deps` and `dependsOn`.\n const defaults = Object.freeze({\n ...(spec.paramDefaults ?? ({} as Partial<P>)),\n }) as Readonly<Partial<P>>\n\n // Shared deps + dependsOn — frozen once and reused across every\n // registration produced by this decorator (one per call site).\n // `Object.freeze` is shallow — the values inside (DI tokens,\n // constructors) are intentionally untouched; freezing them would\n // prevent the container from doing legitimate per-instance\n // bookkeeping.\n const sharedDeps = Object.freeze({ ...(spec.deps ?? ({} as D)) }) as D\n const sharedDependsOn = Object.freeze([...(spec.dependsOn ?? [])])\n const sharedOptional = spec.optional ?? false\n\n /**\n * Build a frozen registration that closes over a specific\n * resolved-params object. The runner sees a normal\n * `(ctx, deps) => value` registration — params are baked into the\n * closure, invisible to the pipeline.\n */\n const buildRegistration = (params: P): ContributorRegistration<K, D, Ctx> => {\n // Shallow-freeze the captured params so a misbehaving `resolve()` /\n // `onError()` can't mutate the closure and bleed into later\n // requests through the same registration. Adopters who really need\n // mutable per-request state should write to `ctx.set(...)` from\n // inside the resolver instead of mutating params.\n const frozenParams = Object.freeze({ ...params }) as P\n const onError: ContributorRegistration<K, D, Ctx>['onError'] = spec.onError\n ? (err: unknown, ctx: Ctx) => spec.onError!(err, ctx, frozenParams)\n : undefined\n const resolve: ContributorRegistration<K, D, Ctx>['resolve'] = (\n ctx: Ctx,\n deps: ResolvedDeps<D>,\n ) => spec.resolve(ctx, deps, frozenParams)\n return Object.freeze({\n key: spec.key,\n deps: sharedDeps,\n dependsOn: sharedDependsOn,\n optional: sharedOptional,\n onError,\n resolve,\n })\n }\n\n // Default-params registration — used for zero-arg decorator\n // applications and for the `.registration` accessor. Cloning\n // `defaults` so the closure can't be mutated through the spec.\n const defaultRegistration = buildRegistration({ ...defaults } as P)\n\n /**\n * Decide whether the decorator was called as a decorator\n * (`@Foo` / `@Foo(target, key)`) or as a factory\n * (`@Foo()` / `@Foo({...})`).\n *\n * - Class decorator: `(target)` where target is a constructor function.\n * - Method decorator: `(target, propertyKey, descriptor?)` where\n * target is a prototype object and propertyKey is a string/symbol.\n * - Factory (defaults): `()` — adopter wrote `@Foo()` (rare; usually\n * they write the bare `@Foo`). Returns a decorator using\n * `paramDefaults`.\n * - Factory (params): `(params)` where params is a plain object.\n *\n * The legacy decorators that ship with KickJS (`@Get('/path')`,\n * `@Cron('* * * *')`, etc.) use the same heuristic, so adopters\n * already know to pass plain object literals as factory args.\n */\n const isDecoratorCall = (args: unknown[]): boolean => {\n // Zero args is a factory call (`@Foo()`), not a direct decorator\n // application — TS never invokes a decorator with zero args.\n if (args.length === 0) return false\n if (args.length >= 2) return true\n const first = args[0]\n // Functions are class constructors at decoration time.\n if (typeof first === 'function') return true\n // Anything else (plain object, undefined, primitive) → factory call.\n return false\n }\n\n const applyAsDecorator = (\n registration: ContributorRegistration<K, D, Ctx>,\n target: object,\n propertyKey?: string | symbol,\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\n // lookup key, matching the convention used by @Middleware and\n // consumed by router-builder.ts.\n const constructor = (target as { constructor: object }).constructor\n pushMethodMeta(METADATA.METHOD_CONTRIBUTORS, constructor, String(propertyKey), registration)\n }\n }\n\n /**\n * `true` for `{...}` and `Object.create(null)`. Rejects every\n * built-in subclass (Map / Set / Date / Error / RegExp / Promise),\n * adopter classes, and arrays.\n */\n const isPlainObject = (value: object): boolean => {\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n }\n\n /**\n * Merge call-site `Partial<P>` over `paramDefaults`. Strict guard:\n * accepts only **plain object literals** (or `Object.create(null)`).\n * Reject everything else with a descriptive `TypeError`.\n *\n * Why strict? Object spread copies enumerable own properties only.\n * `{ ...new Date() }` and `{ ...new Map([...])}` both produce `{}`\n * — the params silently drop. Catching this at the boundary\n * surfaces the mistake instead of routing the request with empty\n * config. Adopters who genuinely need a class-instance shape can\n * destructure it themselves: `Foo({ ...new MyParams() })`.\n */\n const mergeParams = (override: unknown): P => {\n if (override === undefined) return { ...defaults } as P\n if (\n override === null ||\n typeof override !== 'object' ||\n Array.isArray(override) ||\n !isPlainObject(override)\n ) {\n const got =\n override === null\n ? 'null'\n : Array.isArray(override)\n ? 'array'\n : typeof override === 'object'\n ? `instance of ${(override as object).constructor?.name ?? 'unknown class'}`\n : typeof override\n throw new TypeError(\n `defineContextDecorator(${spec.key}): factory call requires a plain object literal, got ${got}. ` +\n `Class instances and built-ins (Map, Date, etc) silently spread to empty objects — ` +\n `call the decorator with a spread object literal instead, e.g. ` +\n `\\`MyDecorator({ ...someInstance })\\`.`,\n )\n }\n return { ...defaults, ...(override as Partial<P>) } as P\n }\n\n function decoratorOrFactory(...args: unknown[]): unknown {\n if (isDecoratorCall(args)) {\n const [target, propertyKey] = args as [\n object,\n string | symbol | undefined,\n PropertyDescriptor?,\n ]\n applyAsDecorator(defaultRegistration, target, propertyKey)\n return undefined\n }\n // Factory call — capture merged params and return a decorator.\n const params = mergeParams(args[0])\n const registration = buildRegistration(params)\n return (target: object, propertyKey?: string | symbol) => {\n applyAsDecorator(registration, target, propertyKey)\n }\n }\n\n Object.defineProperty(decoratorOrFactory, 'registration', {\n value: defaultRegistration,\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n Object.defineProperty(decoratorOrFactory, 'with', {\n value: (params: Partial<P>) => ({\n registration: buildRegistration(mergeParams(params)),\n }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return decoratorOrFactory as unknown as ContextDecorator<K, D, P, 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 { AnyContributorRegistration } 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 *\n * `registration` is the type-erased {@link AnyContributorRegistration}\n * — the runner doesn't care about each registration's narrow `D` /\n * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic\n * contributors in the same `externalSources` / `contributors()`\n * array. The narrow generics from `defineContextDecorator` survive\n * at the *definition* site (where `resolve` is typed); they're erased\n * here so collections compose without `as any` casts.\n */\nexport interface SourcedRegistration {\n registration: AnyContributorRegistration\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 AnyContributorRegistration[]\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 AnyContributorRegistration[],\n route: string | undefined,\n): AnyContributorRegistration[] {\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, AnyContributorRegistration[]>()\n const byKey = new Map<string, AnyContributorRegistration>()\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: AnyContributorRegistration[] = []\n for (const reg of registrations) {\n if (indegree.get(reg.key) === 0) queue.push(reg)\n }\n\n const sorted: AnyContributorRegistration[] = []\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 AnyContributorRegistration[],\n byKey: ReadonlyMap<string, AnyContributorRegistration>,\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-lookup 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> = {},\n overrides: Partial<TConfig> = {},\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> = {},\n overrides: Partial<TConfig> = {},\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 *\n * `description` and `example` may both be multi-line — typegen preserves\n * line breaks when rendering them as JSDoc. There is no upper limit on\n * the example size; entire shape definitions or worked snippets are fine.\n */\nexport interface AugmentationMeta {\n /**\n * Free-form description of what the augmentation customises. May be\n * multi-line — newlines are preserved in the generated JSDoc.\n */\n description?: string\n /**\n * TS snippet showing a typical shape. May be multi-line; rendered\n * inside a fenced code block in the generated catalogue. Use this\n * for anything from `'{ foo: string }'` up to a full interface body\n * — typegen no longer flattens newlines.\n */\n example?: string\n}\n\n/**\n * Advertise an augmentable interface so `kick typegen` can list it in\n * `.kickjs/types/augmentations.d.ts` for project-wide discovery.\n *\n * **This function is a runtime AND type-level no-op.** It does NOT\n * augment the interface for TypeScript. The actual augmentation is\n * the `declare module` block — `defineAugmentation` only adds an\n * entry to the typegen catalogue so other contributors / adopters\n * can find the interface and know its expected shape.\n *\n * Both calls are needed:\n *\n * ```ts\n * import { defineAugmentation } from '@forinda/kickjs'\n *\n * // (1) The actual TS augmentation — what `ctx.get('tenant')` reads.\n * declare module '@forinda/kickjs' {\n * interface ContextMeta {\n * tenant: { id: string; name: string }\n * }\n * }\n *\n * // (2) Catalogue entry — what `kick typegen` lists in\n * // `.kickjs/types/augmentations.d.ts` for browseability.\n * defineAugmentation('ContextMeta', {\n * description: 'Tenant resolved from x-tenant-id by TenantAdapter',\n * example: `{\n * tenant: {\n * id: string\n * name: string\n * plan: 'free' | 'pro' | 'enterprise'\n * featureFlags: Record<string, boolean>\n * }\n * }`,\n * })\n * ```\n *\n * Skip `defineAugmentation` if you don't care about the catalogue — the\n * `declare module` block alone is enough for runtime + type behaviour.\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,eAAe,QAAQ;AAC5B,OAAK,cAAc,QAAQ,eAAe;;;;;;CAO5C,MAAM,QAAW,IAAkC;AACjD,OAAK,2BAA2B;AAEhC,MAAI,KAAK,UAAU,OACjB,OAAM,IAAI,iBAAiB,KAAK,KAAK;AAGvC,MAAI,KAAK,UAAU,eAAe,KAAK,oBAAoB,KAAK,YAC9D,OAAM,IAAI,iBAAiB,KAAK,KAAK;AAGvC,MAAI,KAAK,UAAU,YACjB,MAAK;AAGP,MAAI;GACF,MAAM,SAAS,MAAM,IAAI;AACzB,QAAK,WAAW;AAChB,UAAO;WACA,OAAO;AACd,QAAK,WAAW;AAChB,SAAM;;;;CAKV,WAAgC;AAC9B,OAAK,2BAA2B;AAChC,SAAO,KAAK;;;CAId,WAAgC;AAC9B,OAAK,2BAA2B;AAChC,SAAO;GACL,UAAU,KAAK;GACf,WAAW,KAAK;GAChB,OAAO,KAAK;GACZ,GAAI,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cACwB;EACxB,MAAM,SAAS,YAAY,QAAQ,UAAU,UAAU;EAKvD,MAAM,QAAQ,QAAQ,MAAM,QAAQ;GAAE,MAAM;GAAc;GAAQ,CAAC;AACjE,QAAqB,OAAO;AAC9B,SAAO;;CAGT,MAAM,cAAc,cAAsB,SAAmD;EAC3F,IAAI;AAEJ,SAAO;GACL,MAAM;GACN,MAAM,YAAY,KAAqB;IACrC,MAAM,QAAQ,KAAK,UAAU,EAAE,EAAE,KAAK,QAAQ,IAAI,UAAU,QAAQ,IAAa,CAAC;AAElF,YAAQ,UAAU,cAAc,OADjB,MAAM,KAAK,WAAW,GAAG,KAAK,CACqB;AAClE,UAAM,MAAM,cAAc,IAAI;;GAEhC,MAAM,WAAW,KAAqB;AACpC,UAAM,OAAO,aAAa,IAAI;;GAEhC,MAAM,WAAW;AACf,UAAM,OAAO,YAAY;;GAE3B,MAAM,gBAAgB;AACpB,WAAQ,MAAM,OAAO,iBAAiB,IAAK;KAAE,MAAM;KAAc,QAAQ;KAAM;;GAElF;;CAGH,MAAM,YAAY,WAChB,UAAU,QAAQ,MAAM,OAAO,OAAO;AAExC,SAAQ,UAAU,WAAmB,WACnC,UAAU,YAAY,QAAQ,MAAM,UAAU,EAAE,MAAM,OAAO;AAE/D,SAAQ,SAAS,SAAuC,WAAW,QAAQ,MAAM,KAAK;AAEtF,QAAO,eAAe,SAAS,cAAc,EAAE,OAAO,OAAO,OAAO,EAAE,GAAG,SAAS,CAAC,EAAE,CAAC;AAEtF,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACpCT,SAAgB,mBAAmB,MAAc,MAA+B"}
@@ -1,137 +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 { h as __require, t as Container } from "./container-SMnB5yeT.mjs";
12
- import { z } from "zod";
13
- //#region src/config/env.ts
14
- /**
15
- * Lazily load `.env` via dotenv if it is installed in the consumer app.
16
- * `dotenv` is an **optional peer dependency** of `@forinda/kickjs` —
17
- * apps that want `.env` file support install it themselves (the CLI
18
- * generators add it to every scaffolded `package.json`). Apps that
19
- * inject env via the shell, Docker, or a secret manager can skip it
20
- * entirely and `process.env` is read as-is.
21
- *
22
- * We call `dotenv.config()` directly rather than `require('dotenv/config')`
23
- * so that a re-evaluation of this module (e.g. Vite SSR full-reload after
24
- * editing `.env`) can re-read the file. `dotenv/config` is a side-effect
25
- * shim that CJS caches aggressively, so the second `require` is a no-op
26
- * and new keys never reach `process.env` — the root cause of the
27
- * "DATABASE_URL undefined until restart" bug on Windows dev.
28
- */
29
- function tryLoadDotenv() {
30
- try {
31
- __require("dotenv").config({
32
- override: false,
33
- quiet: true
34
- });
35
- } catch {}
36
- }
37
- tryLoadDotenv();
38
- /**
39
- * Base environment schema with common server variables.
40
- * Users extend this with their own application-specific vars.
41
- */
42
- const baseEnvSchema = z.object({
43
- PORT: z.coerce.number().default(3e3),
44
- NODE_ENV: z.enum([
45
- "development",
46
- "production",
47
- "test"
48
- ]).default("development"),
49
- LOG_LEVEL: z.string().default("info")
50
- });
51
- /** Cached env config to avoid re-parsing — keyed by schema reference */
52
- let cachedEnv = null;
53
- let cachedSchema = null;
54
- /**
55
- * Define a custom env schema. The base schema (`PORT`, `NODE_ENV`,
56
- * `LOG_LEVEL`) is always merged in, so users never need to remember to
57
- * extend it themselves — both styles below produce the same result and
58
- * both surface the base keys in `KickEnv`.
59
- *
60
- * Returns a Zod schema that validates `process.env`.
61
- *
62
- * @example
63
- * ```ts
64
- * // Style A — return a fresh object; base fields are merged automatically
65
- * export default defineEnv(() =>
66
- * z.object({
67
- * DATABASE_URL: z.string().url(),
68
- * JWT_SECRET: z.string().min(32),
69
- * })
70
- * )
71
- *
72
- * // Style B — explicitly extend `base` (still works, identical result)
73
- * export default defineEnv((base) =>
74
- * base.extend({
75
- * DATABASE_URL: z.string().url(),
76
- * })
77
- * )
78
- * ```
79
- *
80
- * User-defined keys override base keys when they collide, so a project
81
- * can re-type `PORT` or tighten `NODE_ENV` without losing the rest of
82
- * the base shape.
83
- */
84
- function defineEnv(extend) {
85
- const userSchema = extend(baseEnvSchema);
86
- return baseEnvSchema.extend(userSchema.shape);
87
- }
88
- function loadEnv(schema) {
89
- const s = schema ?? cachedSchema ?? baseEnvSchema;
90
- if (cachedEnv && cachedSchema === s) return cachedEnv;
91
- cachedSchema = s;
92
- cachedEnv = s.parse(process.env);
93
- Container._envResolver = (key) => cachedEnv?.[key];
94
- return cachedEnv;
95
- }
96
- function getEnv(key, schema) {
97
- return (schema ? loadEnv(schema) : loadEnv())[key];
98
- }
99
- /**
100
- * Reload env from `process.env`. Re-reads `.env` via dotenv (if
101
- * installed), then re-parses the result against the **same** schema
102
- * the project registered at startup. Called during HMR rebuild and by
103
- * `envWatchPlugin` to pick up `.env` file changes mid-session.
104
- *
105
- * Crucially, this preserves the registered schema. Wiping it would
106
- * silently downgrade `ConfigService` and `@Value()` back to the base
107
- * schema on the next read, so every user-defined key would start
108
- * resolving as `undefined` after the first `.env` save — which was the
109
- * original "config disappears in dev" bug.
110
- *
111
- * If you need to fully forget the schema (e.g. tests that swap schemas
112
- * between cases), call {@link resetEnvCache} instead.
113
- */
114
- function reloadEnv() {
115
- try {
116
- __require("dotenv").config({
117
- override: true,
118
- quiet: true
119
- });
120
- } catch {}
121
- cachedEnv = null;
122
- if (cachedSchema) loadEnv(cachedSchema);
123
- }
124
- /**
125
- * Fully reset the env cache, including the registered schema. Use this
126
- * in tests that need to swap schemas between cases — `reloadEnv()`
127
- * deliberately preserves the schema to avoid the "user keys vanish on
128
- * `.env` reload" footgun.
129
- */
130
- function resetEnvCache() {
131
- cachedEnv = null;
132
- cachedSchema = null;
133
- }
134
- //#endregion
135
- export { reloadEnv as a, loadEnv as i, defineEnv as n, resetEnvCache as o, getEnv as r, baseEnvSchema as t };
136
-
137
- //# sourceMappingURL=env-C4Yr6nN8.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-DvZfBNIf.d.mts","names":[],"sources":["../src/core/metadata.ts","../src/core/circuit-breaker.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/asset-keys.ts"],"mappings":";;;;;;;;;;;;;;;;;;KAeK,OAAA,qBAA4B,cAAA;;iBAKjB,YAAA,GAAA,CAAgB,GAAA,EAAK,OAAA,EAAS,KAAA,EAAO,CAAA,EAAG,MAAA;;iBAKxC,aAAA,GAAA,CAAiB,GAAA,EAAK,OAAA,EAAS,KAAA,EAAO,CAAA,EAAG,MAAA,UAAgB,MAAA;AALzE;AAAA,iBAYgB,YAAA,GAAA,CAAgB,GAAA,EAAK,OAAA,EAAS,MAAA,UAAgB,QAAA,EAAU,CAAA,GAAI,CAAA;;iBAK5D,aAAA,GAAA,CAAiB,GAAA,EAAK,OAAA,EAAS,MAAA,UAAgB,MAAA,UAAgB,QAAA,EAAU,CAAA,GAAI,CAAA;;iBAK7E,YAAA,CAAa,GAAA,EAAK,OAAA,EAAS,MAAA;;iBAK3B,uBAAA,GAAA,CAA2B,GAAA,EAAK,OAAA,EAAS,MAAA,WAAiB,CAAA;;iBAK1D,wBAAA,GAAA,CACd,GAAA,EAAK,OAAA,EACL,MAAA,UACA,MAAA,WACC,CAAA;;iBAOa,aAAA,GAAA,CAAiB,GAAA,EAAK,OAAA,EAAS,MAAA,aAAmB,KAAA,EAAO,CAAA;AAtCzE;AAAA,iBA4CgB,cAAA,GAAA,CACd,GAAA,EAAK,OAAA,EACL,MAAA,UACA,MAAA,aACG,KAAA,EAAO,CAAA;;iBASI,YAAA,MAAA,CAAmB,GAAA,EAAK,OAAA,EAAS,MAAA,UAAgB,MAAA,EAAQ,CAAA,EAAG,QAAA,EAAU,CAAA;;iBAQtE,UAAA,MAAA,CAAiB,GA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B,MAAA;AAAA;;;;APCxE;;;;UOSiB,mBAAA;EACf,MAAA,GAAS,aAAA;EACT,UAAA,IAAc,IAAA,UAAc,OAAA,GAAU,OAAA,CAAQ,OAAA;AAAA;;;;;;APJhD;;UOciB,cAAA;EAAA,CACd,MAAA,GAAS,OAAA,CAAQ,OAAA,IAAW,UAAA,GAAa,MAAA;EAC1C,MAAA,CAAO,SAAA,UAAmB,MAAA,GAAS,OAAA,CAAQ,OAAA,IAAW,UAAA,GAAa,MAAA;EACnE,KAAA,CAAM,IAAA,EAAM,mBAAA,CAAoB,OAAA,IAAW,UAAA;EAAA,SAClC,UAAA,EAAY,QAAA,CAAS,oBAAA,CAAqB,OAAA,EAAS,MAAA;AAAA;;;;;;;;;;APb9D;;;;;;;;;;;;;;;;iBOgDgB,aAAA,WAAwB,MAAA,oCAAA,CACtC,OAAA,EAAS,oBAAA,CAAqB,OAAA,EAAS,MAAA,IACtC,cAAA,CAAe,OAAA,EAAS,MAAA;;;KChEf,gBAAA;AAAA,UAEK,YAAA;;EAEf,GAAA;;EAEA,GAAA;AAAA;AAAA,UAGe,qBAAA;;;;;;AR/B4B;;EQuC3C,QAAA,GAAW,gBAAA;AAAA;AAAA,UAGI,oBAAA;EACf,KAAA,EAAO,YAAA;ERxBmB;;;;;;;EQgC1B,uBAAA;AAAA;;;AR3BF;;;;;;;;iBQwCgB,cAAA,CACd,SAAA,UACA,KAAA,qBACA,IAAA,GAAM,qBAAA,GACL,oBAAA;;iBA2Da,QAAA,CAAS,IAAA"}
@@ -1,76 +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 "reflect-metadata";
12
- //#region src/core/metadata.ts
13
- /** Set metadata on a class (or prototype for property decorators) */
14
- function setClassMeta(key, value, target) {
15
- Reflect.defineMetadata(key, value, target);
16
- }
17
- /** Set metadata on a specific method */
18
- function setMethodMeta(key, value, target, method) {
19
- Reflect.defineMetadata(key, value, target, method);
20
- }
21
- /** Get metadata from a class, returning `fallback` if not set */
22
- function getClassMeta(key, target, fallback) {
23
- return Reflect.getMetadata(key, target) ?? fallback;
24
- }
25
- /** Get metadata from a specific method, returning `fallback` if not set */
26
- function getMethodMeta(key, target, method, fallback) {
27
- return Reflect.getMetadata(key, target, method) ?? fallback;
28
- }
29
- /** Check if metadata exists on a class */
30
- function hasClassMeta(key, target) {
31
- return Reflect.hasMetadata(key, target);
32
- }
33
- /** Get metadata from a class with no default (returns undefined if absent) */
34
- function getClassMetaOrUndefined(key, target) {
35
- return Reflect.getMetadata(key, target);
36
- }
37
- /** Get metadata from a method with no default (returns undefined if absent) */
38
- function getMethodMetaOrUndefined(key, target, method) {
39
- return Reflect.getMetadata(key, target, method);
40
- }
41
- /** Append items to an array stored in class metadata */
42
- function pushClassMeta(key, target, ...items) {
43
- const existing = Reflect.getOwnMetadata(key, target) ?? [];
44
- Reflect.defineMetadata(key, [...existing, ...items], target);
45
- }
46
- /** Append items to an array stored in method metadata */
47
- function pushMethodMeta(key, target, method, ...items) {
48
- const existing = Reflect.getOwnMetadata(key, target, method) ?? [];
49
- Reflect.defineMetadata(key, [...existing, ...items], target, method);
50
- }
51
- /** Set a key/value in a Map stored in class metadata */
52
- function setInMetaMap(key, target, mapKey, mapValue) {
53
- const inherited = Reflect.getOwnMetadata(key, target);
54
- const map = inherited ? new Map(inherited) : /* @__PURE__ */ new Map();
55
- map.set(mapKey, mapValue);
56
- Reflect.defineMetadata(key, map, target);
57
- }
58
- /** Get a Map from class metadata (returns empty Map if absent) */
59
- function getMetaMap(key, target) {
60
- return Reflect.getMetadata(key, target) ?? /* @__PURE__ */ new Map();
61
- }
62
- /** Set a key/value in a Record stored in class metadata */
63
- function setInMetaRecord(key, target, recKey, recValue) {
64
- const inherited = Reflect.getOwnMetadata(key, target);
65
- const rec = inherited ? { ...inherited } : {};
66
- rec[recKey] = recValue;
67
- Reflect.defineMetadata(key, rec, target);
68
- }
69
- /** Get a Record from class metadata (returns empty object if absent) */
70
- function getMetaRecord(key, target) {
71
- return Reflect.getMetadata(key, target) ?? {};
72
- }
73
- //#endregion
74
- export { getMethodMeta as a, pushClassMeta as c, setInMetaMap as d, setInMetaRecord as f, getMetaRecord as i, pushMethodMeta as l, getClassMetaOrUndefined as n, getMethodMetaOrUndefined as o, setMethodMeta as p, getMetaMap as r, hasClassMeta as s, getClassMeta as t, setClassMeta as u };
75
-
76
- //# sourceMappingURL=metadata-CdYaU-XM.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"plugin-DF8Xfv9Z.d.mts","names":[],"sources":["../src/core/plugin.ts"],"mappings":";;;;;;;;AA0DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAAiB,UAAA;;EAEf,IAAA;;;;;;;;;;;;;;;;;;;EAoBA,SAAA,YAAqB,gBAAA;;;;;EAMrB,QAAA,EAAU,SAAA,EAAW,SAAA;;;;;EAMrB,OAAA,KAAY,cAAA;;;;;EAMZ,QAAA,KAAa,UAAA;;;;;EAMb,UAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCA,YAAA,KAAiB,wBAAA;;;;;EAMjB,OAAA,EAAS,SAAA,EAAW,SAAA,UAAmB,OAAA;;;;;EAMvC,QAAA,YAAoB,OAAA;;;;;;;;;;;;;EAcpB,UAAA,eAAyB,OAAA;;;;;;EAOzB,YAAA;AAAA"}
@@ -1,164 +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
- //#region src/http/query/types.ts
12
- const FILTER_OPERATORS = new Set([
13
- "eq",
14
- "neq",
15
- "gt",
16
- "gte",
17
- "lt",
18
- "lte",
19
- "between",
20
- "in",
21
- "contains",
22
- "starts",
23
- "ends"
24
- ]);
25
- //#endregion
26
- //#region src/http/query/parse-query.ts
27
- const MAX_SEARCH_LENGTH = 200;
28
- const DEFAULT_PAGE = 1;
29
- const DEFAULT_LIMIT = 20;
30
- const MAX_LIMIT = 100;
31
- /** Parse filter strings like "status:eq:active" into structured objects */
32
- function parseFilters(filterParam, allowedFields) {
33
- if (!filterParam) return [];
34
- const items = Array.isArray(filterParam) ? filterParam : [filterParam];
35
- const results = [];
36
- const allowed = allowedFields ? new Set(allowedFields) : null;
37
- for (const item of items) {
38
- const firstColon = item.indexOf(":");
39
- if (firstColon === -1) continue;
40
- const secondColon = item.indexOf(":", firstColon + 1);
41
- if (secondColon === -1) continue;
42
- const field = item.slice(0, firstColon);
43
- const operator = item.slice(firstColon + 1, secondColon);
44
- const value = item.slice(secondColon + 1);
45
- if (!field || !value) continue;
46
- if (!FILTER_OPERATORS.has(operator)) continue;
47
- if (allowed && !allowed.has(field)) continue;
48
- results.push({
49
- field,
50
- operator,
51
- value
52
- });
53
- }
54
- return results;
55
- }
56
- /** Parse sort strings like "firstName:asc" into structured objects */
57
- function parseSort(sortParam, allowedFields) {
58
- if (!sortParam) return [];
59
- const items = Array.isArray(sortParam) ? sortParam : [sortParam];
60
- const results = [];
61
- const allowed = allowedFields ? new Set(allowedFields) : null;
62
- for (const item of items) {
63
- const lastColon = item.lastIndexOf(":");
64
- if (lastColon === -1) continue;
65
- const field = item.slice(0, lastColon);
66
- const dir = item.slice(lastColon + 1).toLowerCase();
67
- if (!field) continue;
68
- if (dir !== "asc" && dir !== "desc") continue;
69
- if (allowed && !allowed.has(field)) continue;
70
- results.push({
71
- field,
72
- direction: dir
73
- });
74
- }
75
- return results;
76
- }
77
- /** Parse page/limit into pagination with computed offset */
78
- function parsePagination(params) {
79
- let page = typeof params.page === "string" ? Number.parseInt(params.page, 10) : params.page ?? DEFAULT_PAGE;
80
- let limit = typeof params.limit === "string" ? Number.parseInt(params.limit, 10) : params.limit ?? DEFAULT_LIMIT;
81
- if (Number.isNaN(page) || page < 1) page = DEFAULT_PAGE;
82
- if (Number.isNaN(limit) || limit < 1) limit = DEFAULT_LIMIT;
83
- if (limit > MAX_LIMIT) limit = MAX_LIMIT;
84
- return {
85
- page,
86
- limit,
87
- offset: (page - 1) * limit
88
- };
89
- }
90
- /** Sanitize and truncate search query */
91
- function parseSearchQuery(q) {
92
- if (!q) return "";
93
- return q.trim().slice(0, MAX_SEARCH_LENGTH);
94
- }
95
- /**
96
- * Normalize a QueryFieldConfig into the string-based form.
97
- * Detects column-object-based configs (DrizzleQueryParamsConfig) by checking
98
- * for a `columns` property and extracts `Object.keys()`.
99
- */
100
- function normalizeFieldConfig(config) {
101
- if (!config) return void 0;
102
- if ("columns" in config && config.columns && typeof config.columns === "object") return {
103
- filterable: Object.keys(config.columns),
104
- sortable: config.sortable ? Object.keys(config.sortable) : void 0,
105
- searchable: void 0
106
- };
107
- return config;
108
- }
109
- /**
110
- * Parse a raw Express query object into a structured, ORM-agnostic ParsedQuery.
111
- *
112
- * @param query - Raw query string object from `req.query` or Zod-validated object
113
- * @param fieldConfig - Optional field restrictions (whitelist filterable/sortable/searchable).
114
- * Accepts both string-based configs (`{ filterable, sortable, searchable }`) and
115
- * column-object configs (`{ columns, sortable, searchColumns }`).
116
- *
117
- * @example
118
- * ```ts
119
- * // String-based config
120
- * const parsed = parseQuery(ctx.query, {
121
- * filterable: ['status', 'priority'],
122
- * sortable: ['createdAt', 'title'],
123
- * })
124
- *
125
- * // Column-object config (DrizzleQueryParamsConfig)
126
- * const parsed = parseQuery(ctx.query, TASK_QUERY_CONFIG)
127
- * ```
128
- *
129
- * Query string format:
130
- * - Filters: `?filter=field:operator:value` (repeatable)
131
- * - Sort: `?sort=field:asc|desc` (repeatable)
132
- * - Pagination: `?page=1&limit=20`
133
- * - Search: `?q=search+term`
134
- *
135
- * Filter operators: eq, neq, gt, gte, lt, lte, between, in, contains, starts, ends
136
- */
137
- function parseQuery(query, fieldConfig) {
138
- const normalized = normalizeFieldConfig(fieldConfig);
139
- return {
140
- filters: parseFilters(query.filter, normalized?.filterable),
141
- sort: parseSort(query.sort, normalized?.sortable),
142
- pagination: parsePagination({
143
- page: query.page,
144
- limit: query.limit
145
- }),
146
- search: parseSearchQuery(query.q)
147
- };
148
- }
149
- /** Convert ParsedQuery back into query string parameters */
150
- function buildQueryParams(parsed) {
151
- const params = {};
152
- if (parsed.filters?.length) params.filter = parsed.filters.map((f) => `${f.field}:${f.operator}:${f.value}`);
153
- if (parsed.sort?.length) params.sort = parsed.sort.map((s) => `${s.field}:${s.direction}`);
154
- if (parsed.pagination) {
155
- params.page = parsed.pagination.page;
156
- params.limit = parsed.pagination.limit;
157
- }
158
- if (parsed.search) params.q = parsed.search;
159
- return params;
160
- }
161
- //#endregion
162
- export { parseSearchQuery as a, parseQuery as i, parseFilters as n, parseSort as o, parsePagination as r, FILTER_OPERATORS as s, buildQueryParams as t };
163
-
164
- //# sourceMappingURL=query-nAYUgagU.mjs.map