@forinda/kickjs 5.2.0 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/application-mir5CSWO.mjs +12 -0
  2. package/dist/{application-Bw87drVl.mjs.map → application-mir5CSWO.mjs.map} +1 -1
  3. package/dist/bootstrap-B7j_-dOg.mjs +12 -0
  4. package/dist/{bootstrap-CsQ7LE-W.mjs.map → bootstrap-B7j_-dOg.mjs.map} +1 -1
  5. package/dist/config/index.d.mts +1 -1
  6. package/dist/config/index.mjs +2 -4
  7. package/dist/config-Dk5RVTnD.mjs +12 -0
  8. package/dist/{config-DKRN5fqC.mjs.map → config-Dk5RVTnD.mjs.map} +1 -1
  9. package/dist/container-DArhTDQQ.mjs +12 -0
  10. package/dist/{container-C0FlgLNH.mjs.map → container-DArhTDQQ.mjs.map} +1 -1
  11. package/dist/{context-Ymvv-85x.d.mts → context-BAdAV-zO.d.mts} +48 -11
  12. package/dist/context-BAdAV-zO.d.mts.map +1 -0
  13. package/dist/context-CIoXqpAX.mjs +12 -0
  14. package/dist/context-CIoXqpAX.mjs.map +1 -0
  15. package/dist/core/adapter.mjs +2 -2
  16. package/dist/core/app-module.mjs +2 -2
  17. package/dist/core/cache.mjs +2 -103
  18. package/dist/core/cache.mjs.map +1 -1
  19. package/dist/core/container.mjs +2 -3
  20. package/dist/core/cron.mjs +2 -32
  21. package/dist/core/cron.mjs.map +1 -1
  22. package/dist/core/decorators.d.mts +2 -2
  23. package/dist/core/decorators.mjs +2 -241
  24. package/dist/core/decorators.mjs.map +1 -1
  25. package/dist/core/errors.mjs +2 -110
  26. package/dist/core/errors.mjs.map +1 -1
  27. package/dist/core/interfaces.mjs +2 -53
  28. package/dist/core/interfaces.mjs.map +1 -1
  29. package/dist/core/logger.mjs +2 -207
  30. package/dist/core/logger.mjs.map +1 -1
  31. package/dist/core/path.mjs +2 -35
  32. package/dist/core/path.mjs.map +1 -1
  33. package/dist/core/plugin.mjs +2 -2
  34. package/dist/core/reactivity.mjs +2 -179
  35. package/dist/core/reactivity.mjs.map +1 -1
  36. package/dist/core-BQZyB8Wv.mjs +12 -0
  37. package/dist/{core-K0J8AH_4.mjs.map → core-BQZyB8Wv.mjs.map} +1 -1
  38. package/dist/{decorators-CRmHuzxz.d.mts → decorators-J5mC7D-6.d.mts} +44 -4
  39. package/dist/{decorators-CRmHuzxz.d.mts.map → decorators-J5mC7D-6.d.mts.map} +1 -1
  40. package/dist/env-BL0xOTyi.mjs +12 -0
  41. package/dist/{env-CDMCT10_.mjs.map → env-BL0xOTyi.mjs.map} +1 -1
  42. package/dist/http/application.mjs +2 -3
  43. package/dist/http/bootstrap.mjs +2 -3
  44. package/dist/http/context.d.mts +2 -2
  45. package/dist/http/context.mjs +2 -3
  46. package/dist/http/middleware/cors.mjs +2 -73
  47. package/dist/http/middleware/cors.mjs.map +1 -1
  48. package/dist/http/middleware/csrf.mjs +2 -62
  49. package/dist/http/middleware/csrf.mjs.map +1 -1
  50. package/dist/http/middleware/error-handler.mjs +2 -54
  51. package/dist/http/middleware/error-handler.mjs.map +1 -1
  52. package/dist/http/middleware/helmet.mjs +2 -41
  53. package/dist/http/middleware/helmet.mjs.map +1 -1
  54. package/dist/http/middleware/rate-limit.mjs +2 -91
  55. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  56. package/dist/http/middleware/request-id.mjs +2 -25
  57. package/dist/http/middleware/request-id.mjs.map +1 -1
  58. package/dist/http/middleware/request-logger.mjs +2 -39
  59. package/dist/http/middleware/request-logger.mjs.map +1 -1
  60. package/dist/http/middleware/session.mjs +2 -167
  61. package/dist/http/middleware/session.mjs.map +1 -1
  62. package/dist/http/middleware/spa.mjs +2 -98
  63. package/dist/http/middleware/spa.mjs.map +1 -1
  64. package/dist/http/middleware/upload.d.mts +1 -1
  65. package/dist/http/middleware/upload.mjs +2 -181
  66. package/dist/http/middleware/upload.mjs.map +1 -1
  67. package/dist/http/middleware/validate.mjs +2 -68
  68. package/dist/http/middleware/validate.mjs.map +1 -1
  69. package/dist/http/middleware/views.d.mts +1 -1
  70. package/dist/http/middleware/views.mjs +2 -56
  71. package/dist/http/middleware/views.mjs.map +1 -1
  72. package/dist/http/query/index.mjs +2 -3
  73. package/dist/http/router-builder.mjs +2 -105
  74. package/dist/http/router-builder.mjs.map +1 -1
  75. package/dist/{index-DhNglXyS.d.mts → index-BbtF8kIr.d.mts} +2 -2
  76. package/dist/{index-DhNglXyS.d.mts.map → index-BbtF8kIr.d.mts.map} +1 -1
  77. package/dist/index.d.mts +6 -6
  78. package/dist/index.mjs +2 -171
  79. package/dist/index.mjs.map +1 -1
  80. package/dist/metadata-Dn6kNT82.mjs +12 -0
  81. package/dist/{metadata-DPLdmj1w.mjs.map → metadata-Dn6kNT82.mjs.map} +1 -1
  82. package/dist/query-B7n5isk_.mjs +12 -0
  83. package/dist/{query-CD0AMqxx.mjs.map → query-B7n5isk_.mjs.map} +1 -1
  84. package/dist/{upload-BM9uyR6Y.d.mts → upload-tGMrlhEB.d.mts} +2 -2
  85. package/dist/{upload-BM9uyR6Y.d.mts.map → upload-tGMrlhEB.d.mts.map} +1 -1
  86. package/dist/{views-DkNp9JJs.d.mts → views-oKRSw0Op.d.mts} +2 -2
  87. package/dist/{views-DkNp9JJs.d.mts.map → views-oKRSw0Op.d.mts.map} +1 -1
  88. package/package.json +1 -1
  89. package/dist/application-Bw87drVl.mjs +0 -574
  90. package/dist/bootstrap-CsQ7LE-W.mjs +0 -195
  91. package/dist/config-DKRN5fqC.mjs +0 -135
  92. package/dist/container-C0FlgLNH.mjs +0 -897
  93. package/dist/context-CDFiXWcV.mjs +0 -348
  94. package/dist/context-CDFiXWcV.mjs.map +0 -1
  95. package/dist/context-Ymvv-85x.d.mts.map +0 -1
  96. package/dist/core-K0J8AH_4.mjs +0 -820
  97. package/dist/env-CDMCT10_.mjs +0 -137
  98. package/dist/metadata-DPLdmj1w.mjs +0 -76
  99. package/dist/query-CD0AMqxx.mjs +0 -164
@@ -1,897 +0,0 @@
1
- /**
2
- * @forinda/kickjs v5.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 { METADATA, Scope } from "./core/interfaces.mjs";
12
- import { createLogger } from "./core/logger.mjs";
13
- import { i as getMetaRecord, n as getClassMetaOrUndefined, o as getMethodMetaOrUndefined, r as getMetaMap, t as getClassMeta } from "./metadata-DPLdmj1w.mjs";
14
- import { createRequire } from "node:module";
15
- import "reflect-metadata";
16
- import { existsSync, readFileSync, readdirSync } from "node:fs";
17
- import { isAbsolute, join, resolve, sep } from "node:path";
18
- //#region \0rolldown/runtime.js
19
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
- //#endregion
21
- //#region src/core/token.ts
22
- /**
23
- * Collision-safe injection tokens with phantom type parameters.
24
- *
25
- * `createToken<T>(name)` is the recommended way to declare any DI token
26
- * that isn't a class. Each call returns a unique frozen object — even if
27
- * two files write `createToken<X>('Logger')`, they produce two distinct
28
- * references that the container treats as different tokens. Collisions
29
- * become impossible by construction, not by convention.
30
- *
31
- * The phantom type parameter `T` lets `container.resolve(token)` infer
32
- * the correct return type without any codegen.
33
- *
34
- * ## Hardening layers
35
- *
36
- * KickJS has four DI token kinds, listed from safest to riskiest:
37
- *
38
- * 1. **Class identity** — `container.resolve(UserService)`. Reference
39
- * equality, never collides. Type-safe via `Constructor<T>` overload.
40
- * 2. **`createToken<T>(name)`** — frozen object identity, never collides.
41
- * Type-safe via the `InjectionToken<T>` overload.
42
- * 3. **Symbol** — `Symbol('foo')` is unique per call but `Symbol.for('foo')`
43
- * is interned and CAN collide. Discouraged.
44
- * 4. **Raw string `@Inject('foo')`** — high collision risk, untyped.
45
- * Reserved for legacy code and runtime-computed token names.
46
- *
47
- * Prefer (1) and (2). Use (4) only when you have to.
48
- *
49
- * @example
50
- * ```ts
51
- * // src/tokens.ts
52
- * export const DATABASE_URL = createToken<string>('config.database.url')
53
- * export const FEATURE_FLAGS = createToken<FeatureFlags>('app.features')
54
- *
55
- * // bootstrap
56
- * container.registerInstance(DATABASE_URL, process.env.DATABASE_URL!)
57
- *
58
- * // anywhere else
59
- * const url = container.resolve(DATABASE_URL) // typed as `string`
60
- * ```
61
- *
62
- * @module @forinda/kickjs/core/token
63
- */
64
- /**
65
- * Symbol marker stamped on every InjectionToken so the container can
66
- * detect them at runtime regardless of which package created them.
67
- *
68
- * Uses `Symbol.for()` so cross-package isolation (different copies of
69
- * `@forinda/kickjs` loaded under different module identities) still
70
- * shares the same marker.
71
- */
72
- const INJECTION_TOKEN = Symbol.for("@kickjs/InjectionToken");
73
- /**
74
- * Create a collision-safe injection token.
75
- *
76
- * The returned token is a frozen object identified by reference, not by
77
- * the `name` string. The `name` is used only for error messages, logs,
78
- * and debugging.
79
- */
80
- function createToken(name) {
81
- return Object.freeze({
82
- [INJECTION_TOKEN]: true,
83
- name
84
- });
85
- }
86
- /** Type guard — returns `true` if `value` is an InjectionToken */
87
- function isInjectionToken(value) {
88
- return typeof value === "object" && value !== null && value[INJECTION_TOKEN] === true;
89
- }
90
- //#endregion
91
- //#region src/core/asset-keys.ts
92
- /**
93
- * Compute final manifest keys for a namespace's discovered paths,
94
- * given the chosen strategy. Pure function — no fs / config / globals
95
- * involved.
96
- *
97
- * @param namespace assetMap key — e.g. `'mails'`, `'pages'`.
98
- * @param paths source-relative file paths (POSIX separators) discovered
99
- * under the namespace's `src` directory.
100
- * @param opts grouping options.
101
- */
102
- function groupAssetKeys(namespace, paths, opts = {}) {
103
- const strategy = opts.strategy ?? "auto";
104
- if (strategy === "with-extension") return {
105
- pairs: paths.map((rel) => ({
106
- rel,
107
- key: `${namespace}/${rel}`
108
- })),
109
- collisionGroupsResolved: 0
110
- };
111
- if (strategy === "strip") return {
112
- pairs: paths.map((rel) => ({
113
- rel,
114
- key: `${namespace}/${stripExt(rel)}`
115
- })),
116
- collisionGroupsResolved: 0
117
- };
118
- const groups = /* @__PURE__ */ new Map();
119
- for (const rel of paths) {
120
- const strippedKey = `${namespace}/${stripExt(rel)}`;
121
- const arr = groups.get(strippedKey);
122
- if (arr) arr.push(rel);
123
- else groups.set(strippedKey, [rel]);
124
- }
125
- let collisionGroupsResolved = 0;
126
- const keyByRel = /* @__PURE__ */ new Map();
127
- for (const [strippedKey, rels] of groups) if (rels.length === 1) keyByRel.set(rels[0], strippedKey);
128
- else {
129
- collisionGroupsResolved += 1;
130
- for (const rel of rels) keyByRel.set(rel, `${namespace}/${rel}`);
131
- }
132
- return {
133
- pairs: paths.map((rel) => ({
134
- rel,
135
- key: keyByRel.get(rel) ?? `${namespace}/${rel}`
136
- })),
137
- collisionGroupsResolved
138
- };
139
- }
140
- /** Strip the final extension from a path. `'mails/welcome.ejs'` → `'mails/welcome'`. */
141
- function stripExt(path) {
142
- const lastSlash = path.lastIndexOf("/");
143
- const filename = lastSlash >= 0 ? path.slice(lastSlash + 1) : path;
144
- const lastDot = filename.lastIndexOf(".");
145
- if (lastDot <= 0) return path;
146
- return (lastSlash >= 0 ? path.slice(0, lastSlash + 1) : "") + filename.slice(0, lastDot);
147
- }
148
- //#endregion
149
- //#region src/core/assets.ts
150
- /**
151
- * Asset manager runtime (assets-plan.md PR 3).
152
- *
153
- * Three accessor surfaces over one resolver engine:
154
- *
155
- * - `assets.x.y()` — Proxy ambient, autocomplete-friendly default.
156
- * - `useAssets()` — hook returning the same Proxy; mockable per-call.
157
- * - `resolveAsset(ns, k)` — string resolver for dynamic dispatch.
158
- *
159
- * Resolution path:
160
- *
161
- * 1. Load the build-time manifest (`<outDir>/.kickjs-assets.json`)
162
- * when present. Manifest existence = "we're running from a built
163
- * dist". Fast path; mapped paths returned verbatim.
164
- * 2. Otherwise (dev / test) walk the assetMap src directories from
165
- * `kick.config.{json,js,cjs}` and synthesise the same manifest
166
- * shape in memory. First call pays the walk cost; subsequent
167
- * calls hit the cache.
168
- * 3. `KICK_ASSETS_ROOT` env var overrides everything — the resolver
169
- * treats the path as the manifest directory and skips discovery.
170
- *
171
- * @module @forinda/kickjs/core/assets
172
- */
173
- const ASSET_MANIFEST_VERSION = 1;
174
- /**
175
- * DI token for the `assets` Proxy. Adopter code that wants to
176
- * receive assets via constructor injection registers via
177
- * `container.registerInstance(ASSETS, useAssets())` in `bootstrap()`
178
- * and injects with `@Inject(ASSETS)`.
179
- */
180
- const ASSETS = createToken("kick/assets/Map");
181
- var UnknownAssetError = class extends Error {
182
- namespace;
183
- key;
184
- constructor(namespace, key) {
185
- super(`Unknown asset '${namespace}/${key}'. Make sure the namespace exists in kick.config.ts assetMap and that the file is present in the source directory.`);
186
- this.name = "UnknownAssetError";
187
- this.namespace = namespace;
188
- this.key = key;
189
- }
190
- };
191
- let manifestCache = void 0;
192
- function resolveAsset(namespace, key) {
193
- const resolved = loadManifest();
194
- if (!resolved) throw new UnknownAssetError(namespace, key);
195
- const entry = resolved.manifest.entries[`${namespace}/${key}`];
196
- if (!entry) throw new UnknownAssetError(namespace, key);
197
- return isAbsolute(entry) ? entry : resolve(resolved.root, entry);
198
- }
199
- /** Reset the manifest cache. Tests use this; production code shouldn't need it. */
200
- function clearAssetCache() {
201
- manifestCache = void 0;
202
- }
203
- function loadManifest() {
204
- if (process.env.NODE_ENV !== "production") return discoverManifest();
205
- if (manifestCache !== void 0) return manifestCache;
206
- manifestCache = discoverManifest();
207
- return manifestCache;
208
- }
209
- function discoverManifest() {
210
- const envRoot = process.env.KICK_ASSETS_ROOT;
211
- if (envRoot) {
212
- const fromEnv = readBuiltManifest(envRoot);
213
- if (fromEnv) return fromEnv;
214
- }
215
- const cwd = process.cwd();
216
- const config = loadConfigSync(cwd);
217
- const configOutDir = config?.build?.outDir;
218
- if (configOutDir && !STANDARD_OUT_DIRS.includes(configOutDir)) {
219
- const found = readBuiltManifest(resolve(cwd, configOutDir));
220
- if (found) return found;
221
- }
222
- for (const candidate of STANDARD_OUT_DIRS) {
223
- const found = readBuiltManifest(join(cwd, candidate));
224
- if (found) return found;
225
- }
226
- return synthesiseDevManifest(cwd, config);
227
- }
228
- const STANDARD_OUT_DIRS = [
229
- "dist",
230
- "build",
231
- "out"
232
- ];
233
- function readBuiltManifest(dir) {
234
- const path = join(dir, ".kickjs-assets.json");
235
- if (!existsSync(path)) return null;
236
- try {
237
- const raw = readFileSync(path, "utf-8");
238
- const parsed = JSON.parse(raw);
239
- if (parsed.version !== 1) return null;
240
- if (!parsed.entries || typeof parsed.entries !== "object") return null;
241
- return {
242
- manifest: parsed,
243
- root: resolve(dir)
244
- };
245
- } catch {
246
- return null;
247
- }
248
- }
249
- function synthesiseDevManifest(cwd, preloadedConfig) {
250
- const config = preloadedConfig === void 0 ? loadConfigSync(cwd) : preloadedConfig;
251
- if (!config?.assetMap) return null;
252
- const entries = {};
253
- for (const [namespace, entry] of Object.entries(config.assetMap)) {
254
- if (!entry || typeof entry.src !== "string") continue;
255
- const srcAbs = resolve(cwd, entry.src);
256
- if (!existsSync(srcAbs)) continue;
257
- const collected = [];
258
- walkSync(srcAbs, srcAbs, (relPath, absPath) => {
259
- if (entry.glob && !matchesGlobLite(relPath, entry.glob, namespace)) return;
260
- collected.push({
261
- rel: relPath,
262
- abs: absPath
263
- });
264
- });
265
- collected.sort((a, b) => a.rel.localeCompare(b.rel));
266
- const { pairs, collisionGroupsResolved } = groupAssetKeys(namespace, collected.map((c) => c.rel), { strategy: entry.keys ?? "auto" });
267
- const absByRel = new Map(collected.map((c) => [c.rel, c.abs]));
268
- for (const { rel, key } of pairs) {
269
- const abs = absByRel.get(rel);
270
- if (abs) entries[key] = abs;
271
- }
272
- if (collisionGroupsResolved > 0 && process.env.NODE_ENV !== "production") console.log(`[kickjs/assets] '${namespace}': ${collisionGroupsResolved} basename collision(s) auto-resolved by keeping extensions (set assetMap.${namespace}.keys to 'strip' or 'with-extension' to override).`);
273
- }
274
- return {
275
- manifest: {
276
- version: 1,
277
- entries
278
- },
279
- root: cwd
280
- };
281
- }
282
- const warnedGlobs = /* @__PURE__ */ new Set();
283
- /**
284
- * Tiny glob matcher used only by dev manifest synthesis. Covers the
285
- * common assetMap glob patterns (`**\/*`, `**\/*.ext`,
286
- * `**\/*.{a,b}`). Anything exotic prints a one-time warning + falls
287
- * through to `**\/*` semantics rather than silently dropping files.
288
- *
289
- * The build pipeline (`packages/cli/src/asset-manager/build.ts`) uses
290
- * the full `glob` package; adopters who hit the dev-mode warning
291
- * should run `kick build:assets` to produce a real manifest.
292
- */
293
- function matchesGlobLite(relPath, pattern, namespace) {
294
- if (pattern === "**/*" || pattern === "**") return true;
295
- const singleExt = /^\*\*\/\*\.(\w+)$/.exec(pattern);
296
- if (singleExt) return relPath.endsWith(`.${singleExt[1]}`);
297
- const braceExt = /^\*\*\/\*\.\{([^}]+)\}$/.exec(pattern);
298
- if (braceExt) return braceExt[1].split(",").map((e) => e.trim()).some((ext) => relPath.endsWith(`.${ext}`));
299
- const tag = `${namespace}::${pattern}`;
300
- if (!warnedGlobs.has(tag)) {
301
- warnedGlobs.add(tag);
302
- console.warn(`[kickjs/assets] Dev-mode glob '${pattern}' on '${namespace}' isn't recognised by the lite matcher. Falling back to '**/*'. Run 'kick build:assets' to use the full glob engine.`);
303
- }
304
- return true;
305
- }
306
- function walkSync(root, dir, onFile) {
307
- let entries;
308
- try {
309
- entries = readdirSync(dir, { withFileTypes: true });
310
- } catch {
311
- return;
312
- }
313
- for (const entry of entries) {
314
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
315
- const full = join(dir, entry.name);
316
- if (entry.isDirectory()) walkSync(root, full, onFile);
317
- else if (entry.isFile()) onFile(full.slice(root.length + 1).split(sep).join("/"), full);
318
- }
319
- }
320
- /**
321
- * Sync `kick.config.{json,cjs,js}` loader for dev manifest
322
- * synthesis. Avoids dynamic `import()` (would force every assets
323
- * lookup to be async). TypeScript configs (`kick.config.ts`) are
324
- * skipped here — adopters who use them should run `kick build:assets`
325
- * to produce a real manifest the resolver can read.
326
- */
327
- function loadConfigSync(cwd) {
328
- const jsonPath = join(cwd, "kick.config.json");
329
- if (existsSync(jsonPath)) try {
330
- return JSON.parse(readFileSync(jsonPath, "utf-8"));
331
- } catch {
332
- return null;
333
- }
334
- for (const filename of ["kick.config.cjs", "kick.config.js"]) {
335
- const path = join(cwd, filename);
336
- if (!existsSync(path)) continue;
337
- try {
338
- const { createRequire } = __require("node:module");
339
- const mod = createRequire(join(cwd, "package.json"))(path);
340
- return mod.default ?? mod ?? null;
341
- } catch {
342
- continue;
343
- }
344
- }
345
- return null;
346
- }
347
- /**
348
- * Keys we MUST return `undefined` for: returning anything truthy
349
- * here causes Promise resolution to treat the Proxy as a thenable
350
- * and `await` it (resolving to whatever `then.call(...)` produces).
351
- * Two-element list deliberately — every other coercion-related key
352
- * goes through {@link PASSTHROUGH_KEYS} below so `String(assets)`,
353
- * template literals, and `util.inspect` keep working.
354
- */
355
- const PROMISE_DETECTION_KEYS = new Set(["then"]);
356
- /**
357
- * Keys we let fall through to the proxy target (a function-shaped
358
- * object). The default `Object.prototype` implementations of
359
- * `toString` / `valueOf` etc. are correct for these — returning
360
- * `undefined` here would break `String(assets)` and template
361
- * literals (`${assets}`) because `Symbol.toPrimitive` falling through
362
- * to a missing `toString` throws. Adopters that hit `assets.toString`
363
- * get `'function () {}'` back, which is fine — the contract is
364
- * "asset access returns paths"; everything else is incidental.
365
- */
366
- const PASSTHROUGH_KEYS = new Set([
367
- "toString",
368
- "valueOf",
369
- "constructor",
370
- "prototype",
371
- "name",
372
- "length",
373
- "asymmetricMatch",
374
- "nodeType",
375
- Symbol.toPrimitive,
376
- Symbol.toStringTag,
377
- Symbol.iterator,
378
- Symbol.asyncIterator
379
- ]);
380
- function createNamespaceProxy(parts) {
381
- const target = function() {};
382
- return new Proxy(target, {
383
- apply() {
384
- if (parts.length < 2) throw new UnknownAssetError(parts[0] ?? "", "");
385
- const [namespace, ...rest] = parts;
386
- return resolveAsset(namespace, rest.join("/"));
387
- },
388
- get(t, prop) {
389
- if (PROMISE_DETECTION_KEYS.has(prop)) return void 0;
390
- if (PASSTHROUGH_KEYS.has(prop)) return Reflect.get(t, prop);
391
- if (typeof prop === "symbol") return void 0;
392
- return createNamespaceProxy([...parts, prop]);
393
- }
394
- });
395
- }
396
- function createAssetProxy() {
397
- return new Proxy({}, { get(t, prop) {
398
- if (PROMISE_DETECTION_KEYS.has(prop)) return void 0;
399
- if (PASSTHROUGH_KEYS.has(prop)) return Reflect.get(t, prop);
400
- if (typeof prop === "symbol") return void 0;
401
- return createNamespaceProxy([prop]);
402
- } });
403
- }
404
- /**
405
- * Variant A — the ambient Proxy. Default accessor for static call
406
- * sites where the namespace + key are literals known at compile time.
407
- *
408
- * @example
409
- * ```ts
410
- * import { assets } from '@forinda/kickjs'
411
- * const path = assets.mails.welcome()
412
- * ```
413
- */
414
- const assets = createAssetProxy();
415
- /**
416
- * Variant B — the hook accessor. Returns the same Proxy as `assets`;
417
- * factory shape exists for testability + DI. Mock via
418
- * `vi.mock('@forinda/kickjs', () => ({ useAssets: () => fakeAssets }))`.
419
- *
420
- * @example
421
- * ```ts
422
- * import { useAssets } from '@forinda/kickjs'
423
- * class MailService {
424
- * private assets = useAssets()
425
- * send(name: string) {
426
- * return ejs.renderFile(this.assets.mails[name](), {})
427
- * }
428
- * }
429
- * ```
430
- */
431
- function useAssets() {
432
- return assets;
433
- }
434
- //#endregion
435
- //#region src/core/container.ts
436
- const log = createLogger("Container");
437
- /** Create a Registration with observability defaults */
438
- function createReg(fields) {
439
- return {
440
- kind: "unknown",
441
- resolveCount: 0,
442
- postConstructStatus: "skipped",
443
- dependencies: [],
444
- ...fields
445
- };
446
- }
447
- /** Format a token for display in error messages */
448
- function tokenName(token) {
449
- if (typeof token === "symbol") return token.toString();
450
- if (isInjectionToken(token)) return token.name;
451
- return token?.name || String(token);
452
- }
453
- function getPersistentStore() {
454
- if (!globalThis.__kickjs_persistent) globalThis.__kickjs_persistent = {
455
- factories: [],
456
- instances: [],
457
- resolvedInstances: /* @__PURE__ */ new Map()
458
- };
459
- return globalThis.__kickjs_persistent;
460
- }
461
- /**
462
- * Inversion-of-Control (IoC) container that manages dependency registration,
463
- * resolution, and lifecycle. Implements the Singleton pattern so all parts of
464
- * the application share a single container instance.
465
- *
466
- * Supports constructor injection, property injection (@Autowired),
467
- * factory registrations, and lifecycle hooks (@PostConstruct).
468
- *
469
- * Persistent state (DB connections, Redis, etc.) is stored on globalThis so
470
- * it survives both Container.reset() and Vite module re-evaluation.
471
- */
472
- var Container = class Container {
473
- static instance;
474
- registrations = /* @__PURE__ */ new Map();
475
- resolving = /* @__PURE__ */ new Set();
476
- changeListeners = /* @__PURE__ */ new Set();
477
- pendingChanges = [];
478
- notifyTimer = null;
479
- static DEBOUNCE_MS = 50;
480
- /** Callback set by the decorators module to flush pending registrations */
481
- static _onReady = null;
482
- /** Callback invoked on reset so decorators can update their container reference */
483
- static _onReset = null;
484
- /**
485
- * Environment resolver for @Value decorator. Set by the unified
486
- * `@forinda/kickjs` config layer to return Zod-validated, type-coerced
487
- * env values instead of raw process.env strings.
488
- */
489
- static _envResolver = null;
490
- /**
491
- * Request store provider for REQUEST-scoped DI. Set by the HTTP layer
492
- * inside `@forinda/kickjs` to return the current request's
493
- * AsyncLocalStorage store. Returns { instances: Map, values: Map } or
494
- * null if outside a request.
495
- */
496
- static _requestStoreProvider = null;
497
- static getInstance() {
498
- if (!Container.instance) Container.instance = new Container();
499
- if (Container._onReady) {
500
- Container._onReady(Container.instance);
501
- Container._onReady = null;
502
- }
503
- return Container.instance;
504
- }
505
- /**
506
- * Resets the container by replacing the singleton with a fresh instance.
507
- * Persistent registrations (DB, Redis, etc.) are replayed from globalThis
508
- * so they survive both reset() and Vite module re-evaluation.
509
- */
510
- static reset() {
511
- Container.instance = new Container();
512
- Container._onReset?.(Container.instance);
513
- const store = getPersistentStore();
514
- for (const { token, factory, scope } of store.factories) if (!Container.instance.has(token)) {
515
- const name = tokenName(token);
516
- const existing = store.resolvedInstances.get(name);
517
- Container.instance.registrations.set(token, createReg({
518
- target: Object,
519
- scope,
520
- factory,
521
- kind: "factory",
522
- instance: existing,
523
- resolveCount: existing ? 1 : 0,
524
- postConstructStatus: existing ? "completed" : "skipped"
525
- }));
526
- }
527
- for (const { token, instance } of store.instances) if (!Container.instance.has(token)) Container.instance.registrations.set(token, createReg({
528
- target: instance.constructor,
529
- scope: Scope.SINGLETON,
530
- instance,
531
- kind: "instance",
532
- postConstructStatus: "completed",
533
- resolveCount: 1
534
- }));
535
- }
536
- /**
537
- * Create an isolated container instance (not the global singleton).
538
- * Useful for concurrent tests that must not share DI state.
539
- *
540
- * @example
541
- * ```ts
542
- * const container = Container.create()
543
- * container.register(UserService, UserService)
544
- * const svc = container.resolve(UserService)
545
- * ```
546
- */
547
- static create() {
548
- return new Container();
549
- }
550
- /** Register a class constructor under the given token */
551
- register(token, target, scope = Scope.SINGLETON) {
552
- const kind = getClassMeta(METADATA.CLASS_KIND, target, "unknown");
553
- const reg = createReg({
554
- target,
555
- scope,
556
- kind,
557
- dependencies: this.extractDependencies(target)
558
- });
559
- this.registrations.set(token, reg);
560
- if (typeof token === "function" && token.name) this.registrations.set(`__hmr__${token.name}`, reg);
561
- this.emit(tokenName(token), "registered", kind);
562
- }
563
- /** Register a factory function under the given token */
564
- registerFactory(token, factory, scope = Scope.SINGLETON) {
565
- const store = getPersistentStore();
566
- const name = tokenName(token);
567
- const factoryUnchanged = store.factories.find((r) => tokenName(r.token) === name)?.factory === factory;
568
- const existingInstance = factoryUnchanged ? store.resolvedInstances.get(name) : void 0;
569
- if (!factoryUnchanged) store.resolvedInstances.delete(name);
570
- this.registrations.set(token, createReg({
571
- target: Object,
572
- scope,
573
- factory,
574
- kind: "factory",
575
- instance: existingInstance,
576
- resolveCount: existingInstance ? 1 : 0,
577
- postConstructStatus: existingInstance ? "completed" : "skipped"
578
- }));
579
- const idx = store.factories.findIndex((r) => tokenName(r.token) === name);
580
- if (idx >= 0) store.factories[idx] = {
581
- token,
582
- factory,
583
- scope
584
- };
585
- else store.factories.push({
586
- token,
587
- factory,
588
- scope
589
- });
590
- this.emit(name, "registered", "factory");
591
- }
592
- /** Register a pre-constructed singleton instance */
593
- registerInstance(token, instance) {
594
- const store = getPersistentStore();
595
- const name = tokenName(token);
596
- this.registrations.set(token, createReg({
597
- target: instance.constructor,
598
- scope: Scope.SINGLETON,
599
- instance,
600
- kind: "instance",
601
- postConstructStatus: "completed",
602
- resolveCount: 1,
603
- firstResolvedAt: Date.now(),
604
- lastResolvedAt: Date.now()
605
- }));
606
- store.resolvedInstances.set(name, instance);
607
- const idx = store.instances.findIndex((r) => tokenName(r.token) === name);
608
- if (idx >= 0) store.instances[idx] = {
609
- token,
610
- instance
611
- };
612
- else store.instances.push({
613
- token,
614
- instance
615
- });
616
- this.emit(name, "registered", "instance");
617
- }
618
- /** Check if a binding exists for the given token */
619
- has(token) {
620
- return this.registrations.has(token);
621
- }
622
- /** Return a snapshot of all registered tokens with their scope and instantiation status */
623
- getRegistrations() {
624
- const entries = [];
625
- for (const [token, reg] of this.registrations) entries.push({
626
- token: tokenName(token),
627
- scope: reg.scope,
628
- kind: reg.kind,
629
- instantiated: reg.scope === Scope.SINGLETON ? reg.instance !== void 0 : reg.resolveCount > 0,
630
- resolveCount: reg.resolveCount,
631
- lastResolvedAt: reg.lastResolvedAt,
632
- firstResolvedAt: reg.firstResolvedAt,
633
- resolveDurationMs: reg.resolveDurationMs,
634
- postConstructStatus: reg.postConstructStatus,
635
- dependencies: reg.dependencies
636
- });
637
- return entries;
638
- }
639
- resolve(token) {
640
- let reg = this.registrations.get(token);
641
- if (!reg && typeof token === "function" && token.name) reg = this.registrations.get(`__hmr__${token.name}`);
642
- if (!reg) throw new Error(`No binding found for: ${tokenName(token)}`);
643
- if (reg.scope === Scope.SINGLETON && reg.instance !== void 0) {
644
- reg.resolveCount++;
645
- reg.lastResolvedAt = Date.now();
646
- this.emit(tokenName(token), "resolved", reg.kind);
647
- return reg.instance;
648
- }
649
- if (reg.scope === Scope.REQUEST) {
650
- if (!Container._requestStoreProvider) throw new Error(`Cannot resolve REQUEST-scoped "${tokenName(token)}": no request store provider configured. Ensure requestScopeMiddleware() is in your middleware pipeline.`);
651
- const store = Container._requestStoreProvider();
652
- if (!store) throw new Error(`Cannot resolve REQUEST-scoped "${tokenName(token)}" outside an HTTP request context.`);
653
- if (store.values.has(token)) {
654
- reg.resolveCount++;
655
- reg.lastResolvedAt = Date.now();
656
- this.emit(tokenName(token), "resolved", reg.kind);
657
- return store.values.get(token);
658
- }
659
- if (store.instances.has(token)) {
660
- reg.resolveCount++;
661
- reg.lastResolvedAt = Date.now();
662
- this.emit(tokenName(token), "resolved", reg.kind);
663
- return store.instances.get(token);
664
- }
665
- if (reg.factory) {
666
- const start = performance.now();
667
- const instance = reg.factory();
668
- reg.resolveDurationMs = performance.now() - start;
669
- reg.resolveCount++;
670
- reg.lastResolvedAt = Date.now();
671
- if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now();
672
- store.instances.set(token, instance);
673
- this.emit(tokenName(token), "resolved", reg.kind);
674
- return instance;
675
- }
676
- const start = performance.now();
677
- const instance = this.createInstance(reg);
678
- reg.resolveDurationMs = performance.now() - start;
679
- reg.resolveCount++;
680
- reg.lastResolvedAt = Date.now();
681
- if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now();
682
- store.instances.set(token, instance);
683
- this.emit(tokenName(token), "resolved", reg.kind);
684
- return instance;
685
- }
686
- if (reg.factory) {
687
- const start = performance.now();
688
- const instance = reg.factory();
689
- reg.resolveDurationMs = performance.now() - start;
690
- reg.resolveCount++;
691
- reg.lastResolvedAt = Date.now();
692
- if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now();
693
- if (reg.scope === Scope.SINGLETON) {
694
- reg.instance = instance;
695
- getPersistentStore().resolvedInstances.set(tokenName(token), instance);
696
- }
697
- this.emit(tokenName(token), "resolved", reg.kind);
698
- return instance;
699
- }
700
- if (this.resolving.has(token)) {
701
- const chain = [...this.resolving].map(tokenName);
702
- chain.push(tokenName(token));
703
- throw new Error(`Circular dependency detected: ${chain.join(" -> ")}`);
704
- }
705
- this.resolving.add(token);
706
- try {
707
- const start = performance.now();
708
- const instance = this.createInstance(reg);
709
- reg.resolveDurationMs = performance.now() - start;
710
- reg.resolveCount++;
711
- reg.lastResolvedAt = Date.now();
712
- if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now();
713
- if (reg.scope === Scope.SINGLETON) reg.instance = instance;
714
- this.emit(tokenName(token), "resolved", reg.kind);
715
- return instance;
716
- } finally {
717
- this.resolving.delete(token);
718
- }
719
- }
720
- /** Lifecycle hook called during Application.setup() after module registration */
721
- bootstrap() {}
722
- /**
723
- * Subscribe to container changes. Returns an unsubscribe function.
724
- *
725
- * Changes are batched (50ms debounce) so bulk operations like
726
- * `kick g module` creating 10+ files emit ONE batch, not 10 events.
727
- *
728
- * Any adapter can subscribe:
729
- * - SwaggerAdapter: re-build spec when controllers change
730
- * - DevToolsAdapter: push SSE events to dashboard
731
- * - WsAdapter: re-discover namespaces when controllers change
732
- * - OtelAdapter: emit tracing spans for DI resolution
733
- * - Custom user adapters
734
- *
735
- * @example
736
- * ```ts
737
- * const unsub = container.onChange((changes) => {
738
- * for (const c of changes) {
739
- * console.log(`${c.event}: ${c.token} (${c.kind})`)
740
- * }
741
- * })
742
- * // later:
743
- * unsub()
744
- * ```
745
- */
746
- onChange(callback) {
747
- this.changeListeners.add(callback);
748
- return () => this.changeListeners.delete(callback);
749
- }
750
- /**
751
- * Invalidate a specific registration. Clears the cached instance so the
752
- * next resolve() creates a fresh one. Also invalidates dependents
753
- * (anything that injected this token) by walking the dependency graph.
754
- *
755
- * Called by the Vite HMR plugin when a module file changes.
756
- * Skips persistent registrations (DB connections, etc.).
757
- */
758
- invalidate(token) {
759
- const name = tokenName(token);
760
- const reg = this.registrations.get(token) ?? this.registrations.get(`__hmr__${name}`);
761
- if (!reg) return;
762
- if (getPersistentStore().resolvedInstances.has(name)) return;
763
- reg.instance = void 0;
764
- reg.resolveCount = 0;
765
- reg.postConstructStatus = "skipped";
766
- this.emit(name, "invalidated", reg.kind);
767
- for (const [depToken, depReg] of this.registrations) if (depReg.dependencies.includes(name)) this.invalidate(depToken);
768
- }
769
- /** Batch-emit a change event (debounced, flushed after 50ms of quiet) */
770
- emit(token, event, kind) {
771
- const existing = this.pendingChanges.find((p) => p.token === token && p.event === event);
772
- if (existing) existing.timestamp = Date.now();
773
- else this.pendingChanges.push({
774
- token,
775
- event,
776
- kind,
777
- timestamp: Date.now()
778
- });
779
- if (this.notifyTimer) clearTimeout(this.notifyTimer);
780
- this.notifyTimer = setTimeout(() => {
781
- const batch = this.pendingChanges.splice(0);
782
- if (batch.length === 0) return;
783
- for (const listener of this.changeListeners) try {
784
- listener(batch);
785
- } catch {}
786
- }, Container.DEBOUNCE_MS);
787
- }
788
- /** Flush pending change events immediately (useful in tests) */
789
- flushChanges() {
790
- if (this.notifyTimer) {
791
- clearTimeout(this.notifyTimer);
792
- this.notifyTimer = null;
793
- }
794
- const batch = this.pendingChanges.splice(0);
795
- if (batch.length === 0) return;
796
- for (const listener of this.changeListeners) try {
797
- listener(batch);
798
- } catch {}
799
- }
800
- createInstance(reg) {
801
- const args = getClassMeta(METADATA.PARAM_TYPES, reg.target, []).map((paramType, index) => {
802
- const token = getMetaRecord(METADATA.INJECT, reg.target)[index] || paramType;
803
- if (reg.scope === Scope.SINGLETON) {
804
- const depReg = this.registrations.get(token);
805
- if (depReg && depReg.scope === Scope.REQUEST) throw new Error(`Cannot inject REQUEST-scoped "${tokenName(token)}" into SINGLETON "${tokenName(reg.target)}". Singletons outlive requests. Use TRANSIENT or REQUEST scope for the parent.`);
806
- }
807
- return this.resolve(token);
808
- });
809
- const instance = new reg.target(...args);
810
- this.injectProperties(instance, reg.target);
811
- const postConstruct = getClassMetaOrUndefined(METADATA.POST_CONSTRUCT, reg.target.prototype);
812
- if (postConstruct && typeof instance[postConstruct] === "function") try {
813
- const result = instance[postConstruct]();
814
- if (result && typeof result.then === "function") {
815
- reg.postConstructStatus = "pending";
816
- result.then(() => {
817
- reg.postConstructStatus = "completed";
818
- }).catch(() => {
819
- reg.postConstructStatus = "failed";
820
- });
821
- log.warn(`@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise but the container is synchronous. The async operation will not be awaited.`);
822
- } else reg.postConstructStatus = "completed";
823
- } catch (err) {
824
- reg.postConstructStatus = "failed";
825
- log.error(err, `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`);
826
- }
827
- return instance;
828
- }
829
- /**
830
- * Extract every dependency token name a class declares — both
831
- * constructor params (`@Inject` + emitted `design:paramtypes`) and
832
- * `@Autowired` properties (read lazily at injection time, but
833
- * captured here so devtools surfaces a complete dependency graph).
834
- *
835
- * Without the property branch, classes that rely entirely on
836
- * `@Autowired` show `dependencies: []` in the introspection panel
837
- * even though they have real DI deps — see /_debug topology.
838
- */
839
- extractDependencies(target) {
840
- const paramTypes = getClassMeta(METADATA.PARAM_TYPES, target, []);
841
- const injectTokens = getMetaRecord(METADATA.INJECT, target);
842
- const ctorDeps = paramTypes.map((type, index) => {
843
- return tokenName(injectTokens[index] || type);
844
- });
845
- const autowiredProps = getMetaMap(METADATA.AUTOWIRED, target.prototype);
846
- const propDeps = [];
847
- for (const [prop, token] of autowiredProps) {
848
- const resolvedToken = token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop);
849
- if (resolvedToken) propDeps.push(tokenName(resolvedToken));
850
- }
851
- return [...new Set([...ctorDeps, ...propDeps])];
852
- }
853
- injectProperties(instance, target) {
854
- const autowiredProps = getMetaMap(METADATA.AUTOWIRED, target.prototype);
855
- for (const [prop, token] of autowiredProps) {
856
- const resolvedToken = token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop);
857
- if (resolvedToken) Object.defineProperty(instance, prop, {
858
- get: () => this.resolve(resolvedToken),
859
- enumerable: true,
860
- configurable: true
861
- });
862
- }
863
- const valueProps = getMetaMap(METADATA.VALUE, target.prototype);
864
- for (const [prop, config] of valueProps) Object.defineProperty(instance, prop, {
865
- get() {
866
- if (Container._envResolver) {
867
- const val = Container._envResolver(config.envKey);
868
- if (val !== void 0) return val;
869
- }
870
- const val = process.env[config.envKey];
871
- if (val !== void 0) return val;
872
- if (config.defaultValue !== void 0) return config.defaultValue;
873
- throw new Error(`@Value('${config.envKey}'): Environment variable "${config.envKey}" is not set and no default was provided.`);
874
- },
875
- enumerable: true,
876
- configurable: true
877
- });
878
- const assetProps = getMetaMap(METADATA.ASSET, target.prototype);
879
- if (assetProps.size > 0) for (const [prop, config] of assetProps) {
880
- const slashIdx = config.assetKey.indexOf("/");
881
- if (slashIdx === -1) throw new Error(`@Asset('${config.assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`);
882
- const namespace = config.assetKey.slice(0, slashIdx);
883
- const key = config.assetKey.slice(slashIdx + 1);
884
- Object.defineProperty(instance, prop, {
885
- get() {
886
- return resolveAsset(namespace, key);
887
- },
888
- enumerable: true,
889
- configurable: true
890
- });
891
- }
892
- }
893
- };
894
- //#endregion
895
- export { UnknownAssetError as a, resolveAsset as c, stripExt as d, INJECTION_TOKEN as f, __require as h, ASSET_MANIFEST_VERSION as i, useAssets as l, isInjectionToken as m, tokenName as n, assets as o, createToken as p, ASSETS as r, clearAssetCache as s, Container as t, groupAssetKeys as u };
896
-
897
- //# sourceMappingURL=container-C0FlgLNH.mjs.map