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