@forinda/kickjs 3.1.3 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-DjL8ql5d.d.mts → adapter-DLEHb0K6.d.mts} +14 -3
- package/dist/adapter-DLEHb0K6.d.mts.map +1 -0
- package/dist/{app-module-Cotu9TIC.d.mts → app-module-ERR9jhow.d.mts} +12 -2
- package/dist/app-module-ERR9jhow.d.mts.map +1 -0
- package/dist/{application-BVl6L8xo.mjs → application-x8CXLOlv.mjs} +92 -22
- package/dist/application-x8CXLOlv.mjs.map +1 -0
- package/dist/{bootstrap-D6leYXz2.mjs → bootstrap-CYnxozL_.mjs} +6 -6
- package/dist/{bootstrap-D6leYXz2.mjs.map → bootstrap-CYnxozL_.mjs.map} +1 -1
- package/dist/{cache-CcTzzNdr.d.mts → cache-V91BNTIM.d.mts} +1 -1
- package/dist/{cache-CcTzzNdr.d.mts.map → cache-V91BNTIM.d.mts.map} +1 -1
- package/dist/{chunk-CVPG7JJl.mjs → chunk-Bt-rz0Tp.mjs} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +3 -3
- package/dist/{config-gkVEnxVm.mjs → config-aWxKLk4A.mjs} +3 -3
- package/dist/{config-gkVEnxVm.mjs.map → config-aWxKLk4A.mjs.map} +1 -1
- package/dist/{container-BBZLlK6y.mjs → container-Dnk43k54.mjs} +3 -3
- package/dist/{container-BBZLlK6y.mjs.map → container-Dnk43k54.mjs.map} +1 -1
- package/dist/{container-BJb34faa.d.mts → container-fIS1uLx-.d.mts} +2 -2
- package/dist/{container-BJb34faa.d.mts.map → container-fIS1uLx-.d.mts.map} +1 -1
- package/dist/context-OktlOQBQ.mjs +327 -0
- package/dist/context-OktlOQBQ.mjs.map +1 -0
- package/dist/context-decorator-GA8-hDLe.d.mts +111 -0
- package/dist/context-decorator-GA8-hDLe.d.mts.map +1 -0
- 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 +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 +1 -1
- package/dist/core/decorators.mjs +3 -3
- 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 +3 -1
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.d.mts +1 -1
- package/dist/core/logger.mjs +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 +435 -0
- package/dist/core-DANnH5-e.mjs.map +1 -0
- package/dist/{cron-H-IyLcOr.d.mts → cron-CfsPdi7R.d.mts} +1 -1
- package/dist/{cron-H-IyLcOr.d.mts.map → cron-CfsPdi7R.d.mts.map} +1 -1
- package/dist/{decorators-C9_SN7ge.d.mts → decorators-H42oPg0m.d.mts} +2 -2
- package/dist/{decorators-C9_SN7ge.d.mts.map → decorators-H42oPg0m.d.mts.map} +1 -1
- package/dist/{env-Cu5hWsuE.mjs → env-Cs8Wt8A_.mjs} +4 -4
- package/dist/{env-Cu5hWsuE.mjs.map → env-Cs8Wt8A_.mjs.map} +1 -1
- package/dist/{errors-BOUCRl-p.d.mts → errors-D_CWI7Bl.d.mts} +1 -1
- package/dist/{errors-BOUCRl-p.d.mts.map → errors-D_CWI7Bl.d.mts.map} +1 -1
- package/dist/execution-context-Dl2CKqSo.d.mts +57 -0
- package/dist/execution-context-Dl2CKqSo.d.mts.map +1 -0
- package/dist/http/application.d.mts +60 -6
- package/dist/http/application.d.mts.map +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +21 -32
- package/dist/http/context.d.mts.map +1 -1
- package/dist/http/context.mjs +2 -271
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.mjs +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +1 -1
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +3 -3
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +1 -1
- package/dist/http/middleware/validate.mjs +2 -2
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.d.mts +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +14 -2
- package/dist/http/router-builder.d.mts.map +1 -1
- package/dist/http/router-builder.mjs +59 -7
- package/dist/http/router-builder.mjs.map +1 -1
- package/dist/index-BQM9pJrV.d.mts +275 -0
- package/dist/index-BQM9pJrV.d.mts.map +1 -0
- package/dist/{index-DNVfGjF9.d.mts → index-Cf-MGrqT.d.mts} +2 -2
- package/dist/{index-DNVfGjF9.d.mts.map → index-Cf-MGrqT.d.mts.map} +1 -1
- package/dist/{index-Co7a3Zat.d.mts → index-RNK41JPE.d.mts} +1 -1
- package/dist/{index-Co7a3Zat.d.mts.map → index-RNK41JPE.d.mts.map} +1 -1
- package/dist/index.d.mts +38 -19
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +11 -11
- package/dist/{interfaces-DXjE8Re1.d.mts → interfaces-CwcdqfNq.d.mts} +3 -1
- package/dist/{interfaces-DXjE8Re1.d.mts.map → interfaces-CwcdqfNq.d.mts.map} +1 -1
- package/dist/{logger-CW6FHtvU.d.mts → logger-GK8yT0BD.d.mts} +1 -1
- package/dist/{logger-CW6FHtvU.d.mts.map → logger-GK8yT0BD.d.mts.map} +1 -1
- package/dist/{metadata-BwRJ69bC.mjs → metadata-BFuoSEX6.mjs} +2 -2
- package/dist/{metadata-BwRJ69bC.mjs.map → metadata-BFuoSEX6.mjs.map} +1 -1
- package/dist/{path-B4JcbwKX.d.mts → path-Bj3vZMUY.d.mts} +1 -1
- package/dist/path-Bj3vZMUY.d.mts.map +1 -0
- package/dist/{plugin-Cvacmm7N.d.mts → plugin-3rKA0Loy.d.mts} +36 -4
- package/dist/plugin-3rKA0Loy.d.mts.map +1 -0
- package/dist/{query-BQ2UT3oi.mjs → query-BcYEjYyX.mjs} +2 -2
- package/dist/{query-BQ2UT3oi.mjs.map → query-BcYEjYyX.mjs.map} +1 -1
- package/dist/{reactivity-I8nDlg4c.d.mts → reactivity-CczHu3R-.d.mts} +1 -1
- package/dist/{reactivity-I8nDlg4c.d.mts.map → reactivity-CczHu3R-.d.mts.map} +1 -1
- package/package.json +1 -1
- package/dist/adapter-DjL8ql5d.d.mts.map +0 -1
- package/dist/app-module-Cotu9TIC.d.mts.map +0 -1
- package/dist/application-BVl6L8xo.mjs.map +0 -1
- package/dist/core-qyPNtpKp.mjs +0 -121
- package/dist/core-qyPNtpKp.mjs.map +0 -1
- package/dist/http/context.mjs.map +0 -1
- package/dist/index-CwqjAF6I.d.mts +0 -112
- package/dist/index-CwqjAF6I.d.mts.map +0 -1
- package/dist/path-B4JcbwKX.d.mts.map +0 -1
- package/dist/plugin-Cvacmm7N.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"container-BBZLlK6y.mjs","names":[],"sources":["../src/core/token.ts","../src/core/container.ts"],"sourcesContent":["/**\n * Collision-safe injection tokens with phantom type parameters.\n *\n * `createToken<T>(name)` is the recommended way to declare any DI token\n * that isn't a class. Each call returns a unique frozen object — even if\n * two files write `createToken<X>('Logger')`, they produce two distinct\n * references that the container treats as different tokens. Collisions\n * become impossible by construction, not by convention.\n *\n * The phantom type parameter `T` lets `container.resolve(token)` infer\n * the correct return type without any codegen.\n *\n * ## Hardening layers\n *\n * KickJS has four DI token kinds, listed from safest to riskiest:\n *\n * 1. **Class identity** — `container.resolve(UserService)`. Reference\n * equality, never collides. Type-safe via `Constructor<T>` overload.\n * 2. **`createToken<T>(name)`** — frozen object identity, never collides.\n * Type-safe via the `InjectionToken<T>` overload.\n * 3. **Symbol** — `Symbol('foo')` is unique per call but `Symbol.for('foo')`\n * is interned and CAN collide. Discouraged.\n * 4. **Raw string `@Inject('foo')`** — high collision risk, untyped.\n * Reserved for legacy code and runtime-computed token names.\n *\n * Prefer (1) and (2). Use (4) only when you have to.\n *\n * @example\n * ```ts\n * // src/tokens.ts\n * export const DATABASE_URL = createToken<string>('config.database.url')\n * export const FEATURE_FLAGS = createToken<FeatureFlags>('app.features')\n *\n * // bootstrap\n * container.registerInstance(DATABASE_URL, process.env.DATABASE_URL!)\n *\n * // anywhere else\n * const url = container.resolve(DATABASE_URL) // typed as `string`\n * ```\n *\n * @module @forinda/kickjs/core/token\n */\n\n/**\n * Symbol marker stamped on every InjectionToken so the container can\n * detect them at runtime regardless of which package created them.\n *\n * Uses `Symbol.for()` so cross-package isolation (different copies of\n * `@forinda/kickjs` loaded under different module identities) still\n * shares the same marker.\n */\nexport const INJECTION_TOKEN: unique symbol = Symbol.for('@kickjs/InjectionToken') as never\n\n/**\n * A type-safe DI token. Each `createToken()` call returns a unique frozen\n * object identified by reference, not by the `name` string. Two\n * `createToken<X>('foo')` calls in different files produce two distinct\n * tokens that the container treats independently.\n *\n * The phantom `_type` parameter is never assigned at runtime — it exists\n * solely to thread the type through `container.resolve(token)`.\n */\nexport interface InjectionToken<T> {\n readonly [INJECTION_TOKEN]: true\n /** Descriptive name used in error messages, logs, and devtools */\n readonly name: string\n /** Phantom — never assigned at runtime */\n readonly _type?: T\n}\n\n/**\n * Create a collision-safe injection token.\n *\n * The returned token is a frozen object identified by reference, not by\n * the `name` string. The `name` is used only for error messages, logs,\n * and debugging.\n */\nexport function createToken<T>(name: string): InjectionToken<T> {\n return Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name,\n })\n}\n\n/** Type guard — returns `true` if `value` is an InjectionToken */\nexport function isInjectionToken(value: unknown): value is InjectionToken<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[INJECTION_TOKEN] === true\n )\n}\n","import 'reflect-metadata'\nimport {\n Constructor,\n Scope,\n METADATA,\n type ClassKind,\n type PostConstructStatus,\n} from './interfaces'\nimport { createLogger } from './logger'\nimport {\n getClassMeta,\n getClassMetaOrUndefined,\n getMetaMap,\n getMetaRecord,\n getMethodMetaOrUndefined,\n} from './metadata'\nimport { isInjectionToken, type InjectionToken } from './token'\n\nconst log = createLogger('Container')\n\n/** Internal registration entry that tracks how a dependency should be resolved */\ninterface Registration {\n target: Constructor\n scope: Scope\n instance?: any\n factory?: () => any\n // Observability fields\n kind: ClassKind\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n}\n\n/** Create a Registration with observability defaults */\nfunction createReg(\n fields: Partial<Registration> & Pick<Registration, 'target' | 'scope'>,\n): Registration {\n return {\n kind: 'unknown',\n resolveCount: 0,\n postConstructStatus: 'skipped',\n dependencies: [],\n ...fields,\n }\n}\n\n/** Format a token for display in error messages */\nexport function tokenName(token: any): string {\n if (typeof token === 'symbol') return token.toString()\n if (isInjectionToken(token)) return token.name\n return token?.name || String(token)\n}\n\n// ── Persistent Store ────────────────────────────────────────────────────\n// globalThis-based storage that survives BOTH Container.reset() AND Vite's\n// ssrLoadModule() re-evaluation. When Vite re-evaluates a module, the\n// Container class gets a new identity (new statics). But globalThis persists.\n//\n// This is how DB connections, Redis clients, WsAdapter instances, and any\n// other stateful bindings survive HMR without being dropped.\n//\n// Pattern from: React Router (globalThis for state), Vinxi (globalThis.app)\n\n// ── Change Event System ─────────────────────────────────────────────────\n// Batched (50ms debounce) so `kick g module` creating 10+ files emits ONE\n// notification, not 10. Any adapter can subscribe: Swagger, DevTools, WS, etc.\n\n/** A single container change event */\nexport interface ContainerChangeEvent {\n token: string\n event: 'registered' | 'resolved' | 'invalidated'\n kind?: ClassKind\n timestamp: number\n}\n\n/** Listener that receives batched change events */\nexport type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void\n\n/**\n * Type-safe registry of string DI tokens. Augmented by `kick typegen` —\n * the generated `.kickjs/types/registry.d.ts` adds entries like:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickJsRegistry {\n * UserService: import('../../src/modules/users/user.service').UserService\n * }\n * }\n * ```\n *\n * Once typegen has run, `container.resolve('UserService')` returns the\n * correct type instead of `any`. Class-token resolution\n * (`container.resolve(UserService)`) is already type-safe via the\n * `Constructor<T>` overload and does not need typegen.\n */\nexport interface KickJsRegistry {}\n\ninterface PersistentStore {\n factories: Array<{ token: any; factory: () => any; scope: Scope }>\n instances: Array<{ token: any; instance: any }>\n /** Resolved instances keyed by string name — survives class identity changes */\n resolvedInstances: Map<string, any>\n}\n\nfunction getPersistentStore(): PersistentStore {\n if (!(globalThis as any).__kickjs_persistent) {\n ;(globalThis as any).__kickjs_persistent = {\n factories: [],\n instances: [],\n resolvedInstances: new Map(),\n } satisfies PersistentStore\n }\n return (globalThis as any).__kickjs_persistent\n}\n\n/**\n * Inversion-of-Control (IoC) container that manages dependency registration,\n * resolution, and lifecycle. Implements the Singleton pattern so all parts of\n * the application share a single container instance.\n *\n * Supports constructor injection, property injection (@Autowired),\n * factory registrations, and lifecycle hooks (@PostConstruct).\n *\n * Persistent state (DB connections, Redis, etc.) is stored on globalThis so\n * it survives both Container.reset() and Vite module re-evaluation.\n */\nexport class Container {\n private static instance: Container\n private registrations = new Map<any, Registration>()\n private resolving = new Set<any>()\n\n // ── Reactive change tracking ──────────────────────────────────────\n private changeListeners = new Set<ContainerChangeListener>()\n private pendingChanges: ContainerChangeEvent[] = []\n private notifyTimer: ReturnType<typeof setTimeout> | null = null\n private static readonly DEBOUNCE_MS = 50\n\n /** Callback set by the decorators module to flush pending registrations */\n static _onReady: ((container: Container) => void) | null = null\n /** Callback invoked on reset so decorators can update their container reference */\n static _onReset: ((container: Container) => void) | null = null\n /**\n * Environment resolver for @Value decorator. Set by @forinda/kickjs-config\n * to return Zod-validated, type-coerced env values instead of raw process.env strings.\n */\n static _envResolver: ((key: string) => any) | null = null\n /**\n * Request store provider for REQUEST-scoped DI. Set by @forinda/kickjs-http\n * to return the current request's AsyncLocalStorage store.\n * Returns { instances: Map, values: Map } or null if outside a request.\n */\n static _requestStoreProvider:\n | (() => { instances: Map<any, any>; values: Map<any, any> } | null)\n | null = null\n\n static getInstance(): Container {\n if (!Container.instance) {\n Container.instance = new Container()\n }\n // Flush any decorator registrations that queued before the container existed\n if (Container._onReady) {\n Container._onReady(Container.instance)\n Container._onReady = null\n }\n return Container.instance\n }\n\n /**\n * Resets the container by replacing the singleton with a fresh instance.\n * Persistent registrations (DB, Redis, etc.) are replayed from globalThis\n * so they survive both reset() and Vite module re-evaluation.\n */\n static reset(): void {\n Container.instance = new Container()\n // Notify decorators so they update their container reference\n Container._onReset?.(Container.instance)\n // Replay persistent registrations from globalThis store\n const store = getPersistentStore()\n for (const { token, factory, scope } of store.factories) {\n if (!Container.instance.has(token)) {\n // Check if we have a previously resolved instance for this token\n const name = tokenName(token)\n const existing = store.resolvedInstances.get(name)\n Container.instance.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existing, // Reuse resolved instance if available\n resolveCount: existing ? 1 : 0,\n postConstructStatus: existing ? 'completed' : 'skipped',\n }),\n )\n }\n }\n for (const { token, instance } of store.instances) {\n if (!Container.instance.has(token)) {\n Container.instance.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n }),\n )\n }\n }\n }\n\n /**\n * Create an isolated container instance (not the global singleton).\n * Useful for concurrent tests that must not share DI state.\n *\n * @example\n * ```ts\n * const container = Container.create()\n * container.register(UserService, UserService)\n * const svc = container.resolve(UserService)\n * ```\n */\n static create(): Container {\n return new Container()\n }\n\n /** Register a class constructor under the given token */\n register(token: any, target: Constructor, scope: Scope = Scope.SINGLETON): void {\n const kind = getClassMeta<ClassKind>(METADATA.CLASS_KIND, target, 'unknown')\n const dependencies = this.extractDependencies(target)\n const reg = createReg({ target, scope, kind, dependencies })\n this.registrations.set(token, reg)\n // Store a name-based fallback so HMR class re-creation (new identity)\n // can still resolve by the original class name.\n if (typeof token === 'function' && token.name) {\n this.registrations.set(`__hmr__${token.name}`, reg)\n }\n this.emit(tokenName(token), 'registered', kind)\n }\n\n /** Register a factory function under the given token */\n registerFactory(token: any, factory: () => any, scope: Scope = Scope.SINGLETON): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n // Check if we already have a resolved instance from a previous HMR cycle.\n // Only reuse if the factory hasn't changed (same reference). When a new\n // factory is provided (e.g. swapping implementations), clear the stale\n // instance so the new factory runs on next resolve.\n const existingEntry = store.factories.find((r) => tokenName(r.token) === name)\n const factoryUnchanged = existingEntry?.factory === factory\n const existingInstance = factoryUnchanged ? store.resolvedInstances.get(name) : undefined\n\n // Clear stale resolved instance when factory changes\n if (!factoryUnchanged) {\n store.resolvedInstances.delete(name)\n }\n\n this.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existingInstance,\n resolveCount: existingInstance ? 1 : 0,\n postConstructStatus: existingInstance ? 'completed' : 'skipped',\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n const idx = store.factories.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.factories[idx] = { token, factory, scope }\n } else {\n store.factories.push({ token, factory, scope })\n }\n this.emit(name, 'registered', 'factory')\n }\n\n /** Register a pre-constructed singleton instance */\n registerInstance(token: any, instance: any): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n\n this.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n firstResolvedAt: Date.now(),\n lastResolvedAt: Date.now(),\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n store.resolvedInstances.set(name, instance)\n const idx = store.instances.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.instances[idx] = { token, instance }\n } else {\n store.instances.push({ token, instance })\n }\n this.emit(name, 'registered', 'instance')\n }\n\n /** Check if a binding exists for the given token */\n has(token: any): boolean {\n return this.registrations.has(token)\n }\n\n /** Return a snapshot of all registered tokens with their scope and instantiation status */\n getRegistrations(): Array<{\n token: string\n scope: string\n kind: ClassKind\n instantiated: boolean\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n }> {\n const entries: Array<ReturnType<Container['getRegistrations']>[number]> = []\n for (const [token, reg] of this.registrations) {\n entries.push({\n token: tokenName(token),\n scope: reg.scope,\n kind: reg.kind,\n // Singletons check cached instance; transients check resolveCount\n instantiated:\n reg.scope === Scope.SINGLETON ? reg.instance !== undefined : reg.resolveCount > 0,\n resolveCount: reg.resolveCount,\n lastResolvedAt: reg.lastResolvedAt,\n firstResolvedAt: reg.firstResolvedAt,\n resolveDurationMs: reg.resolveDurationMs,\n postConstructStatus: reg.postConstructStatus,\n dependencies: reg.dependencies,\n })\n }\n return entries\n }\n\n /**\n * Resolve a dependency by its token.\n *\n * Four overloads, in order of preference:\n * - **`InjectionToken<T>`** (from `createToken<T>(name)`) → returns `T`.\n * Collision-safe by construction; no codegen required.\n * - **Class constructor** → returns an instance of that class. Always\n * type-safe; no codegen required.\n * - **String token in `KickJsRegistry`** (populated by `kick typegen`) →\n * returns the augmented type.\n * - **Anything else** → returns `any`. Use this only for legacy code or\n * string tokens that haven't been registered with typegen yet.\n */\n resolve<T>(token: InjectionToken<T>): T\n resolve<T>(token: Constructor<T>): T\n resolve<K extends keyof KickJsRegistry & string>(token: K): KickJsRegistry[K]\n resolve<T = any>(token: any): T\n resolve<T = any>(token: any): T {\n let reg = this.registrations.get(token)\n // HMR fallback: when Vite re-evaluates a module, decorated classes get new\n // identity. Try resolving by class name if the primary token lookup fails.\n if (!reg && typeof token === 'function' && token.name) {\n reg = this.registrations.get(`__hmr__${token.name}`)\n }\n if (!reg) {\n throw new Error(`No binding found for: ${tokenName(token)}`)\n }\n\n if (reg.scope === Scope.SINGLETON && reg.instance !== undefined) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return reg.instance\n }\n\n // REQUEST scope: one instance per HTTP request, cached in AsyncLocalStorage\n if (reg.scope === Scope.REQUEST) {\n if (!Container._requestStoreProvider) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\": no request store provider configured. ` +\n `Ensure requestScopeMiddleware() is in your middleware pipeline.`,\n )\n }\n const store = Container._requestStoreProvider()\n if (!store) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\" outside an HTTP request context.`,\n )\n }\n // Check for pre-registered request values (user, tenant, etc.)\n if (store.values.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.values.get(token) as T\n }\n // Check per-request instance cache\n if (store.instances.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.instances.get(token) as T\n }\n // Create instance and cache for this request only\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n store.instances.set(token, instance)\n return instance as T\n }\n\n if (reg.factory) {\n const start = performance.now()\n const instance = reg.factory()\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n // Persist resolved factory instances so they survive module re-evaluation\n getPersistentStore().resolvedInstances.set(tokenName(token), instance)\n }\n return instance\n }\n\n if (this.resolving.has(token)) {\n const chain = [...this.resolving].map(tokenName)\n chain.push(tokenName(token))\n throw new Error(`Circular dependency detected: ${chain.join(' -> ')}`)\n }\n this.resolving.add(token)\n\n try {\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n }\n return instance\n } finally {\n this.resolving.delete(token)\n }\n }\n\n /** Lifecycle hook called during Application.setup() after module registration */\n bootstrap(): void {\n // Reserved for future use — adapters and modules register via\n // container.register(), registerFactory(), and registerInstance().\n }\n\n // ── Reactive Change API ─────────────────────────────────────────────\n\n /**\n * Subscribe to container changes. Returns an unsubscribe function.\n *\n * Changes are batched (50ms debounce) so bulk operations like\n * `kick g module` creating 10+ files emit ONE batch, not 10 events.\n *\n * Any adapter can subscribe:\n * - SwaggerAdapter: re-build spec when controllers change\n * - DevToolsAdapter: push SSE events to dashboard\n * - WsAdapter: re-discover namespaces when controllers change\n * - OtelAdapter: emit tracing spans for DI resolution\n * - Custom user adapters\n *\n * @example\n * ```ts\n * const unsub = container.onChange((changes) => {\n * for (const c of changes) {\n * console.log(`${c.event}: ${c.token} (${c.kind})`)\n * }\n * })\n * // later:\n * unsub()\n * ```\n */\n onChange(callback: ContainerChangeListener): () => void {\n this.changeListeners.add(callback)\n return () => this.changeListeners.delete(callback)\n }\n\n /**\n * Invalidate a specific registration. Clears the cached instance so the\n * next resolve() creates a fresh one. Also invalidates dependents\n * (anything that injected this token) by walking the dependency graph.\n *\n * Called by the Vite HMR plugin when a module file changes.\n * Skips persistent registrations (DB connections, etc.).\n */\n invalidate(token: any): void {\n const name = tokenName(token)\n // Try both the token itself and the HMR fallback name\n const reg = this.registrations.get(token) ?? this.registrations.get(`__hmr__${name}`)\n if (!reg) return\n\n // Don't invalidate persistent registrations (DB, Redis, etc.)\n const store = getPersistentStore()\n if (store.resolvedInstances.has(name)) return\n\n // Clear cached instance — next resolve() will re-create\n reg.instance = undefined\n reg.resolveCount = 0\n reg.postConstructStatus = 'skipped'\n this.emit(name, 'invalidated', reg.kind)\n\n // Walk dependency graph — invalidate anything that injected this token\n for (const [depToken, depReg] of this.registrations) {\n if (depReg.dependencies.includes(name)) {\n this.invalidate(depToken)\n }\n }\n }\n\n /** Batch-emit a change event (debounced, flushed after 50ms of quiet) */\n private emit(token: string, event: ContainerChangeEvent['event'], kind?: ClassKind): void {\n this.pendingChanges.push({ token, event, kind, timestamp: Date.now() })\n\n if (this.notifyTimer) clearTimeout(this.notifyTimer)\n this.notifyTimer = setTimeout(() => {\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }, Container.DEBOUNCE_MS)\n }\n\n /** Flush pending change events immediately (useful in tests) */\n flushChanges(): void {\n if (this.notifyTimer) {\n clearTimeout(this.notifyTimer)\n this.notifyTimer = null\n }\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }\n\n private createInstance(reg: Registration): any {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, reg.target, [])\n\n const args = paramTypes.map((paramType, index) => {\n // Check for @Inject token override on constructor parameter\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, reg.target)\n const token = injectTokens[index] || paramType\n // Scope validation: SINGLETON cannot inject REQUEST-scoped dependencies\n if (reg.scope === Scope.SINGLETON) {\n const depReg = this.registrations.get(token)\n if (depReg && depReg.scope === Scope.REQUEST) {\n throw new Error(\n `Cannot inject REQUEST-scoped \"${tokenName(token)}\" into SINGLETON \"${tokenName(reg.target)}\". ` +\n `Singletons outlive requests. Use TRANSIENT or REQUEST scope for the parent.`,\n )\n }\n }\n return this.resolve(token)\n })\n\n const instance = new reg.target(...args)\n\n // Property injection via @Autowired\n this.injectProperties(instance, reg.target)\n\n // @PostConstruct lifecycle hook\n const postConstruct = getClassMetaOrUndefined<string | symbol>(\n METADATA.POST_CONSTRUCT,\n reg.target.prototype,\n )\n if (postConstruct && typeof instance[postConstruct] === 'function') {\n try {\n const result = instance[postConstruct]()\n if (result && typeof result.then === 'function') {\n reg.postConstructStatus = 'pending'\n ;(result as Promise<void>)\n .then(() => {\n reg.postConstructStatus = 'completed'\n })\n .catch(() => {\n reg.postConstructStatus = 'failed'\n })\n log.warn(\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise ` +\n `but the container is synchronous. The async operation will not be awaited.`,\n )\n } else {\n reg.postConstructStatus = 'completed'\n }\n } catch (err) {\n reg.postConstructStatus = 'failed'\n log.error(\n err,\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`,\n )\n }\n }\n\n return instance\n }\n\n /** Extract dependency token names from constructor metadata */\n private extractDependencies(target: Constructor): string[] {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, target, [])\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, target)\n return paramTypes.map((type, index) => {\n const token = injectTokens[index] || type\n return tokenName(token)\n })\n }\n\n private injectProperties(instance: any, target: Constructor): void {\n // @Autowired — lazy DI property injection\n const autowiredProps = getMetaMap<string, any>(METADATA.AUTOWIRED, target.prototype)\n\n for (const [prop, token] of autowiredProps) {\n const resolvedToken =\n token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop)\n if (resolvedToken) {\n Object.defineProperty(instance, prop, {\n get: () => this.resolve(resolvedToken),\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n // @Value — lazy environment variable injection\n const valueProps = getMetaMap<string, { envKey: string; defaultValue?: any }>(\n METADATA.VALUE,\n target.prototype,\n )\n\n for (const [prop, config] of valueProps) {\n Object.defineProperty(instance, prop, {\n get() {\n // Use the registered env resolver if available (set by @forinda/kickjs-config)\n // This returns Zod-validated, type-coerced values (e.g. PORT as number)\n if (Container._envResolver) {\n const val = Container._envResolver(config.envKey)\n if (val !== undefined) return val\n }\n\n // Fallback to raw process.env for apps not using @forinda/kickjs-config\n const val = process.env[config.envKey]\n if (val !== undefined) return val\n if (config.defaultValue !== undefined) return config.defaultValue\n throw new Error(\n `@Value('${config.envKey}'): Environment variable \"${config.envKey}\" is not set and no default was provided.`,\n )\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAa,kBAAiC,OAAO,IAAI,yBAAyB;;;;;;;;AA0BlF,SAAgB,YAAe,MAAiC;AAC9D,QAAO,OAAO,OAAO;GAClB,kBAAkB;EACnB;EACD,CAAC;;;AAIJ,SAAgB,iBAAiB,OAAkD;AACjF,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,qBAAqB;;;;ACvE5D,MAAM,MAAM,aAAa,YAAY;;AAmBrC,SAAS,UACP,QACc;AACd,QAAO;EACL,MAAM;EACN,cAAc;EACd,qBAAqB;EACrB,cAAc,EAAE;EAChB,GAAG;EACJ;;;AAIH,SAAgB,UAAU,OAAoB;AAC5C,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,UAAU;AACtD,KAAI,iBAAiB,MAAM,CAAE,QAAO,MAAM;AAC1C,QAAO,OAAO,QAAQ,OAAO,MAAM;;AAsDrC,SAAS,qBAAsC;AAC7C,KAAI,CAAE,WAAmB,oBACrB,YAAmB,sBAAsB;EACzC,WAAW,EAAE;EACb,WAAW,EA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G,OAAO,cAAc,CAAC,mBACrE;;AAIL,SAAO;;;CAIT,oBAA4B,QAA+B;EACzD,MAAM,aAAa,aAA4B,SAAS,aAAa,QAAQ,EAAE,CAAC;EAChF,MAAM,eAAe,cAAmB,SAAS,QAAQ,OAAO;AAChE,SAAO,WAAW,KAAK,MAAM,UAAU;AAErC,UAAO,UADO,aAAa,UAAU,KACd;IACvB;;CAGJ,iBAAyB,UAAe,QAA2B;EAEjE,MAAM,iBAAiB,WAAwB,SAAS,WAAW,OAAO,UAAU;AAEpF,OAAK,MAAM,CAAC,MAAM,UAAU,gBAAgB;GAC1C,MAAM,gBACJ,SAAS,yBAAyB,SAAS,eAAe,OAAO,WAAW,KAAK;AACnF,OAAI,cACF,QAAO,eAAe,UAAU,MAAM;IACpC,WAAW,KAAK,QAAQ,cAAc;IACtC,YAAY;IACZ,cAAc;IACf,CAAC;;EAKN,MAAM,aAAa,WACjB,SAAS,OACT,OAAO,UACR;AAED,OAAK,MAAM,CAAC,MAAM,WAAW,WAC3B,QAAO,eAAe,UAAU,MAAM;GACpC,MAAM;AAGJ,QAAI,UAAU,cAAc;KAC1B,MAAM,MAAM,UAAU,aAAa,OAAO,OAAO;AACjD,SAAI,QAAQ,KAAA,EAAW,QAAO;;IAIhC,MAAM,MAAM,QAAQ,IAAI,OAAO;AAC/B,QAAI,QAAQ,KAAA,EAAW,QAAO;AAC9B,QAAI,OAAO,iBAAiB,KAAA,EAAW,QAAO,OAAO;AACrD,UAAM,IAAI,MACR,WAAW,OAAO,OAAO,4BAA4B,OAAO,OAAO,2CACpE;;GAEH,YAAY;GACZ,cAAc;GACf,CAAC"}
|
|
1
|
+
{"version":3,"file":"container-Dnk43k54.mjs","names":[],"sources":["../src/core/token.ts","../src/core/container.ts"],"sourcesContent":["/**\n * Collision-safe injection tokens with phantom type parameters.\n *\n * `createToken<T>(name)` is the recommended way to declare any DI token\n * that isn't a class. Each call returns a unique frozen object — even if\n * two files write `createToken<X>('Logger')`, they produce two distinct\n * references that the container treats as different tokens. Collisions\n * become impossible by construction, not by convention.\n *\n * The phantom type parameter `T` lets `container.resolve(token)` infer\n * the correct return type without any codegen.\n *\n * ## Hardening layers\n *\n * KickJS has four DI token kinds, listed from safest to riskiest:\n *\n * 1. **Class identity** — `container.resolve(UserService)`. Reference\n * equality, never collides. Type-safe via `Constructor<T>` overload.\n * 2. **`createToken<T>(name)`** — frozen object identity, never collides.\n * Type-safe via the `InjectionToken<T>` overload.\n * 3. **Symbol** — `Symbol('foo')` is unique per call but `Symbol.for('foo')`\n * is interned and CAN collide. Discouraged.\n * 4. **Raw string `@Inject('foo')`** — high collision risk, untyped.\n * Reserved for legacy code and runtime-computed token names.\n *\n * Prefer (1) and (2). Use (4) only when you have to.\n *\n * @example\n * ```ts\n * // src/tokens.ts\n * export const DATABASE_URL = createToken<string>('config.database.url')\n * export const FEATURE_FLAGS = createToken<FeatureFlags>('app.features')\n *\n * // bootstrap\n * container.registerInstance(DATABASE_URL, process.env.DATABASE_URL!)\n *\n * // anywhere else\n * const url = container.resolve(DATABASE_URL) // typed as `string`\n * ```\n *\n * @module @forinda/kickjs/core/token\n */\n\n/**\n * Symbol marker stamped on every InjectionToken so the container can\n * detect them at runtime regardless of which package created them.\n *\n * Uses `Symbol.for()` so cross-package isolation (different copies of\n * `@forinda/kickjs` loaded under different module identities) still\n * shares the same marker.\n */\nexport const INJECTION_TOKEN: unique symbol = Symbol.for('@kickjs/InjectionToken') as never\n\n/**\n * A type-safe DI token. Each `createToken()` call returns a unique frozen\n * object identified by reference, not by the `name` string. Two\n * `createToken<X>('foo')` calls in different files produce two distinct\n * tokens that the container treats independently.\n *\n * The phantom `_type` parameter is never assigned at runtime — it exists\n * solely to thread the type through `container.resolve(token)`.\n */\nexport interface InjectionToken<T> {\n readonly [INJECTION_TOKEN]: true\n /** Descriptive name used in error messages, logs, and devtools */\n readonly name: string\n /** Phantom — never assigned at runtime */\n readonly _type?: T\n}\n\n/**\n * Create a collision-safe injection token.\n *\n * The returned token is a frozen object identified by reference, not by\n * the `name` string. The `name` is used only for error messages, logs,\n * and debugging.\n */\nexport function createToken<T>(name: string): InjectionToken<T> {\n return Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name,\n })\n}\n\n/** Type guard — returns `true` if `value` is an InjectionToken */\nexport function isInjectionToken(value: unknown): value is InjectionToken<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[INJECTION_TOKEN] === true\n )\n}\n","import 'reflect-metadata'\nimport {\n Constructor,\n Scope,\n METADATA,\n type ClassKind,\n type PostConstructStatus,\n} from './interfaces'\nimport { createLogger } from './logger'\nimport {\n getClassMeta,\n getClassMetaOrUndefined,\n getMetaMap,\n getMetaRecord,\n getMethodMetaOrUndefined,\n} from './metadata'\nimport { isInjectionToken, type InjectionToken } from './token'\n\nconst log = createLogger('Container')\n\n/** Internal registration entry that tracks how a dependency should be resolved */\ninterface Registration {\n target: Constructor\n scope: Scope\n instance?: any\n factory?: () => any\n // Observability fields\n kind: ClassKind\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n}\n\n/** Create a Registration with observability defaults */\nfunction createReg(\n fields: Partial<Registration> & Pick<Registration, 'target' | 'scope'>,\n): Registration {\n return {\n kind: 'unknown',\n resolveCount: 0,\n postConstructStatus: 'skipped',\n dependencies: [],\n ...fields,\n }\n}\n\n/** Format a token for display in error messages */\nexport function tokenName(token: any): string {\n if (typeof token === 'symbol') return token.toString()\n if (isInjectionToken(token)) return token.name\n return token?.name || String(token)\n}\n\n// ── Persistent Store ────────────────────────────────────────────────────\n// globalThis-based storage that survives BOTH Container.reset() AND Vite's\n// ssrLoadModule() re-evaluation. When Vite re-evaluates a module, the\n// Container class gets a new identity (new statics). But globalThis persists.\n//\n// This is how DB connections, Redis clients, WsAdapter instances, and any\n// other stateful bindings survive HMR without being dropped.\n//\n// Pattern from: React Router (globalThis for state), Vinxi (globalThis.app)\n\n// ── Change Event System ─────────────────────────────────────────────────\n// Batched (50ms debounce) so `kick g module` creating 10+ files emits ONE\n// notification, not 10. Any adapter can subscribe: Swagger, DevTools, WS, etc.\n\n/** A single container change event */\nexport interface ContainerChangeEvent {\n token: string\n event: 'registered' | 'resolved' | 'invalidated'\n kind?: ClassKind\n timestamp: number\n}\n\n/** Listener that receives batched change events */\nexport type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void\n\n/**\n * Type-safe registry of string DI tokens. Augmented by `kick typegen` —\n * the generated `.kickjs/types/registry.d.ts` adds entries like:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickJsRegistry {\n * UserService: import('../../src/modules/users/user.service').UserService\n * }\n * }\n * ```\n *\n * Once typegen has run, `container.resolve('UserService')` returns the\n * correct type instead of `any`. Class-token resolution\n * (`container.resolve(UserService)`) is already type-safe via the\n * `Constructor<T>` overload and does not need typegen.\n */\nexport interface KickJsRegistry {}\n\ninterface PersistentStore {\n factories: Array<{ token: any; factory: () => any; scope: Scope }>\n instances: Array<{ token: any; instance: any }>\n /** Resolved instances keyed by string name — survives class identity changes */\n resolvedInstances: Map<string, any>\n}\n\nfunction getPersistentStore(): PersistentStore {\n if (!(globalThis as any).__kickjs_persistent) {\n ;(globalThis as any).__kickjs_persistent = {\n factories: [],\n instances: [],\n resolvedInstances: new Map(),\n } satisfies PersistentStore\n }\n return (globalThis as any).__kickjs_persistent\n}\n\n/**\n * Inversion-of-Control (IoC) container that manages dependency registration,\n * resolution, and lifecycle. Implements the Singleton pattern so all parts of\n * the application share a single container instance.\n *\n * Supports constructor injection, property injection (@Autowired),\n * factory registrations, and lifecycle hooks (@PostConstruct).\n *\n * Persistent state (DB connections, Redis, etc.) is stored on globalThis so\n * it survives both Container.reset() and Vite module re-evaluation.\n */\nexport class Container {\n private static instance: Container\n private registrations = new Map<any, Registration>()\n private resolving = new Set<any>()\n\n // ── Reactive change tracking ──────────────────────────────────────\n private changeListeners = new Set<ContainerChangeListener>()\n private pendingChanges: ContainerChangeEvent[] = []\n private notifyTimer: ReturnType<typeof setTimeout> | null = null\n private static readonly DEBOUNCE_MS = 50\n\n /** Callback set by the decorators module to flush pending registrations */\n static _onReady: ((container: Container) => void) | null = null\n /** Callback invoked on reset so decorators can update their container reference */\n static _onReset: ((container: Container) => void) | null = null\n /**\n * Environment resolver for @Value decorator. Set by @forinda/kickjs-config\n * to return Zod-validated, type-coerced env values instead of raw process.env strings.\n */\n static _envResolver: ((key: string) => any) | null = null\n /**\n * Request store provider for REQUEST-scoped DI. Set by @forinda/kickjs-http\n * to return the current request's AsyncLocalStorage store.\n * Returns { instances: Map, values: Map } or null if outside a request.\n */\n static _requestStoreProvider:\n | (() => { instances: Map<any, any>; values: Map<any, any> } | null)\n | null = null\n\n static getInstance(): Container {\n if (!Container.instance) {\n Container.instance = new Container()\n }\n // Flush any decorator registrations that queued before the container existed\n if (Container._onReady) {\n Container._onReady(Container.instance)\n Container._onReady = null\n }\n return Container.instance\n }\n\n /**\n * Resets the container by replacing the singleton with a fresh instance.\n * Persistent registrations (DB, Redis, etc.) are replayed from globalThis\n * so they survive both reset() and Vite module re-evaluation.\n */\n static reset(): void {\n Container.instance = new Container()\n // Notify decorators so they update their container reference\n Container._onReset?.(Container.instance)\n // Replay persistent registrations from globalThis store\n const store = getPersistentStore()\n for (const { token, factory, scope } of store.factories) {\n if (!Container.instance.has(token)) {\n // Check if we have a previously resolved instance for this token\n const name = tokenName(token)\n const existing = store.resolvedInstances.get(name)\n Container.instance.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existing, // Reuse resolved instance if available\n resolveCount: existing ? 1 : 0,\n postConstructStatus: existing ? 'completed' : 'skipped',\n }),\n )\n }\n }\n for (const { token, instance } of store.instances) {\n if (!Container.instance.has(token)) {\n Container.instance.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n }),\n )\n }\n }\n }\n\n /**\n * Create an isolated container instance (not the global singleton).\n * Useful for concurrent tests that must not share DI state.\n *\n * @example\n * ```ts\n * const container = Container.create()\n * container.register(UserService, UserService)\n * const svc = container.resolve(UserService)\n * ```\n */\n static create(): Container {\n return new Container()\n }\n\n /** Register a class constructor under the given token */\n register(token: any, target: Constructor, scope: Scope = Scope.SINGLETON): void {\n const kind = getClassMeta<ClassKind>(METADATA.CLASS_KIND, target, 'unknown')\n const dependencies = this.extractDependencies(target)\n const reg = createReg({ target, scope, kind, dependencies })\n this.registrations.set(token, reg)\n // Store a name-based fallback so HMR class re-creation (new identity)\n // can still resolve by the original class name.\n if (typeof token === 'function' && token.name) {\n this.registrations.set(`__hmr__${token.name}`, reg)\n }\n this.emit(tokenName(token), 'registered', kind)\n }\n\n /** Register a factory function under the given token */\n registerFactory(token: any, factory: () => any, scope: Scope = Scope.SINGLETON): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n // Check if we already have a resolved instance from a previous HMR cycle.\n // Only reuse if the factory hasn't changed (same reference). When a new\n // factory is provided (e.g. swapping implementations), clear the stale\n // instance so the new factory runs on next resolve.\n const existingEntry = store.factories.find((r) => tokenName(r.token) === name)\n const factoryUnchanged = existingEntry?.factory === factory\n const existingInstance = factoryUnchanged ? store.resolvedInstances.get(name) : undefined\n\n // Clear stale resolved instance when factory changes\n if (!factoryUnchanged) {\n store.resolvedInstances.delete(name)\n }\n\n this.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existingInstance,\n resolveCount: existingInstance ? 1 : 0,\n postConstructStatus: existingInstance ? 'completed' : 'skipped',\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n const idx = store.factories.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.factories[idx] = { token, factory, scope }\n } else {\n store.factories.push({ token, factory, scope })\n }\n this.emit(name, 'registered', 'factory')\n }\n\n /** Register a pre-constructed singleton instance */\n registerInstance(token: any, instance: any): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n\n this.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n firstResolvedAt: Date.now(),\n lastResolvedAt: Date.now(),\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n store.resolvedInstances.set(name, instance)\n const idx = store.instances.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.instances[idx] = { token, instance }\n } else {\n store.instances.push({ token, instance })\n }\n this.emit(name, 'registered', 'instance')\n }\n\n /** Check if a binding exists for the given token */\n has(token: any): boolean {\n return this.registrations.has(token)\n }\n\n /** Return a snapshot of all registered tokens with their scope and instantiation status */\n getRegistrations(): Array<{\n token: string\n scope: string\n kind: ClassKind\n instantiated: boolean\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n }> {\n const entries: Array<ReturnType<Container['getRegistrations']>[number]> = []\n for (const [token, reg] of this.registrations) {\n entries.push({\n token: tokenName(token),\n scope: reg.scope,\n kind: reg.kind,\n // Singletons check cached instance; transients check resolveCount\n instantiated:\n reg.scope === Scope.SINGLETON ? reg.instance !== undefined : reg.resolveCount > 0,\n resolveCount: reg.resolveCount,\n lastResolvedAt: reg.lastResolvedAt,\n firstResolvedAt: reg.firstResolvedAt,\n resolveDurationMs: reg.resolveDurationMs,\n postConstructStatus: reg.postConstructStatus,\n dependencies: reg.dependencies,\n })\n }\n return entries\n }\n\n /**\n * Resolve a dependency by its token.\n *\n * Four overloads, in order of preference:\n * - **`InjectionToken<T>`** (from `createToken<T>(name)`) → returns `T`.\n * Collision-safe by construction; no codegen required.\n * - **Class constructor** → returns an instance of that class. Always\n * type-safe; no codegen required.\n * - **String token in `KickJsRegistry`** (populated by `kick typegen`) →\n * returns the augmented type.\n * - **Anything else** → returns `any`. Use this only for legacy code or\n * string tokens that haven't been registered with typegen yet.\n */\n resolve<T>(token: InjectionToken<T>): T\n resolve<T>(token: Constructor<T>): T\n resolve<K extends keyof KickJsRegistry & string>(token: K): KickJsRegistry[K]\n resolve<T = any>(token: any): T\n resolve<T = any>(token: any): T {\n let reg = this.registrations.get(token)\n // HMR fallback: when Vite re-evaluates a module, decorated classes get new\n // identity. Try resolving by class name if the primary token lookup fails.\n if (!reg && typeof token === 'function' && token.name) {\n reg = this.registrations.get(`__hmr__${token.name}`)\n }\n if (!reg) {\n throw new Error(`No binding found for: ${tokenName(token)}`)\n }\n\n if (reg.scope === Scope.SINGLETON && reg.instance !== undefined) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return reg.instance\n }\n\n // REQUEST scope: one instance per HTTP request, cached in AsyncLocalStorage\n if (reg.scope === Scope.REQUEST) {\n if (!Container._requestStoreProvider) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\": no request store provider configured. ` +\n `Ensure requestScopeMiddleware() is in your middleware pipeline.`,\n )\n }\n const store = Container._requestStoreProvider()\n if (!store) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\" outside an HTTP request context.`,\n )\n }\n // Check for pre-registered request values (user, tenant, etc.)\n if (store.values.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.values.get(token) as T\n }\n // Check per-request instance cache\n if (store.instances.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.instances.get(token) as T\n }\n // Create instance and cache for this request only\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n store.instances.set(token, instance)\n return instance as T\n }\n\n if (reg.factory) {\n const start = performance.now()\n const instance = reg.factory()\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n // Persist resolved factory instances so they survive module re-evaluation\n getPersistentStore().resolvedInstances.set(tokenName(token), instance)\n }\n return instance\n }\n\n if (this.resolving.has(token)) {\n const chain = [...this.resolving].map(tokenName)\n chain.push(tokenName(token))\n throw new Error(`Circular dependency detected: ${chain.join(' -> ')}`)\n }\n this.resolving.add(token)\n\n try {\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n }\n return instance\n } finally {\n this.resolving.delete(token)\n }\n }\n\n /** Lifecycle hook called during Application.setup() after module registration */\n bootstrap(): void {\n // Reserved for future use — adapters and modules register via\n // container.register(), registerFactory(), and registerInstance().\n }\n\n // ── Reactive Change API ─────────────────────────────────────────────\n\n /**\n * Subscribe to container changes. Returns an unsubscribe function.\n *\n * Changes are batched (50ms debounce) so bulk operations like\n * `kick g module` creating 10+ files emit ONE batch, not 10 events.\n *\n * Any adapter can subscribe:\n * - SwaggerAdapter: re-build spec when controllers change\n * - DevToolsAdapter: push SSE events to dashboard\n * - WsAdapter: re-discover namespaces when controllers change\n * - OtelAdapter: emit tracing spans for DI resolution\n * - Custom user adapters\n *\n * @example\n * ```ts\n * const unsub = container.onChange((changes) => {\n * for (const c of changes) {\n * console.log(`${c.event}: ${c.token} (${c.kind})`)\n * }\n * })\n * // later:\n * unsub()\n * ```\n */\n onChange(callback: ContainerChangeListener): () => void {\n this.changeListeners.add(callback)\n return () => this.changeListeners.delete(callback)\n }\n\n /**\n * Invalidate a specific registration. Clears the cached instance so the\n * next resolve() creates a fresh one. Also invalidates dependents\n * (anything that injected this token) by walking the dependency graph.\n *\n * Called by the Vite HMR plugin when a module file changes.\n * Skips persistent registrations (DB connections, etc.).\n */\n invalidate(token: any): void {\n const name = tokenName(token)\n // Try both the token itself and the HMR fallback name\n const reg = this.registrations.get(token) ?? this.registrations.get(`__hmr__${name}`)\n if (!reg) return\n\n // Don't invalidate persistent registrations (DB, Redis, etc.)\n const store = getPersistentStore()\n if (store.resolvedInstances.has(name)) return\n\n // Clear cached instance — next resolve() will re-create\n reg.instance = undefined\n reg.resolveCount = 0\n reg.postConstructStatus = 'skipped'\n this.emit(name, 'invalidated', reg.kind)\n\n // Walk dependency graph — invalidate anything that injected this token\n for (const [depToken, depReg] of this.registrations) {\n if (depReg.dependencies.includes(name)) {\n this.invalidate(depToken)\n }\n }\n }\n\n /** Batch-emit a change event (debounced, flushed after 50ms of quiet) */\n private emit(token: string, event: ContainerChangeEvent['event'], kind?: ClassKind): void {\n this.pendingChanges.push({ token, event, kind, timestamp: Date.now() })\n\n if (this.notifyTimer) clearTimeout(this.notifyTimer)\n this.notifyTimer = setTimeout(() => {\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }, Container.DEBOUNCE_MS)\n }\n\n /** Flush pending change events immediately (useful in tests) */\n flushChanges(): void {\n if (this.notifyTimer) {\n clearTimeout(this.notifyTimer)\n this.notifyTimer = null\n }\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }\n\n private createInstance(reg: Registration): any {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, reg.target, [])\n\n const args = paramTypes.map((paramType, index) => {\n // Check for @Inject token override on constructor parameter\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, reg.target)\n const token = injectTokens[index] || paramType\n // Scope validation: SINGLETON cannot inject REQUEST-scoped dependencies\n if (reg.scope === Scope.SINGLETON) {\n const depReg = this.registrations.get(token)\n if (depReg && depReg.scope === Scope.REQUEST) {\n throw new Error(\n `Cannot inject REQUEST-scoped \"${tokenName(token)}\" into SINGLETON \"${tokenName(reg.target)}\". ` +\n `Singletons outlive requests. Use TRANSIENT or REQUEST scope for the parent.`,\n )\n }\n }\n return this.resolve(token)\n })\n\n const instance = new reg.target(...args)\n\n // Property injection via @Autowired\n this.injectProperties(instance, reg.target)\n\n // @PostConstruct lifecycle hook\n const postConstruct = getClassMetaOrUndefined<string | symbol>(\n METADATA.POST_CONSTRUCT,\n reg.target.prototype,\n )\n if (postConstruct && typeof instance[postConstruct] === 'function') {\n try {\n const result = instance[postConstruct]()\n if (result && typeof result.then === 'function') {\n reg.postConstructStatus = 'pending'\n ;(result as Promise<void>)\n .then(() => {\n reg.postConstructStatus = 'completed'\n })\n .catch(() => {\n reg.postConstructStatus = 'failed'\n })\n log.warn(\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise ` +\n `but the container is synchronous. The async operation will not be awaited.`,\n )\n } else {\n reg.postConstructStatus = 'completed'\n }\n } catch (err) {\n reg.postConstructStatus = 'failed'\n log.error(\n err,\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`,\n )\n }\n }\n\n return instance\n }\n\n /** Extract dependency token names from constructor metadata */\n private extractDependencies(target: Constructor): string[] {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, target, [])\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, target)\n return paramTypes.map((type, index) => {\n const token = injectTokens[index] || type\n return tokenName(token)\n })\n }\n\n private injectProperties(instance: any, target: Constructor): void {\n // @Autowired — lazy DI property injection\n const autowiredProps = getMetaMap<string, any>(METADATA.AUTOWIRED, target.prototype)\n\n for (const [prop, token] of autowiredProps) {\n const resolvedToken =\n token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop)\n if (resolvedToken) {\n Object.defineProperty(instance, prop, {\n get: () => this.resolve(resolvedToken),\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n // @Value — lazy environment variable injection\n const valueProps = getMetaMap<string, { envKey: string; defaultValue?: any }>(\n METADATA.VALUE,\n target.prototype,\n )\n\n for (const [prop, config] of valueProps) {\n Object.defineProperty(instance, prop, {\n get() {\n // Use the registered env resolver if available (set by @forinda/kickjs-config)\n // This returns Zod-validated, type-coerced values (e.g. PORT as number)\n if (Container._envResolver) {\n const val = Container._envResolver(config.envKey)\n if (val !== undefined) return val\n }\n\n // Fallback to raw process.env for apps not using @forinda/kickjs-config\n const val = process.env[config.envKey]\n if (val !== undefined) return val\n if (config.defaultValue !== undefined) return config.defaultValue\n throw new Error(\n `@Value('${config.envKey}'): Environment variable \"${config.envKey}\" is not set and no default was provided.`,\n )\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAa,kBAAiC,OAAO,IAAI,yBAAyB;;;;;;;;AA0BlF,SAAgB,YAAe,MAAiC;AAC9D,QAAO,OAAO,OAAO;GAClB,kBAAkB;EACnB;EACD,CAAC;;;AAIJ,SAAgB,iBAAiB,OAAkD;AACjF,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,qBAAqB;;;;ACvE5D,MAAM,MAAM,aAAa,YAAY;;AAmBrC,SAAS,UACP,QACc;AACd,QAAO;EACL,MAAM;EACN,cAAc;EACd,qBAAqB;EACrB,cAAc,EAAE;EAChB,GAAG;EACJ;;;AAIH,SAAgB,UAAU,OAAoB;AAC5C,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,UAAU;AACtD,KAAI,iBAAiB,MAAM,CAAE,QAAO,MAAM;AAC1C,QAAO,OAAO,QAAQ,OAAO,MAAM;;AAsDrC,SAAS,qBAAsC;AAC7C,KAAI,CAAE,WAAmB,oBACrB,YAAmB,sBAAsB;EACzC,WAAW,EAAE;EACb,WAAW,EAAE;EACb,mCAAmB,IAAI,KAAK;EAC7B;AAEH,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;CAIT,oBAA4B,QAA+B;EACzD,MAAM,aAAa,aAA4B,SAAS,aAAa,QAAQ,EAAE,CAAC;EAChF,MAAM,eAAe,cAAmB,SAAS,QAAQ,OAAO;AAChE,SAAO,WAAW,KAAK,MAAM,UAAU;AAErC,UAAO,UADO,aAAa,UAAU,KACd;IACvB;;CAGJ,iBAAyB,UAAe,QAA2B;EAEjE,MAAM,iBAAiB,WAAwB,SAAS,WAAW,OAAO,UAAU;AAEpF,OAAK,MAAM,CAAC,MAAM,UAAU,gBAAgB;GAC1C,MAAM,gBACJ,SAAS,yBAAyB,SAAS,eAAe,OAAO,WAAW,KAAK;AACnF,OAAI,cACF,QAAO,eAAe,UAAU,MAAM;IACpC,WAAW,KAAK,QAAQ,cAAc;IACtC,YAAY;IACZ,cAAc;IACf,CAAC;;EAKN,MAAM,aAAa,WACjB,SAAS,OACT,OAAO,UACR;AAED,OAAK,MAAM,CAAC,MAAM,WAAW,WAC3B,QAAO,eAAe,UAAU,MAAM;GACpC,MAAM;AAGJ,QAAI,UAAU,cAAc;KAC1B,MAAM,MAAM,UAAU,aAAa,OAAO,OAAO;AACjD,SAAI,QAAQ,KAAA,EAAW,QAAO;;IAIhC,MAAM,MAAM,QAAQ,IAAI,OAAO;AAC/B,QAAI,QAAQ,KAAA,EAAW,QAAO;AAC9B,QAAI,OAAO,iBAAiB,KAAA,EAAW,QAAO,OAAO;AACrD,UAAM,IAAI,MACR,WAAW,OAAO,OAAO,4BAA4B,OAAO,OAAO,2CACpE;;GAEH,YAAY;GACZ,cAAc;GACf,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { c as Scope, i as Constructor, r as ClassKind, s as PostConstructStatus } from "./interfaces-
|
|
2
|
+
import { c as Scope, i as Constructor, r as ClassKind, s as PostConstructStatus } from "./interfaces-CwcdqfNq.mjs";
|
|
3
3
|
//#region src/core/token.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Collision-safe injection tokens with phantom type parameters.
|
|
@@ -250,4 +250,4 @@ declare class Container {
|
|
|
250
250
|
}
|
|
251
251
|
//#endregion
|
|
252
252
|
export { tokenName as a, createToken as c, KickJsRegistry as i, isInjectionToken as l, ContainerChangeEvent as n, INJECTION_TOKEN as o, ContainerChangeListener as r, InjectionToken as s, Container as t };
|
|
253
|
-
//# sourceMappingURL=container-
|
|
253
|
+
//# sourceMappingURL=container-fIS1uLx-.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"container-
|
|
1
|
+
{"version":3,"file":"container-fIS1uLx-.d.mts","names":[],"sources":["../src/core/token.ts","../src/core/container.ts"],"mappings":";;;;;;;AAmDA;;;;;AAWA;;;;;;;;;;;AAeA;;;;;;;;;;AAQA;;;;;;;;;;;;ACnCA;;;;;AAqBA;;;AArBA,cDCa,eAAA;;;;;;;;AC4Bb;;UDjBiB,cAAA;EAAA,UACL,eAAA;ECgB0D;EAAA,SDd3D,IAAA;ECiCoB;EAAA,SD/BpB,KAAA,GAAQ,CAAA;AAAA;;AC8DnB;;;;;;iBDpDgB,WAAA,GAAA,CAAe,IAAA,WAAe,cAAA,CAAe,CAAA;;iBAQ7C,gBAAA,CAAiB,KAAA,YAAiB,KAAA,IAAS,cAAA;;;;iBCnC3C,SAAA,CAAU,KAAA;;UAqBT,oBAAA;EACf,KAAA;EACA,KAAA;EACA,IAAA,GAAO,SAAA;EACP,SAAA;AAAA;;KAIU,uBAAA,IAA2B,OAAA,EAAS,oBAAA;;;;;;;ADFhD;;;;;;;;;;AAQA;UCaiB,cAAA;;;;;;;;;;AAhDjB;;cA+Ea,SAAA;EAAA,eACI,QAAA;EAAA,QACP,aAAA;EAAA,QACA,SAAA;EAAA,QAGA,eAAA;EAAA,QACA,cAAA;EAAA,QACA,WAAA;EAAA,wBACgB,WAAA;EAjExB;EAAA,OAoEO,QAAA,IAAY,SAAA,EAAW,SAAA;EAnEvB;EAAA,OAqEA,QAAA,IAAY,SAAA,EAAW,SAAA;EApErB;;AA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QASA,gBAAA;AAAA"}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v3.2.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 { Logger } from "./core/logger.mjs";
|
|
12
|
+
import { i as parseQuery } from "./query-BcYEjYyX.mjs";
|
|
13
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
14
|
+
//#region src/http/request-store.ts
|
|
15
|
+
/** AsyncLocalStorage instance shared across the framework */
|
|
16
|
+
const requestStore = new AsyncLocalStorage();
|
|
17
|
+
/**
|
|
18
|
+
* Get the current request store. Throws if called outside a request context.
|
|
19
|
+
* Used by the Container to resolve REQUEST-scoped dependencies.
|
|
20
|
+
*/
|
|
21
|
+
function getRequestStore() {
|
|
22
|
+
const store = requestStore.getStore();
|
|
23
|
+
if (!store) throw new Error("No active request context. REQUEST-scoped services can only be resolved during an HTTP request.");
|
|
24
|
+
return store;
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/http/context.ts
|
|
28
|
+
const log = Logger.for("RequestContext");
|
|
29
|
+
/**
|
|
30
|
+
* One-time non-production warning when {@link RequestContext} falls back to
|
|
31
|
+
* `req.__ctxMeta` because no AsyncLocalStorage frame is active. This is the
|
|
32
|
+
* back-compat path for ad-hoc context construction (mostly tests). The
|
|
33
|
+
* fallback is deprecated and will be removed in the next major.
|
|
34
|
+
*/
|
|
35
|
+
let warnedAboutCtxMetaFallback = false;
|
|
36
|
+
function warnCtxMetaFallbackOnce() {
|
|
37
|
+
if (warnedAboutCtxMetaFallback) return;
|
|
38
|
+
warnedAboutCtxMetaFallback = true;
|
|
39
|
+
if (process.env.NODE_ENV === "production") return;
|
|
40
|
+
log.warn("RequestContext.metadata fell back to req.__ctxMeta because no AsyncLocalStorage frame was active. Mount requestScopeMiddleware() before constructing RequestContext to use the unified ALS-backed store. The req.__ctxMeta path is deprecated and will be removed in the next major.");
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Unified request/response abstraction passed to every controller method.
|
|
44
|
+
* Shields handlers from raw Express objects and provides convenience methods.
|
|
45
|
+
*
|
|
46
|
+
* Implements {@link ExecutionContext} so the transport-agnostic Context
|
|
47
|
+
* Contributor pipeline (#107) can run against this concrete HTTP context
|
|
48
|
+
* the same way it will run against future WS / queue / cron contexts.
|
|
49
|
+
*/
|
|
50
|
+
var RequestContext = class {
|
|
51
|
+
constructor(req, res, next) {
|
|
52
|
+
this.req = req;
|
|
53
|
+
this.res = res;
|
|
54
|
+
this.next = next;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Per-request metadata map shared across all RequestContext instances
|
|
58
|
+
* for the same request.
|
|
59
|
+
*
|
|
60
|
+
* Backed by `requestStore.getStore()?.values` (the AsyncLocalStorage
|
|
61
|
+
* map shared with the Context Contributor pipeline) when an ALS frame
|
|
62
|
+
* is active — the canonical, supported path.
|
|
63
|
+
*
|
|
64
|
+
* Falls back to a lazily-attached `req.__ctxMeta` Map for ad-hoc
|
|
65
|
+
* construction outside any frame — typically test code that builds a
|
|
66
|
+
* RequestContext directly without mounting `requestScopeMiddleware()`.
|
|
67
|
+
* That fallback path is **deprecated** and will be removed in the next
|
|
68
|
+
* major; a one-time non-production warning fires the first time it is
|
|
69
|
+
* hit so adopters can migrate to ALS-backed contexts.
|
|
70
|
+
*/
|
|
71
|
+
get metadata() {
|
|
72
|
+
const store = requestStore.getStore();
|
|
73
|
+
if (store) return store.values;
|
|
74
|
+
warnCtxMetaFallbackOnce();
|
|
75
|
+
const r = this.req;
|
|
76
|
+
if (!r.__ctxMeta) r.__ctxMeta = /* @__PURE__ */ new Map();
|
|
77
|
+
return r.__ctxMeta;
|
|
78
|
+
}
|
|
79
|
+
get body() {
|
|
80
|
+
return this.req.body;
|
|
81
|
+
}
|
|
82
|
+
get params() {
|
|
83
|
+
return this.req.params;
|
|
84
|
+
}
|
|
85
|
+
get query() {
|
|
86
|
+
return this.req.query;
|
|
87
|
+
}
|
|
88
|
+
get headers() {
|
|
89
|
+
return this.req.headers;
|
|
90
|
+
}
|
|
91
|
+
get requestId() {
|
|
92
|
+
return this.req.requestId ?? this.req.headers["x-request-id"];
|
|
93
|
+
}
|
|
94
|
+
/** Session data (requires session middleware) */
|
|
95
|
+
get session() {
|
|
96
|
+
return this.req.session;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The authenticated user set by AuthAdapter.
|
|
100
|
+
* Reads from the per-request metadata store first (`ctx.set('user', ...)`),
|
|
101
|
+
* then falls back to `req.user` (set directly by AuthAdapter middleware).
|
|
102
|
+
*
|
|
103
|
+
* Extend the `AuthUser` interface via module augmentation in `@forinda/kickjs-auth`
|
|
104
|
+
* to get full typing.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```ts
|
|
108
|
+
* @Get('/me')
|
|
109
|
+
* @Authenticated()
|
|
110
|
+
* getProfile(ctx: RequestContext) {
|
|
111
|
+
* const user = ctx.user
|
|
112
|
+
* if (!user) return ctx.notFound()
|
|
113
|
+
* return ctx.json({ user })
|
|
114
|
+
* }
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
get user() {
|
|
118
|
+
return this.metadata.get("user") ?? this.req.user;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Tenant identifier for multi-tenant apps. Reads `user.tenantId` —
|
|
122
|
+
* populated either by `AuthAdapter.testMode({ tenantId })`, a tenant
|
|
123
|
+
* resolver middleware, or manually on the strategy's `mapPayload`.
|
|
124
|
+
*
|
|
125
|
+
* Augment `AuthUser` (or `ContextMeta['user']`) to widen the return
|
|
126
|
+
* type if your user shape guarantees a non-`string | undefined` id.
|
|
127
|
+
*/
|
|
128
|
+
get tenantId() {
|
|
129
|
+
return this.user?.tenantId;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Effective role list for the current user. Prefers `user.tenantRoles`
|
|
133
|
+
* (populated by `AuthAdapterOptions.roleResolver` under a tenant) and
|
|
134
|
+
* falls back to `user.roles`. Returns an empty array when the user is
|
|
135
|
+
* absent or the shape has neither field.
|
|
136
|
+
*/
|
|
137
|
+
get roles() {
|
|
138
|
+
const u = this.user;
|
|
139
|
+
return u?.tenantRoles ?? u?.roles ?? [];
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Parse the request query string into structured filters, sort, pagination, and search.
|
|
143
|
+
* Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).
|
|
144
|
+
*
|
|
145
|
+
* Generic over the field config: when passed an inline literal (or
|
|
146
|
+
* `as const`), `filters[].field` and `sort[].field` are narrowed to
|
|
147
|
+
* the exact whitelisted field names. Pass nothing or a non-literal
|
|
148
|
+
* config and you get the loose `string` fallback.
|
|
149
|
+
*
|
|
150
|
+
* @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```ts
|
|
154
|
+
* @Get('/')
|
|
155
|
+
* async list(ctx: RequestContext) {
|
|
156
|
+
* const parsed = ctx.qs({
|
|
157
|
+
* filterable: ['status', 'priority'],
|
|
158
|
+
* sortable: ['createdAt', 'title'],
|
|
159
|
+
* } as const)
|
|
160
|
+
* parsed.filters[0].field // typed as 'status' | 'priority'
|
|
161
|
+
* parsed.sort[0].field // typed as 'createdAt' | 'title'
|
|
162
|
+
* }
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
qs(fieldConfig) {
|
|
166
|
+
return parseQuery(this.req.query, fieldConfig);
|
|
167
|
+
}
|
|
168
|
+
/** Single uploaded file (requires @FileUpload({ mode: 'single' })) */
|
|
169
|
+
get file() {
|
|
170
|
+
return this.req.file;
|
|
171
|
+
}
|
|
172
|
+
/** Array of uploaded files (requires @FileUpload({ mode: 'array' })) */
|
|
173
|
+
get files() {
|
|
174
|
+
return this.req.files;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Read a value from the per-request metadata store.
|
|
178
|
+
*
|
|
179
|
+
* When `ContextMeta` has been augmented with a matching key, the return
|
|
180
|
+
* type is inferred automatically. For ad-hoc keys, pass a generic:
|
|
181
|
+
* `ctx.get<MyType>('custom')`.
|
|
182
|
+
*/
|
|
183
|
+
get(key) {
|
|
184
|
+
return this.metadata.get(key);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Write a value to the per-request metadata store.
|
|
188
|
+
*
|
|
189
|
+
* When `ContextMeta` has been augmented with a matching key, the value
|
|
190
|
+
* type is checked at compile time.
|
|
191
|
+
*/
|
|
192
|
+
set(key, value) {
|
|
193
|
+
this.metadata.set(key, value);
|
|
194
|
+
}
|
|
195
|
+
json(data, status = 200) {
|
|
196
|
+
return this.res.status(status).json(data);
|
|
197
|
+
}
|
|
198
|
+
created(data) {
|
|
199
|
+
return this.res.status(201).json(data);
|
|
200
|
+
}
|
|
201
|
+
noContent() {
|
|
202
|
+
return this.res.status(204).end();
|
|
203
|
+
}
|
|
204
|
+
notFound(message = "Not Found") {
|
|
205
|
+
return this.res.status(404).json({ message });
|
|
206
|
+
}
|
|
207
|
+
badRequest(message) {
|
|
208
|
+
return this.res.status(400).json({ message });
|
|
209
|
+
}
|
|
210
|
+
html(content, status = 200) {
|
|
211
|
+
return this.res.status(status).type("html").send(content);
|
|
212
|
+
}
|
|
213
|
+
download(buffer, filename, contentType = "application/octet-stream") {
|
|
214
|
+
this.res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
|
215
|
+
this.res.setHeader("Content-Type", contentType);
|
|
216
|
+
return this.res.send(buffer);
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).
|
|
220
|
+
* Requires a ViewAdapter to be configured in bootstrap().
|
|
221
|
+
*
|
|
222
|
+
* @param template - Template name (without extension, relative to viewsDir)
|
|
223
|
+
* @param data - Data to pass to the template
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* ```ts
|
|
227
|
+
* ctx.render('dashboard', { user, title: 'Dashboard' })
|
|
228
|
+
* ctx.render('emails/welcome', { name: 'Alice' })
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
render(template, data = {}) {
|
|
232
|
+
return this.res.render(template, data);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Parse query params and return a standardized paginated response.
|
|
236
|
+
* Calls `ctx.qs()` internally, then wraps your data with pagination meta.
|
|
237
|
+
*
|
|
238
|
+
* @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`
|
|
239
|
+
* @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields
|
|
240
|
+
*
|
|
241
|
+
* @example
|
|
242
|
+
* ```ts
|
|
243
|
+
* @Get('/')
|
|
244
|
+
* async list(ctx: RequestContext) {
|
|
245
|
+
* return ctx.paginate(
|
|
246
|
+
* async (parsed) => {
|
|
247
|
+
* const data = await db.select().from(users)
|
|
248
|
+
* .where(query.where).limit(parsed.pagination.limit)
|
|
249
|
+
* .offset(parsed.pagination.offset).all()
|
|
250
|
+
* const total = await db.select({ count: count() }).from(users).get()
|
|
251
|
+
* return { data, total: total?.count ?? 0 }
|
|
252
|
+
* },
|
|
253
|
+
* { filterable: ['name', 'role'], sortable: ['createdAt'] },
|
|
254
|
+
* )
|
|
255
|
+
* }
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
258
|
+
async paginate(fetcher, fieldConfig) {
|
|
259
|
+
const parsed = this.qs(fieldConfig);
|
|
260
|
+
const { data, total } = await fetcher(parsed);
|
|
261
|
+
const { page, limit } = parsed.pagination;
|
|
262
|
+
const totalPages = Math.ceil(total / limit) || 1;
|
|
263
|
+
const response = {
|
|
264
|
+
data,
|
|
265
|
+
meta: {
|
|
266
|
+
page,
|
|
267
|
+
limit,
|
|
268
|
+
total,
|
|
269
|
+
totalPages,
|
|
270
|
+
hasNext: page < totalPages,
|
|
271
|
+
hasPrev: page > 1
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
return this.json(response);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Start an SSE (Server-Sent Events) stream.
|
|
278
|
+
* Sets the correct headers and returns helpers to send events.
|
|
279
|
+
*
|
|
280
|
+
* @example
|
|
281
|
+
* ```ts
|
|
282
|
+
* @Get('/events')
|
|
283
|
+
* async stream(ctx: RequestContext) {
|
|
284
|
+
* const sse = ctx.sse()
|
|
285
|
+
*
|
|
286
|
+
* const interval = setInterval(() => {
|
|
287
|
+
* sse.send({ time: new Date().toISOString() }, 'tick')
|
|
288
|
+
* }, 1000)
|
|
289
|
+
*
|
|
290
|
+
* sse.onClose(() => clearInterval(interval))
|
|
291
|
+
* }
|
|
292
|
+
* ```
|
|
293
|
+
*/
|
|
294
|
+
sse() {
|
|
295
|
+
this.res.writeHead(200, {
|
|
296
|
+
"Content-Type": "text/event-stream",
|
|
297
|
+
"Cache-Control": "no-cache",
|
|
298
|
+
Connection: "keep-alive",
|
|
299
|
+
"X-Accel-Buffering": "no"
|
|
300
|
+
});
|
|
301
|
+
this.res.flushHeaders();
|
|
302
|
+
const closeCallbacks = [];
|
|
303
|
+
this.req.on("close", () => {
|
|
304
|
+
for (const cb of closeCallbacks) cb();
|
|
305
|
+
});
|
|
306
|
+
return {
|
|
307
|
+
send: (data, event, id) => {
|
|
308
|
+
if (id) this.res.write(`id: ${id}\n`);
|
|
309
|
+
if (event) this.res.write(`event: ${event}\n`);
|
|
310
|
+
this.res.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
311
|
+
},
|
|
312
|
+
comment: (text) => {
|
|
313
|
+
this.res.write(`: ${text}\n\n`);
|
|
314
|
+
},
|
|
315
|
+
onClose: (fn) => {
|
|
316
|
+
closeCallbacks.push(fn);
|
|
317
|
+
},
|
|
318
|
+
close: () => {
|
|
319
|
+
this.res.end();
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
//#endregion
|
|
325
|
+
export { getRequestStore as n, requestStore as r, RequestContext as t };
|
|
326
|
+
|
|
327
|
+
//# sourceMappingURL=context-OktlOQBQ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-OktlOQBQ.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n */\n values: Map<string, unknown>\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n","import type { Request, Response, NextFunction } from 'express'\nimport { type ContextMeta, type ExecutionContext, type MetaValue } from '../core/execution-context'\nimport { Logger } from '../core/logger'\nimport { requestStore } from './request-store'\nimport {\n parseQuery,\n type QueryFieldConfig,\n type PaginatedResponse,\n type TypedParsedQuery,\n} from './query'\n\n/**\n * Re-export the augmentable {@link ContextMeta} registry from core/.\n * Declared in `core/execution-context.ts` so non-HTTP transports\n * (WS/queue/cron, V2) share one declaration site. Apps still augment\n * via the canonical `declare module '@forinda/kickjs'` form.\n */\nexport type { ContextMeta } from '../core/execution-context'\n\nconst log = Logger.for('RequestContext')\n\n/**\n * One-time non-production warning when {@link RequestContext} falls back to\n * `req.__ctxMeta` because no AsyncLocalStorage frame is active. This is the\n * back-compat path for ad-hoc context construction (mostly tests). The\n * fallback is deprecated and will be removed in the next major.\n */\nlet warnedAboutCtxMetaFallback = false\nfunction warnCtxMetaFallbackOnce(): void {\n if (warnedAboutCtxMetaFallback) return\n warnedAboutCtxMetaFallback = true\n if (process.env.NODE_ENV === 'production') return\n log.warn(\n 'RequestContext.metadata fell back to req.__ctxMeta because no AsyncLocalStorage frame ' +\n 'was active. Mount requestScopeMiddleware() before constructing RequestContext to use ' +\n 'the unified ALS-backed store. The req.__ctxMeta path is deprecated and will be ' +\n 'removed in the next major.',\n )\n}\n\n/**\n * The shape of a single route entry in `KickRoutes`. Generated by\n * `kick typegen` and consumed via the `Ctx<T>` helper. Each field is\n * `unknown` by default and is filled in as the typegen learns more\n * about the route (URL params from the path, body/query from validation\n * schemas, etc.).\n */\nexport interface RouteShape {\n params?: unknown\n body?: unknown\n query?: unknown\n response?: unknown\n}\n\n/**\n * Unified request/response abstraction passed to every controller method.\n * Shields handlers from raw Express objects and provides convenience methods.\n *\n * Implements {@link ExecutionContext} so the transport-agnostic Context\n * Contributor pipeline (#107) can run against this concrete HTTP context\n * the same way it will run against future WS / queue / cron contexts.\n */\nexport class RequestContext<TBody = any, TParams = any, TQuery = any> implements ExecutionContext {\n constructor(\n public readonly req: Request,\n public readonly res: Response,\n public readonly next: NextFunction,\n ) {}\n\n /**\n * Per-request metadata map shared across all RequestContext instances\n * for the same request.\n *\n * Backed by `requestStore.getStore()?.values` (the AsyncLocalStorage\n * map shared with the Context Contributor pipeline) when an ALS frame\n * is active — the canonical, supported path.\n *\n * Falls back to a lazily-attached `req.__ctxMeta` Map for ad-hoc\n * construction outside any frame — typically test code that builds a\n * RequestContext directly without mounting `requestScopeMiddleware()`.\n * That fallback path is **deprecated** and will be removed in the next\n * major; a one-time non-production warning fires the first time it is\n * hit so adopters can migrate to ALS-backed contexts.\n */\n private get metadata(): Map<string, any> {\n const store = requestStore.getStore()\n if (store) return store.values as Map<string, any>\n\n warnCtxMetaFallbackOnce()\n const r = this.req as any\n if (!r.__ctxMeta) r.__ctxMeta = new Map<string, any>()\n return r.__ctxMeta\n }\n\n // ── Request Data ────────────────────────────────────────────────────\n\n get body(): TBody {\n return this.req.body as TBody\n }\n\n get params(): TParams {\n return this.req.params as TParams\n }\n\n get query(): TQuery {\n return this.req.query as TQuery\n }\n\n get headers() {\n return this.req.headers\n }\n\n get requestId(): string | undefined {\n return (this.req as any).requestId ?? (this.req.headers['x-request-id'] as string | undefined)\n }\n\n /** Session data (requires session middleware) */\n get session(): any {\n return (this.req as any).session\n }\n\n /**\n * The authenticated user set by AuthAdapter.\n * Reads from the per-request metadata store first (`ctx.set('user', ...)`),\n * then falls back to `req.user` (set directly by AuthAdapter middleware).\n *\n * Extend the `AuthUser` interface via module augmentation in `@forinda/kickjs-auth`\n * to get full typing.\n *\n * @example\n * ```ts\n * @Get('/me')\n * @Authenticated()\n * getProfile(ctx: RequestContext) {\n * const user = ctx.user\n * if (!user) return ctx.notFound()\n * return ctx.json({ user })\n * }\n * ```\n */\n get user(): MetaValue<'user', Record<string, any>> | undefined {\n return this.metadata.get('user') ?? (this.req as any).user\n }\n\n /**\n * Tenant identifier for multi-tenant apps. Reads `user.tenantId` —\n * populated either by `AuthAdapter.testMode({ tenantId })`, a tenant\n * resolver middleware, or manually on the strategy's `mapPayload`.\n *\n * Augment `AuthUser` (or `ContextMeta['user']`) to widen the return\n * type if your user shape guarantees a non-`string | undefined` id.\n */\n get tenantId(): string | undefined {\n const u = this.user as Record<string, any> | undefined\n return u?.tenantId\n }\n\n /**\n * Effective role list for the current user. Prefers `user.tenantRoles`\n * (populated by `AuthAdapterOptions.roleResolver` under a tenant) and\n * falls back to `user.roles`. Returns an empty array when the user is\n * absent or the shape has neither field.\n */\n get roles(): string[] {\n const u = this.user as Record<string, any> | undefined\n return u?.tenantRoles ?? u?.roles ?? []\n }\n\n // ── Query String Parsing ───────────────────────────────────────────\n\n /**\n * Parse the request query string into structured filters, sort, pagination, and search.\n * Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).\n *\n * Generic over the field config: when passed an inline literal (or\n * `as const`), `filters[].field` and `sort[].field` are narrowed to\n * the exact whitelisted field names. Pass nothing or a non-literal\n * config and you get the loose `string` fallback.\n *\n * @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * } as const)\n * parsed.filters[0].field // typed as 'status' | 'priority'\n * parsed.sort[0].field // typed as 'createdAt' | 'title'\n * }\n * ```\n */\n qs<TConfig extends QueryFieldConfig | undefined = undefined>(\n fieldConfig?: TConfig,\n ): TypedParsedQuery<TConfig> {\n return parseQuery<TConfig>(this.req.query as Record<string, any>, fieldConfig)\n }\n\n // ── File Uploads ────────────────────────────────────────────────────\n\n /** Single uploaded file (requires @FileUpload({ mode: 'single' })) */\n get file(): any {\n return (this.req as any).file\n }\n\n /** Array of uploaded files (requires @FileUpload({ mode: 'array' })) */\n get files(): any[] | undefined {\n return (this.req as any).files\n }\n\n // ── Metadata Store ──────────────────────────────────────────────────\n\n /**\n * Read a value from the per-request metadata store.\n *\n * When `ContextMeta` has been augmented with a matching key, the return\n * type is inferred automatically. For ad-hoc keys, pass a generic:\n * `ctx.get<MyType>('custom')`.\n */\n get<K extends string>(key: K): MetaValue<K> | undefined {\n return this.metadata.get(key)\n }\n\n /**\n * Write a value to the per-request metadata store.\n *\n * When `ContextMeta` has been augmented with a matching key, the value\n * type is checked at compile time.\n */\n set<K extends string>(key: K, value: MetaValue<K>): void {\n this.metadata.set(key, value)\n }\n\n // ── Response Helpers ────────────────────────────────────────────────\n\n json(data: any, status = 200) {\n return this.res.status(status).json(data)\n }\n\n created(data: any) {\n return this.res.status(201).json(data)\n }\n\n noContent() {\n return this.res.status(204).end()\n }\n\n notFound(message = 'Not Found') {\n return this.res.status(404).json({ message })\n }\n\n badRequest(message: string) {\n return this.res.status(400).json({ message })\n }\n\n html(content: string, status = 200) {\n return this.res.status(status).type('html').send(content)\n }\n\n download(buffer: Buffer, filename: string, contentType = 'application/octet-stream') {\n this.res.setHeader('Content-Disposition', `attachment; filename=\"${filename}\"`)\n this.res.setHeader('Content-Type', contentType)\n return this.res.send(buffer)\n }\n\n /**\n * Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).\n * Requires a ViewAdapter to be configured in bootstrap().\n *\n * @param template - Template name (without extension, relative to viewsDir)\n * @param data - Data to pass to the template\n *\n * @example\n * ```ts\n * ctx.render('dashboard', { user, title: 'Dashboard' })\n * ctx.render('emails/welcome', { name: 'Alice' })\n * ```\n */\n render(template: string, data: Record<string, any> = {}) {\n return this.res.render(template, data)\n }\n\n /**\n * Parse query params and return a standardized paginated response.\n * Calls `ctx.qs()` internally, then wraps your data with pagination meta.\n *\n * @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`\n * @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * return ctx.paginate(\n * async (parsed) => {\n * const data = await db.select().from(users)\n * .where(query.where).limit(parsed.pagination.limit)\n * .offset(parsed.pagination.offset).all()\n * const total = await db.select({ count: count() }).from(users).get()\n * return { data, total: total?.count ?? 0 }\n * },\n * { filterable: ['name', 'role'], sortable: ['createdAt'] },\n * )\n * }\n * ```\n */\n async paginate<T, TConfig extends QueryFieldConfig | undefined = undefined>(\n fetcher: (parsed: TypedParsedQuery<TConfig>) => Promise<{ data: T[]; total: number }>,\n fieldConfig?: TConfig,\n ) {\n const parsed = this.qs<TConfig>(fieldConfig)\n const { data, total } = await fetcher(parsed)\n const { page, limit } = parsed.pagination\n const totalPages = Math.ceil(total / limit) || 1\n\n const response: PaginatedResponse<T> = {\n data,\n meta: {\n page,\n limit,\n total,\n totalPages,\n hasNext: page < totalPages,\n hasPrev: page > 1,\n },\n }\n\n return this.json(response)\n }\n\n // ── Server-Sent Events ──────────────────────────────────────────────\n\n /**\n * Start an SSE (Server-Sent Events) stream.\n * Sets the correct headers and returns helpers to send events.\n *\n * @example\n * ```ts\n * @Get('/events')\n * async stream(ctx: RequestContext) {\n * const sse = ctx.sse()\n *\n * const interval = setInterval(() => {\n * sse.send({ time: new Date().toISOString() }, 'tick')\n * }, 1000)\n *\n * sse.onClose(() => clearInterval(interval))\n * }\n * ```\n */\n sse() {\n this.res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n this.res.flushHeaders()\n\n const closeCallbacks: Array<() => void> = []\n\n this.req.on('close', () => {\n for (const cb of closeCallbacks) cb()\n })\n\n return {\n /** Send an SSE event with optional event name and id */\n send: (data: any, event?: string, id?: string) => {\n if (id) this.res.write(`id: ${id}\\n`)\n if (event) this.res.write(`event: ${event}\\n`)\n this.res.write(`data: ${JSON.stringify(data)}\\n\\n`)\n },\n /** Send a comment (keeps connection alive) */\n comment: (text: string) => {\n this.res.write(`: ${text}\\n\\n`)\n },\n /** Register a callback when the client disconnects */\n onClose: (fn: () => void) => {\n closeCallbacks.push(fn)\n },\n /** End the SSE stream */\n close: () => {\n this.res.end()\n },\n }\n }\n}\n\n/**\n * Short alias for `RequestContext` parameterised by a route shape.\n *\n * Use with `kick typegen`'s generated `KickRoutes` namespace for\n * fully-typed `ctx.params`, `ctx.body`, and `ctx.query`. Metadata\n * typing (`ctx.get()`, `ctx.set()`, `ctx.user`) comes from\n * `ContextMeta` augmentation and works on all `RequestContext` instances.\n *\n * @example\n * ```ts\n * @Get('/:id')\n * getUser(ctx: Ctx<KickRoutes.UserController['getUser']>) {\n * ctx.params.id // typed from RouteShape\n * ctx.body // typed from RouteShape\n * ctx.user // typed from ContextMeta\n * ctx.get('tenant') // typed from ContextMeta\n * }\n * ```\n */\nexport type Ctx<TRoute extends RouteShape = RouteShape> = RequestContext<\n TRoute extends { body: infer B } ? B : any,\n TRoute extends { params: infer P } ? P : any,\n TRoute extends { query: infer Q } ? Q : any\n>\n\n/**\n * Global ambient registry of typed routes, populated by `kick typegen`.\n *\n * Each interface inside `KickRoutes` corresponds to a controller class;\n * each property is one route method on that controller. The values\n * conform to `RouteShape`.\n *\n * Empty by default — declarations come from `.kickjs/types/routes.d.ts`\n * generated alongside the rest of the typegen output.\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {}\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAa,eAAe,IAAI,mBAAiC;;;;;AAMjE,SAAgB,kBAAgC;CAC9C,MAAM,QAAQ,aAAa,UAAU;AACrC,KAAI,CAAC,MACH,OAAM,IAAI,MACR,kGACD;AAEH,QAAO;;;;ACtBT,MAAM,MAAM,OAAO,IAAI,iBAAiB;;;;;;;AAQxC,IAAI,6BAA6B;AACjC,SAAS,0BAAgC;AACvC,KAAI,2BAA4B;AAChC,8BAA6B;AAC7B,KAAI,QAAQ,IAAI,aAAa,aAAc;AAC3C,KAAI,KACF,uRAID;;;;;;;;;;AAyBH,IAAa,iBAAb,MAAkG;CAChG,YACE,KACA,KACA,MACA;AAHgB,OAAA,MAAA;AACA,OAAA,MAAA;AACA,OAAA,OAAA;;;;;;;;;;;;;;;;;CAkBlB,IAAY,WAA6B;EACvC,MAAM,QAAQ,aAAa,UAAU;AACrC,MAAI,MAAO,QAAO,MAAM;AAExB,2BAAyB;EACzB,MAAM,IAAI,KAAK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