@navios/di 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/README.md +196 -219
  3. package/docs/README.md +69 -11
  4. package/docs/api-reference.md +281 -117
  5. package/docs/container.md +220 -56
  6. package/docs/examples/request-scope-example.mts +2 -2
  7. package/docs/factory.md +3 -8
  8. package/docs/getting-started.md +37 -8
  9. package/docs/migration.md +318 -37
  10. package/docs/request-contexts.md +263 -175
  11. package/docs/scopes.md +79 -42
  12. package/lib/browser/index.d.mts +1577 -0
  13. package/lib/browser/index.d.mts.map +1 -0
  14. package/lib/browser/index.mjs +3013 -0
  15. package/lib/browser/index.mjs.map +1 -0
  16. package/lib/index-7jfWsiG4.d.mts +1211 -0
  17. package/lib/index-7jfWsiG4.d.mts.map +1 -0
  18. package/lib/index-DW3K5sOX.d.cts +1206 -0
  19. package/lib/index-DW3K5sOX.d.cts.map +1 -0
  20. package/lib/index.cjs +389 -0
  21. package/lib/index.cjs.map +1 -0
  22. package/lib/index.d.cts +376 -0
  23. package/lib/index.d.cts.map +1 -0
  24. package/lib/index.d.mts +371 -78
  25. package/lib/index.d.mts.map +1 -0
  26. package/lib/index.mjs +325 -63
  27. package/lib/index.mjs.map +1 -1
  28. package/lib/testing/index.cjs +9 -0
  29. package/lib/testing/index.d.cts +2 -0
  30. package/lib/testing/index.d.mts +2 -2
  31. package/lib/testing/index.mjs +2 -72
  32. package/lib/testing-BG_fa9TJ.mjs +2656 -0
  33. package/lib/testing-BG_fa9TJ.mjs.map +1 -0
  34. package/lib/testing-DIaIRiJz.cjs +2896 -0
  35. package/lib/testing-DIaIRiJz.cjs.map +1 -0
  36. package/package.json +29 -7
  37. package/project.json +2 -2
  38. package/src/__tests__/async-local-storage.browser.spec.mts +240 -0
  39. package/src/__tests__/async-local-storage.spec.mts +333 -0
  40. package/src/__tests__/container.spec.mts +30 -25
  41. package/src/__tests__/e2e.browser.spec.mts +790 -0
  42. package/src/__tests__/e2e.spec.mts +1222 -0
  43. package/src/__tests__/factory.spec.mts +1 -1
  44. package/src/__tests__/get-injectors.spec.mts +1 -1
  45. package/src/__tests__/injectable.spec.mts +1 -1
  46. package/src/__tests__/injection-token.spec.mts +1 -1
  47. package/src/__tests__/library-findings.spec.mts +563 -0
  48. package/src/__tests__/registry.spec.mts +2 -2
  49. package/src/__tests__/request-scope.spec.mts +266 -274
  50. package/src/__tests__/service-instantiator.spec.mts +18 -17
  51. package/src/__tests__/service-locator-event-bus.spec.mts +9 -9
  52. package/src/__tests__/service-locator-manager.spec.mts +15 -15
  53. package/src/__tests__/service-locator.spec.mts +167 -244
  54. package/src/__tests__/unified-api.spec.mts +27 -27
  55. package/src/__type-tests__/factory.spec-d.mts +2 -2
  56. package/src/__type-tests__/inject.spec-d.mts +2 -2
  57. package/src/__type-tests__/injectable.spec-d.mts +1 -1
  58. package/src/browser.mts +16 -0
  59. package/src/container/container.mts +319 -0
  60. package/src/container/index.mts +2 -0
  61. package/src/container/scoped-container.mts +350 -0
  62. package/src/decorators/factory.decorator.mts +4 -4
  63. package/src/decorators/injectable.decorator.mts +5 -5
  64. package/src/errors/di-error.mts +12 -5
  65. package/src/errors/index.mts +0 -8
  66. package/src/index.mts +156 -15
  67. package/src/interfaces/container.interface.mts +82 -0
  68. package/src/interfaces/factory.interface.mts +2 -2
  69. package/src/interfaces/index.mts +1 -0
  70. package/src/internal/context/async-local-storage.mts +120 -0
  71. package/src/internal/context/factory-context.mts +18 -0
  72. package/src/internal/context/index.mts +3 -0
  73. package/src/{request-context-holder.mts → internal/context/request-context.mts} +40 -27
  74. package/src/internal/context/resolution-context.mts +63 -0
  75. package/src/internal/context/sync-local-storage.mts +51 -0
  76. package/src/internal/core/index.mts +5 -0
  77. package/src/internal/core/instance-resolver.mts +641 -0
  78. package/src/{service-instantiator.mts → internal/core/instantiator.mts} +31 -27
  79. package/src/internal/core/invalidator.mts +437 -0
  80. package/src/internal/core/service-locator.mts +202 -0
  81. package/src/{token-processor.mts → internal/core/token-processor.mts} +79 -60
  82. package/src/{base-instance-holder-manager.mts → internal/holder/base-holder-manager.mts} +91 -21
  83. package/src/internal/holder/holder-manager.mts +85 -0
  84. package/src/internal/holder/holder-storage.interface.mts +116 -0
  85. package/src/internal/holder/index.mts +6 -0
  86. package/src/internal/holder/instance-holder.mts +109 -0
  87. package/src/internal/holder/request-storage.mts +134 -0
  88. package/src/internal/holder/singleton-storage.mts +105 -0
  89. package/src/internal/index.mts +4 -0
  90. package/src/internal/lifecycle/circular-detector.mts +77 -0
  91. package/src/internal/lifecycle/index.mts +2 -0
  92. package/src/{service-locator-event-bus.mts → internal/lifecycle/lifecycle-event-bus.mts} +11 -4
  93. package/src/testing/__tests__/test-container.spec.mts +2 -2
  94. package/src/testing/test-container.mts +4 -4
  95. package/src/token/index.mts +2 -0
  96. package/src/{injection-token.mts → token/injection-token.mts} +1 -1
  97. package/src/{registry.mts → token/registry.mts} +1 -1
  98. package/src/utils/get-injectable-token.mts +1 -1
  99. package/src/utils/get-injectors.mts +32 -15
  100. package/src/utils/types.mts +1 -1
  101. package/tsdown.config.mts +67 -0
  102. package/lib/_tsup-dts-rollup.d.mts +0 -1283
  103. package/lib/_tsup-dts-rollup.d.ts +0 -1283
  104. package/lib/chunk-2M576LCC.mjs +0 -2043
  105. package/lib/chunk-2M576LCC.mjs.map +0 -1
  106. package/lib/index.d.ts +0 -78
  107. package/lib/index.js +0 -2127
  108. package/lib/index.js.map +0 -1
  109. package/lib/testing/index.d.ts +0 -2
  110. package/lib/testing/index.js +0 -2060
  111. package/lib/testing/index.js.map +0 -1
  112. package/lib/testing/index.mjs.map +0 -1
  113. package/src/container.mts +0 -227
  114. package/src/factory-context.mts +0 -8
  115. package/src/instance-resolver.mts +0 -559
  116. package/src/request-context-manager.mts +0 -149
  117. package/src/service-invalidator.mts +0 -429
  118. package/src/service-locator-instance-holder.mts +0 -70
  119. package/src/service-locator-manager.mts +0 -85
  120. package/src/service-locator.mts +0 -246
  121. package/tsup.config.mts +0 -12
  122. /package/src/{injector.mts → injectors.mts} +0 -0
@@ -0,0 +1,2896 @@
1
+
2
+ //#region src/enums/injectable-scope.enum.mts
3
+ let InjectableScope = /* @__PURE__ */ function(InjectableScope$1) {
4
+ /**
5
+ * Singleton scope: The instance is created once and shared across the application.
6
+ */
7
+ InjectableScope$1["Singleton"] = "Singleton";
8
+ /**
9
+ * Instance scope: A new instance is created for each injection.
10
+ */
11
+ InjectableScope$1["Transient"] = "Transient";
12
+ /**
13
+ * Request scope: The instance is created once per request and shared within that request context.
14
+ */
15
+ InjectableScope$1["Request"] = "Request";
16
+ return InjectableScope$1;
17
+ }({});
18
+
19
+ //#endregion
20
+ //#region src/enums/injectable-type.enum.mts
21
+ let InjectableType = /* @__PURE__ */ function(InjectableType$1) {
22
+ InjectableType$1["Class"] = "Class";
23
+ InjectableType$1["Factory"] = "Factory";
24
+ return InjectableType$1;
25
+ }({});
26
+
27
+ //#endregion
28
+ //#region src/token/injection-token.mts
29
+ var InjectionToken = class InjectionToken {
30
+ name;
31
+ schema;
32
+ id = globalThis.crypto.randomUUID();
33
+ formattedName = null;
34
+ constructor(name, schema) {
35
+ this.name = name;
36
+ this.schema = schema;
37
+ }
38
+ static create(name, schema) {
39
+ return new InjectionToken(name, schema);
40
+ }
41
+ static bound(token, value) {
42
+ return new BoundInjectionToken(token, value);
43
+ }
44
+ static factory(token, factory) {
45
+ return new FactoryInjectionToken(token, factory);
46
+ }
47
+ static refineType(token) {
48
+ return token;
49
+ }
50
+ toString() {
51
+ if (this.formattedName) return this.formattedName;
52
+ const { name } = this;
53
+ if (typeof name === "function") this.formattedName = `${name.name}(${this.id})`;
54
+ else if (typeof name === "symbol") this.formattedName = `${name.toString()}(${this.id})`;
55
+ else this.formattedName = `${name}(${this.id})`;
56
+ return this.formattedName;
57
+ }
58
+ };
59
+ var BoundInjectionToken = class {
60
+ token;
61
+ value;
62
+ id;
63
+ name;
64
+ schema;
65
+ constructor(token, value) {
66
+ this.token = token;
67
+ this.value = value;
68
+ this.name = token.name;
69
+ this.id = token.id;
70
+ this.schema = token.schema;
71
+ }
72
+ toString() {
73
+ return this.token.toString();
74
+ }
75
+ };
76
+ var FactoryInjectionToken = class {
77
+ token;
78
+ factory;
79
+ value;
80
+ resolved = false;
81
+ id;
82
+ name;
83
+ schema;
84
+ constructor(token, factory) {
85
+ this.token = token;
86
+ this.factory = factory;
87
+ this.name = token.name;
88
+ this.id = token.id;
89
+ this.schema = token.schema;
90
+ }
91
+ async resolve(ctx) {
92
+ if (!this.value) {
93
+ this.value = await this.factory(ctx);
94
+ this.resolved = true;
95
+ }
96
+ return this.value;
97
+ }
98
+ toString() {
99
+ return this.token.toString();
100
+ }
101
+ };
102
+
103
+ //#endregion
104
+ //#region src/token/registry.mts
105
+ var Registry = class {
106
+ factories = /* @__PURE__ */ new Map();
107
+ constructor(parent) {
108
+ this.parent = parent;
109
+ }
110
+ has(token) {
111
+ if (this.factories.has(token.id)) return true;
112
+ if (this.parent) return this.parent.has(token);
113
+ return false;
114
+ }
115
+ get(token) {
116
+ const factory = this.factories.get(token.id);
117
+ if (!factory) {
118
+ if (this.parent) return this.parent.get(token);
119
+ throw new Error(`[Registry] No factory found for ${token.toString()}`);
120
+ }
121
+ return factory;
122
+ }
123
+ set(token, scope, target, type) {
124
+ this.factories.set(token.id, {
125
+ scope,
126
+ originalToken: token,
127
+ target,
128
+ type
129
+ });
130
+ }
131
+ delete(token) {
132
+ this.factories.delete(token.id);
133
+ }
134
+ };
135
+ const globalRegistry = new Registry();
136
+
137
+ //#endregion
138
+ //#region src/symbols/injectable-token.mts
139
+ const InjectableTokenMeta = Symbol.for("InjectableTokenMeta");
140
+
141
+ //#endregion
142
+ //#region src/decorators/injectable.decorator.mts
143
+ function Injectable({ scope = InjectableScope.Singleton, token, schema, registry = globalRegistry } = {}) {
144
+ return (target, context) => {
145
+ if (context && context.kind !== "class" || target instanceof Function && !context) throw new Error("[ServiceLocator] @Injectable decorator can only be used on classes.");
146
+ if (schema && token) throw new Error("[ServiceLocator] @Injectable decorator cannot have both a token and a schema");
147
+ let injectableToken = token ?? InjectionToken.create(target, schema);
148
+ registry.set(injectableToken, scope, target, InjectableType.Class);
149
+ target[InjectableTokenMeta] = injectableToken;
150
+ return target;
151
+ };
152
+ }
153
+
154
+ //#endregion
155
+ //#region src/errors/di-error.mts
156
+ let DIErrorCode = /* @__PURE__ */ function(DIErrorCode$1) {
157
+ DIErrorCode$1["FactoryNotFound"] = "FactoryNotFound";
158
+ DIErrorCode$1["FactoryTokenNotResolved"] = "FactoryTokenNotResolved";
159
+ DIErrorCode$1["InstanceNotFound"] = "InstanceNotFound";
160
+ DIErrorCode$1["InstanceDestroying"] = "InstanceDestroying";
161
+ DIErrorCode$1["CircularDependency"] = "CircularDependency";
162
+ DIErrorCode$1["UnknownError"] = "UnknownError";
163
+ return DIErrorCode$1;
164
+ }({});
165
+ var DIError = class DIError extends Error {
166
+ context;
167
+ constructor(code, message, context) {
168
+ super(message);
169
+ this.code = code;
170
+ this.message = message;
171
+ this.context = context;
172
+ }
173
+ static factoryNotFound(name) {
174
+ return new DIError(DIErrorCode.FactoryNotFound, `Factory ${name} not found`, { name });
175
+ }
176
+ static factoryTokenNotResolved(token) {
177
+ return new DIError(DIErrorCode.FactoryTokenNotResolved, `Factory token not resolved: ${token?.toString() ?? "unknown"}`, { token });
178
+ }
179
+ static instanceNotFound(name) {
180
+ return new DIError(DIErrorCode.InstanceNotFound, `Instance ${name} not found`, { name });
181
+ }
182
+ static instanceDestroying(name) {
183
+ return new DIError(DIErrorCode.InstanceDestroying, `Instance ${name} destroying`, { name });
184
+ }
185
+ static unknown(message, context) {
186
+ if (message instanceof Error) return new DIError(DIErrorCode.UnknownError, message.message, {
187
+ ...context,
188
+ parent: message
189
+ });
190
+ return new DIError(DIErrorCode.UnknownError, message, context);
191
+ }
192
+ static circularDependency(cycle) {
193
+ const cycleStr = cycle.join(" -> ");
194
+ return new DIError(DIErrorCode.CircularDependency, `Circular dependency detected: ${cycleStr}`, { cycle });
195
+ }
196
+ };
197
+
198
+ //#endregion
199
+ //#region src/internal/context/sync-local-storage.mts
200
+ /**
201
+ * A synchronous-only polyfill for AsyncLocalStorage.
202
+ *
203
+ * This provides the same API as Node's AsyncLocalStorage but only works
204
+ * for synchronous code paths. It uses a simple stack-based approach.
205
+ *
206
+ * Limitations:
207
+ * - Context does NOT propagate across async boundaries (setTimeout, promises, etc.)
208
+ * - Only suitable for environments where DI resolution is synchronous
209
+ *
210
+ * This is acceptable for browser environments where:
211
+ * 1. Constructors are typically synchronous
212
+ * 2. Circular dependency detection mainly needs sync tracking
213
+ */
214
+ var SyncLocalStorage = class {
215
+ stack = [];
216
+ /**
217
+ * Runs a function within the given store context.
218
+ * The context is only available synchronously within the function.
219
+ */
220
+ run(store, fn) {
221
+ this.stack.push(store);
222
+ try {
223
+ return fn();
224
+ } finally {
225
+ this.stack.pop();
226
+ }
227
+ }
228
+ /**
229
+ * Gets the current store value, or undefined if not in a context.
230
+ */
231
+ getStore() {
232
+ return this.stack.length > 0 ? this.stack[this.stack.length - 1] : void 0;
233
+ }
234
+ /**
235
+ * Exits the current context and runs the function without any store.
236
+ * This matches AsyncLocalStorage.exit() behavior.
237
+ */
238
+ exit(fn) {
239
+ const savedStack = this.stack;
240
+ this.stack = [];
241
+ try {
242
+ return fn();
243
+ } finally {
244
+ this.stack = savedStack;
245
+ }
246
+ }
247
+ };
248
+
249
+ //#endregion
250
+ //#region src/internal/context/async-local-storage.mts
251
+ /**
252
+ * Cross-platform AsyncLocalStorage wrapper.
253
+ *
254
+ * Provides AsyncLocalStorage on Node.js/Bun and falls back to
255
+ * a synchronous-only polyfill in browser environments.
256
+ */
257
+ /**
258
+ * Detects if we're running in a Node.js-like environment with async_hooks support.
259
+ */ function hasAsyncHooksSupport() {
260
+ if (typeof process !== "undefined" && process.versions && process.versions.node) return true;
261
+ if (typeof process !== "undefined" && process.versions && "bun" in process.versions) return true;
262
+ if (typeof globalThis.Deno !== "undefined") return true;
263
+ return false;
264
+ }
265
+ let AsyncLocalStorageClass = null;
266
+ let initialized = false;
267
+ let forceSyncMode = false;
268
+ /**
269
+ * Gets the appropriate AsyncLocalStorage implementation for the current environment.
270
+ *
271
+ * - On Node.js/Bun/Deno: Returns the native AsyncLocalStorage
272
+ * - On browsers: Returns SyncLocalStorage polyfill
273
+ */ function getAsyncLocalStorageClass() {
274
+ if (initialized) return AsyncLocalStorageClass;
275
+ initialized = true;
276
+ if (!forceSyncMode && hasAsyncHooksSupport()) try {
277
+ AsyncLocalStorageClass = require("node:async_hooks").AsyncLocalStorage;
278
+ } catch {
279
+ AsyncLocalStorageClass = SyncLocalStorage;
280
+ }
281
+ else AsyncLocalStorageClass = SyncLocalStorage;
282
+ return AsyncLocalStorageClass;
283
+ }
284
+ /**
285
+ * Creates a new AsyncLocalStorage instance appropriate for the current environment.
286
+ */ function createAsyncLocalStorage() {
287
+ return new (getAsyncLocalStorageClass())();
288
+ }
289
+
290
+ //#endregion
291
+ //#region src/internal/context/resolution-context.mts
292
+ /**
293
+ * AsyncLocalStorage for tracking the current resolution context.
294
+ *
295
+ * This allows tracking which service is being instantiated even across
296
+ * async boundaries (like when inject() is called inside a constructor).
297
+ * Essential for circular dependency detection.
298
+ */ const resolutionContext = createAsyncLocalStorage();
299
+ /**
300
+ * Runs a function within a resolution context.
301
+ *
302
+ * The context tracks which holder is currently being instantiated,
303
+ * allowing circular dependency detection to work correctly.
304
+ *
305
+ * @param waiterHolder The holder being instantiated
306
+ * @param getHolder Function to retrieve holders by name
307
+ * @param fn The function to run within the context
308
+ */ function withResolutionContext(waiterHolder, getHolder, fn) {
309
+ return resolutionContext.run({
310
+ waiterHolder,
311
+ getHolder
312
+ }, fn);
313
+ }
314
+ /**
315
+ * Gets the current resolution context, if any.
316
+ *
317
+ * Returns undefined if we're not inside a resolution context
318
+ * (e.g., when resolving a top-level service that has no parent).
319
+ */ function getCurrentResolutionContext() {
320
+ return resolutionContext.getStore();
321
+ }
322
+ /**
323
+ * Runs a function outside any resolution context.
324
+ *
325
+ * This is useful for async injections that should not participate
326
+ * in circular dependency detection since they don't block.
327
+ *
328
+ * @param fn The function to run without resolution context
329
+ */ function withoutResolutionContext(fn) {
330
+ return resolutionContext.run(void 0, fn);
331
+ }
332
+
333
+ //#endregion
334
+ //#region src/utils/get-injectors.mts
335
+ function getInjectors() {
336
+ let currentFactoryContext = null;
337
+ function provideFactoryContext$1(context) {
338
+ const original = currentFactoryContext;
339
+ currentFactoryContext = context;
340
+ return original;
341
+ }
342
+ function getFactoryContext() {
343
+ if (!currentFactoryContext) throw new Error("[Injector] Trying to access injection context outside of a injectable context");
344
+ return currentFactoryContext;
345
+ }
346
+ let promiseCollector = null;
347
+ let injectState = null;
348
+ function getRequest(token, args, skipCycleTracking = false) {
349
+ if (!injectState) throw new Error("[Injector] Trying to make a request outside of a injectable context");
350
+ if (injectState.isFrozen) {
351
+ const idx = injectState.currentIndex++;
352
+ const request$1 = injectState.requests[idx];
353
+ if (request$1.token !== token) throw new Error(`[Injector] Wrong token order. Expected ${request$1.token.toString()} but got ${token.toString()}`);
354
+ return request$1;
355
+ }
356
+ let result = null;
357
+ let error = null;
358
+ const doInject = () => getFactoryContext().inject(token, args).then((r) => {
359
+ result = r;
360
+ return r;
361
+ }).catch((e) => {
362
+ error = e;
363
+ });
364
+ const request = {
365
+ token,
366
+ promise: skipCycleTracking ? withoutResolutionContext(doInject) : doInject(),
367
+ get result() {
368
+ return result;
369
+ },
370
+ get error() {
371
+ return error;
372
+ }
373
+ };
374
+ injectState.requests.push(request);
375
+ injectState.currentIndex++;
376
+ return request;
377
+ }
378
+ function asyncInject$1(token, args) {
379
+ if (!injectState) throw new Error("[Injector] Trying to access inject outside of a injectable context");
380
+ const request = getRequest(token[InjectableTokenMeta] ?? token, args, true);
381
+ return request.promise.then((result) => {
382
+ if (request.error) throw request.error;
383
+ return result;
384
+ });
385
+ }
386
+ function wrapSyncInit$1(cb) {
387
+ return (previousState) => {
388
+ const promises = [];
389
+ const originalPromiseCollector = promiseCollector;
390
+ const originalInjectState = injectState;
391
+ injectState = previousState ? {
392
+ ...previousState,
393
+ currentIndex: 0
394
+ } : {
395
+ currentIndex: 0,
396
+ isFrozen: false,
397
+ requests: []
398
+ };
399
+ promiseCollector = (promise) => {
400
+ promises.push(promise);
401
+ };
402
+ const result = cb();
403
+ promiseCollector = originalPromiseCollector;
404
+ const newInjectState = {
405
+ ...injectState,
406
+ isFrozen: true
407
+ };
408
+ injectState = originalInjectState;
409
+ return [
410
+ result,
411
+ promises,
412
+ newInjectState
413
+ ];
414
+ };
415
+ }
416
+ function inject$1(token, args) {
417
+ const realToken = token[InjectableTokenMeta] ?? token;
418
+ if (!injectState) throw new Error("[Injector] Trying to access inject outside of a injectable context");
419
+ const instance = getFactoryContext().container.tryGetSync(realToken, args);
420
+ if (!instance) {
421
+ const request = getRequest(realToken, args);
422
+ if (request.error) throw request.error;
423
+ else if (request.result) return request.result;
424
+ if (promiseCollector) promiseCollector(request.promise);
425
+ return new Proxy({}, { get() {
426
+ throw new Error(`[Injector] Trying to access ${realToken.toString()} before it's initialized, please move the code to a onServiceInit method`);
427
+ } });
428
+ }
429
+ return instance;
430
+ }
431
+ function optional$1(token, args) {
432
+ try {
433
+ return inject$1(token, args);
434
+ } catch {
435
+ return null;
436
+ }
437
+ }
438
+ return {
439
+ asyncInject: asyncInject$1,
440
+ inject: inject$1,
441
+ optional: optional$1,
442
+ wrapSyncInit: wrapSyncInit$1,
443
+ provideFactoryContext: provideFactoryContext$1
444
+ };
445
+ }
446
+
447
+ //#endregion
448
+ //#region src/utils/get-injectable-token.mts
449
+ function getInjectableToken(target) {
450
+ const token = target[InjectableTokenMeta];
451
+ if (!token) throw new Error(`[ServiceLocator] Class ${target.name} is not decorated with @Injectable.`);
452
+ return token;
453
+ }
454
+
455
+ //#endregion
456
+ //#region src/injectors.mts
457
+ const defaultInjectors = getInjectors();
458
+ const asyncInject = defaultInjectors.asyncInject;
459
+ const inject = defaultInjectors.inject;
460
+ const optional = defaultInjectors.optional;
461
+ const wrapSyncInit = defaultInjectors.wrapSyncInit;
462
+ const provideFactoryContext = defaultInjectors.provideFactoryContext;
463
+
464
+ //#endregion
465
+ //#region src/internal/lifecycle/circular-detector.mts
466
+ /**
467
+ * Detects circular dependencies by analyzing the waitingFor relationships
468
+ * between service holders.
469
+ *
470
+ * Uses BFS to traverse the waitingFor graph starting from a target holder
471
+ * and checks if following the chain leads back to the waiter, indicating a circular dependency.
472
+ */ var CircularDetector = class {
473
+ /**
474
+ * Detects if waiting for `targetName` from `waiterName` would create a cycle.
475
+ *
476
+ * This works by checking if `targetName` (or any holder in its waitingFor chain)
477
+ * is currently waiting for `waiterName`. If so, waiting would create a deadlock.
478
+ *
479
+ * @param waiterName The name of the holder that wants to wait
480
+ * @param targetName The name of the holder being waited on
481
+ * @param getHolder Function to retrieve a holder by name
482
+ * @returns The cycle path if a cycle is detected, null otherwise
483
+ */ static detectCycle(waiterName, targetName, getHolder) {
484
+ const visited = /* @__PURE__ */ new Set();
485
+ const queue = [{
486
+ name: targetName,
487
+ path: [waiterName, targetName]
488
+ }];
489
+ while (queue.length > 0) {
490
+ const { name: currentName, path } = queue.shift();
491
+ if (currentName === waiterName) return path;
492
+ if (visited.has(currentName)) continue;
493
+ visited.add(currentName);
494
+ const holder = getHolder(currentName);
495
+ if (!holder) continue;
496
+ for (const waitingForName of holder.waitingFor) if (!visited.has(waitingForName)) queue.push({
497
+ name: waitingForName,
498
+ path: [...path, waitingForName]
499
+ });
500
+ }
501
+ return null;
502
+ }
503
+ /**
504
+ * Formats a cycle path into a human-readable string.
505
+ *
506
+ * @param cycle The cycle path (array of service names)
507
+ * @returns Formatted string like "ServiceA -> ServiceB -> ServiceA"
508
+ */ static formatCycle(cycle) {
509
+ return cycle.join(" -> ");
510
+ }
511
+ };
512
+
513
+ //#endregion
514
+ //#region src/internal/holder/instance-holder.mts
515
+ /**
516
+ * Represents the lifecycle status of an instance holder.
517
+ */
518
+ let InstanceStatus = /* @__PURE__ */ function(InstanceStatus$1) {
519
+ /** Instance has been successfully created and is ready for use */
520
+ InstanceStatus$1["Created"] = "created";
521
+ /** Instance is currently being created (async initialization in progress) */
522
+ InstanceStatus$1["Creating"] = "creating";
523
+ /** Instance is being destroyed (cleanup in progress) */
524
+ InstanceStatus$1["Destroying"] = "destroying";
525
+ /** Instance creation failed with an error */
526
+ InstanceStatus$1["Error"] = "error";
527
+ return InstanceStatus$1;
528
+ }({});
529
+
530
+ //#endregion
531
+ //#region src/internal/holder/base-holder-manager.mts
532
+ /**
533
+ * Abstract base class providing common functionality for managing InstanceHolder objects.
534
+ *
535
+ * Provides shared patterns for holder storage, creation, and lifecycle management
536
+ * used by both singleton (HolderManager) and request-scoped (RequestContext) managers.
537
+ */ var BaseHolderManager = class BaseHolderManager {
538
+ logger;
539
+ _holders;
540
+ constructor(logger = null) {
541
+ this.logger = logger;
542
+ this._holders = /* @__PURE__ */ new Map();
543
+ }
544
+ /**
545
+ * Protected getter for accessing the holders map from subclasses.
546
+ */ get holders() {
547
+ return this._holders;
548
+ }
549
+ /**
550
+ * Deletes a holder by name.
551
+ * @param name The name of the holder to delete
552
+ * @returns true if the holder was deleted, false if it didn't exist
553
+ */ delete(name) {
554
+ return this._holders.delete(name);
555
+ }
556
+ /**
557
+ * Filters holders based on a predicate function.
558
+ * @param predicate Function to test each holder
559
+ * @returns A new Map containing only the holders that match the predicate
560
+ */ filter(predicate) {
561
+ return new Map([...this._holders].filter(([key, value]) => predicate(value, key)));
562
+ }
563
+ /**
564
+ * Clears all holders from this manager.
565
+ */ clear() {
566
+ this._holders.clear();
567
+ }
568
+ /**
569
+ * Gets the number of holders currently managed.
570
+ */ size() {
571
+ return this._holders.size;
572
+ }
573
+ /**
574
+ * Creates a new holder with Creating status and a deferred creation promise.
575
+ * This is useful for creating placeholder holders that can be fulfilled later.
576
+ * @param name The name of the instance
577
+ * @param type The injectable type
578
+ * @param scope The injectable scope
579
+ * @param deps Optional set of dependencies
580
+ * @returns A tuple containing the deferred promise and the holder
581
+ */ createCreatingHolder(name, type, scope, deps = /* @__PURE__ */ new Set()) {
582
+ const deferred = Promise.withResolvers();
583
+ return [deferred, {
584
+ status: InstanceStatus.Creating,
585
+ name,
586
+ instance: null,
587
+ creationPromise: deferred.promise,
588
+ destroyPromise: null,
589
+ type,
590
+ scope,
591
+ deps,
592
+ destroyListeners: [],
593
+ createdAt: Date.now(),
594
+ waitingFor: /* @__PURE__ */ new Set()
595
+ }];
596
+ }
597
+ /**
598
+ * Creates a new holder with Created status and an actual instance.
599
+ * This is useful for creating holders that already have their instance ready.
600
+ * @param name The name of the instance
601
+ * @param instance The actual instance to store
602
+ * @param type The injectable type
603
+ * @param scope The injectable scope
604
+ * @param deps Optional set of dependencies
605
+ * @returns The created holder
606
+ */ createCreatedHolder(name, instance, type, scope, deps = /* @__PURE__ */ new Set()) {
607
+ return {
608
+ status: InstanceStatus.Created,
609
+ name,
610
+ instance,
611
+ creationPromise: null,
612
+ destroyPromise: null,
613
+ type,
614
+ scope,
615
+ deps,
616
+ destroyListeners: [],
617
+ createdAt: Date.now(),
618
+ waitingFor: /* @__PURE__ */ new Set()
619
+ };
620
+ }
621
+ /**
622
+ * Gets all holder names currently managed.
623
+ */ getAllNames() {
624
+ return Array.from(this._holders.keys());
625
+ }
626
+ /**
627
+ * Gets all holders currently managed.
628
+ */ getAllHolders() {
629
+ return Array.from(this._holders.values());
630
+ }
631
+ /**
632
+ * Checks if this manager has any holders.
633
+ */ isEmpty() {
634
+ return this._holders.size === 0;
635
+ }
636
+ /**
637
+ * Waits for a holder to be ready and returns the appropriate result.
638
+ * This is a shared utility used by both singleton and request-scoped resolution.
639
+ *
640
+ * @param holder The holder to wait for
641
+ * @param waiterHolder Optional holder that is doing the waiting (for circular dependency detection)
642
+ * @param getHolder Optional function to retrieve holders by name (required if waiterHolder is provided)
643
+ * @returns A promise that resolves with [undefined, holder] on success or [DIError] on failure
644
+ */ static async waitForHolderReady(holder, waiterHolder, getHolder) {
645
+ switch (holder.status) {
646
+ case InstanceStatus.Creating:
647
+ if (waiterHolder && getHolder) {
648
+ const cycle = CircularDetector.detectCycle(waiterHolder.name, holder.name, getHolder);
649
+ if (cycle) return [DIError.circularDependency(cycle)];
650
+ waiterHolder.waitingFor.add(holder.name);
651
+ }
652
+ try {
653
+ await holder.creationPromise;
654
+ } finally {
655
+ if (waiterHolder) waiterHolder.waitingFor.delete(holder.name);
656
+ }
657
+ return BaseHolderManager.waitForHolderReady(holder, waiterHolder, getHolder);
658
+ case InstanceStatus.Destroying: return [DIError.instanceDestroying(holder.name)];
659
+ case InstanceStatus.Error: return [holder.instance];
660
+ case InstanceStatus.Created: return [void 0, holder];
661
+ default: return [DIError.instanceNotFound("unknown")];
662
+ }
663
+ }
664
+ };
665
+
666
+ //#endregion
667
+ //#region src/internal/context/request-context.mts
668
+ /**
669
+ * Default implementation of RequestContext.
670
+ *
671
+ * Extends BaseHolderManager to provide holder management functionality
672
+ * with request-specific metadata and lifecycle support.
673
+ */ var DefaultRequestContext = class extends BaseHolderManager {
674
+ requestId;
675
+ priority;
676
+ metadata = /* @__PURE__ */ new Map();
677
+ createdAt = Date.now();
678
+ constructor(requestId, priority = 100, initialMetadata) {
679
+ super(null), this.requestId = requestId, this.priority = priority;
680
+ if (initialMetadata) Object.entries(initialMetadata).forEach(([key, value]) => {
681
+ this.metadata.set(key, value);
682
+ });
683
+ }
684
+ /**
685
+ * Public getter for holders to maintain interface compatibility.
686
+ */ get holders() {
687
+ return this._holders;
688
+ }
689
+ /**
690
+ * Gets a holder by name. For RequestContext, this is a simple lookup.
691
+ */ get(name) {
692
+ return this._holders.get(name);
693
+ }
694
+ /**
695
+ * Sets a holder by name.
696
+ */ set(name, holder) {
697
+ this._holders.set(name, holder);
698
+ }
699
+ /**
700
+ * Checks if a holder exists by name.
701
+ */ has(name) {
702
+ return this._holders.has(name);
703
+ }
704
+ addInstance(instanceName, instance, holder) {
705
+ if (instanceName instanceof InjectionToken) {
706
+ const name = instanceName.toString();
707
+ const createdHolder = this.createCreatedHolder(name, instance, InjectableType.Class, InjectableScope.Singleton, /* @__PURE__ */ new Set());
708
+ this._holders.set(name, createdHolder);
709
+ } else {
710
+ if (!holder) throw new Error("Holder is required when adding an instance by name");
711
+ this._holders.set(instanceName, holder);
712
+ }
713
+ }
714
+ clear() {
715
+ super.clear();
716
+ this.metadata.clear();
717
+ }
718
+ getMetadata(key) {
719
+ return this.metadata.get(key);
720
+ }
721
+ setMetadata(key, value) {
722
+ this.metadata.set(key, value);
723
+ }
724
+ };
725
+ /**
726
+ * Creates a new request context with the given parameters.
727
+ */ function createRequestContext(requestId, priority = 100, initialMetadata) {
728
+ return new DefaultRequestContext(requestId, priority, initialMetadata);
729
+ }
730
+
731
+ //#endregion
732
+ //#region src/internal/holder/request-storage.mts
733
+ /**
734
+ * Storage implementation for Request-scoped services.
735
+ *
736
+ * Wraps a RequestContext instance from a ScopedContainer and provides
737
+ * the IHolderStorage interface. This allows the InstanceResolver to work
738
+ * with request-scoped storage using the same interface as singleton storage.
739
+ */
740
+ var RequestStorage = class {
741
+ scope = InjectableScope.Request;
742
+ constructor(contextHolder, holderManager) {
743
+ this.contextHolder = contextHolder;
744
+ this.holderManager = holderManager;
745
+ }
746
+ get(instanceName) {
747
+ const holder = this.contextHolder.get(instanceName);
748
+ if (!holder) return null;
749
+ switch (holder.status) {
750
+ case InstanceStatus.Destroying: return [DIError.instanceDestroying(instanceName), holder];
751
+ case InstanceStatus.Error: return [holder.instance, holder];
752
+ case InstanceStatus.Creating:
753
+ case InstanceStatus.Created: return [void 0, holder];
754
+ default: return null;
755
+ }
756
+ }
757
+ set(instanceName, holder) {
758
+ this.contextHolder.set(instanceName, holder);
759
+ }
760
+ delete(instanceName) {
761
+ return this.contextHolder.delete(instanceName);
762
+ }
763
+ createHolder(instanceName, type, deps) {
764
+ return this.holderManager.createCreatingHolder(instanceName, type, this.scope, deps);
765
+ }
766
+ handles(scope) {
767
+ return scope === InjectableScope.Request;
768
+ }
769
+ getAllNames() {
770
+ const names = [];
771
+ for (const [name] of this.contextHolder.holders) names.push(name);
772
+ return names;
773
+ }
774
+ forEach(callback) {
775
+ for (const [name, holder] of this.contextHolder.holders) callback(name, holder);
776
+ }
777
+ findByInstance(instance) {
778
+ for (const holder of this.contextHolder.holders.values()) if (holder.instance === instance) return holder;
779
+ return null;
780
+ }
781
+ findDependents(instanceName) {
782
+ const dependents = [];
783
+ for (const [name, holder] of this.contextHolder.holders) if (holder.deps.has(instanceName)) dependents.push(name);
784
+ for (const [name, holder] of this.holderManager.filter(() => true)) if (holder.deps.has(instanceName)) dependents.push(name);
785
+ return dependents;
786
+ }
787
+ };
788
+
789
+ //#endregion
790
+ //#region src/container/scoped-container.mts
791
+ /**
792
+ * Request-scoped dependency injection container.
793
+ *
794
+ * Wraps a parent Container and provides isolated request-scoped instances
795
+ * while delegating singleton and transient resolution to the parent.
796
+ * This design eliminates race conditions that can occur with async operations
797
+ * when multiple requests are processed concurrently.
798
+ */ var ScopedContainer = class {
799
+ parent;
800
+ registry;
801
+ requestId;
802
+ requestContextHolder;
803
+ holderStorage;
804
+ disposed = false;
805
+ constructor(parent, registry, requestId, metadata, priority = 100) {
806
+ this.parent = parent;
807
+ this.registry = registry;
808
+ this.requestId = requestId;
809
+ this.requestContextHolder = new DefaultRequestContext(requestId, priority, metadata);
810
+ this.holderStorage = new RequestStorage(this.requestContextHolder, this.parent.getServiceLocator().getManager());
811
+ }
812
+ /**
813
+ * Gets the request context holder for this scoped container.
814
+ */ getRequestContextHolder() {
815
+ return this.requestContextHolder;
816
+ }
817
+ /**
818
+ * Gets the holder storage for this scoped container.
819
+ * Used by InstanceResolver for request-scoped resolution.
820
+ */ getHolderStorage() {
821
+ return this.holderStorage;
822
+ }
823
+ /**
824
+ * Gets the request ID for this scoped container.
825
+ */ getRequestId() {
826
+ return this.requestId;
827
+ }
828
+ /**
829
+ * Gets the parent container.
830
+ */ getParent() {
831
+ return this.parent;
832
+ }
833
+ /**
834
+ * Gets metadata from the request context.
835
+ */ getMetadata(key) {
836
+ return this.requestContextHolder.getMetadata(key);
837
+ }
838
+ /**
839
+ * Sets metadata on the request context.
840
+ */ setMetadata(key, value) {
841
+ this.requestContextHolder.setMetadata(key, value);
842
+ }
843
+ /**
844
+ * Adds a pre-prepared instance to the request context.
845
+ */ addInstance(token, instance) {
846
+ this.requestContextHolder.addInstance(token, instance);
847
+ }
848
+ async get(token, args) {
849
+ if (this.disposed) throw DIError.unknown(`ScopedContainer for request ${this.requestId} has been disposed`);
850
+ const actualToken = this.parent.getServiceLocator().getTokenProcessor().normalizeToken(token);
851
+ if (this.isRequestScoped(actualToken)) return this.resolveRequestScoped(actualToken, args);
852
+ return this.parent.getWithContext(token, args, this);
853
+ }
854
+ /**
855
+ * Invalidates a service and its dependencies.
856
+ * For request-scoped services, invalidation is handled within this context.
857
+ */ async invalidate(service) {
858
+ const holder = this.holderStorage.findByInstance(service);
859
+ if (holder) {
860
+ await this.parent.getServiceLocator().getInvalidator().invalidateWithStorage(holder.name, this.holderStorage, 1, { emitEvents: false });
861
+ return;
862
+ }
863
+ await this.parent.invalidate(service);
864
+ }
865
+ /**
866
+ * Checks if a service is registered.
867
+ */ isRegistered(token) {
868
+ return this.parent.isRegistered(token);
869
+ }
870
+ /**
871
+ * Disposes this scoped container and cleans up all request-scoped instances.
872
+ * This is an alias for endRequest() for IContainer compatibility.
873
+ */ async dispose() {
874
+ await this.endRequest();
875
+ }
876
+ /**
877
+ * Ends the request and cleans up all request-scoped instances.
878
+ * Uses the invalidation system to properly cascade to dependent singletons.
879
+ */ async endRequest() {
880
+ if (this.disposed) return;
881
+ this.disposed = true;
882
+ await this.parent.getServiceLocator().getInvalidator().clearAllWithStorage(this.holderStorage, {
883
+ waitForSettlement: true,
884
+ maxRounds: 10
885
+ });
886
+ this.requestContextHolder.clear();
887
+ this.parent.removeActiveRequest(this.requestId);
888
+ }
889
+ /**
890
+ * Waits for all pending operations to complete.
891
+ */ async ready() {
892
+ await this.parent.ready();
893
+ }
894
+ /**
895
+ * @internal
896
+ * Attempts to get an instance synchronously if it already exists and is ready.
897
+ * For request-scoped services, checks this container's context first.
898
+ * For other services, delegates to the parent container.
899
+ *
900
+ * Returns null if the instance doesn't exist or is not yet ready (still creating).
901
+ */ tryGetSync(token, args) {
902
+ const actualToken = this.parent.getServiceLocator().getTokenProcessor().normalizeToken(token);
903
+ if (this.isRequestScoped(actualToken)) {
904
+ const instanceName = this.parent.getServiceLocator().getInstanceIdentifier(token, args);
905
+ const holder = this.requestContextHolder.get(instanceName);
906
+ if (holder && holder.status === InstanceStatus.Created) return holder.instance;
907
+ return null;
908
+ }
909
+ return this.parent.tryGetSync(token, args);
910
+ }
911
+ /**
912
+ * Checks if a token is for a request-scoped service.
913
+ */ isRequestScoped(token) {
914
+ const realToken = this.parent.getServiceLocator().getTokenProcessor().getRealToken(token);
915
+ if (!this.registry.has(realToken)) return false;
916
+ return this.registry.get(realToken).scope === InjectableScope.Request;
917
+ }
918
+ /**
919
+ * Resolves a request-scoped service from this container's context.
920
+ * Uses locking to prevent duplicate initialization during concurrent resolution.
921
+ */ async resolveRequestScoped(token, args) {
922
+ const instanceName = this.parent.getServiceLocator().getInstanceIdentifier(token, args);
923
+ const existingHolder = this.requestContextHolder.get(instanceName);
924
+ if (existingHolder) {
925
+ const [error, readyHolder] = await BaseHolderManager.waitForHolderReady(existingHolder);
926
+ if (error) throw error;
927
+ return readyHolder.instance;
928
+ }
929
+ return this.parent.resolveForRequest(token, args, this);
930
+ }
931
+ /**
932
+ * Stores an instance in the request context.
933
+ * Called by Container during request-scoped service resolution.
934
+ */ storeRequestInstance(instanceName, instance, holder) {
935
+ this.requestContextHolder.addInstance(instanceName, instance, holder);
936
+ }
937
+ /**
938
+ * Gets an existing instance from the request context.
939
+ * Called by Container during resolution to check for existing instances.
940
+ */ getRequestInstance(instanceName) {
941
+ return this.requestContextHolder.get(instanceName);
942
+ }
943
+ /**
944
+ * Generates a prefixed event name for request-scoped services.
945
+ * Format: {requestId}:{instanceName}
946
+ */ getPrefixedEventName(instanceName) {
947
+ return `${this.requestId}:${instanceName}`;
948
+ }
949
+ };
950
+
951
+ //#endregion
952
+ //#region src/internal/holder/singleton-storage.mts
953
+ /**
954
+ * Storage implementation for Singleton-scoped services.
955
+ *
956
+ * Wraps a HolderManager instance and provides the IHolderStorage interface.
957
+ * This allows the InstanceResolver to work with singleton storage
958
+ * using the same interface as request-scoped storage.
959
+ */
960
+ var SingletonStorage = class {
961
+ scope = InjectableScope.Singleton;
962
+ constructor(manager) {
963
+ this.manager = manager;
964
+ }
965
+ get(instanceName) {
966
+ const [error, holder] = this.manager.get(instanceName);
967
+ if (!error) return [void 0, holder];
968
+ switch (error.code) {
969
+ case DIErrorCode.InstanceNotFound: return null;
970
+ case DIErrorCode.InstanceDestroying: return [error, holder];
971
+ default: return [error];
972
+ }
973
+ }
974
+ set(instanceName, holder) {
975
+ this.manager.set(instanceName, holder);
976
+ }
977
+ delete(instanceName) {
978
+ return this.manager.delete(instanceName);
979
+ }
980
+ createHolder(instanceName, type, deps) {
981
+ return this.manager.createCreatingHolder(instanceName, type, this.scope, deps);
982
+ }
983
+ handles(scope) {
984
+ return scope === InjectableScope.Singleton;
985
+ }
986
+ getAllNames() {
987
+ return this.manager.getAllNames();
988
+ }
989
+ forEach(callback) {
990
+ for (const [name, holder] of this.manager.filter(() => true)) callback(name, holder);
991
+ }
992
+ findByInstance(instance) {
993
+ for (const [, holder] of this.manager.filter((h) => h.instance === instance)) return holder;
994
+ return null;
995
+ }
996
+ findDependents(instanceName) {
997
+ const dependents = [];
998
+ for (const [name, holder] of this.manager.filter(() => true)) if (holder.deps.has(instanceName)) dependents.push(name);
999
+ return dependents;
1000
+ }
1001
+ };
1002
+
1003
+ //#endregion
1004
+ //#region src/internal/core/instance-resolver.mts
1005
+ /**
1006
+ * Resolves instances from tokens, handling caching, creation, and scope rules.
1007
+ *
1008
+ * Uses the Storage Strategy pattern for unified singleton/request-scoped handling.
1009
+ * Coordinates with Instantiator for actual service creation.
1010
+ */ var InstanceResolver = class {
1011
+ registry;
1012
+ manager;
1013
+ instantiator;
1014
+ tokenProcessor;
1015
+ logger;
1016
+ serviceLocator;
1017
+ singletonStorage;
1018
+ constructor(registry, manager, instantiator, tokenProcessor, logger = null, serviceLocator) {
1019
+ this.registry = registry;
1020
+ this.manager = manager;
1021
+ this.instantiator = instantiator;
1022
+ this.tokenProcessor = tokenProcessor;
1023
+ this.logger = logger;
1024
+ this.serviceLocator = serviceLocator;
1025
+ this.singletonStorage = new SingletonStorage(manager);
1026
+ }
1027
+ /**
1028
+ * Resolves an instance for the given token and arguments.
1029
+ * This method is used for singleton and transient services.
1030
+ *
1031
+ * @param token The injection token
1032
+ * @param args Optional arguments
1033
+ * @param contextContainer The container to use for creating FactoryContext
1034
+ */ async resolveInstance(token, args, contextContainer) {
1035
+ return this.resolveWithStorage(token, args, contextContainer, this.singletonStorage);
1036
+ }
1037
+ /**
1038
+ * Resolves a request-scoped instance for a ScopedContainer.
1039
+ * The service will be stored in the ScopedContainer's request context.
1040
+ *
1041
+ * @param token The injection token
1042
+ * @param args Optional arguments
1043
+ * @param scopedContainer The ScopedContainer that owns the request context
1044
+ */ async resolveRequestScopedInstance(token, args, scopedContainer) {
1045
+ return this.resolveWithStorage(token, args, scopedContainer, scopedContainer.getHolderStorage(), scopedContainer);
1046
+ }
1047
+ /**
1048
+ * Unified resolution method that works with any IHolderStorage.
1049
+ * This eliminates duplication between singleton and request-scoped resolution.
1050
+ *
1051
+ * IMPORTANT: The check-and-store logic is carefully designed to avoid race conditions.
1052
+ * The storage check and holder creation must happen synchronously (no awaits between).
1053
+ *
1054
+ * @param token The injection token
1055
+ * @param args Optional arguments
1056
+ * @param contextContainer The container for FactoryContext
1057
+ * @param storage The storage strategy to use
1058
+ * @param scopedContainer Optional scoped container for request-scoped services
1059
+ */ async resolveWithStorage(token, args, contextContainer, storage, scopedContainer) {
1060
+ const [err, data] = await this.resolveTokenAndPrepareInstanceName(token, args, contextContainer);
1061
+ if (err) return [err];
1062
+ const { instanceName, validatedArgs, realToken } = data;
1063
+ const getResult = storage.get(instanceName);
1064
+ if (getResult !== null) {
1065
+ const [error, holder$1] = getResult;
1066
+ if (!error && holder$1) {
1067
+ const readyResult = await this.waitForInstanceReady(holder$1);
1068
+ if (readyResult[0]) return [readyResult[0]];
1069
+ return [void 0, readyResult[1].instance];
1070
+ }
1071
+ if (error) {
1072
+ const handledResult = await this.handleStorageError(instanceName, error, holder$1, storage);
1073
+ if (handledResult) return handledResult;
1074
+ }
1075
+ }
1076
+ const [createError, holder] = await this.createAndStoreInstance(instanceName, realToken, validatedArgs, contextContainer, storage, scopedContainer);
1077
+ if (createError) return [createError];
1078
+ return [void 0, holder.instance];
1079
+ }
1080
+ /**
1081
+ * Handles storage error states (destroying, error, etc.).
1082
+ * Returns a result if handled, null if should proceed with creation.
1083
+ */ async handleStorageError(instanceName, error, holder, storage) {
1084
+ switch (error.code) {
1085
+ case DIErrorCode.InstanceDestroying:
1086
+ this.logger?.log(`[InstanceResolver] Instance ${instanceName} is being destroyed, waiting...`);
1087
+ if (holder?.destroyPromise) await holder.destroyPromise;
1088
+ const newResult = storage.get(instanceName);
1089
+ if (newResult !== null && !newResult[0]) {
1090
+ const readyResult = await this.waitForInstanceReady(newResult[1]);
1091
+ if (readyResult[0]) return [readyResult[0]];
1092
+ return [void 0, readyResult[1].instance];
1093
+ }
1094
+ return null;
1095
+ default: return [error];
1096
+ }
1097
+ }
1098
+ /**
1099
+ * Creates a new instance and stores it using the provided storage strategy.
1100
+ * This unified method replaces instantiateServiceFromRegistry and createRequestScopedInstance.
1101
+ *
1102
+ * For transient services, the instance is created but not stored (no caching).
1103
+ */ async createAndStoreInstance(instanceName, realToken, args, contextContainer, storage, scopedContainer) {
1104
+ this.logger?.log(`[InstanceResolver]#createAndStoreInstance() Creating instance for ${instanceName}`);
1105
+ if (!this.registry.has(realToken)) return [DIError.factoryNotFound(realToken.name.toString())];
1106
+ const ctx = this.createFactoryContext(contextContainer);
1107
+ const record = this.registry.get(realToken);
1108
+ const { scope, type } = record;
1109
+ if (scope === InjectableScope.Transient) return this.createTransientInstance(instanceName, record, args, ctx);
1110
+ const [deferred, holder] = this.manager.createCreatingHolder(instanceName, type, scope, ctx.deps);
1111
+ storage.set(instanceName, holder);
1112
+ const getHolder = (name) => {
1113
+ const storageResult = storage.get(name);
1114
+ if (storageResult !== null) {
1115
+ const [, storageHolder] = storageResult;
1116
+ if (storageHolder) return storageHolder;
1117
+ }
1118
+ const [, managerHolder] = this.manager.get(name);
1119
+ return managerHolder;
1120
+ };
1121
+ withResolutionContext(holder, getHolder, () => {
1122
+ this.instantiator.instantiateService(ctx, record, args).then(async (result) => {
1123
+ const [error, instance] = result.length === 2 ? result : [result[0], void 0];
1124
+ await this.handleInstantiationResult(instanceName, holder, ctx, deferred, scope, error, instance, scopedContainer);
1125
+ }).catch(async (error) => {
1126
+ await this.handleInstantiationError(instanceName, holder, deferred, scope, error);
1127
+ }).catch(() => {});
1128
+ });
1129
+ return this.waitForInstanceReady(holder);
1130
+ }
1131
+ /**
1132
+ * Creates a transient instance without storage or locking.
1133
+ * Each call creates a new instance.
1134
+ */ async createTransientInstance(instanceName, record, args, ctx) {
1135
+ this.logger?.log(`[InstanceResolver]#createTransientInstance() Creating transient instance for ${instanceName}`);
1136
+ const tempHolder = {
1137
+ status: InstanceStatus.Creating,
1138
+ name: instanceName,
1139
+ instance: null,
1140
+ creationPromise: null,
1141
+ destroyPromise: null,
1142
+ type: record.type,
1143
+ scope: InjectableScope.Transient,
1144
+ deps: ctx.deps,
1145
+ destroyListeners: [],
1146
+ createdAt: Date.now(),
1147
+ waitingFor: /* @__PURE__ */ new Set()
1148
+ };
1149
+ const getHolder = (name) => {
1150
+ const [, managerHolder] = this.manager.get(name);
1151
+ return managerHolder;
1152
+ };
1153
+ const [error, instance] = await withResolutionContext(tempHolder, getHolder, () => this.instantiator.instantiateService(ctx, record, args));
1154
+ if (error) return [error];
1155
+ return [void 0, {
1156
+ status: InstanceStatus.Created,
1157
+ name: instanceName,
1158
+ instance,
1159
+ creationPromise: null,
1160
+ destroyPromise: null,
1161
+ type: record.type,
1162
+ scope: InjectableScope.Transient,
1163
+ deps: ctx.deps,
1164
+ destroyListeners: ctx.getDestroyListeners(),
1165
+ createdAt: Date.now(),
1166
+ waitingFor: /* @__PURE__ */ new Set()
1167
+ }];
1168
+ }
1169
+ /**
1170
+ * Gets a synchronous instance (for sync operations).
1171
+ */ getSyncInstance(token, args, contextContainer) {
1172
+ const [err, { actualToken, validatedArgs }] = this.tokenProcessor.validateAndResolveTokenArgs(token, args);
1173
+ if (err) return null;
1174
+ const instanceName = this.tokenProcessor.generateInstanceName(actualToken, validatedArgs);
1175
+ if ("getRequestInstance" in contextContainer) {
1176
+ const requestHolder = contextContainer.getRequestInstance(instanceName);
1177
+ if (requestHolder) return requestHolder.instance;
1178
+ }
1179
+ const [error, holder] = this.manager.get(instanceName);
1180
+ if (error) return null;
1181
+ return holder.instance;
1182
+ }
1183
+ /**
1184
+ * Internal method to resolve token args and create instance name.
1185
+ * Handles factory token resolution and validation.
1186
+ */ async resolveTokenAndPrepareInstanceName(token, args, contextContainer) {
1187
+ const [err, { actualToken, validatedArgs }] = this.tokenProcessor.validateAndResolveTokenArgs(token, args);
1188
+ if (err instanceof DIError && err.code === DIErrorCode.UnknownError) return [err];
1189
+ else if (err instanceof DIError && err.code === DIErrorCode.FactoryTokenNotResolved && actualToken instanceof FactoryInjectionToken) {
1190
+ this.logger?.log(`[InstanceResolver]#resolveTokenAndPrepareInstanceName() Factory token not resolved, resolving it`);
1191
+ await actualToken.resolve(this.createFactoryContext(contextContainer));
1192
+ return this.resolveTokenAndPrepareInstanceName(token, void 0, contextContainer);
1193
+ }
1194
+ return [void 0, {
1195
+ instanceName: this.tokenProcessor.generateInstanceName(actualToken, validatedArgs),
1196
+ validatedArgs,
1197
+ actualToken,
1198
+ realToken: actualToken instanceof BoundInjectionToken || actualToken instanceof FactoryInjectionToken ? actualToken.token : actualToken
1199
+ }];
1200
+ }
1201
+ /**
1202
+ * Waits for an instance holder to be ready and returns the appropriate result.
1203
+ * Uses the shared utility from BaseHolderManager.
1204
+ * Passes the current resolution context for circular dependency detection.
1205
+ */ waitForInstanceReady(holder) {
1206
+ const ctx = getCurrentResolutionContext();
1207
+ return BaseHolderManager.waitForHolderReady(holder, ctx?.waiterHolder, ctx?.getHolder);
1208
+ }
1209
+ /**
1210
+ * Handles the result of service instantiation.
1211
+ */ async handleInstantiationResult(instanceName, holder, ctx, deferred, scope, error, instance, scopedContainer) {
1212
+ holder.destroyListeners = ctx.getDestroyListeners();
1213
+ holder.creationPromise = null;
1214
+ if (error) await this.handleInstantiationError(instanceName, holder, deferred, scope, error);
1215
+ else await this.handleInstantiationSuccess(instanceName, holder, ctx, deferred, instance, scopedContainer);
1216
+ }
1217
+ /**
1218
+ * Handles successful service instantiation.
1219
+ */ async handleInstantiationSuccess(instanceName, holder, ctx, deferred, instance, scopedContainer) {
1220
+ holder.instance = instance;
1221
+ holder.status = InstanceStatus.Created;
1222
+ if (ctx.deps.size > 0) ctx.deps.forEach((dependency) => {
1223
+ holder.destroyListeners.push(this.serviceLocator.getEventBus().on(dependency, "destroy", () => {
1224
+ this.logger?.log(`[InstanceResolver] Dependency ${dependency} destroyed, invalidating ${instanceName}`);
1225
+ this.serviceLocator.getInvalidator().invalidate(instanceName);
1226
+ }));
1227
+ if (scopedContainer) {
1228
+ const prefixedDependency = scopedContainer.getPrefixedEventName(dependency);
1229
+ holder.destroyListeners.push(this.serviceLocator.getEventBus().on(prefixedDependency, "destroy", () => {
1230
+ this.logger?.log(`[InstanceResolver] Request-scoped dependency ${dependency} destroyed, invalidating ${instanceName}`);
1231
+ scopedContainer.invalidate(instance);
1232
+ }));
1233
+ }
1234
+ });
1235
+ this.logger?.log(`[InstanceResolver] Instance ${instanceName} created successfully`);
1236
+ deferred.resolve([void 0, instance]);
1237
+ }
1238
+ /**
1239
+ * Handles service instantiation errors.
1240
+ */ async handleInstantiationError(instanceName, holder, deferred, scope, error) {
1241
+ this.logger?.error(`[InstanceResolver] Error creating instance for ${instanceName}`, error);
1242
+ holder.status = InstanceStatus.Error;
1243
+ holder.instance = error;
1244
+ holder.creationPromise = null;
1245
+ if (scope === InjectableScope.Singleton) {
1246
+ this.logger?.log(`[InstanceResolver] Singleton ${instanceName} failed, will be invalidated`);
1247
+ this.serviceLocator.getInvalidator().invalidate(instanceName).catch(() => {});
1248
+ }
1249
+ deferred.reject(error);
1250
+ }
1251
+ /**
1252
+ * Creates a factory context for dependency injection during service instantiation.
1253
+ */ createFactoryContext(contextContainer) {
1254
+ return this.tokenProcessor.createFactoryContext(contextContainer);
1255
+ }
1256
+ };
1257
+
1258
+ //#endregion
1259
+ //#region src/internal/core/instantiator.mts
1260
+ /**
1261
+ * Creates service instances from registry records.
1262
+ *
1263
+ * Handles both class-based (@Injectable) and factory-based (@Factory) services,
1264
+ * managing the instantiation lifecycle including sync initialization retries
1265
+ * and lifecycle hook invocation (onServiceInit, onServiceDestroy).
1266
+ */ var Instantiator = class {
1267
+ injectors;
1268
+ constructor(injectors) {
1269
+ this.injectors = injectors;
1270
+ }
1271
+ /**
1272
+ * Instantiates a service based on its registry record.
1273
+ * @param ctx The factory context for dependency injection
1274
+ * @param record The factory record from the registry
1275
+ * @param args Optional arguments for the service
1276
+ * @returns Promise resolving to [undefined, instance] or [error]
1277
+ */ async instantiateService(ctx, record, args = void 0) {
1278
+ try {
1279
+ switch (record.type) {
1280
+ case InjectableType.Class: return this.instantiateClass(ctx, record, args);
1281
+ case InjectableType.Factory: return this.instantiateFactory(ctx, record, args);
1282
+ default: throw DIError.unknown(`[Instantiator] Unknown service type: ${record.type}`);
1283
+ }
1284
+ } catch (error) {
1285
+ return [error instanceof DIError ? error : DIError.unknown(String(error))];
1286
+ }
1287
+ }
1288
+ /**
1289
+ * Instantiates a class-based service (Injectable decorator).
1290
+ * @param ctx The factory context for dependency injection
1291
+ * @param record The factory record from the registry
1292
+ * @param args Optional arguments for the service constructor
1293
+ * @returns Promise resolving to [undefined, instance] or [error]
1294
+ */ async instantiateClass(ctx, record, args) {
1295
+ try {
1296
+ const tryLoad = this.injectors.wrapSyncInit(() => {
1297
+ const original = this.injectors.provideFactoryContext(ctx);
1298
+ let result = new record.target(...args ? [args] : []);
1299
+ this.injectors.provideFactoryContext(original);
1300
+ return result;
1301
+ });
1302
+ let [instance, promises, injectState] = tryLoad();
1303
+ if (promises.length > 0) {
1304
+ if ((await Promise.allSettled(promises)).some((result) => result.status === "rejected")) throw DIError.unknown(`[Instantiator] Service ${record.target.name} cannot be instantiated.`);
1305
+ const newRes = tryLoad(injectState);
1306
+ instance = newRes[0];
1307
+ promises = newRes[1];
1308
+ }
1309
+ if (promises.length > 0) {
1310
+ console.error(`[Instantiator] ${record.target.name} has problem with it's definition.
1311
+
1312
+ One or more of the dependencies are registered as a InjectableScope.Instance and are used with inject.
1313
+
1314
+ Please use inject asyncInject of inject to load those dependencies.`);
1315
+ throw DIError.unknown(`[Instantiator] Service ${record.target.name} cannot be instantiated.`);
1316
+ }
1317
+ if ("onServiceInit" in instance) await instance.onServiceInit();
1318
+ if ("onServiceDestroy" in instance) ctx.addDestroyListener(async () => {
1319
+ await instance.onServiceDestroy();
1320
+ });
1321
+ return [void 0, instance];
1322
+ } catch (error) {
1323
+ return [error instanceof DIError ? error : DIError.unknown(String(error))];
1324
+ }
1325
+ }
1326
+ /**
1327
+ * Instantiates a factory-based service (Factory decorator).
1328
+ * @param ctx The factory context for dependency injection
1329
+ * @param record The factory record from the registry
1330
+ * @param args Optional arguments for the factory
1331
+ * @returns Promise resolving to [undefined, instance] or [error]
1332
+ */ async instantiateFactory(ctx, record, args) {
1333
+ try {
1334
+ const tryLoad = this.injectors.wrapSyncInit(() => {
1335
+ const original = this.injectors.provideFactoryContext(ctx);
1336
+ let result = new record.target();
1337
+ this.injectors.provideFactoryContext(original);
1338
+ return result;
1339
+ });
1340
+ let [builder, promises, injectState] = tryLoad();
1341
+ if (promises.length > 0) {
1342
+ if ((await Promise.allSettled(promises)).some((result) => result.status === "rejected")) throw DIError.unknown(`[Instantiator] Service ${record.target.name} cannot be instantiated.`);
1343
+ const newRes = tryLoad(injectState);
1344
+ builder = newRes[0];
1345
+ promises = newRes[1];
1346
+ }
1347
+ if (promises.length > 0) {
1348
+ console.error(`[Instantiator] ${record.target.name} has problem with it's definition.
1349
+
1350
+ One or more of the dependencies are registered as a InjectableScope.Instance and are used with inject.
1351
+
1352
+ Please use asyncInject instead of inject to load those dependencies.`);
1353
+ throw DIError.unknown(`[Instantiator] Service ${record.target.name} cannot be instantiated.`);
1354
+ }
1355
+ if (typeof builder.create !== "function") throw DIError.unknown(`[Instantiator] Factory ${record.target.name} does not implement the create method.`);
1356
+ return [void 0, await builder.create(ctx, args)];
1357
+ } catch (error) {
1358
+ return [error instanceof DIError ? error : DIError.unknown(String(error))];
1359
+ }
1360
+ }
1361
+ };
1362
+
1363
+ //#endregion
1364
+ //#region src/internal/core/invalidator.mts
1365
+ /**
1366
+ * Manages graceful service cleanup with dependency-aware invalidation.
1367
+ *
1368
+ * Ensures services are destroyed in the correct order based on their dependencies.
1369
+ * Works with any IHolderStorage implementation, enabling unified invalidation
1370
+ * for both singleton and request-scoped services.
1371
+ */ var Invalidator = class {
1372
+ eventBus;
1373
+ logger;
1374
+ storage;
1375
+ constructor(manager, eventBus, logger = null) {
1376
+ this.eventBus = eventBus;
1377
+ this.logger = logger;
1378
+ this.storage = new SingletonStorage(manager);
1379
+ }
1380
+ /**
1381
+ * Invalidates a service and all its dependencies.
1382
+ * Works with the configured storage (singleton by default).
1383
+ */ invalidate(service, round = 1) {
1384
+ return this.invalidateWithStorage(service, this.storage, round);
1385
+ }
1386
+ /**
1387
+ * Invalidates a service using a specific storage.
1388
+ * This allows request-scoped invalidation using a RequestStorage.
1389
+ *
1390
+ * @param service The instance name to invalidate
1391
+ * @param storage The storage to use for this invalidation
1392
+ * @param round Current invalidation round (for recursion limiting)
1393
+ * @param options Additional options for invalidation behavior
1394
+ */ async invalidateWithStorage(service, storage, round = 1, options = {}) {
1395
+ const { cascade = true, _invalidating = /* @__PURE__ */ new Set() } = options;
1396
+ if (_invalidating.has(service)) {
1397
+ this.logger?.log(`[Invalidator] Skipping ${service} - already being invalidated in this chain`);
1398
+ return;
1399
+ }
1400
+ this.logger?.log(`[Invalidator] Starting invalidation process for ${service}`);
1401
+ const result = storage.get(service);
1402
+ if (result === null) return;
1403
+ _invalidating.add(service);
1404
+ const optionsWithTracking = {
1405
+ ...options,
1406
+ _invalidating
1407
+ };
1408
+ if (cascade) {
1409
+ const dependents = storage.findDependents(service);
1410
+ for (const dependentName of dependents) await this.invalidateWithStorage(dependentName, storage, round, optionsWithTracking);
1411
+ }
1412
+ const [, holder] = result;
1413
+ if (holder) await this.invalidateHolderWithStorage(service, holder, storage, round, optionsWithTracking);
1414
+ }
1415
+ /**
1416
+ * Gracefully clears all services using invalidation logic.
1417
+ * This method respects service dependencies and ensures proper cleanup order.
1418
+ * Services that depend on others will be invalidated first, then their dependencies.
1419
+ */ async clearAll(options = {}) {
1420
+ return this.clearAllWithStorage(this.storage, options);
1421
+ }
1422
+ /**
1423
+ * Gracefully clears all services in a specific storage.
1424
+ * This allows clearing request-scoped services using a RequestStorage.
1425
+ */ async clearAllWithStorage(storage, options = {}) {
1426
+ const { maxRounds = 10, waitForSettlement = true } = options;
1427
+ this.logger?.log("[Invalidator] Starting graceful clearing of all services");
1428
+ if (waitForSettlement) {
1429
+ this.logger?.log("[Invalidator] Waiting for all services to settle...");
1430
+ await this.readyWithStorage(storage);
1431
+ }
1432
+ const allServiceNames = storage.getAllNames();
1433
+ if (allServiceNames.length === 0) this.logger?.log("[Invalidator] No services to clear");
1434
+ else {
1435
+ this.logger?.log(`[Invalidator] Found ${allServiceNames.length} services to clear: ${allServiceNames.join(", ")}`);
1436
+ await this.clearServicesWithDependencyAwarenessForStorage(allServiceNames, maxRounds, storage);
1437
+ }
1438
+ this.logger?.log("[Invalidator] Graceful clearing completed");
1439
+ }
1440
+ /**
1441
+ * Waits for all services to settle (either created, destroyed, or error state).
1442
+ */ async ready() {
1443
+ return this.readyWithStorage(this.storage);
1444
+ }
1445
+ /**
1446
+ * Waits for all services in a specific storage to settle.
1447
+ */ async readyWithStorage(storage) {
1448
+ const holders = [];
1449
+ storage.forEach((_, holder) => holders.push(holder));
1450
+ await Promise.all(holders.map((holder) => this.waitForHolderToSettle(holder)));
1451
+ }
1452
+ /**
1453
+ * Invalidates a single holder using a specific storage.
1454
+ */ async invalidateHolderWithStorage(key, holder, storage, round, options = {}) {
1455
+ const { emitEvents = true, onInvalidated } = options;
1456
+ await this.invalidateHolderByStatus(holder, round, {
1457
+ context: key,
1458
+ onCreationError: () => this.logger?.error(`[Invalidator] ${key} creation triggered too many invalidation rounds`),
1459
+ onRecursiveInvalidate: () => this.invalidateWithStorage(key, storage, round + 1, options),
1460
+ onDestroy: () => this.destroyHolderWithStorage(key, holder, storage, emitEvents, onInvalidated)
1461
+ });
1462
+ }
1463
+ /**
1464
+ * Common invalidation logic for holders based on their status.
1465
+ */ async invalidateHolderByStatus(holder, round, options) {
1466
+ switch (holder.status) {
1467
+ case InstanceStatus.Destroying:
1468
+ await holder.destroyPromise;
1469
+ break;
1470
+ case InstanceStatus.Creating:
1471
+ await holder.creationPromise;
1472
+ if (round > 3) {
1473
+ options.onCreationError();
1474
+ return;
1475
+ }
1476
+ await options.onRecursiveInvalidate();
1477
+ break;
1478
+ default:
1479
+ await options.onDestroy();
1480
+ break;
1481
+ }
1482
+ }
1483
+ /**
1484
+ * Destroys a holder using a specific storage.
1485
+ */ async destroyHolderWithStorage(key, holder, storage, emitEvents, onInvalidated) {
1486
+ holder.status = InstanceStatus.Destroying;
1487
+ this.logger?.log(`[Invalidator] Invalidating ${key} and notifying listeners`);
1488
+ holder.destroyPromise = Promise.all(holder.destroyListeners.map((listener) => listener())).then(async () => {
1489
+ holder.destroyListeners = [];
1490
+ holder.deps.clear();
1491
+ storage.delete(key);
1492
+ if (emitEvents && this.eventBus) await this.emitInstanceEvent(key, "destroy");
1493
+ if (onInvalidated) await onInvalidated(key);
1494
+ });
1495
+ await holder.destroyPromise;
1496
+ }
1497
+ /**
1498
+ * Waits for a holder to settle (either created, destroyed, or error state).
1499
+ */ async waitForHolderToSettle(holder) {
1500
+ switch (holder.status) {
1501
+ case InstanceStatus.Creating:
1502
+ await holder.creationPromise;
1503
+ break;
1504
+ case InstanceStatus.Destroying:
1505
+ await holder.destroyPromise;
1506
+ break;
1507
+ case InstanceStatus.Created:
1508
+ case InstanceStatus.Error: break;
1509
+ }
1510
+ }
1511
+ /**
1512
+ * Clears services with dependency awareness for a specific storage.
1513
+ */ async clearServicesWithDependencyAwarenessForStorage(serviceNames, maxRounds, storage) {
1514
+ const clearedServices = /* @__PURE__ */ new Set();
1515
+ let round = 1;
1516
+ while (clearedServices.size < serviceNames.length && round <= maxRounds) {
1517
+ this.logger?.log(`[Invalidator] Clearing round ${round}/${maxRounds}, ${clearedServices.size}/${serviceNames.length} services cleared`);
1518
+ const servicesToClearThisRound = this.findServicesReadyForClearingInStorage(serviceNames, clearedServices, storage);
1519
+ if (servicesToClearThisRound.length === 0) {
1520
+ const remainingServices = serviceNames.filter((name) => !clearedServices.has(name));
1521
+ if (remainingServices.length > 0) {
1522
+ this.logger?.warn(`[Invalidator] No services ready for clearing, forcing cleanup of remaining: ${remainingServices.join(", ")}`);
1523
+ await this.forceClearServicesInStorage(remainingServices, storage);
1524
+ remainingServices.forEach((name) => clearedServices.add(name));
1525
+ }
1526
+ break;
1527
+ }
1528
+ const clearPromises = servicesToClearThisRound.map(async (serviceName) => {
1529
+ try {
1530
+ await this.invalidateWithStorage(serviceName, storage, round);
1531
+ clearedServices.add(serviceName);
1532
+ this.logger?.log(`[Invalidator] Successfully cleared service: ${serviceName}`);
1533
+ } catch (error) {
1534
+ this.logger?.error(`[Invalidator] Error clearing service ${serviceName}:`, error);
1535
+ clearedServices.add(serviceName);
1536
+ }
1537
+ });
1538
+ await Promise.all(clearPromises);
1539
+ round++;
1540
+ }
1541
+ if (clearedServices.size < serviceNames.length) this.logger?.warn(`[Invalidator] Clearing completed after ${maxRounds} rounds, but ${serviceNames.length - clearedServices.size} services may not have been properly cleared`);
1542
+ }
1543
+ /**
1544
+ * Finds services that are ready to be cleared in the current round.
1545
+ * A service is ready if all its dependencies have already been cleared.
1546
+ */ findServicesReadyForClearingInStorage(allServiceNames, clearedServices, storage) {
1547
+ return allServiceNames.filter((serviceName) => {
1548
+ if (clearedServices.has(serviceName)) return false;
1549
+ const result = storage.get(serviceName);
1550
+ if (result === null || result[0]) return true;
1551
+ const [, holder] = result;
1552
+ return !Array.from(holder.deps).some((dep) => !clearedServices.has(dep));
1553
+ });
1554
+ }
1555
+ /**
1556
+ * Force clears services that couldn't be cleared through normal dependency resolution.
1557
+ * This handles edge cases like circular dependencies.
1558
+ */ async forceClearServicesInStorage(serviceNames, storage) {
1559
+ const promises = serviceNames.map(async (serviceName) => {
1560
+ try {
1561
+ const result = storage.get(serviceName);
1562
+ if (result !== null && !result[0]) {
1563
+ const [, holder] = result;
1564
+ await this.destroyHolderWithStorage(serviceName, holder, storage, true);
1565
+ }
1566
+ } catch (error) {
1567
+ this.logger?.error(`[Invalidator] Error force clearing service ${serviceName}:`, error);
1568
+ }
1569
+ });
1570
+ await Promise.all(promises);
1571
+ }
1572
+ /**
1573
+ * Emits events to listeners for instance lifecycle events.
1574
+ */ emitInstanceEvent(name, event = "create") {
1575
+ if (!this.eventBus) return Promise.resolve();
1576
+ this.logger?.log(`[Invalidator]#emitInstanceEvent() Notifying listeners for ${name} with event ${event}`);
1577
+ return this.eventBus.emit(name, event);
1578
+ }
1579
+ };
1580
+
1581
+ //#endregion
1582
+ //#region src/internal/lifecycle/lifecycle-event-bus.mts
1583
+ /**
1584
+ * Event bus for service lifecycle events (create, destroy, etc.).
1585
+ *
1586
+ * Enables loose coupling between services by allowing them to subscribe
1587
+ * to lifecycle events of their dependencies without direct references.
1588
+ * Used primarily for invalidation cascading.
1589
+ */ var LifecycleEventBus = class {
1590
+ logger;
1591
+ listeners = /* @__PURE__ */ new Map();
1592
+ constructor(logger = null) {
1593
+ this.logger = logger;
1594
+ }
1595
+ on(ns, event, listener) {
1596
+ this.logger?.debug(`[LifecycleEventBus]#on(): ns:${ns} event:${event}`);
1597
+ if (!this.listeners.has(ns)) this.listeners.set(ns, /* @__PURE__ */ new Map());
1598
+ const nsEvents = this.listeners.get(ns);
1599
+ if (!nsEvents.has(event)) nsEvents.set(event, /* @__PURE__ */ new Set());
1600
+ nsEvents.get(event).add(listener);
1601
+ return () => {
1602
+ nsEvents.get(event)?.delete(listener);
1603
+ if (nsEvents.get(event)?.size === 0) nsEvents.delete(event);
1604
+ if (nsEvents.size === 0) this.listeners.delete(ns);
1605
+ };
1606
+ }
1607
+ async emit(key, event) {
1608
+ if (!this.listeners.has(key)) return;
1609
+ const events = this.listeners.get(key);
1610
+ this.logger?.debug(`[LifecycleEventBus]#emit(): ${key}:${event}`);
1611
+ return await Promise.allSettled([...events.get(event) ?? []].map((listener) => listener(event))).then((results) => {
1612
+ const res = results.filter((result) => result.status === "rejected").map((result) => {
1613
+ this.logger?.warn(`[LifecycleEventBus]#emit(): ${key}:${event} rejected with`, result.reason);
1614
+ return result;
1615
+ });
1616
+ if (res.length > 0) return Promise.reject(res);
1617
+ return results;
1618
+ });
1619
+ }
1620
+ };
1621
+
1622
+ //#endregion
1623
+ //#region src/internal/holder/holder-manager.mts
1624
+ /**
1625
+ * Manages the storage and retrieval of singleton instance holders.
1626
+ *
1627
+ * Provides CRUD operations and filtering for the holder map.
1628
+ * Handles holder state validation (destroying, error states) on retrieval.
1629
+ */ var HolderManager = class extends BaseHolderManager {
1630
+ constructor(logger = null) {
1631
+ super(logger);
1632
+ }
1633
+ get(name) {
1634
+ const holder = this._holders.get(name);
1635
+ if (holder) {
1636
+ if (holder.status === InstanceStatus.Destroying) {
1637
+ this.logger?.log(`[HolderManager]#get() Instance ${holder.name} is destroying`);
1638
+ return [DIError.instanceDestroying(holder.name), holder];
1639
+ } else if (holder.status === InstanceStatus.Error) {
1640
+ this.logger?.log(`[HolderManager]#get() Instance ${holder.name} is in error state`);
1641
+ return [holder.instance, holder];
1642
+ }
1643
+ return [void 0, holder];
1644
+ } else {
1645
+ this.logger?.log(`[HolderManager]#get() Instance ${name} not found`);
1646
+ return [DIError.instanceNotFound(name)];
1647
+ }
1648
+ }
1649
+ set(name, holder) {
1650
+ this._holders.set(name, holder);
1651
+ }
1652
+ has(name) {
1653
+ const [error, holder] = this.get(name);
1654
+ if (!error) return [void 0, true];
1655
+ if (error.code === DIErrorCode.InstanceDestroying) return [error];
1656
+ return [void 0, !!holder];
1657
+ }
1658
+ /**
1659
+ * Creates a new holder with Created status and stores it.
1660
+ * This is useful for creating holders that already have their instance ready.
1661
+ * @param name The name of the instance
1662
+ * @param instance The actual instance to store
1663
+ * @param type The injectable type
1664
+ * @param scope The injectable scope
1665
+ * @param deps Optional set of dependencies
1666
+ * @returns The created holder
1667
+ */ storeCreatedHolder(name, instance, type, scope, deps = /* @__PURE__ */ new Set()) {
1668
+ const holder = this.createCreatedHolder(name, instance, type, scope, deps);
1669
+ this._holders.set(name, holder);
1670
+ return holder;
1671
+ }
1672
+ };
1673
+
1674
+ //#endregion
1675
+ //#region src/internal/core/token-processor.mts
1676
+ /**
1677
+ * Handles token validation, normalization, and instance name generation.
1678
+ *
1679
+ * Provides utilities for resolving tokens to their underlying InjectionToken,
1680
+ * validating arguments against schemas, and generating unique instance identifiers.
1681
+ */ var TokenProcessor = class {
1682
+ logger;
1683
+ constructor(logger = null) {
1684
+ this.logger = logger;
1685
+ }
1686
+ /**
1687
+ * Normalizes a token to an InjectionToken.
1688
+ * Handles class constructors by getting their injectable token.
1689
+ *
1690
+ * @param token A class constructor, InjectionToken, BoundInjectionToken, or FactoryInjectionToken
1691
+ * @returns The normalized InjectionTokenType
1692
+ */ normalizeToken(token) {
1693
+ if (typeof token === "function") return getInjectableToken(token);
1694
+ return token;
1695
+ }
1696
+ /**
1697
+ * Gets the underlying "real" token from wrapped tokens.
1698
+ * For BoundInjectionToken and FactoryInjectionToken, returns the wrapped token.
1699
+ * For other tokens, returns the token itself.
1700
+ *
1701
+ * @param token The token to unwrap
1702
+ * @returns The underlying InjectionToken
1703
+ */ getRealToken(token) {
1704
+ if (token instanceof BoundInjectionToken || token instanceof FactoryInjectionToken) return token.token;
1705
+ return token;
1706
+ }
1707
+ /**
1708
+ * Convenience method that normalizes a token and then gets the real token.
1709
+ * Useful for checking registry entries where you need the actual registered token.
1710
+ *
1711
+ * @param token Any injectable type
1712
+ * @returns The underlying InjectionToken
1713
+ */ getRegistryToken(token) {
1714
+ return this.getRealToken(this.normalizeToken(token));
1715
+ }
1716
+ /**
1717
+ * Validates and resolves token arguments, handling factory token resolution and validation.
1718
+ */ validateAndResolveTokenArgs(token, args) {
1719
+ let actualToken = token;
1720
+ if (typeof token === "function") actualToken = getInjectableToken(token);
1721
+ let realArgs = args;
1722
+ if (actualToken instanceof BoundInjectionToken) realArgs = actualToken.value;
1723
+ else if (actualToken instanceof FactoryInjectionToken) if (actualToken.resolved) realArgs = actualToken.value;
1724
+ else return [DIError.factoryTokenNotResolved(token.name), { actualToken }];
1725
+ if (!actualToken.schema) return [void 0, {
1726
+ actualToken,
1727
+ validatedArgs: realArgs
1728
+ }];
1729
+ const validatedArgs = actualToken.schema?.safeParse(realArgs);
1730
+ if (validatedArgs && !validatedArgs.success) {
1731
+ this.logger?.error(`[TokenProcessor]#validateAndResolveTokenArgs(): Error validating args for ${actualToken.name.toString()}`, validatedArgs.error);
1732
+ return [DIError.unknown(validatedArgs.error), { actualToken }];
1733
+ }
1734
+ return [void 0, {
1735
+ actualToken,
1736
+ validatedArgs: validatedArgs?.data
1737
+ }];
1738
+ }
1739
+ /**
1740
+ * Generates a unique instance name based on token and arguments.
1741
+ */ generateInstanceName(token, args) {
1742
+ if (!args) return token.toString();
1743
+ const formattedArgs = Object.entries(args).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, value]) => `${key}=${this.formatArgValue(value)}`).join(",");
1744
+ return `${token.toString()}:${formattedArgs.replaceAll(/"/g, "").replaceAll(/:/g, "=")}`;
1745
+ }
1746
+ /**
1747
+ * Formats a single argument value for instance name generation.
1748
+ */ formatArgValue(value) {
1749
+ if (typeof value === "function") return `fn_${value.name}(${value.length})`;
1750
+ if (typeof value === "symbol") return value.toString();
1751
+ return JSON.stringify(value).slice(0, 40);
1752
+ }
1753
+ /**
1754
+ * Creates a factory context for dependency injection during service instantiation.
1755
+ * @param container The container instance (Container or ScopedContainer) for dependency resolution
1756
+ * @param onDependencyResolved Callback when a dependency is resolved, receives the instance name
1757
+ */ createFactoryContext(container, onDependencyResolved) {
1758
+ const destroyListeners = /* @__PURE__ */ new Set();
1759
+ const deps = /* @__PURE__ */ new Set();
1760
+ function addDestroyListener(listener) {
1761
+ destroyListeners.add(listener);
1762
+ }
1763
+ function getDestroyListeners() {
1764
+ return Array.from(destroyListeners);
1765
+ }
1766
+ const self = this;
1767
+ return {
1768
+ async inject(token, args) {
1769
+ const actualToken = typeof token === "function" ? getInjectableToken(token) : token;
1770
+ const instanceName = self.generateInstanceName(actualToken, args);
1771
+ deps.add(instanceName);
1772
+ if (onDependencyResolved) onDependencyResolved(instanceName);
1773
+ return container.get(token, args);
1774
+ },
1775
+ addDestroyListener,
1776
+ getDestroyListeners,
1777
+ container,
1778
+ deps
1779
+ };
1780
+ }
1781
+ };
1782
+
1783
+ //#endregion
1784
+ //#region src/internal/core/service-locator.mts
1785
+ /**
1786
+ * Core DI engine that coordinates service instantiation, resolution, and lifecycle.
1787
+ *
1788
+ * Acts as the central orchestrator for dependency injection operations,
1789
+ * delegating to specialized components (InstanceResolver, Instantiator, Invalidator)
1790
+ * for specific tasks.
1791
+ */ var ServiceLocator = class {
1792
+ registry;
1793
+ logger;
1794
+ injectors;
1795
+ eventBus;
1796
+ manager;
1797
+ instantiator;
1798
+ tokenProcessor;
1799
+ invalidator;
1800
+ instanceResolver;
1801
+ constructor(registry = globalRegistry, logger = null, injectors = defaultInjectors) {
1802
+ this.registry = registry;
1803
+ this.logger = logger;
1804
+ this.injectors = injectors;
1805
+ this.eventBus = new LifecycleEventBus(logger);
1806
+ this.manager = new HolderManager(logger);
1807
+ this.instantiator = new Instantiator(injectors);
1808
+ this.tokenProcessor = new TokenProcessor(logger);
1809
+ this.invalidator = new Invalidator(this.manager, this.eventBus, logger);
1810
+ this.instanceResolver = new InstanceResolver(this.registry, this.manager, this.instantiator, this.tokenProcessor, logger, this);
1811
+ }
1812
+ getEventBus() {
1813
+ return this.eventBus;
1814
+ }
1815
+ getManager() {
1816
+ return this.manager;
1817
+ }
1818
+ getInvalidator() {
1819
+ return this.invalidator;
1820
+ }
1821
+ getTokenProcessor() {
1822
+ return this.tokenProcessor;
1823
+ }
1824
+ getInstanceIdentifier(token, args) {
1825
+ const [err, { actualToken, validatedArgs }] = this.tokenProcessor.validateAndResolveTokenArgs(token, args);
1826
+ if (err) throw err;
1827
+ return this.tokenProcessor.generateInstanceName(actualToken, validatedArgs);
1828
+ }
1829
+ /**
1830
+ * Gets or creates an instance for the given token.
1831
+ * @param token The injection token
1832
+ * @param args Optional arguments
1833
+ * @param contextContainer The container to use for creating FactoryContext
1834
+ */ async getInstance(token, args, contextContainer) {
1835
+ const [err, data] = await this.instanceResolver.resolveInstance(token, args, contextContainer);
1836
+ if (err) return [err];
1837
+ return [void 0, data];
1838
+ }
1839
+ /**
1840
+ * Gets or throws an instance for the given token.
1841
+ * @param token The injection token
1842
+ * @param args Optional arguments
1843
+ * @param contextContainer The container to use for creating FactoryContext
1844
+ */ async getOrThrowInstance(token, args, contextContainer) {
1845
+ const [error, instance] = await this.getInstance(token, args, contextContainer);
1846
+ if (error) throw error;
1847
+ return instance;
1848
+ }
1849
+ /**
1850
+ * Resolves a request-scoped service for a ScopedContainer.
1851
+ * The service will be stored in the ScopedContainer's request context.
1852
+ *
1853
+ * @param token The injection token
1854
+ * @param args Optional arguments
1855
+ * @param scopedContainer The ScopedContainer that owns the request context
1856
+ */ async resolveRequestScoped(token, args, scopedContainer) {
1857
+ const [err, data] = await this.instanceResolver.resolveRequestScopedInstance(token, args, scopedContainer);
1858
+ if (err) throw err;
1859
+ return data;
1860
+ }
1861
+ getSyncInstance(token, args, contextContainer) {
1862
+ return this.instanceResolver.getSyncInstance(token, args, contextContainer);
1863
+ }
1864
+ invalidate(service, round = 1) {
1865
+ return this.invalidator.invalidate(service, round);
1866
+ }
1867
+ /**
1868
+ * Gracefully clears all services in the ServiceLocator using invalidation logic.
1869
+ * This method respects service dependencies and ensures proper cleanup order.
1870
+ * Services that depend on others will be invalidated first, then their dependencies.
1871
+ *
1872
+ * @param options Optional configuration for the clearing process
1873
+ * @returns Promise that resolves when all services have been cleared
1874
+ */ async clearAll(options = {}) {
1875
+ return this.invalidator.clearAll(options);
1876
+ }
1877
+ /**
1878
+ * Waits for all services to settle (either created, destroyed, or error state).
1879
+ */ async ready() {
1880
+ return this.invalidator.ready();
1881
+ }
1882
+ /**
1883
+ * Helper method for InstanceResolver to generate instance names.
1884
+ * This is needed for the factory context creation.
1885
+ */ generateInstanceName(token, args) {
1886
+ return this.tokenProcessor.generateInstanceName(token, args);
1887
+ }
1888
+ };
1889
+
1890
+ //#endregion
1891
+ //#region src/container/container.mts
1892
+ function applyDecs2203RFactory$1() {
1893
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
1894
+ return function addInitializer(initializer) {
1895
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
1896
+ assertCallable(initializer, "An initializer");
1897
+ initializers.push(initializer);
1898
+ };
1899
+ }
1900
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
1901
+ var kindStr;
1902
+ switch (kind) {
1903
+ case 1:
1904
+ kindStr = "accessor";
1905
+ break;
1906
+ case 2:
1907
+ kindStr = "method";
1908
+ break;
1909
+ case 3:
1910
+ kindStr = "getter";
1911
+ break;
1912
+ case 4:
1913
+ kindStr = "setter";
1914
+ break;
1915
+ default: kindStr = "field";
1916
+ }
1917
+ var ctx = {
1918
+ kind: kindStr,
1919
+ name: isPrivate ? "#" + name : name,
1920
+ static: isStatic,
1921
+ private: isPrivate,
1922
+ metadata
1923
+ };
1924
+ var decoratorFinishedRef = { v: false };
1925
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
1926
+ var get, set;
1927
+ if (kind === 0) if (isPrivate) {
1928
+ get = desc.get;
1929
+ set = desc.set;
1930
+ } else {
1931
+ get = function() {
1932
+ return this[name];
1933
+ };
1934
+ set = function(v) {
1935
+ this[name] = v;
1936
+ };
1937
+ }
1938
+ else if (kind === 2) get = function() {
1939
+ return desc.value;
1940
+ };
1941
+ else {
1942
+ if (kind === 1 || kind === 3) get = function() {
1943
+ return desc.get.call(this);
1944
+ };
1945
+ if (kind === 1 || kind === 4) set = function(v) {
1946
+ desc.set.call(this, v);
1947
+ };
1948
+ }
1949
+ ctx.access = get && set ? {
1950
+ get,
1951
+ set
1952
+ } : get ? { get } : { set };
1953
+ try {
1954
+ return dec(value, ctx);
1955
+ } finally {
1956
+ decoratorFinishedRef.v = true;
1957
+ }
1958
+ }
1959
+ function assertNotFinished(decoratorFinishedRef, fnName) {
1960
+ if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished");
1961
+ }
1962
+ function assertCallable(fn, hint) {
1963
+ if (typeof fn !== "function") throw new TypeError(hint + " must be a function");
1964
+ }
1965
+ function assertValidReturnValue(kind, value) {
1966
+ var type = typeof value;
1967
+ if (kind === 1) {
1968
+ if (type !== "object" || value === null) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
1969
+ if (value.get !== void 0) assertCallable(value.get, "accessor.get");
1970
+ if (value.set !== void 0) assertCallable(value.set, "accessor.set");
1971
+ if (value.init !== void 0) assertCallable(value.init, "accessor.init");
1972
+ } else if (type !== "function") {
1973
+ var hint;
1974
+ if (kind === 0) hint = "field";
1975
+ else if (kind === 10) hint = "class";
1976
+ else hint = "method";
1977
+ throw new TypeError(hint + " decorators must return a function or void 0");
1978
+ }
1979
+ }
1980
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
1981
+ var decs = decInfo[0];
1982
+ var desc, init, value;
1983
+ if (isPrivate) if (kind === 0 || kind === 1) desc = {
1984
+ get: decInfo[3],
1985
+ set: decInfo[4]
1986
+ };
1987
+ else if (kind === 3) desc = { get: decInfo[3] };
1988
+ else if (kind === 4) desc = { set: decInfo[3] };
1989
+ else desc = { value: decInfo[3] };
1990
+ else if (kind !== 0) desc = Object.getOwnPropertyDescriptor(base, name);
1991
+ if (kind === 1) value = {
1992
+ get: desc.get,
1993
+ set: desc.set
1994
+ };
1995
+ else if (kind === 2) value = desc.value;
1996
+ else if (kind === 3) value = desc.get;
1997
+ else if (kind === 4) value = desc.set;
1998
+ var newValue, get, set;
1999
+ if (typeof decs === "function") {
2000
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
2001
+ if (newValue !== void 0) {
2002
+ assertValidReturnValue(kind, newValue);
2003
+ if (kind === 0) init = newValue;
2004
+ else if (kind === 1) {
2005
+ init = newValue.init;
2006
+ get = newValue.get || value.get;
2007
+ set = newValue.set || value.set;
2008
+ value = {
2009
+ get,
2010
+ set
2011
+ };
2012
+ } else value = newValue;
2013
+ }
2014
+ } else for (var i = decs.length - 1; i >= 0; i--) {
2015
+ var dec = decs[i];
2016
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
2017
+ if (newValue !== void 0) {
2018
+ assertValidReturnValue(kind, newValue);
2019
+ var newInit;
2020
+ if (kind === 0) newInit = newValue;
2021
+ else if (kind === 1) {
2022
+ newInit = newValue.init;
2023
+ get = newValue.get || value.get;
2024
+ set = newValue.set || value.set;
2025
+ value = {
2026
+ get,
2027
+ set
2028
+ };
2029
+ } else value = newValue;
2030
+ if (newInit !== void 0) if (init === void 0) init = newInit;
2031
+ else if (typeof init === "function") init = [init, newInit];
2032
+ else init.push(newInit);
2033
+ }
2034
+ }
2035
+ if (kind === 0 || kind === 1) {
2036
+ if (init === void 0) init = function(instance, init$1) {
2037
+ return init$1;
2038
+ };
2039
+ else if (typeof init !== "function") {
2040
+ var ownInitializers = init;
2041
+ init = function(instance, init$1) {
2042
+ var value$1 = init$1;
2043
+ for (var i$1 = 0; i$1 < ownInitializers.length; i$1++) value$1 = ownInitializers[i$1].call(instance, value$1);
2044
+ return value$1;
2045
+ };
2046
+ } else {
2047
+ var originalInitializer = init;
2048
+ init = function(instance, init$1) {
2049
+ return originalInitializer.call(instance, init$1);
2050
+ };
2051
+ }
2052
+ ret.push(init);
2053
+ }
2054
+ if (kind !== 0) {
2055
+ if (kind === 1) {
2056
+ desc.get = value.get;
2057
+ desc.set = value.set;
2058
+ } else if (kind === 2) desc.value = value;
2059
+ else if (kind === 3) desc.get = value;
2060
+ else if (kind === 4) desc.set = value;
2061
+ if (isPrivate) if (kind === 1) {
2062
+ ret.push(function(instance, args) {
2063
+ return value.get.call(instance, args);
2064
+ });
2065
+ ret.push(function(instance, args) {
2066
+ return value.set.call(instance, args);
2067
+ });
2068
+ } else if (kind === 2) ret.push(value);
2069
+ else ret.push(function(instance, args) {
2070
+ return value.call(instance, args);
2071
+ });
2072
+ else Object.defineProperty(base, name, desc);
2073
+ }
2074
+ }
2075
+ function applyMemberDecs(Class, decInfos, metadata) {
2076
+ var ret = [];
2077
+ var protoInitializers;
2078
+ var staticInitializers;
2079
+ var existingProtoNonFields = /* @__PURE__ */ new Map();
2080
+ var existingStaticNonFields = /* @__PURE__ */ new Map();
2081
+ for (var i = 0; i < decInfos.length; i++) {
2082
+ var decInfo = decInfos[i];
2083
+ if (!Array.isArray(decInfo)) continue;
2084
+ var kind = decInfo[1];
2085
+ var name = decInfo[2];
2086
+ var isPrivate = decInfo.length > 3;
2087
+ var isStatic = kind >= 5;
2088
+ var base;
2089
+ var initializers;
2090
+ if (isStatic) {
2091
+ base = Class;
2092
+ kind = kind - 5;
2093
+ staticInitializers = staticInitializers || [];
2094
+ initializers = staticInitializers;
2095
+ } else {
2096
+ base = Class.prototype;
2097
+ protoInitializers = protoInitializers || [];
2098
+ initializers = protoInitializers;
2099
+ }
2100
+ if (kind !== 0 && !isPrivate) {
2101
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
2102
+ var existingKind = existingNonFields.get(name) || 0;
2103
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
2104
+ else if (!existingKind && kind > 2) existingNonFields.set(name, kind);
2105
+ else existingNonFields.set(name, true);
2106
+ }
2107
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
2108
+ }
2109
+ pushInitializers(ret, protoInitializers);
2110
+ pushInitializers(ret, staticInitializers);
2111
+ return ret;
2112
+ }
2113
+ function pushInitializers(ret, initializers) {
2114
+ if (initializers) ret.push(function(instance) {
2115
+ for (var i = 0; i < initializers.length; i++) initializers[i].call(instance);
2116
+ return instance;
2117
+ });
2118
+ }
2119
+ function applyClassDecs(targetClass, classDecs, metadata) {
2120
+ if (classDecs.length > 0) {
2121
+ var initializers = [];
2122
+ var newClass = targetClass;
2123
+ var name = targetClass.name;
2124
+ for (var i = classDecs.length - 1; i >= 0; i--) {
2125
+ var decoratorFinishedRef = { v: false };
2126
+ try {
2127
+ var nextNewClass = classDecs[i](newClass, {
2128
+ kind: "class",
2129
+ name,
2130
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
2131
+ metadata
2132
+ });
2133
+ } finally {
2134
+ decoratorFinishedRef.v = true;
2135
+ }
2136
+ if (nextNewClass !== void 0) {
2137
+ assertValidReturnValue(10, nextNewClass);
2138
+ newClass = nextNewClass;
2139
+ }
2140
+ }
2141
+ return [defineMetadata(newClass, metadata), function() {
2142
+ for (var i$1 = 0; i$1 < initializers.length; i$1++) initializers[i$1].call(newClass);
2143
+ }];
2144
+ }
2145
+ }
2146
+ function defineMetadata(Class, metadata) {
2147
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
2148
+ configurable: true,
2149
+ enumerable: true,
2150
+ value: metadata
2151
+ });
2152
+ }
2153
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
2154
+ if (parentClass !== void 0) var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
2155
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
2156
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
2157
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
2158
+ return {
2159
+ e,
2160
+ get c() {
2161
+ return applyClassDecs(targetClass, classDecs, metadata);
2162
+ }
2163
+ };
2164
+ };
2165
+ }
2166
+ function _apply_decs_2203_r$1(targetClass, memberDecs, classDecs, parentClass) {
2167
+ return (_apply_decs_2203_r$1 = applyDecs2203RFactory$1())(targetClass, memberDecs, classDecs, parentClass);
2168
+ }
2169
+ var _dec$1, _initClass$1;
2170
+ let _Container$1;
2171
+ _dec$1 = Injectable();
2172
+ var Container = class {
2173
+ registry;
2174
+ logger;
2175
+ injectors;
2176
+ static {
2177
+ ({c: [_Container$1, _initClass$1]} = _apply_decs_2203_r$1(this, [], [_dec$1]));
2178
+ }
2179
+ constructor(registry = globalRegistry, logger = null, injectors = defaultInjectors) {
2180
+ this.registry = registry;
2181
+ this.logger = logger;
2182
+ this.injectors = injectors;
2183
+ this.serviceLocator = new ServiceLocator(registry, logger, injectors);
2184
+ this.registerSelf();
2185
+ }
2186
+ serviceLocator;
2187
+ activeRequestIds = /* @__PURE__ */ new Set();
2188
+ registerSelf() {
2189
+ const token = getInjectableToken(_Container$1);
2190
+ const instanceName = this.serviceLocator.getInstanceIdentifier(token);
2191
+ this.serviceLocator.getManager().storeCreatedHolder(instanceName, this, InjectableType.Class, InjectableScope.Singleton);
2192
+ }
2193
+ async get(token, args) {
2194
+ const realToken = this.serviceLocator.getTokenProcessor().getRegistryToken(token);
2195
+ if (this.registry.has(realToken)) {
2196
+ if (this.registry.get(realToken).scope === InjectableScope.Request) throw DIError.unknown(`Cannot resolve request-scoped service "${String(realToken.name)}" from Container. Use beginRequest() to create a ScopedContainer for request-scoped services.`);
2197
+ }
2198
+ return this.serviceLocator.getOrThrowInstance(token, args, this);
2199
+ }
2200
+ /**
2201
+ * Gets an instance with a specific container context.
2202
+ * Used by ScopedContainer to delegate singleton/transient resolution
2203
+ * while maintaining the correct container context for nested inject() calls.
2204
+ *
2205
+ * @internal
2206
+ */ async getWithContext(token, args, contextContainer) {
2207
+ return this.serviceLocator.getOrThrowInstance(token, args, contextContainer);
2208
+ }
2209
+ /**
2210
+ * Resolves a request-scoped service for a ScopedContainer.
2211
+ * The service will be stored in the ScopedContainer's request context.
2212
+ *
2213
+ * @internal
2214
+ */ async resolveForRequest(token, args, scopedContainer) {
2215
+ return this.serviceLocator.resolveRequestScoped(token, args, scopedContainer);
2216
+ }
2217
+ /**
2218
+ * Gets the underlying ServiceLocator instance for advanced usage
2219
+ */ getServiceLocator() {
2220
+ return this.serviceLocator;
2221
+ }
2222
+ /**
2223
+ * Gets the registry
2224
+ */ getRegistry() {
2225
+ return this.registry;
2226
+ }
2227
+ /**
2228
+ * Invalidates a service and its dependencies
2229
+ */ async invalidate(service) {
2230
+ const holder = this.getHolderByInstance(service);
2231
+ if (holder) await this.serviceLocator.invalidate(holder.name);
2232
+ }
2233
+ /**
2234
+ * Gets a service holder by instance (reverse lookup)
2235
+ */ getHolderByInstance(instance) {
2236
+ const holderMap = Array.from(this.serviceLocator.getManager().filter((holder) => holder.instance === instance).values());
2237
+ return holderMap.length > 0 ? holderMap[0] : null;
2238
+ }
2239
+ /**
2240
+ * Checks if a service is registered in the container
2241
+ */ isRegistered(token) {
2242
+ try {
2243
+ return this.serviceLocator.getInstanceIdentifier(token) !== null;
2244
+ } catch {
2245
+ return false;
2246
+ }
2247
+ }
2248
+ /**
2249
+ * Disposes the container and cleans up all resources
2250
+ */ async dispose() {
2251
+ await this.serviceLocator.clearAll();
2252
+ }
2253
+ /**
2254
+ * Waits for all pending operations to complete
2255
+ */ async ready() {
2256
+ await this.serviceLocator.ready();
2257
+ }
2258
+ /**
2259
+ * @internal
2260
+ * Attempts to get an instance synchronously if it already exists.
2261
+ * Returns null if the instance doesn't exist or is not ready.
2262
+ */ tryGetSync(token, args) {
2263
+ return this.serviceLocator.getSyncInstance(token, args, this);
2264
+ }
2265
+ /**
2266
+ * Begins a new request context and returns a ScopedContainer.
2267
+ *
2268
+ * The ScopedContainer provides isolated request-scoped service resolution
2269
+ * while delegating singleton and transient services to this Container.
2270
+ *
2271
+ * @param requestId Unique identifier for this request
2272
+ * @param metadata Optional metadata for the request
2273
+ * @param priority Priority for resolution (higher = more priority)
2274
+ * @returns A ScopedContainer for this request
2275
+ */ beginRequest(requestId, metadata, priority = 100) {
2276
+ if (this.activeRequestIds.has(requestId)) throw DIError.unknown(`Request context "${requestId}" already exists. Use a unique request ID.`);
2277
+ this.activeRequestIds.add(requestId);
2278
+ this.logger?.log(`[Container] Started request context: ${requestId}`);
2279
+ return new ScopedContainer(this, this.registry, requestId, metadata, priority);
2280
+ }
2281
+ /**
2282
+ * Removes a request ID from the active set.
2283
+ * Called by ScopedContainer when the request ends.
2284
+ *
2285
+ * @internal
2286
+ */ removeActiveRequest(requestId) {
2287
+ this.activeRequestIds.delete(requestId);
2288
+ this.logger?.log(`[Container] Ended request context: ${requestId}`);
2289
+ }
2290
+ /**
2291
+ * Gets the set of active request IDs.
2292
+ */ getActiveRequestIds() {
2293
+ return this.activeRequestIds;
2294
+ }
2295
+ /**
2296
+ * Checks if a request ID is currently active.
2297
+ */ hasActiveRequest(requestId) {
2298
+ return this.activeRequestIds.has(requestId);
2299
+ }
2300
+ /**
2301
+ * Clears all instances and bindings from the container.
2302
+ * This is useful for testing or resetting the container state.
2303
+ */ clear() {
2304
+ return this.serviceLocator.clearAll();
2305
+ }
2306
+ static {
2307
+ _initClass$1();
2308
+ }
2309
+ };
2310
+
2311
+ //#endregion
2312
+ //#region src/testing/test-container.mts
2313
+ function applyDecs2203RFactory() {
2314
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
2315
+ return function addInitializer(initializer) {
2316
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
2317
+ assertCallable(initializer, "An initializer");
2318
+ initializers.push(initializer);
2319
+ };
2320
+ }
2321
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
2322
+ var kindStr;
2323
+ switch (kind) {
2324
+ case 1:
2325
+ kindStr = "accessor";
2326
+ break;
2327
+ case 2:
2328
+ kindStr = "method";
2329
+ break;
2330
+ case 3:
2331
+ kindStr = "getter";
2332
+ break;
2333
+ case 4:
2334
+ kindStr = "setter";
2335
+ break;
2336
+ default: kindStr = "field";
2337
+ }
2338
+ var ctx = {
2339
+ kind: kindStr,
2340
+ name: isPrivate ? "#" + name : name,
2341
+ static: isStatic,
2342
+ private: isPrivate,
2343
+ metadata
2344
+ };
2345
+ var decoratorFinishedRef = { v: false };
2346
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
2347
+ var get, set;
2348
+ if (kind === 0) if (isPrivate) {
2349
+ get = desc.get;
2350
+ set = desc.set;
2351
+ } else {
2352
+ get = function() {
2353
+ return this[name];
2354
+ };
2355
+ set = function(v) {
2356
+ this[name] = v;
2357
+ };
2358
+ }
2359
+ else if (kind === 2) get = function() {
2360
+ return desc.value;
2361
+ };
2362
+ else {
2363
+ if (kind === 1 || kind === 3) get = function() {
2364
+ return desc.get.call(this);
2365
+ };
2366
+ if (kind === 1 || kind === 4) set = function(v) {
2367
+ desc.set.call(this, v);
2368
+ };
2369
+ }
2370
+ ctx.access = get && set ? {
2371
+ get,
2372
+ set
2373
+ } : get ? { get } : { set };
2374
+ try {
2375
+ return dec(value, ctx);
2376
+ } finally {
2377
+ decoratorFinishedRef.v = true;
2378
+ }
2379
+ }
2380
+ function assertNotFinished(decoratorFinishedRef, fnName) {
2381
+ if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished");
2382
+ }
2383
+ function assertCallable(fn, hint) {
2384
+ if (typeof fn !== "function") throw new TypeError(hint + " must be a function");
2385
+ }
2386
+ function assertValidReturnValue(kind, value) {
2387
+ var type = typeof value;
2388
+ if (kind === 1) {
2389
+ if (type !== "object" || value === null) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
2390
+ if (value.get !== void 0) assertCallable(value.get, "accessor.get");
2391
+ if (value.set !== void 0) assertCallable(value.set, "accessor.set");
2392
+ if (value.init !== void 0) assertCallable(value.init, "accessor.init");
2393
+ } else if (type !== "function") {
2394
+ var hint;
2395
+ if (kind === 0) hint = "field";
2396
+ else if (kind === 10) hint = "class";
2397
+ else hint = "method";
2398
+ throw new TypeError(hint + " decorators must return a function or void 0");
2399
+ }
2400
+ }
2401
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
2402
+ var decs = decInfo[0];
2403
+ var desc, init, value;
2404
+ if (isPrivate) if (kind === 0 || kind === 1) desc = {
2405
+ get: decInfo[3],
2406
+ set: decInfo[4]
2407
+ };
2408
+ else if (kind === 3) desc = { get: decInfo[3] };
2409
+ else if (kind === 4) desc = { set: decInfo[3] };
2410
+ else desc = { value: decInfo[3] };
2411
+ else if (kind !== 0) desc = Object.getOwnPropertyDescriptor(base, name);
2412
+ if (kind === 1) value = {
2413
+ get: desc.get,
2414
+ set: desc.set
2415
+ };
2416
+ else if (kind === 2) value = desc.value;
2417
+ else if (kind === 3) value = desc.get;
2418
+ else if (kind === 4) value = desc.set;
2419
+ var newValue, get, set;
2420
+ if (typeof decs === "function") {
2421
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
2422
+ if (newValue !== void 0) {
2423
+ assertValidReturnValue(kind, newValue);
2424
+ if (kind === 0) init = newValue;
2425
+ else if (kind === 1) {
2426
+ init = newValue.init;
2427
+ get = newValue.get || value.get;
2428
+ set = newValue.set || value.set;
2429
+ value = {
2430
+ get,
2431
+ set
2432
+ };
2433
+ } else value = newValue;
2434
+ }
2435
+ } else for (var i = decs.length - 1; i >= 0; i--) {
2436
+ var dec = decs[i];
2437
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
2438
+ if (newValue !== void 0) {
2439
+ assertValidReturnValue(kind, newValue);
2440
+ var newInit;
2441
+ if (kind === 0) newInit = newValue;
2442
+ else if (kind === 1) {
2443
+ newInit = newValue.init;
2444
+ get = newValue.get || value.get;
2445
+ set = newValue.set || value.set;
2446
+ value = {
2447
+ get,
2448
+ set
2449
+ };
2450
+ } else value = newValue;
2451
+ if (newInit !== void 0) if (init === void 0) init = newInit;
2452
+ else if (typeof init === "function") init = [init, newInit];
2453
+ else init.push(newInit);
2454
+ }
2455
+ }
2456
+ if (kind === 0 || kind === 1) {
2457
+ if (init === void 0) init = function(instance, init$1) {
2458
+ return init$1;
2459
+ };
2460
+ else if (typeof init !== "function") {
2461
+ var ownInitializers = init;
2462
+ init = function(instance, init$1) {
2463
+ var value$1 = init$1;
2464
+ for (var i$1 = 0; i$1 < ownInitializers.length; i$1++) value$1 = ownInitializers[i$1].call(instance, value$1);
2465
+ return value$1;
2466
+ };
2467
+ } else {
2468
+ var originalInitializer = init;
2469
+ init = function(instance, init$1) {
2470
+ return originalInitializer.call(instance, init$1);
2471
+ };
2472
+ }
2473
+ ret.push(init);
2474
+ }
2475
+ if (kind !== 0) {
2476
+ if (kind === 1) {
2477
+ desc.get = value.get;
2478
+ desc.set = value.set;
2479
+ } else if (kind === 2) desc.value = value;
2480
+ else if (kind === 3) desc.get = value;
2481
+ else if (kind === 4) desc.set = value;
2482
+ if (isPrivate) if (kind === 1) {
2483
+ ret.push(function(instance, args) {
2484
+ return value.get.call(instance, args);
2485
+ });
2486
+ ret.push(function(instance, args) {
2487
+ return value.set.call(instance, args);
2488
+ });
2489
+ } else if (kind === 2) ret.push(value);
2490
+ else ret.push(function(instance, args) {
2491
+ return value.call(instance, args);
2492
+ });
2493
+ else Object.defineProperty(base, name, desc);
2494
+ }
2495
+ }
2496
+ function applyMemberDecs(Class, decInfos, metadata) {
2497
+ var ret = [];
2498
+ var protoInitializers;
2499
+ var staticInitializers;
2500
+ var existingProtoNonFields = /* @__PURE__ */ new Map();
2501
+ var existingStaticNonFields = /* @__PURE__ */ new Map();
2502
+ for (var i = 0; i < decInfos.length; i++) {
2503
+ var decInfo = decInfos[i];
2504
+ if (!Array.isArray(decInfo)) continue;
2505
+ var kind = decInfo[1];
2506
+ var name = decInfo[2];
2507
+ var isPrivate = decInfo.length > 3;
2508
+ var isStatic = kind >= 5;
2509
+ var base;
2510
+ var initializers;
2511
+ if (isStatic) {
2512
+ base = Class;
2513
+ kind = kind - 5;
2514
+ staticInitializers = staticInitializers || [];
2515
+ initializers = staticInitializers;
2516
+ } else {
2517
+ base = Class.prototype;
2518
+ protoInitializers = protoInitializers || [];
2519
+ initializers = protoInitializers;
2520
+ }
2521
+ if (kind !== 0 && !isPrivate) {
2522
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
2523
+ var existingKind = existingNonFields.get(name) || 0;
2524
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
2525
+ else if (!existingKind && kind > 2) existingNonFields.set(name, kind);
2526
+ else existingNonFields.set(name, true);
2527
+ }
2528
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
2529
+ }
2530
+ pushInitializers(ret, protoInitializers);
2531
+ pushInitializers(ret, staticInitializers);
2532
+ return ret;
2533
+ }
2534
+ function pushInitializers(ret, initializers) {
2535
+ if (initializers) ret.push(function(instance) {
2536
+ for (var i = 0; i < initializers.length; i++) initializers[i].call(instance);
2537
+ return instance;
2538
+ });
2539
+ }
2540
+ function applyClassDecs(targetClass, classDecs, metadata) {
2541
+ if (classDecs.length > 0) {
2542
+ var initializers = [];
2543
+ var newClass = targetClass;
2544
+ var name = targetClass.name;
2545
+ for (var i = classDecs.length - 1; i >= 0; i--) {
2546
+ var decoratorFinishedRef = { v: false };
2547
+ try {
2548
+ var nextNewClass = classDecs[i](newClass, {
2549
+ kind: "class",
2550
+ name,
2551
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
2552
+ metadata
2553
+ });
2554
+ } finally {
2555
+ decoratorFinishedRef.v = true;
2556
+ }
2557
+ if (nextNewClass !== void 0) {
2558
+ assertValidReturnValue(10, nextNewClass);
2559
+ newClass = nextNewClass;
2560
+ }
2561
+ }
2562
+ return [defineMetadata(newClass, metadata), function() {
2563
+ for (var i$1 = 0; i$1 < initializers.length; i$1++) initializers[i$1].call(newClass);
2564
+ }];
2565
+ }
2566
+ }
2567
+ function defineMetadata(Class, metadata) {
2568
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
2569
+ configurable: true,
2570
+ enumerable: true,
2571
+ value: metadata
2572
+ });
2573
+ }
2574
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
2575
+ if (parentClass !== void 0) var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
2576
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
2577
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
2578
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
2579
+ return {
2580
+ e,
2581
+ get c() {
2582
+ return applyClassDecs(targetClass, classDecs, metadata);
2583
+ }
2584
+ };
2585
+ };
2586
+ }
2587
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
2588
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
2589
+ }
2590
+ var _dec, _initClass, _Container;
2591
+ /**
2592
+ * A binding builder for the TestContainer that allows chaining binding operations.
2593
+ */ var TestBindingBuilder = class {
2594
+ container;
2595
+ token;
2596
+ constructor(container, token) {
2597
+ this.container = container;
2598
+ this.token = token;
2599
+ }
2600
+ /**
2601
+ * Binds the token to a specific value.
2602
+ * This is useful for testing with mock values or constants.
2603
+ * @param value The value to bind to the token
2604
+ */ toValue(value) {
2605
+ const instanceName = this.container.getServiceLocator().getInstanceIdentifier(this.token);
2606
+ this.container.getServiceLocator().getManager().storeCreatedHolder(instanceName, value, InjectableType.Class, InjectableScope.Singleton);
2607
+ return this.container;
2608
+ }
2609
+ /**
2610
+ * Binds the token to a class constructor.
2611
+ * @param target The class constructor to bind to
2612
+ */ toClass(target) {
2613
+ this.container["registry"].set(this.token, InjectableScope.Singleton, target, InjectableType.Class);
2614
+ return this.container;
2615
+ }
2616
+ };
2617
+ let _TestContainer;
2618
+ _dec = Injectable();
2619
+ var TestContainer = class extends (_Container = _Container$1) {
2620
+ static {
2621
+ ({c: [_TestContainer, _initClass]} = _apply_decs_2203_r(this, [], [_dec], _Container));
2622
+ }
2623
+ constructor(registry = globalRegistry, logger = null, injectors = void 0) {
2624
+ super(registry, logger, injectors);
2625
+ }
2626
+ bind(token) {
2627
+ let realToken = token;
2628
+ if (typeof token === "function") realToken = getInjectableToken(token);
2629
+ return new TestBindingBuilder(this, realToken);
2630
+ }
2631
+ bindValue(token, value) {
2632
+ return this.bind(token).toValue(value);
2633
+ }
2634
+ bindClass(token, target) {
2635
+ return this.bind(token).toClass(target);
2636
+ }
2637
+ /**
2638
+ * Creates a new TestContainer instance with the same configuration.
2639
+ * This is useful for creating isolated test containers.
2640
+ * @returns A new TestContainer instance
2641
+ */ createChild() {
2642
+ return new _TestContainer(this.registry, this.logger, this.injectors);
2643
+ }
2644
+ static {
2645
+ _initClass();
2646
+ }
2647
+ };
2648
+
2649
+ //#endregion
2650
+ Object.defineProperty(exports, 'BaseHolderManager', {
2651
+ enumerable: true,
2652
+ get: function () {
2653
+ return BaseHolderManager;
2654
+ }
2655
+ });
2656
+ Object.defineProperty(exports, 'BoundInjectionToken', {
2657
+ enumerable: true,
2658
+ get: function () {
2659
+ return BoundInjectionToken;
2660
+ }
2661
+ });
2662
+ Object.defineProperty(exports, 'CircularDetector', {
2663
+ enumerable: true,
2664
+ get: function () {
2665
+ return CircularDetector;
2666
+ }
2667
+ });
2668
+ Object.defineProperty(exports, 'DIError', {
2669
+ enumerable: true,
2670
+ get: function () {
2671
+ return DIError;
2672
+ }
2673
+ });
2674
+ Object.defineProperty(exports, 'DIErrorCode', {
2675
+ enumerable: true,
2676
+ get: function () {
2677
+ return DIErrorCode;
2678
+ }
2679
+ });
2680
+ Object.defineProperty(exports, 'DefaultRequestContext', {
2681
+ enumerable: true,
2682
+ get: function () {
2683
+ return DefaultRequestContext;
2684
+ }
2685
+ });
2686
+ Object.defineProperty(exports, 'FactoryInjectionToken', {
2687
+ enumerable: true,
2688
+ get: function () {
2689
+ return FactoryInjectionToken;
2690
+ }
2691
+ });
2692
+ Object.defineProperty(exports, 'HolderManager', {
2693
+ enumerable: true,
2694
+ get: function () {
2695
+ return HolderManager;
2696
+ }
2697
+ });
2698
+ Object.defineProperty(exports, 'Injectable', {
2699
+ enumerable: true,
2700
+ get: function () {
2701
+ return Injectable;
2702
+ }
2703
+ });
2704
+ Object.defineProperty(exports, 'InjectableScope', {
2705
+ enumerable: true,
2706
+ get: function () {
2707
+ return InjectableScope;
2708
+ }
2709
+ });
2710
+ Object.defineProperty(exports, 'InjectableTokenMeta', {
2711
+ enumerable: true,
2712
+ get: function () {
2713
+ return InjectableTokenMeta;
2714
+ }
2715
+ });
2716
+ Object.defineProperty(exports, 'InjectableType', {
2717
+ enumerable: true,
2718
+ get: function () {
2719
+ return InjectableType;
2720
+ }
2721
+ });
2722
+ Object.defineProperty(exports, 'InjectionToken', {
2723
+ enumerable: true,
2724
+ get: function () {
2725
+ return InjectionToken;
2726
+ }
2727
+ });
2728
+ Object.defineProperty(exports, 'InstanceResolver', {
2729
+ enumerable: true,
2730
+ get: function () {
2731
+ return InstanceResolver;
2732
+ }
2733
+ });
2734
+ Object.defineProperty(exports, 'InstanceStatus', {
2735
+ enumerable: true,
2736
+ get: function () {
2737
+ return InstanceStatus;
2738
+ }
2739
+ });
2740
+ Object.defineProperty(exports, 'Instantiator', {
2741
+ enumerable: true,
2742
+ get: function () {
2743
+ return Instantiator;
2744
+ }
2745
+ });
2746
+ Object.defineProperty(exports, 'Invalidator', {
2747
+ enumerable: true,
2748
+ get: function () {
2749
+ return Invalidator;
2750
+ }
2751
+ });
2752
+ Object.defineProperty(exports, 'LifecycleEventBus', {
2753
+ enumerable: true,
2754
+ get: function () {
2755
+ return LifecycleEventBus;
2756
+ }
2757
+ });
2758
+ Object.defineProperty(exports, 'Registry', {
2759
+ enumerable: true,
2760
+ get: function () {
2761
+ return Registry;
2762
+ }
2763
+ });
2764
+ Object.defineProperty(exports, 'RequestStorage', {
2765
+ enumerable: true,
2766
+ get: function () {
2767
+ return RequestStorage;
2768
+ }
2769
+ });
2770
+ Object.defineProperty(exports, 'ScopedContainer', {
2771
+ enumerable: true,
2772
+ get: function () {
2773
+ return ScopedContainer;
2774
+ }
2775
+ });
2776
+ Object.defineProperty(exports, 'ServiceLocator', {
2777
+ enumerable: true,
2778
+ get: function () {
2779
+ return ServiceLocator;
2780
+ }
2781
+ });
2782
+ Object.defineProperty(exports, 'SingletonStorage', {
2783
+ enumerable: true,
2784
+ get: function () {
2785
+ return SingletonStorage;
2786
+ }
2787
+ });
2788
+ Object.defineProperty(exports, 'TestBindingBuilder', {
2789
+ enumerable: true,
2790
+ get: function () {
2791
+ return TestBindingBuilder;
2792
+ }
2793
+ });
2794
+ Object.defineProperty(exports, 'TokenProcessor', {
2795
+ enumerable: true,
2796
+ get: function () {
2797
+ return TokenProcessor;
2798
+ }
2799
+ });
2800
+ Object.defineProperty(exports, '_Container', {
2801
+ enumerable: true,
2802
+ get: function () {
2803
+ return _Container$1;
2804
+ }
2805
+ });
2806
+ Object.defineProperty(exports, '_TestContainer', {
2807
+ enumerable: true,
2808
+ get: function () {
2809
+ return _TestContainer;
2810
+ }
2811
+ });
2812
+ Object.defineProperty(exports, 'asyncInject', {
2813
+ enumerable: true,
2814
+ get: function () {
2815
+ return asyncInject;
2816
+ }
2817
+ });
2818
+ Object.defineProperty(exports, 'createRequestContext', {
2819
+ enumerable: true,
2820
+ get: function () {
2821
+ return createRequestContext;
2822
+ }
2823
+ });
2824
+ Object.defineProperty(exports, 'defaultInjectors', {
2825
+ enumerable: true,
2826
+ get: function () {
2827
+ return defaultInjectors;
2828
+ }
2829
+ });
2830
+ Object.defineProperty(exports, 'getCurrentResolutionContext', {
2831
+ enumerable: true,
2832
+ get: function () {
2833
+ return getCurrentResolutionContext;
2834
+ }
2835
+ });
2836
+ Object.defineProperty(exports, 'getInjectableToken', {
2837
+ enumerable: true,
2838
+ get: function () {
2839
+ return getInjectableToken;
2840
+ }
2841
+ });
2842
+ Object.defineProperty(exports, 'getInjectors', {
2843
+ enumerable: true,
2844
+ get: function () {
2845
+ return getInjectors;
2846
+ }
2847
+ });
2848
+ Object.defineProperty(exports, 'globalRegistry', {
2849
+ enumerable: true,
2850
+ get: function () {
2851
+ return globalRegistry;
2852
+ }
2853
+ });
2854
+ Object.defineProperty(exports, 'inject', {
2855
+ enumerable: true,
2856
+ get: function () {
2857
+ return inject;
2858
+ }
2859
+ });
2860
+ Object.defineProperty(exports, 'optional', {
2861
+ enumerable: true,
2862
+ get: function () {
2863
+ return optional;
2864
+ }
2865
+ });
2866
+ Object.defineProperty(exports, 'provideFactoryContext', {
2867
+ enumerable: true,
2868
+ get: function () {
2869
+ return provideFactoryContext;
2870
+ }
2871
+ });
2872
+ Object.defineProperty(exports, 'resolutionContext', {
2873
+ enumerable: true,
2874
+ get: function () {
2875
+ return resolutionContext;
2876
+ }
2877
+ });
2878
+ Object.defineProperty(exports, 'withResolutionContext', {
2879
+ enumerable: true,
2880
+ get: function () {
2881
+ return withResolutionContext;
2882
+ }
2883
+ });
2884
+ Object.defineProperty(exports, 'withoutResolutionContext', {
2885
+ enumerable: true,
2886
+ get: function () {
2887
+ return withoutResolutionContext;
2888
+ }
2889
+ });
2890
+ Object.defineProperty(exports, 'wrapSyncInit', {
2891
+ enumerable: true,
2892
+ get: function () {
2893
+ return wrapSyncInit;
2894
+ }
2895
+ });
2896
+ //# sourceMappingURL=testing-DIaIRiJz.cjs.map