@navios/di 0.4.0 → 0.4.2
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/lib/_tsup-dts-rollup.d.mts +77 -5
- package/lib/_tsup-dts-rollup.d.ts +77 -5
- package/lib/chunk-3NLYPYBY.mjs +1627 -0
- package/lib/chunk-3NLYPYBY.mjs.map +1 -0
- package/lib/index.js +11 -1
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +4 -1599
- package/lib/index.mjs.map +1 -1
- package/lib/testing/index.d.mts +2 -0
- package/lib/testing/index.d.ts +2 -0
- package/lib/testing/index.js +1642 -0
- package/lib/testing/index.js.map +1 -0
- package/lib/testing/index.mjs +73 -0
- package/lib/testing/index.mjs.map +1 -0
- package/package.json +11 -1
- package/src/container.mts +11 -3
- package/src/event-emitter.mts +5 -5
- package/src/testing/README.md +80 -0
- package/src/testing/__tests__/test-container.spec.mts +173 -0
- package/src/testing/index.mts +1 -0
- package/src/testing/test-container.mts +120 -0
- package/tsup.config.mts +1 -1
|
@@ -0,0 +1,1627 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
|
|
5
|
+
var __typeError = (msg) => {
|
|
6
|
+
throw TypeError(msg);
|
|
7
|
+
};
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
9
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
10
|
+
var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
|
|
11
|
+
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
|
|
12
|
+
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
|
|
13
|
+
var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
|
|
14
|
+
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
|
|
15
|
+
var __runInitializers = (array, flags, self, value) => {
|
|
16
|
+
for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
|
|
17
|
+
return value;
|
|
18
|
+
};
|
|
19
|
+
var __decorateElement = (array, flags, name, decorators, target, extra) => {
|
|
20
|
+
var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
|
|
21
|
+
var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
|
|
22
|
+
var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
|
|
23
|
+
var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
|
|
24
|
+
return __privateGet(this, extra);
|
|
25
|
+
}, set [name](x) {
|
|
26
|
+
return __privateSet(this, extra, x);
|
|
27
|
+
} }, name));
|
|
28
|
+
k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
|
|
29
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
30
|
+
ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
|
|
31
|
+
if (k) {
|
|
32
|
+
ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
|
|
33
|
+
if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
|
|
34
|
+
if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
|
|
35
|
+
}
|
|
36
|
+
it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
|
|
37
|
+
if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
|
|
38
|
+
else if (typeof it !== "object" || it === null) __typeError("Object expected");
|
|
39
|
+
else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
|
|
40
|
+
}
|
|
41
|
+
return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
|
|
42
|
+
};
|
|
43
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
44
|
+
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
|
|
45
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
46
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
47
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
48
|
+
|
|
49
|
+
// src/enums/injectable-scope.enum.mts
|
|
50
|
+
var InjectableScope = /* @__PURE__ */ ((InjectableScope5) => {
|
|
51
|
+
InjectableScope5["Singleton"] = "Singleton";
|
|
52
|
+
InjectableScope5["Transient"] = "Transient";
|
|
53
|
+
InjectableScope5["Request"] = "Request";
|
|
54
|
+
return InjectableScope5;
|
|
55
|
+
})(InjectableScope || {});
|
|
56
|
+
|
|
57
|
+
// src/enums/injectable-type.enum.mts
|
|
58
|
+
var InjectableType = /* @__PURE__ */ ((InjectableType5) => {
|
|
59
|
+
InjectableType5["Class"] = "Class";
|
|
60
|
+
InjectableType5["Factory"] = "Factory";
|
|
61
|
+
return InjectableType5;
|
|
62
|
+
})(InjectableType || {});
|
|
63
|
+
|
|
64
|
+
// src/injection-token.mts
|
|
65
|
+
var InjectionToken = class _InjectionToken {
|
|
66
|
+
constructor(name, schema) {
|
|
67
|
+
this.name = name;
|
|
68
|
+
this.schema = schema;
|
|
69
|
+
}
|
|
70
|
+
id = globalThis.crypto.randomUUID();
|
|
71
|
+
formattedName = null;
|
|
72
|
+
static create(name, schema) {
|
|
73
|
+
return new _InjectionToken(name, schema);
|
|
74
|
+
}
|
|
75
|
+
static bound(token, value) {
|
|
76
|
+
return new BoundInjectionToken(token, value);
|
|
77
|
+
}
|
|
78
|
+
static factory(token, factory) {
|
|
79
|
+
return new FactoryInjectionToken(token, factory);
|
|
80
|
+
}
|
|
81
|
+
static refineType(token) {
|
|
82
|
+
return token;
|
|
83
|
+
}
|
|
84
|
+
toString() {
|
|
85
|
+
if (this.formattedName) {
|
|
86
|
+
return this.formattedName;
|
|
87
|
+
}
|
|
88
|
+
const { name } = this;
|
|
89
|
+
if (typeof name === "function") {
|
|
90
|
+
const className = name.name;
|
|
91
|
+
this.formattedName = `${className}(${this.id})`;
|
|
92
|
+
} else if (typeof name === "symbol") {
|
|
93
|
+
this.formattedName = `${name.toString()}(${this.id})`;
|
|
94
|
+
} else {
|
|
95
|
+
this.formattedName = `${name}(${this.id})`;
|
|
96
|
+
}
|
|
97
|
+
return this.formattedName;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
var BoundInjectionToken = class {
|
|
101
|
+
constructor(token, value) {
|
|
102
|
+
this.token = token;
|
|
103
|
+
this.value = value;
|
|
104
|
+
this.name = token.name;
|
|
105
|
+
this.id = token.id;
|
|
106
|
+
this.schema = token.schema;
|
|
107
|
+
}
|
|
108
|
+
id;
|
|
109
|
+
name;
|
|
110
|
+
schema;
|
|
111
|
+
toString() {
|
|
112
|
+
return this.token.toString();
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
var FactoryInjectionToken = class {
|
|
116
|
+
constructor(token, factory) {
|
|
117
|
+
this.token = token;
|
|
118
|
+
this.factory = factory;
|
|
119
|
+
this.name = token.name;
|
|
120
|
+
this.id = token.id;
|
|
121
|
+
this.schema = token.schema;
|
|
122
|
+
}
|
|
123
|
+
value;
|
|
124
|
+
resolved = false;
|
|
125
|
+
id;
|
|
126
|
+
name;
|
|
127
|
+
schema;
|
|
128
|
+
async resolve(ctx) {
|
|
129
|
+
if (!this.value) {
|
|
130
|
+
this.value = await this.factory(ctx);
|
|
131
|
+
this.resolved = true;
|
|
132
|
+
}
|
|
133
|
+
return this.value;
|
|
134
|
+
}
|
|
135
|
+
toString() {
|
|
136
|
+
return this.token.toString();
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
// src/registry.mts
|
|
141
|
+
var Registry = class {
|
|
142
|
+
constructor(parent) {
|
|
143
|
+
this.parent = parent;
|
|
144
|
+
}
|
|
145
|
+
factories = /* @__PURE__ */ new Map();
|
|
146
|
+
has(token) {
|
|
147
|
+
if (this.factories.has(token.id)) {
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
if (this.parent) {
|
|
151
|
+
return this.parent.has(token);
|
|
152
|
+
}
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
get(token) {
|
|
156
|
+
const factory = this.factories.get(token.id);
|
|
157
|
+
if (!factory) {
|
|
158
|
+
if (this.parent) {
|
|
159
|
+
return this.parent.get(token);
|
|
160
|
+
}
|
|
161
|
+
throw new Error(`[Registry] No factory found for ${token.toString()}`);
|
|
162
|
+
}
|
|
163
|
+
return factory;
|
|
164
|
+
}
|
|
165
|
+
set(token, scope, target, type) {
|
|
166
|
+
this.factories.set(token.id, { scope, originalToken: token, target, type });
|
|
167
|
+
}
|
|
168
|
+
delete(token) {
|
|
169
|
+
this.factories.delete(token.id);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
var globalRegistry = new Registry();
|
|
173
|
+
|
|
174
|
+
// src/symbols/injectable-token.mts
|
|
175
|
+
var InjectableTokenMeta = Symbol.for("InjectableTokenMeta");
|
|
176
|
+
function Injectable({
|
|
177
|
+
scope = "Singleton" /* Singleton */,
|
|
178
|
+
token,
|
|
179
|
+
registry = globalRegistry
|
|
180
|
+
} = {}) {
|
|
181
|
+
return (target, context) => {
|
|
182
|
+
if (context && context.kind !== "class" || target instanceof Function && !context) {
|
|
183
|
+
throw new Error(
|
|
184
|
+
"[ServiceLocator] @Injectable decorator can only be used on classes."
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
let injectableToken = token ?? InjectionToken.create(target);
|
|
188
|
+
registry.set(injectableToken, scope, target, "Class" /* Class */);
|
|
189
|
+
target[InjectableTokenMeta] = injectableToken;
|
|
190
|
+
return target;
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// src/errors/errors.enum.mts
|
|
195
|
+
var ErrorsEnum = /* @__PURE__ */ ((ErrorsEnum2) => {
|
|
196
|
+
ErrorsEnum2["InstanceExpired"] = "InstanceExpired";
|
|
197
|
+
ErrorsEnum2["InstanceNotFound"] = "InstanceNotFound";
|
|
198
|
+
ErrorsEnum2["InstanceDestroying"] = "InstanceDestroying";
|
|
199
|
+
ErrorsEnum2["UnknownError"] = "UnknownError";
|
|
200
|
+
ErrorsEnum2["FactoryNotFound"] = "FactoryNotFound";
|
|
201
|
+
ErrorsEnum2["FactoryTokenNotResolved"] = "FactoryTokenNotResolved";
|
|
202
|
+
return ErrorsEnum2;
|
|
203
|
+
})(ErrorsEnum || {});
|
|
204
|
+
|
|
205
|
+
// src/errors/factory-not-found.mts
|
|
206
|
+
var FactoryNotFound = class extends Error {
|
|
207
|
+
constructor(name) {
|
|
208
|
+
super(`Factory ${name} not found`);
|
|
209
|
+
this.name = name;
|
|
210
|
+
}
|
|
211
|
+
code = "FactoryNotFound" /* FactoryNotFound */;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
// src/errors/factory-token-not-resolved.mts
|
|
215
|
+
var FactoryTokenNotResolved = class extends Error {
|
|
216
|
+
code = "FactoryTokenNotResolved" /* FactoryTokenNotResolved */;
|
|
217
|
+
constructor(name) {
|
|
218
|
+
super(`Factory token not resolved: ${name.toString()}`);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
// src/errors/instance-destroying.mts
|
|
223
|
+
var InstanceDestroying = class extends Error {
|
|
224
|
+
constructor(name) {
|
|
225
|
+
super(`Instance ${name} destroying`);
|
|
226
|
+
this.name = name;
|
|
227
|
+
}
|
|
228
|
+
code = "InstanceDestroying" /* InstanceDestroying */;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
// src/errors/instance-expired.mts
|
|
232
|
+
var InstanceExpired = class extends Error {
|
|
233
|
+
constructor(name) {
|
|
234
|
+
super(`Instance ${name} expired`);
|
|
235
|
+
this.name = name;
|
|
236
|
+
}
|
|
237
|
+
code = "InstanceExpired" /* InstanceExpired */;
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// src/errors/instance-not-found.mts
|
|
241
|
+
var InstanceNotFound = class extends Error {
|
|
242
|
+
constructor(name) {
|
|
243
|
+
super(`Instance ${name} not found`);
|
|
244
|
+
this.name = name;
|
|
245
|
+
}
|
|
246
|
+
code = "InstanceNotFound" /* InstanceNotFound */;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// src/errors/unknown-error.mts
|
|
250
|
+
var UnknownError = class extends Error {
|
|
251
|
+
code = "UnknownError" /* UnknownError */;
|
|
252
|
+
parent;
|
|
253
|
+
constructor(message) {
|
|
254
|
+
if (message instanceof Error) {
|
|
255
|
+
super(message.message);
|
|
256
|
+
this.parent = message;
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
super(message);
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
// src/utils/get-injectors.mts
|
|
264
|
+
function getInjectors() {
|
|
265
|
+
let currentFactoryContext = null;
|
|
266
|
+
function provideFactoryContext2(context) {
|
|
267
|
+
const original = currentFactoryContext;
|
|
268
|
+
currentFactoryContext = context;
|
|
269
|
+
return original;
|
|
270
|
+
}
|
|
271
|
+
function getFactoryContext() {
|
|
272
|
+
if (!currentFactoryContext) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
"[Injector] Trying to access injection context outside of a injectable context"
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
return currentFactoryContext;
|
|
278
|
+
}
|
|
279
|
+
let promiseCollector = null;
|
|
280
|
+
let injectState = null;
|
|
281
|
+
function asyncInject2(token, args) {
|
|
282
|
+
if (!injectState) {
|
|
283
|
+
throw new Error(
|
|
284
|
+
"[Injector] Trying to access inject outside of a injectable context"
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
if (injectState.isFrozen) {
|
|
288
|
+
const idx = injectState.currentIndex++;
|
|
289
|
+
const request = injectState.requests[idx];
|
|
290
|
+
if (request.token !== token) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
`[Injector] Wrong token order. Expected ${request.token.toString()} but got ${token.toString()}`
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
return request.promise;
|
|
296
|
+
}
|
|
297
|
+
const promise = getFactoryContext().inject(token, args);
|
|
298
|
+
injectState.requests.push({
|
|
299
|
+
token,
|
|
300
|
+
promise
|
|
301
|
+
});
|
|
302
|
+
injectState.currentIndex++;
|
|
303
|
+
return promise;
|
|
304
|
+
}
|
|
305
|
+
function wrapSyncInit2(cb) {
|
|
306
|
+
return (previousState) => {
|
|
307
|
+
const promises = [];
|
|
308
|
+
const originalPromiseCollector = promiseCollector;
|
|
309
|
+
const originalInjectState = injectState;
|
|
310
|
+
injectState = previousState ? {
|
|
311
|
+
...previousState,
|
|
312
|
+
currentIndex: 0
|
|
313
|
+
} : {
|
|
314
|
+
currentIndex: 0,
|
|
315
|
+
isFrozen: false,
|
|
316
|
+
requests: []
|
|
317
|
+
};
|
|
318
|
+
promiseCollector = (promise) => {
|
|
319
|
+
promises.push(promise);
|
|
320
|
+
};
|
|
321
|
+
const result = cb();
|
|
322
|
+
promiseCollector = originalPromiseCollector;
|
|
323
|
+
const newInjectState = {
|
|
324
|
+
...injectState,
|
|
325
|
+
isFrozen: true
|
|
326
|
+
};
|
|
327
|
+
injectState = originalInjectState;
|
|
328
|
+
return [result, promises, newInjectState];
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
function inject2(token, args) {
|
|
332
|
+
const realToken = token[InjectableTokenMeta] ?? token;
|
|
333
|
+
const instance = getFactoryContext().locator.getSyncInstance(
|
|
334
|
+
realToken,
|
|
335
|
+
args
|
|
336
|
+
);
|
|
337
|
+
if (!instance) {
|
|
338
|
+
if (promiseCollector) {
|
|
339
|
+
const promise = getFactoryContext().inject(realToken, args);
|
|
340
|
+
promiseCollector(promise);
|
|
341
|
+
} else {
|
|
342
|
+
throw new Error(`[Injector] Cannot initiate ${realToken.toString()}`);
|
|
343
|
+
}
|
|
344
|
+
return new Proxy(
|
|
345
|
+
{},
|
|
346
|
+
{
|
|
347
|
+
get() {
|
|
348
|
+
throw new Error(
|
|
349
|
+
`[Injector] Trying to access ${realToken.toString()} before it's initialized, please use asyncInject() instead of inject() or do not use the value outside of class methods`
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
return instance;
|
|
356
|
+
}
|
|
357
|
+
const injectors = {
|
|
358
|
+
asyncInject: asyncInject2,
|
|
359
|
+
inject: inject2,
|
|
360
|
+
wrapSyncInit: wrapSyncInit2,
|
|
361
|
+
provideFactoryContext: provideFactoryContext2
|
|
362
|
+
};
|
|
363
|
+
return injectors;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// src/utils/get-injectable-token.mts
|
|
367
|
+
function getInjectableToken(target) {
|
|
368
|
+
const token = target[InjectableTokenMeta];
|
|
369
|
+
if (!token) {
|
|
370
|
+
throw new Error(
|
|
371
|
+
`[ServiceLocator] Class ${target.name} is not decorated with @Injectable.`
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
return token;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// src/utils/defer.mts
|
|
378
|
+
var Deferred = class {
|
|
379
|
+
promise;
|
|
380
|
+
_resolve;
|
|
381
|
+
_reject;
|
|
382
|
+
_isResolved = false;
|
|
383
|
+
_isRejected = false;
|
|
384
|
+
constructor() {
|
|
385
|
+
this.promise = new Promise((resolve, reject) => {
|
|
386
|
+
this._resolve = resolve;
|
|
387
|
+
this._reject = reject;
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Resolves the deferred promise with the given value.
|
|
392
|
+
* @param value The value to resolve with
|
|
393
|
+
* @throws Error if the promise has already been resolved or rejected
|
|
394
|
+
*/
|
|
395
|
+
resolve(value) {
|
|
396
|
+
if (this._isResolved || this._isRejected) {
|
|
397
|
+
throw new Error("Deferred promise has already been resolved or rejected");
|
|
398
|
+
}
|
|
399
|
+
this._isResolved = true;
|
|
400
|
+
this._resolve(value);
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Rejects the deferred promise with the given reason.
|
|
404
|
+
* @param reason The reason for rejection
|
|
405
|
+
* @throws Error if the promise has already been resolved or rejected
|
|
406
|
+
*/
|
|
407
|
+
reject(reason) {
|
|
408
|
+
if (this._isResolved || this._isRejected) {
|
|
409
|
+
throw new Error("Deferred promise has already been resolved or rejected");
|
|
410
|
+
}
|
|
411
|
+
this._isRejected = true;
|
|
412
|
+
this._reject(reason);
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Returns true if the promise has been resolved.
|
|
416
|
+
*/
|
|
417
|
+
get isResolved() {
|
|
418
|
+
return this._isResolved;
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Returns true if the promise has been rejected.
|
|
422
|
+
*/
|
|
423
|
+
get isRejected() {
|
|
424
|
+
return this._isRejected;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Returns true if the promise has been settled (resolved or rejected).
|
|
428
|
+
*/
|
|
429
|
+
get isSettled() {
|
|
430
|
+
return this._isResolved || this._isRejected;
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
function createDeferred() {
|
|
434
|
+
return new Deferred();
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// src/service-locator-instance-holder.mts
|
|
438
|
+
var ServiceLocatorInstanceHolderStatus = /* @__PURE__ */ ((ServiceLocatorInstanceHolderStatus3) => {
|
|
439
|
+
ServiceLocatorInstanceHolderStatus3["Created"] = "created";
|
|
440
|
+
ServiceLocatorInstanceHolderStatus3["Creating"] = "creating";
|
|
441
|
+
ServiceLocatorInstanceHolderStatus3["Destroying"] = "destroying";
|
|
442
|
+
ServiceLocatorInstanceHolderStatus3["Error"] = "error";
|
|
443
|
+
return ServiceLocatorInstanceHolderStatus3;
|
|
444
|
+
})(ServiceLocatorInstanceHolderStatus || {});
|
|
445
|
+
|
|
446
|
+
// src/base-instance-holder-manager.mts
|
|
447
|
+
var BaseInstanceHolderManager = class {
|
|
448
|
+
constructor(logger = null) {
|
|
449
|
+
this.logger = logger;
|
|
450
|
+
this._holders = /* @__PURE__ */ new Map();
|
|
451
|
+
}
|
|
452
|
+
_holders;
|
|
453
|
+
/**
|
|
454
|
+
* Protected getter for accessing the holders map from subclasses.
|
|
455
|
+
*/
|
|
456
|
+
get holders() {
|
|
457
|
+
return this._holders;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Deletes a holder by name.
|
|
461
|
+
* @param name The name of the holder to delete
|
|
462
|
+
* @returns true if the holder was deleted, false if it didn't exist
|
|
463
|
+
*/
|
|
464
|
+
delete(name) {
|
|
465
|
+
return this._holders.delete(name);
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Filters holders based on a predicate function.
|
|
469
|
+
* @param predicate Function to test each holder
|
|
470
|
+
* @returns A new Map containing only the holders that match the predicate
|
|
471
|
+
*/
|
|
472
|
+
filter(predicate) {
|
|
473
|
+
return new Map(
|
|
474
|
+
[...this._holders].filter(([key, value]) => predicate(value, key))
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Clears all holders from this manager.
|
|
479
|
+
*/
|
|
480
|
+
clear() {
|
|
481
|
+
this._holders.clear();
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Gets the number of holders currently managed.
|
|
485
|
+
*/
|
|
486
|
+
size() {
|
|
487
|
+
return this._holders.size;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Creates a new holder with Creating status and a deferred creation promise.
|
|
491
|
+
* This is useful for creating placeholder holders that can be fulfilled later.
|
|
492
|
+
* @param name The name of the instance
|
|
493
|
+
* @param type The injectable type
|
|
494
|
+
* @param scope The injectable scope
|
|
495
|
+
* @param deps Optional set of dependencies
|
|
496
|
+
* @param ttl Optional time-to-live in milliseconds (defaults to Infinity)
|
|
497
|
+
* @returns A tuple containing the deferred promise and the holder
|
|
498
|
+
*/
|
|
499
|
+
createCreatingHolder(name, type, scope, deps = /* @__PURE__ */ new Set(), ttl = Infinity) {
|
|
500
|
+
const deferred = createDeferred();
|
|
501
|
+
const holder = {
|
|
502
|
+
status: "creating" /* Creating */,
|
|
503
|
+
name,
|
|
504
|
+
instance: null,
|
|
505
|
+
creationPromise: deferred.promise,
|
|
506
|
+
destroyPromise: null,
|
|
507
|
+
type,
|
|
508
|
+
scope,
|
|
509
|
+
deps,
|
|
510
|
+
destroyListeners: [],
|
|
511
|
+
createdAt: Date.now(),
|
|
512
|
+
ttl
|
|
513
|
+
};
|
|
514
|
+
return [deferred, holder];
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Creates a new holder with Created status and an actual instance.
|
|
518
|
+
* This is useful for creating holders that already have their instance ready.
|
|
519
|
+
* @param name The name of the instance
|
|
520
|
+
* @param instance The actual instance to store
|
|
521
|
+
* @param type The injectable type
|
|
522
|
+
* @param scope The injectable scope
|
|
523
|
+
* @param deps Optional set of dependencies
|
|
524
|
+
* @param ttl Optional time-to-live in milliseconds (defaults to Infinity)
|
|
525
|
+
* @returns The created holder
|
|
526
|
+
*/
|
|
527
|
+
createCreatedHolder(name, instance, type, scope, deps = /* @__PURE__ */ new Set(), ttl = Infinity) {
|
|
528
|
+
const holder = {
|
|
529
|
+
status: "created" /* Created */,
|
|
530
|
+
name,
|
|
531
|
+
instance,
|
|
532
|
+
creationPromise: null,
|
|
533
|
+
destroyPromise: null,
|
|
534
|
+
type,
|
|
535
|
+
scope,
|
|
536
|
+
deps,
|
|
537
|
+
destroyListeners: [],
|
|
538
|
+
createdAt: Date.now(),
|
|
539
|
+
ttl
|
|
540
|
+
};
|
|
541
|
+
return holder;
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Gets all holder names currently managed.
|
|
545
|
+
*/
|
|
546
|
+
getAllNames() {
|
|
547
|
+
return Array.from(this._holders.keys());
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Gets all holders currently managed.
|
|
551
|
+
*/
|
|
552
|
+
getAllHolders() {
|
|
553
|
+
return Array.from(this._holders.values());
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Checks if this manager has any holders.
|
|
557
|
+
*/
|
|
558
|
+
isEmpty() {
|
|
559
|
+
return this._holders.size === 0;
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
// src/injector.mts
|
|
564
|
+
var defaultInjectors = getInjectors();
|
|
565
|
+
var asyncInject = defaultInjectors.asyncInject;
|
|
566
|
+
var inject = defaultInjectors.inject;
|
|
567
|
+
var wrapSyncInit = defaultInjectors.wrapSyncInit;
|
|
568
|
+
var provideFactoryContext = defaultInjectors.provideFactoryContext;
|
|
569
|
+
|
|
570
|
+
// src/service-instantiator.mts
|
|
571
|
+
var ServiceInstantiator = class {
|
|
572
|
+
constructor(injectors) {
|
|
573
|
+
this.injectors = injectors;
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Instantiates a service based on its registry record.
|
|
577
|
+
* @param ctx The factory context for dependency injection
|
|
578
|
+
* @param record The factory record from the registry
|
|
579
|
+
* @param args Optional arguments for the service
|
|
580
|
+
* @returns Promise resolving to [undefined, instance] or [error]
|
|
581
|
+
*/
|
|
582
|
+
async instantiateService(ctx, record, args = void 0) {
|
|
583
|
+
try {
|
|
584
|
+
switch (record.type) {
|
|
585
|
+
case "Class" /* Class */:
|
|
586
|
+
return this.instantiateClass(ctx, record, args);
|
|
587
|
+
case "Factory" /* Factory */:
|
|
588
|
+
return this.instantiateFactory(ctx, record, args);
|
|
589
|
+
default:
|
|
590
|
+
throw new Error(
|
|
591
|
+
`[ServiceInstantiator] Unknown service type: ${record.type}`
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
} catch (error) {
|
|
595
|
+
return [error instanceof Error ? error : new Error(String(error))];
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Instantiates a class-based service (Injectable decorator).
|
|
600
|
+
* @param ctx The factory context for dependency injection
|
|
601
|
+
* @param record The factory record from the registry
|
|
602
|
+
* @param args Optional arguments for the service constructor
|
|
603
|
+
* @returns Promise resolving to [undefined, instance] or [error]
|
|
604
|
+
*/
|
|
605
|
+
async instantiateClass(ctx, record, args) {
|
|
606
|
+
try {
|
|
607
|
+
const tryLoad = this.injectors.wrapSyncInit(() => {
|
|
608
|
+
const original = this.injectors.provideFactoryContext(ctx);
|
|
609
|
+
let result = new record.target(...args ? [args] : []);
|
|
610
|
+
this.injectors.provideFactoryContext(original);
|
|
611
|
+
return result;
|
|
612
|
+
});
|
|
613
|
+
let [instance, promises, injectState] = tryLoad();
|
|
614
|
+
if (promises.length > 0) {
|
|
615
|
+
const results = await Promise.allSettled(promises);
|
|
616
|
+
if (results.some((result) => result.status === "rejected")) {
|
|
617
|
+
throw new Error(
|
|
618
|
+
`[ServiceInstantiator] Service ${record.target.name} cannot be instantiated.`
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
const newRes = tryLoad(injectState);
|
|
622
|
+
instance = newRes[0];
|
|
623
|
+
promises = newRes[1];
|
|
624
|
+
}
|
|
625
|
+
if (promises.length > 0) {
|
|
626
|
+
console.error(`[ServiceInstantiator] ${record.target.name} has problem with it's definition.
|
|
627
|
+
|
|
628
|
+
One or more of the dependencies are registered as a InjectableScope.Instance and are used with inject.
|
|
629
|
+
|
|
630
|
+
Please use inject asyncInject of inject to load those dependencies.`);
|
|
631
|
+
throw new Error(
|
|
632
|
+
`[ServiceInstantiator] Service ${record.target.name} cannot be instantiated.`
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
if ("onServiceInit" in instance) {
|
|
636
|
+
await instance.onServiceInit();
|
|
637
|
+
}
|
|
638
|
+
if ("onServiceDestroy" in instance) {
|
|
639
|
+
ctx.addDestroyListener(async () => {
|
|
640
|
+
await instance.onServiceDestroy();
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
return [void 0, instance];
|
|
644
|
+
} catch (error) {
|
|
645
|
+
return [error instanceof Error ? error : new Error(String(error))];
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Instantiates a factory-based service (Factory decorator).
|
|
650
|
+
* @param ctx The factory context for dependency injection
|
|
651
|
+
* @param record The factory record from the registry
|
|
652
|
+
* @param args Optional arguments for the factory
|
|
653
|
+
* @returns Promise resolving to [undefined, instance] or [error]
|
|
654
|
+
*/
|
|
655
|
+
async instantiateFactory(ctx, record, args) {
|
|
656
|
+
try {
|
|
657
|
+
const tryLoad = this.injectors.wrapSyncInit(() => {
|
|
658
|
+
const original = this.injectors.provideFactoryContext(ctx);
|
|
659
|
+
let result = new record.target();
|
|
660
|
+
this.injectors.provideFactoryContext(original);
|
|
661
|
+
return result;
|
|
662
|
+
});
|
|
663
|
+
let [builder, promises, injectState] = tryLoad();
|
|
664
|
+
if (promises.length > 0) {
|
|
665
|
+
const results = await Promise.allSettled(promises);
|
|
666
|
+
if (results.some((result) => result.status === "rejected")) {
|
|
667
|
+
throw new Error(
|
|
668
|
+
`[ServiceInstantiator] Service ${record.target.name} cannot be instantiated.`
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
const newRes = tryLoad(injectState);
|
|
672
|
+
builder = newRes[0];
|
|
673
|
+
promises = newRes[1];
|
|
674
|
+
}
|
|
675
|
+
if (promises.length > 0) {
|
|
676
|
+
console.error(`[ServiceInstantiator] ${record.target.name} has problem with it's definition.
|
|
677
|
+
|
|
678
|
+
One or more of the dependencies are registered as a InjectableScope.Instance and are used with inject.
|
|
679
|
+
|
|
680
|
+
Please use asyncInject instead of inject to load those dependencies.`);
|
|
681
|
+
throw new Error(
|
|
682
|
+
`[ServiceInstantiator] Service ${record.target.name} cannot be instantiated.`
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
if (typeof builder.create !== "function") {
|
|
686
|
+
throw new Error(
|
|
687
|
+
`[ServiceInstantiator] Factory ${record.target.name} does not implement the create method.`
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
const instance = await builder.create(ctx, args);
|
|
691
|
+
return [void 0, instance];
|
|
692
|
+
} catch (error) {
|
|
693
|
+
return [error instanceof Error ? error : new Error(String(error))];
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
|
|
698
|
+
// src/request-context-holder.mts
|
|
699
|
+
var DefaultRequestContextHolder = class extends BaseInstanceHolderManager {
|
|
700
|
+
constructor(requestId, priority = 100, initialMetadata) {
|
|
701
|
+
super(null);
|
|
702
|
+
this.requestId = requestId;
|
|
703
|
+
this.priority = priority;
|
|
704
|
+
if (initialMetadata) {
|
|
705
|
+
Object.entries(initialMetadata).forEach(([key, value]) => {
|
|
706
|
+
this.metadata.set(key, value);
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
metadata = /* @__PURE__ */ new Map();
|
|
711
|
+
createdAt = Date.now();
|
|
712
|
+
/**
|
|
713
|
+
* Public getter for holders to maintain interface compatibility.
|
|
714
|
+
*/
|
|
715
|
+
get holders() {
|
|
716
|
+
return this._holders;
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Gets a holder by name. For RequestContextHolder, this is a simple lookup.
|
|
720
|
+
*/
|
|
721
|
+
get(name) {
|
|
722
|
+
return this._holders.get(name);
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Sets a holder by name.
|
|
726
|
+
*/
|
|
727
|
+
set(name, holder) {
|
|
728
|
+
this._holders.set(name, holder);
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Checks if a holder exists by name.
|
|
732
|
+
*/
|
|
733
|
+
has(name) {
|
|
734
|
+
return this._holders.has(name);
|
|
735
|
+
}
|
|
736
|
+
addInstance(instanceName, instance, holder) {
|
|
737
|
+
if (instanceName instanceof InjectionToken) {
|
|
738
|
+
const name = instanceName.toString();
|
|
739
|
+
const createdHolder = this.createCreatedHolder(
|
|
740
|
+
name,
|
|
741
|
+
instance,
|
|
742
|
+
"Class" /* Class */,
|
|
743
|
+
"Singleton" /* Singleton */,
|
|
744
|
+
/* @__PURE__ */ new Set(),
|
|
745
|
+
Infinity
|
|
746
|
+
);
|
|
747
|
+
this._holders.set(name, createdHolder);
|
|
748
|
+
} else {
|
|
749
|
+
if (!holder) {
|
|
750
|
+
throw new Error("Holder is required when adding an instance by name");
|
|
751
|
+
}
|
|
752
|
+
this._holders.set(instanceName, holder);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
clear() {
|
|
756
|
+
super.clear();
|
|
757
|
+
this.metadata.clear();
|
|
758
|
+
}
|
|
759
|
+
getMetadata(key) {
|
|
760
|
+
return this.metadata.get(key);
|
|
761
|
+
}
|
|
762
|
+
setMetadata(key, value) {
|
|
763
|
+
this.metadata.set(key, value);
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
function createRequestContextHolder(requestId, priority = 100, initialMetadata) {
|
|
767
|
+
return new DefaultRequestContextHolder(requestId, priority, initialMetadata);
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
// src/service-locator-event-bus.mts
|
|
771
|
+
var ServiceLocatorEventBus = class {
|
|
772
|
+
constructor(logger = null) {
|
|
773
|
+
this.logger = logger;
|
|
774
|
+
}
|
|
775
|
+
listeners = /* @__PURE__ */ new Map();
|
|
776
|
+
on(ns, event, listener) {
|
|
777
|
+
this.logger?.debug(`[ServiceLocatorEventBus]#on(): ns:${ns} event:${event}`);
|
|
778
|
+
if (!this.listeners.has(ns)) {
|
|
779
|
+
this.listeners.set(ns, /* @__PURE__ */ new Map());
|
|
780
|
+
}
|
|
781
|
+
const nsEvents = this.listeners.get(ns);
|
|
782
|
+
if (!nsEvents.has(event)) {
|
|
783
|
+
nsEvents.set(event, /* @__PURE__ */ new Set());
|
|
784
|
+
}
|
|
785
|
+
nsEvents.get(event).add(listener);
|
|
786
|
+
return () => {
|
|
787
|
+
nsEvents.get(event).delete(listener);
|
|
788
|
+
if (nsEvents.get(event)?.size === 0) {
|
|
789
|
+
nsEvents.delete(event);
|
|
790
|
+
}
|
|
791
|
+
if (nsEvents.size === 0) {
|
|
792
|
+
this.listeners.delete(ns);
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
async emit(key, event) {
|
|
797
|
+
if (!this.listeners.has(key)) {
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
const events = this.listeners.get(key);
|
|
801
|
+
this.logger?.debug(`[ServiceLocatorEventBus]#emit(): ${key}:${event}`);
|
|
802
|
+
const res = await Promise.allSettled(
|
|
803
|
+
[...events.get(event) ?? []].map((listener) => listener(event))
|
|
804
|
+
).then((results) => {
|
|
805
|
+
const res2 = results.filter((result) => result.status === "rejected").map((result) => {
|
|
806
|
+
this.logger?.warn(
|
|
807
|
+
`[ServiceLocatorEventBus]#emit(): ${key}:${event} rejected with`,
|
|
808
|
+
result.reason
|
|
809
|
+
);
|
|
810
|
+
return result;
|
|
811
|
+
});
|
|
812
|
+
if (res2.length > 0) {
|
|
813
|
+
return Promise.reject(res2);
|
|
814
|
+
}
|
|
815
|
+
return results;
|
|
816
|
+
});
|
|
817
|
+
return res;
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
|
|
821
|
+
// src/service-locator-manager.mts
|
|
822
|
+
var ServiceLocatorManager = class extends BaseInstanceHolderManager {
|
|
823
|
+
constructor(logger = null) {
|
|
824
|
+
super(logger);
|
|
825
|
+
}
|
|
826
|
+
get(name) {
|
|
827
|
+
const holder = this._holders.get(name);
|
|
828
|
+
if (holder) {
|
|
829
|
+
if (holder.ttl !== Infinity) {
|
|
830
|
+
const now = Date.now();
|
|
831
|
+
if (now - holder.createdAt > holder.ttl) {
|
|
832
|
+
this.logger?.log(
|
|
833
|
+
`[ServiceLocatorManager]#getInstanceHolder() TTL expired for ${holder.name}`
|
|
834
|
+
);
|
|
835
|
+
return [new InstanceExpired(holder.name), holder];
|
|
836
|
+
}
|
|
837
|
+
} else if (holder.status === "destroying" /* Destroying */) {
|
|
838
|
+
this.logger?.log(
|
|
839
|
+
`[ServiceLocatorManager]#getInstanceHolder() Instance ${holder.name} is destroying`
|
|
840
|
+
);
|
|
841
|
+
return [new InstanceDestroying(holder.name), holder];
|
|
842
|
+
} else if (holder.status === "error" /* Error */) {
|
|
843
|
+
this.logger?.log(
|
|
844
|
+
`[ServiceLocatorManager]#getInstanceHolder() Instance ${holder.name} is in error state`
|
|
845
|
+
);
|
|
846
|
+
return [holder.instance, holder];
|
|
847
|
+
}
|
|
848
|
+
return [void 0, holder];
|
|
849
|
+
} else {
|
|
850
|
+
this.logger?.log(
|
|
851
|
+
`[ServiceLocatorManager]#getInstanceHolder() Instance ${name} not found`
|
|
852
|
+
);
|
|
853
|
+
return [new InstanceNotFound(name)];
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
set(name, holder) {
|
|
857
|
+
this._holders.set(name, holder);
|
|
858
|
+
}
|
|
859
|
+
has(name) {
|
|
860
|
+
const [error, holder] = this.get(name);
|
|
861
|
+
if (!error) {
|
|
862
|
+
return [void 0, true];
|
|
863
|
+
}
|
|
864
|
+
if (["InstanceExpired" /* InstanceExpired */, "InstanceDestroying" /* InstanceDestroying */].includes(
|
|
865
|
+
error.code
|
|
866
|
+
)) {
|
|
867
|
+
return [error];
|
|
868
|
+
}
|
|
869
|
+
return [void 0, !!holder];
|
|
870
|
+
}
|
|
871
|
+
// delete and filter methods are inherited from BaseInstanceHolderManager
|
|
872
|
+
// createCreatingHolder method is inherited from BaseInstanceHolderManager
|
|
873
|
+
/**
|
|
874
|
+
* Creates a new holder with Created status and an actual instance.
|
|
875
|
+
* This is useful for creating holders that already have their instance ready.
|
|
876
|
+
* @param name The name of the instance
|
|
877
|
+
* @param instance The actual instance to store
|
|
878
|
+
* @param type The injectable type
|
|
879
|
+
* @param scope The injectable scope
|
|
880
|
+
* @param deps Optional set of dependencies
|
|
881
|
+
* @param ttl Optional time-to-live in milliseconds (defaults to Infinity)
|
|
882
|
+
* @returns The created holder
|
|
883
|
+
*/
|
|
884
|
+
storeCreatedHolder(name, instance, type, scope, deps = /* @__PURE__ */ new Set(), ttl = Infinity) {
|
|
885
|
+
const holder = this.createCreatedHolder(
|
|
886
|
+
name,
|
|
887
|
+
instance,
|
|
888
|
+
type,
|
|
889
|
+
scope,
|
|
890
|
+
deps,
|
|
891
|
+
ttl
|
|
892
|
+
);
|
|
893
|
+
this._holders.set(name, holder);
|
|
894
|
+
return holder;
|
|
895
|
+
}
|
|
896
|
+
};
|
|
897
|
+
|
|
898
|
+
// src/service-locator.mts
|
|
899
|
+
var ServiceLocator = class {
|
|
900
|
+
constructor(registry = globalRegistry, logger = null, injectors = defaultInjectors) {
|
|
901
|
+
this.registry = registry;
|
|
902
|
+
this.logger = logger;
|
|
903
|
+
this.injectors = injectors;
|
|
904
|
+
this.eventBus = new ServiceLocatorEventBus(logger);
|
|
905
|
+
this.manager = new ServiceLocatorManager(logger);
|
|
906
|
+
this.serviceInstantiator = new ServiceInstantiator(injectors);
|
|
907
|
+
}
|
|
908
|
+
eventBus;
|
|
909
|
+
manager;
|
|
910
|
+
serviceInstantiator;
|
|
911
|
+
requestContexts = /* @__PURE__ */ new Map();
|
|
912
|
+
currentRequestContext = null;
|
|
913
|
+
// ============================================================================
|
|
914
|
+
// PUBLIC METHODS
|
|
915
|
+
// ============================================================================
|
|
916
|
+
getEventBus() {
|
|
917
|
+
return this.eventBus;
|
|
918
|
+
}
|
|
919
|
+
getManager() {
|
|
920
|
+
return this.manager;
|
|
921
|
+
}
|
|
922
|
+
getInstanceIdentifier(token, args) {
|
|
923
|
+
const [err, { actualToken, validatedArgs }] = this.validateAndResolveTokenArgs(token, args);
|
|
924
|
+
if (err) {
|
|
925
|
+
throw err;
|
|
926
|
+
}
|
|
927
|
+
return this.generateInstanceName(actualToken, validatedArgs);
|
|
928
|
+
}
|
|
929
|
+
async getInstance(token, args, onPrepare) {
|
|
930
|
+
const [err, data] = await this.resolveTokenAndPrepareInstanceName(
|
|
931
|
+
token,
|
|
932
|
+
args
|
|
933
|
+
);
|
|
934
|
+
if (err) {
|
|
935
|
+
return [err];
|
|
936
|
+
}
|
|
937
|
+
const { instanceName, validatedArgs, actualToken, realToken } = data;
|
|
938
|
+
onPrepare?.({ instanceName, actualToken, validatedArgs });
|
|
939
|
+
const [error, holder] = await this.retrieveOrCreateInstanceByInstanceName(
|
|
940
|
+
instanceName,
|
|
941
|
+
realToken,
|
|
942
|
+
validatedArgs
|
|
943
|
+
);
|
|
944
|
+
if (error) {
|
|
945
|
+
return [error];
|
|
946
|
+
}
|
|
947
|
+
return [void 0, holder.instance];
|
|
948
|
+
}
|
|
949
|
+
async getOrThrowInstance(token, args) {
|
|
950
|
+
const [error, instance] = await this.getInstance(token, args);
|
|
951
|
+
if (error) {
|
|
952
|
+
throw error;
|
|
953
|
+
}
|
|
954
|
+
return instance;
|
|
955
|
+
}
|
|
956
|
+
getSyncInstance(token, args) {
|
|
957
|
+
const [err, { actualToken, validatedArgs }] = this.validateAndResolveTokenArgs(token, args);
|
|
958
|
+
if (err) {
|
|
959
|
+
return null;
|
|
960
|
+
}
|
|
961
|
+
const instanceName = this.generateInstanceName(actualToken, validatedArgs);
|
|
962
|
+
if (this.currentRequestContext) {
|
|
963
|
+
const requestHolder = this.currentRequestContext.get(instanceName);
|
|
964
|
+
if (requestHolder) {
|
|
965
|
+
return requestHolder.instance;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
const [error, holder] = this.manager.get(instanceName);
|
|
969
|
+
if (error) {
|
|
970
|
+
return null;
|
|
971
|
+
}
|
|
972
|
+
return holder.instance;
|
|
973
|
+
}
|
|
974
|
+
invalidate(service, round = 1) {
|
|
975
|
+
this.logger?.log(
|
|
976
|
+
`[ServiceLocator] Starting invalidation process for ${service}`
|
|
977
|
+
);
|
|
978
|
+
const toInvalidate = this.manager.filter(
|
|
979
|
+
(holder) => holder.name === service || holder.deps.has(service)
|
|
980
|
+
);
|
|
981
|
+
const promises = [];
|
|
982
|
+
for (const [key, holder] of toInvalidate.entries()) {
|
|
983
|
+
promises.push(this.invalidateHolder(key, holder, round));
|
|
984
|
+
}
|
|
985
|
+
return Promise.all(promises);
|
|
986
|
+
}
|
|
987
|
+
/**
|
|
988
|
+
* Invalidates a single holder based on its current status.
|
|
989
|
+
*/
|
|
990
|
+
async invalidateHolder(key, holder, round) {
|
|
991
|
+
switch (holder.status) {
|
|
992
|
+
case "destroying" /* Destroying */:
|
|
993
|
+
this.logger?.trace(`[ServiceLocator] ${key} is already being destroyed`);
|
|
994
|
+
await holder.destroyPromise;
|
|
995
|
+
break;
|
|
996
|
+
case "creating" /* Creating */:
|
|
997
|
+
this.logger?.trace(
|
|
998
|
+
`[ServiceLocator] ${key} is being created, waiting...`
|
|
999
|
+
);
|
|
1000
|
+
await holder.creationPromise;
|
|
1001
|
+
if (round > 3) {
|
|
1002
|
+
this.logger?.error(
|
|
1003
|
+
`[ServiceLocator] ${key} creation triggered too many invalidation rounds`
|
|
1004
|
+
);
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
await this.invalidate(key, round + 1);
|
|
1008
|
+
break;
|
|
1009
|
+
default:
|
|
1010
|
+
await this.destroyHolder(key, holder);
|
|
1011
|
+
break;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Destroys a holder and cleans up its resources.
|
|
1016
|
+
*/
|
|
1017
|
+
async destroyHolder(key, holder) {
|
|
1018
|
+
holder.status = "destroying" /* Destroying */;
|
|
1019
|
+
this.logger?.log(
|
|
1020
|
+
`[ServiceLocator] Invalidating ${key} and notifying listeners`
|
|
1021
|
+
);
|
|
1022
|
+
holder.destroyPromise = Promise.all(
|
|
1023
|
+
holder.destroyListeners.map((listener) => listener())
|
|
1024
|
+
).then(async () => {
|
|
1025
|
+
this.manager.delete(key);
|
|
1026
|
+
await this.emitInstanceEvent(key, "destroy");
|
|
1027
|
+
});
|
|
1028
|
+
await holder.destroyPromise;
|
|
1029
|
+
}
|
|
1030
|
+
async ready() {
|
|
1031
|
+
const holders = Array.from(this.manager.filter(() => true)).map(
|
|
1032
|
+
([, holder]) => holder
|
|
1033
|
+
);
|
|
1034
|
+
await Promise.all(
|
|
1035
|
+
holders.map((holder) => this.waitForHolderToSettle(holder))
|
|
1036
|
+
);
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Waits for a holder to settle (either created, destroyed, or error state).
|
|
1040
|
+
*/
|
|
1041
|
+
async waitForHolderToSettle(holder) {
|
|
1042
|
+
switch (holder.status) {
|
|
1043
|
+
case "creating" /* Creating */:
|
|
1044
|
+
await holder.creationPromise;
|
|
1045
|
+
break;
|
|
1046
|
+
case "destroying" /* Destroying */:
|
|
1047
|
+
await holder.destroyPromise;
|
|
1048
|
+
break;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
// ============================================================================
|
|
1052
|
+
// REQUEST CONTEXT MANAGEMENT
|
|
1053
|
+
// ============================================================================
|
|
1054
|
+
/**
|
|
1055
|
+
* Begins a new request context with the given parameters.
|
|
1056
|
+
* @param requestId Unique identifier for this request
|
|
1057
|
+
* @param metadata Optional metadata for the request
|
|
1058
|
+
* @param priority Priority for resolution (higher = more priority)
|
|
1059
|
+
* @returns The created request context holder
|
|
1060
|
+
*/
|
|
1061
|
+
beginRequest(requestId, metadata, priority = 100) {
|
|
1062
|
+
if (this.requestContexts.has(requestId)) {
|
|
1063
|
+
throw new Error(
|
|
1064
|
+
`[ServiceLocator] Request context ${requestId} already exists`
|
|
1065
|
+
);
|
|
1066
|
+
}
|
|
1067
|
+
const contextHolder = new DefaultRequestContextHolder(
|
|
1068
|
+
requestId,
|
|
1069
|
+
priority,
|
|
1070
|
+
metadata
|
|
1071
|
+
);
|
|
1072
|
+
this.requestContexts.set(requestId, contextHolder);
|
|
1073
|
+
this.currentRequestContext = contextHolder;
|
|
1074
|
+
this.logger?.log(`[ServiceLocator] Started request context: ${requestId}`);
|
|
1075
|
+
return contextHolder;
|
|
1076
|
+
}
|
|
1077
|
+
/**
|
|
1078
|
+
* Ends a request context and cleans up all associated instances.
|
|
1079
|
+
* @param requestId The request ID to end
|
|
1080
|
+
*/
|
|
1081
|
+
async endRequest(requestId) {
|
|
1082
|
+
const contextHolder = this.requestContexts.get(requestId);
|
|
1083
|
+
if (!contextHolder) {
|
|
1084
|
+
this.logger?.warn(
|
|
1085
|
+
`[ServiceLocator] Request context ${requestId} not found`
|
|
1086
|
+
);
|
|
1087
|
+
return;
|
|
1088
|
+
}
|
|
1089
|
+
this.logger?.log(`[ServiceLocator] Ending request context: ${requestId}`);
|
|
1090
|
+
const cleanupPromises = [];
|
|
1091
|
+
for (const [, holder] of contextHolder.holders) {
|
|
1092
|
+
if (holder.destroyListeners.length > 0) {
|
|
1093
|
+
cleanupPromises.push(
|
|
1094
|
+
Promise.all(holder.destroyListeners.map((listener) => listener()))
|
|
1095
|
+
);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
await Promise.all(cleanupPromises);
|
|
1099
|
+
contextHolder.clear();
|
|
1100
|
+
this.requestContexts.delete(requestId);
|
|
1101
|
+
if (this.currentRequestContext === contextHolder) {
|
|
1102
|
+
this.currentRequestContext = Array.from(this.requestContexts.values()).at(-1) ?? null;
|
|
1103
|
+
}
|
|
1104
|
+
this.logger?.log(`[ServiceLocator] Request context ${requestId} ended`);
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* Gets the current request context.
|
|
1108
|
+
* @returns The current request context holder or null
|
|
1109
|
+
*/
|
|
1110
|
+
getCurrentRequestContext() {
|
|
1111
|
+
return this.currentRequestContext;
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Sets the current request context.
|
|
1115
|
+
* @param requestId The request ID to set as current
|
|
1116
|
+
*/
|
|
1117
|
+
setCurrentRequestContext(requestId) {
|
|
1118
|
+
const contextHolder = this.requestContexts.get(requestId);
|
|
1119
|
+
if (!contextHolder) {
|
|
1120
|
+
throw new Error(`[ServiceLocator] Request context ${requestId} not found`);
|
|
1121
|
+
}
|
|
1122
|
+
this.currentRequestContext = contextHolder;
|
|
1123
|
+
}
|
|
1124
|
+
// ============================================================================
|
|
1125
|
+
// PRIVATE METHODS
|
|
1126
|
+
// ============================================================================
|
|
1127
|
+
/**
|
|
1128
|
+
* Validates and resolves token arguments, handling factory token resolution and validation.
|
|
1129
|
+
*/
|
|
1130
|
+
validateAndResolveTokenArgs(token, args) {
|
|
1131
|
+
let actualToken = token;
|
|
1132
|
+
if (typeof token === "function") {
|
|
1133
|
+
actualToken = getInjectableToken(token);
|
|
1134
|
+
}
|
|
1135
|
+
let realArgs = args;
|
|
1136
|
+
if (actualToken instanceof BoundInjectionToken) {
|
|
1137
|
+
realArgs = actualToken.value;
|
|
1138
|
+
} else if (actualToken instanceof FactoryInjectionToken) {
|
|
1139
|
+
if (actualToken.resolved) {
|
|
1140
|
+
realArgs = actualToken.value;
|
|
1141
|
+
} else {
|
|
1142
|
+
return [new FactoryTokenNotResolved(token.name), { actualToken }];
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
if (!actualToken.schema) {
|
|
1146
|
+
return [void 0, { actualToken, validatedArgs: realArgs }];
|
|
1147
|
+
}
|
|
1148
|
+
const validatedArgs = actualToken.schema?.safeParse(realArgs);
|
|
1149
|
+
if (validatedArgs && !validatedArgs.success) {
|
|
1150
|
+
this.logger?.error(
|
|
1151
|
+
`[ServiceLocator]#validateAndResolveTokenArgs(): Error validating args for ${actualToken.name.toString()}`,
|
|
1152
|
+
validatedArgs.error
|
|
1153
|
+
);
|
|
1154
|
+
return [new UnknownError(validatedArgs.error), { actualToken }];
|
|
1155
|
+
}
|
|
1156
|
+
return [void 0, { actualToken, validatedArgs: validatedArgs?.data }];
|
|
1157
|
+
}
|
|
1158
|
+
/**
|
|
1159
|
+
* Internal method to resolve token args and create instance name.
|
|
1160
|
+
* Handles factory token resolution and validation.
|
|
1161
|
+
*/
|
|
1162
|
+
async resolveTokenAndPrepareInstanceName(token, args) {
|
|
1163
|
+
const [err, { actualToken, validatedArgs }] = this.validateAndResolveTokenArgs(token, args);
|
|
1164
|
+
if (err instanceof UnknownError) {
|
|
1165
|
+
return [err];
|
|
1166
|
+
} else if (err instanceof FactoryTokenNotResolved && actualToken instanceof FactoryInjectionToken) {
|
|
1167
|
+
this.logger?.log(
|
|
1168
|
+
`[ServiceLocator]#resolveTokenAndPrepareInstanceName() Factory token not resolved, resolving it`
|
|
1169
|
+
);
|
|
1170
|
+
await actualToken.resolve(this.createFactoryContext());
|
|
1171
|
+
return this.resolveTokenAndPrepareInstanceName(token);
|
|
1172
|
+
}
|
|
1173
|
+
const instanceName = this.generateInstanceName(actualToken, validatedArgs);
|
|
1174
|
+
const realToken = actualToken instanceof BoundInjectionToken || actualToken instanceof FactoryInjectionToken ? actualToken.token : actualToken;
|
|
1175
|
+
return [void 0, { instanceName, validatedArgs, actualToken, realToken }];
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* Gets an instance by its instance name, handling all the logic after instance name creation.
|
|
1179
|
+
*/
|
|
1180
|
+
async retrieveOrCreateInstanceByInstanceName(instanceName, realToken, realArgs) {
|
|
1181
|
+
const existingHolder = await this.tryGetExistingInstance(
|
|
1182
|
+
instanceName,
|
|
1183
|
+
realToken
|
|
1184
|
+
);
|
|
1185
|
+
if (existingHolder) {
|
|
1186
|
+
return existingHolder;
|
|
1187
|
+
}
|
|
1188
|
+
const result = await this.createNewInstance(
|
|
1189
|
+
instanceName,
|
|
1190
|
+
realToken,
|
|
1191
|
+
realArgs
|
|
1192
|
+
);
|
|
1193
|
+
if (result[0]) {
|
|
1194
|
+
return [result[0]];
|
|
1195
|
+
}
|
|
1196
|
+
const [, holder] = result;
|
|
1197
|
+
return this.waitForInstanceReady(holder);
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* Attempts to retrieve an existing instance, handling request-scoped and singleton instances.
|
|
1201
|
+
* Returns null if no instance exists and a new one should be created.
|
|
1202
|
+
*/
|
|
1203
|
+
async tryGetExistingInstance(instanceName, realToken) {
|
|
1204
|
+
const requestResult = await this.tryGetRequestScopedInstance(
|
|
1205
|
+
instanceName,
|
|
1206
|
+
realToken
|
|
1207
|
+
);
|
|
1208
|
+
if (requestResult) {
|
|
1209
|
+
return requestResult;
|
|
1210
|
+
}
|
|
1211
|
+
return this.tryGetSingletonInstance(instanceName);
|
|
1212
|
+
}
|
|
1213
|
+
/**
|
|
1214
|
+
* Attempts to get a request-scoped instance if applicable.
|
|
1215
|
+
*/
|
|
1216
|
+
async tryGetRequestScopedInstance(instanceName, realToken) {
|
|
1217
|
+
if (!this.registry.has(realToken)) {
|
|
1218
|
+
return null;
|
|
1219
|
+
}
|
|
1220
|
+
const record = this.registry.get(realToken);
|
|
1221
|
+
if (record.scope !== "Request" /* Request */) {
|
|
1222
|
+
return null;
|
|
1223
|
+
}
|
|
1224
|
+
if (!this.currentRequestContext) {
|
|
1225
|
+
this.logger?.log(
|
|
1226
|
+
`[ServiceLocator] No current request context available for request-scoped service ${instanceName}`
|
|
1227
|
+
);
|
|
1228
|
+
return [new UnknownError("InstanceNotFound" /* InstanceNotFound */)];
|
|
1229
|
+
}
|
|
1230
|
+
const requestHolder = this.currentRequestContext.get(instanceName);
|
|
1231
|
+
if (!requestHolder) {
|
|
1232
|
+
return null;
|
|
1233
|
+
}
|
|
1234
|
+
return this.waitForInstanceReady(requestHolder);
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Attempts to get a singleton instance from the manager.
|
|
1238
|
+
*/
|
|
1239
|
+
async tryGetSingletonInstance(instanceName) {
|
|
1240
|
+
const [error, holder] = this.manager.get(instanceName);
|
|
1241
|
+
if (!error) {
|
|
1242
|
+
return this.waitForInstanceReady(holder);
|
|
1243
|
+
}
|
|
1244
|
+
switch (error.code) {
|
|
1245
|
+
case "InstanceDestroying" /* InstanceDestroying */:
|
|
1246
|
+
this.logger?.log(
|
|
1247
|
+
`[ServiceLocator] Instance ${instanceName} is being destroyed, waiting...`
|
|
1248
|
+
);
|
|
1249
|
+
await holder?.destroyPromise;
|
|
1250
|
+
return this.tryGetSingletonInstance(instanceName);
|
|
1251
|
+
case "InstanceExpired" /* InstanceExpired */:
|
|
1252
|
+
this.logger?.log(
|
|
1253
|
+
`[ServiceLocator] Instance ${instanceName} expired, invalidating...`
|
|
1254
|
+
);
|
|
1255
|
+
await this.invalidate(instanceName);
|
|
1256
|
+
return this.tryGetSingletonInstance(instanceName);
|
|
1257
|
+
case "InstanceNotFound" /* InstanceNotFound */:
|
|
1258
|
+
return null;
|
|
1259
|
+
// Instance doesn't exist, should create new one
|
|
1260
|
+
default:
|
|
1261
|
+
return [error];
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Waits for an instance holder to be ready and returns the appropriate result.
|
|
1266
|
+
*/
|
|
1267
|
+
async waitForInstanceReady(holder) {
|
|
1268
|
+
switch (holder.status) {
|
|
1269
|
+
case "creating" /* Creating */:
|
|
1270
|
+
await holder.creationPromise;
|
|
1271
|
+
return this.waitForInstanceReady(holder);
|
|
1272
|
+
case "destroying" /* Destroying */:
|
|
1273
|
+
return [new UnknownError("InstanceDestroying" /* InstanceDestroying */)];
|
|
1274
|
+
case "error" /* Error */:
|
|
1275
|
+
return [holder.instance];
|
|
1276
|
+
case "created" /* Created */:
|
|
1277
|
+
return [void 0, holder];
|
|
1278
|
+
default:
|
|
1279
|
+
return [new UnknownError("InstanceNotFound" /* InstanceNotFound */)];
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Emits events to listeners for instance lifecycle events.
|
|
1284
|
+
*/
|
|
1285
|
+
emitInstanceEvent(name, event = "create") {
|
|
1286
|
+
this.logger?.log(
|
|
1287
|
+
`[ServiceLocator]#emitInstanceEvent() Notifying listeners for ${name} with event ${event}`
|
|
1288
|
+
);
|
|
1289
|
+
return this.eventBus.emit(name, event);
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* Creates a new instance for the given token and arguments.
|
|
1293
|
+
*/
|
|
1294
|
+
async createNewInstance(instanceName, realToken, args) {
|
|
1295
|
+
this.logger?.log(
|
|
1296
|
+
`[ServiceLocator]#createNewInstance() Creating instance for ${instanceName}`
|
|
1297
|
+
);
|
|
1298
|
+
if (this.registry.has(realToken)) {
|
|
1299
|
+
return this.instantiateServiceFromRegistry(
|
|
1300
|
+
instanceName,
|
|
1301
|
+
realToken,
|
|
1302
|
+
args
|
|
1303
|
+
);
|
|
1304
|
+
} else {
|
|
1305
|
+
return [new FactoryNotFound(realToken.name.toString())];
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* Instantiates a service from the registry using the service instantiator.
|
|
1310
|
+
*/
|
|
1311
|
+
instantiateServiceFromRegistry(instanceName, token, args) {
|
|
1312
|
+
this.logger?.log(
|
|
1313
|
+
`[ServiceLocator]#instantiateServiceFromRegistry(): Creating instance for ${instanceName} from abstract factory`
|
|
1314
|
+
);
|
|
1315
|
+
const ctx = this.createFactoryContext(
|
|
1316
|
+
this.currentRequestContext || void 0
|
|
1317
|
+
);
|
|
1318
|
+
let record = this.registry.get(token);
|
|
1319
|
+
let { scope, type } = record;
|
|
1320
|
+
const [deferred, holder] = this.manager.createCreatingHolder(
|
|
1321
|
+
instanceName,
|
|
1322
|
+
type,
|
|
1323
|
+
scope,
|
|
1324
|
+
ctx.deps,
|
|
1325
|
+
Infinity
|
|
1326
|
+
);
|
|
1327
|
+
this.serviceInstantiator.instantiateService(ctx, record, args).then(async ([error, instance]) => {
|
|
1328
|
+
await this.handleInstantiationResult(
|
|
1329
|
+
instanceName,
|
|
1330
|
+
holder,
|
|
1331
|
+
ctx,
|
|
1332
|
+
deferred,
|
|
1333
|
+
scope,
|
|
1334
|
+
error,
|
|
1335
|
+
instance
|
|
1336
|
+
);
|
|
1337
|
+
}).catch(async (error) => {
|
|
1338
|
+
await this.handleInstantiationError(
|
|
1339
|
+
instanceName,
|
|
1340
|
+
holder,
|
|
1341
|
+
deferred,
|
|
1342
|
+
scope,
|
|
1343
|
+
error
|
|
1344
|
+
);
|
|
1345
|
+
});
|
|
1346
|
+
this.storeInstanceByScope(scope, instanceName, holder);
|
|
1347
|
+
return [void 0, holder];
|
|
1348
|
+
}
|
|
1349
|
+
/**
|
|
1350
|
+
* Handles the result of service instantiation.
|
|
1351
|
+
*/
|
|
1352
|
+
async handleInstantiationResult(instanceName, holder, ctx, deferred, scope, error, instance) {
|
|
1353
|
+
holder.destroyListeners = ctx.getDestroyListeners();
|
|
1354
|
+
holder.creationPromise = null;
|
|
1355
|
+
if (error) {
|
|
1356
|
+
await this.handleInstantiationError(
|
|
1357
|
+
instanceName,
|
|
1358
|
+
holder,
|
|
1359
|
+
deferred,
|
|
1360
|
+
scope,
|
|
1361
|
+
error
|
|
1362
|
+
);
|
|
1363
|
+
} else {
|
|
1364
|
+
await this.handleInstantiationSuccess(
|
|
1365
|
+
instanceName,
|
|
1366
|
+
holder,
|
|
1367
|
+
ctx,
|
|
1368
|
+
deferred,
|
|
1369
|
+
instance
|
|
1370
|
+
);
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* Handles successful service instantiation.
|
|
1375
|
+
*/
|
|
1376
|
+
async handleInstantiationSuccess(instanceName, holder, ctx, deferred, instance) {
|
|
1377
|
+
holder.instance = instance;
|
|
1378
|
+
holder.status = "created" /* Created */;
|
|
1379
|
+
if (ctx.deps.size > 0) {
|
|
1380
|
+
ctx.deps.forEach((dependency) => {
|
|
1381
|
+
holder.destroyListeners.push(
|
|
1382
|
+
this.eventBus.on(
|
|
1383
|
+
dependency,
|
|
1384
|
+
"destroy",
|
|
1385
|
+
() => this.invalidate(instanceName)
|
|
1386
|
+
)
|
|
1387
|
+
);
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
await this.emitInstanceEvent(instanceName);
|
|
1391
|
+
deferred.resolve([void 0, instance]);
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Handles service instantiation errors.
|
|
1395
|
+
*/
|
|
1396
|
+
async handleInstantiationError(instanceName, holder, deferred, scope, error) {
|
|
1397
|
+
this.logger?.error(
|
|
1398
|
+
`[ServiceLocator] Error creating instance for ${instanceName}`,
|
|
1399
|
+
error
|
|
1400
|
+
);
|
|
1401
|
+
holder.status = "error" /* Error */;
|
|
1402
|
+
holder.instance = error;
|
|
1403
|
+
holder.creationPromise = null;
|
|
1404
|
+
if (scope === "Singleton" /* Singleton */) {
|
|
1405
|
+
setTimeout(() => this.invalidate(instanceName), 10);
|
|
1406
|
+
}
|
|
1407
|
+
deferred.reject(error);
|
|
1408
|
+
}
|
|
1409
|
+
/**
|
|
1410
|
+
* Stores an instance holder based on its scope.
|
|
1411
|
+
*/
|
|
1412
|
+
storeInstanceByScope(scope, instanceName, holder) {
|
|
1413
|
+
switch (scope) {
|
|
1414
|
+
case "Singleton" /* Singleton */:
|
|
1415
|
+
this.logger?.debug(
|
|
1416
|
+
`[ServiceLocator] Setting singleton instance for ${instanceName}`
|
|
1417
|
+
);
|
|
1418
|
+
this.manager.set(instanceName, holder);
|
|
1419
|
+
break;
|
|
1420
|
+
case "Request" /* Request */:
|
|
1421
|
+
if (this.currentRequestContext) {
|
|
1422
|
+
this.logger?.debug(
|
|
1423
|
+
`[ServiceLocator] Setting request-scoped instance for ${instanceName}`
|
|
1424
|
+
);
|
|
1425
|
+
this.currentRequestContext.addInstance(
|
|
1426
|
+
instanceName,
|
|
1427
|
+
holder.instance,
|
|
1428
|
+
holder
|
|
1429
|
+
);
|
|
1430
|
+
}
|
|
1431
|
+
break;
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
/**
|
|
1435
|
+
* Tries to get a pre-prepared instance from request contexts.
|
|
1436
|
+
*/
|
|
1437
|
+
tryGetPrePreparedInstance(instanceName, contextHolder, deps) {
|
|
1438
|
+
if (contextHolder && contextHolder.priority > 0) {
|
|
1439
|
+
const prePreparedInstance = contextHolder.get(instanceName)?.instance;
|
|
1440
|
+
if (prePreparedInstance !== void 0) {
|
|
1441
|
+
this.logger?.debug(
|
|
1442
|
+
`[ServiceLocator] Using pre-prepared instance ${instanceName} from request context ${contextHolder.requestId}`
|
|
1443
|
+
);
|
|
1444
|
+
deps.add(instanceName);
|
|
1445
|
+
return prePreparedInstance;
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
if (this.currentRequestContext && this.currentRequestContext !== contextHolder) {
|
|
1449
|
+
const prePreparedInstance = this.currentRequestContext.get(instanceName)?.instance;
|
|
1450
|
+
if (prePreparedInstance !== void 0) {
|
|
1451
|
+
this.logger?.debug(
|
|
1452
|
+
`[ServiceLocator] Using pre-prepared instance ${instanceName} from current request context ${this.currentRequestContext.requestId}`
|
|
1453
|
+
);
|
|
1454
|
+
deps.add(instanceName);
|
|
1455
|
+
return prePreparedInstance;
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
return void 0;
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* Creates a factory context for dependency injection during service instantiation.
|
|
1462
|
+
* @param contextHolder Optional request context holder for priority-based resolution
|
|
1463
|
+
*/
|
|
1464
|
+
createFactoryContext(contextHolder) {
|
|
1465
|
+
const destroyListeners = /* @__PURE__ */ new Set();
|
|
1466
|
+
const deps = /* @__PURE__ */ new Set();
|
|
1467
|
+
const self = this;
|
|
1468
|
+
function addDestroyListener(listener) {
|
|
1469
|
+
destroyListeners.add(listener);
|
|
1470
|
+
}
|
|
1471
|
+
function getDestroyListeners() {
|
|
1472
|
+
return Array.from(destroyListeners);
|
|
1473
|
+
}
|
|
1474
|
+
return {
|
|
1475
|
+
// @ts-expect-error This is correct type
|
|
1476
|
+
async inject(token, args) {
|
|
1477
|
+
const instanceName = self.generateInstanceName(token, args);
|
|
1478
|
+
const prePreparedInstance = self.tryGetPrePreparedInstance(
|
|
1479
|
+
instanceName,
|
|
1480
|
+
contextHolder,
|
|
1481
|
+
deps
|
|
1482
|
+
);
|
|
1483
|
+
if (prePreparedInstance !== void 0) {
|
|
1484
|
+
return prePreparedInstance;
|
|
1485
|
+
}
|
|
1486
|
+
const [error, instance] = await self.getInstance(
|
|
1487
|
+
token,
|
|
1488
|
+
args,
|
|
1489
|
+
({ instanceName: instanceName2 }) => {
|
|
1490
|
+
deps.add(instanceName2);
|
|
1491
|
+
}
|
|
1492
|
+
);
|
|
1493
|
+
if (error) {
|
|
1494
|
+
throw error;
|
|
1495
|
+
}
|
|
1496
|
+
return instance;
|
|
1497
|
+
},
|
|
1498
|
+
addDestroyListener,
|
|
1499
|
+
getDestroyListeners,
|
|
1500
|
+
locator: self,
|
|
1501
|
+
deps
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* Generates a unique instance name based on token and arguments.
|
|
1506
|
+
*/
|
|
1507
|
+
generateInstanceName(token, args) {
|
|
1508
|
+
if (!args) {
|
|
1509
|
+
return token.toString();
|
|
1510
|
+
}
|
|
1511
|
+
const formattedArgs = Object.entries(args).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, value]) => `${key}=${this.formatArgValue(value)}`).join(",");
|
|
1512
|
+
return `${token.toString()}:${formattedArgs.replaceAll(/"/g, "").replaceAll(/:/g, "=")}`;
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* Formats a single argument value for instance name generation.
|
|
1516
|
+
*/
|
|
1517
|
+
formatArgValue(value) {
|
|
1518
|
+
if (typeof value === "function") {
|
|
1519
|
+
return `fn_${value.name}(${value.length})`;
|
|
1520
|
+
}
|
|
1521
|
+
if (typeof value === "symbol") {
|
|
1522
|
+
return value.toString();
|
|
1523
|
+
}
|
|
1524
|
+
return JSON.stringify(value).slice(0, 40);
|
|
1525
|
+
}
|
|
1526
|
+
};
|
|
1527
|
+
|
|
1528
|
+
// src/container.mts
|
|
1529
|
+
var _Container_decorators, _init;
|
|
1530
|
+
_Container_decorators = [Injectable()];
|
|
1531
|
+
var _Container = class _Container {
|
|
1532
|
+
constructor(registry = globalRegistry, logger = null, injectors = defaultInjectors) {
|
|
1533
|
+
this.registry = registry;
|
|
1534
|
+
this.logger = logger;
|
|
1535
|
+
this.injectors = injectors;
|
|
1536
|
+
this.serviceLocator = new ServiceLocator(registry, logger, injectors);
|
|
1537
|
+
this.registerSelf();
|
|
1538
|
+
}
|
|
1539
|
+
serviceLocator;
|
|
1540
|
+
registerSelf() {
|
|
1541
|
+
const token = getInjectableToken(_Container);
|
|
1542
|
+
const instanceName = this.serviceLocator.getInstanceIdentifier(token);
|
|
1543
|
+
this.serviceLocator.getManager().storeCreatedHolder(
|
|
1544
|
+
instanceName,
|
|
1545
|
+
this,
|
|
1546
|
+
"Class" /* Class */,
|
|
1547
|
+
"Singleton" /* Singleton */
|
|
1548
|
+
);
|
|
1549
|
+
}
|
|
1550
|
+
async get(token, args) {
|
|
1551
|
+
return this.serviceLocator.getOrThrowInstance(token, args);
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Gets the underlying ServiceLocator instance for advanced usage
|
|
1555
|
+
*/
|
|
1556
|
+
getServiceLocator() {
|
|
1557
|
+
return this.serviceLocator;
|
|
1558
|
+
}
|
|
1559
|
+
/**
|
|
1560
|
+
* Invalidates a service and its dependencies
|
|
1561
|
+
*/
|
|
1562
|
+
async invalidate(service) {
|
|
1563
|
+
const holderMap = this.serviceLocator.getManager().filter((holder2) => holder2.instance === service);
|
|
1564
|
+
if (holderMap.size === 0) {
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
const holder = holderMap.values().next().value;
|
|
1568
|
+
if (holder) {
|
|
1569
|
+
await this.serviceLocator.invalidate(holder.name);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Waits for all pending operations to complete
|
|
1574
|
+
*/
|
|
1575
|
+
async ready() {
|
|
1576
|
+
await this.serviceLocator.ready();
|
|
1577
|
+
}
|
|
1578
|
+
// ============================================================================
|
|
1579
|
+
// REQUEST CONTEXT MANAGEMENT
|
|
1580
|
+
// ============================================================================
|
|
1581
|
+
/**
|
|
1582
|
+
* Begins a new request context with the given parameters.
|
|
1583
|
+
* @param requestId Unique identifier for this request
|
|
1584
|
+
* @param metadata Optional metadata for the request
|
|
1585
|
+
* @param priority Priority for resolution (higher = more priority)
|
|
1586
|
+
* @returns The created request context holder
|
|
1587
|
+
*/
|
|
1588
|
+
beginRequest(requestId, metadata, priority = 100) {
|
|
1589
|
+
return this.serviceLocator.beginRequest(requestId, metadata, priority);
|
|
1590
|
+
}
|
|
1591
|
+
/**
|
|
1592
|
+
* Ends a request context and cleans up all associated instances.
|
|
1593
|
+
* @param requestId The request ID to end
|
|
1594
|
+
*/
|
|
1595
|
+
async endRequest(requestId) {
|
|
1596
|
+
await this.serviceLocator.endRequest(requestId);
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* Gets the current request context.
|
|
1600
|
+
* @returns The current request context holder or null
|
|
1601
|
+
*/
|
|
1602
|
+
getCurrentRequestContext() {
|
|
1603
|
+
return this.serviceLocator.getCurrentRequestContext();
|
|
1604
|
+
}
|
|
1605
|
+
/**
|
|
1606
|
+
* Sets the current request context.
|
|
1607
|
+
* @param requestId The request ID to set as current
|
|
1608
|
+
*/
|
|
1609
|
+
setCurrentRequestContext(requestId) {
|
|
1610
|
+
this.serviceLocator.setCurrentRequestContext(requestId);
|
|
1611
|
+
}
|
|
1612
|
+
/**
|
|
1613
|
+
* Clears all instances and bindings from the container.
|
|
1614
|
+
* This is useful for testing or resetting the container state.
|
|
1615
|
+
*/
|
|
1616
|
+
clear() {
|
|
1617
|
+
this.serviceLocator.getManager().clear();
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
_init = __decoratorStart(null);
|
|
1621
|
+
_Container = __decorateElement(_init, 0, "Container", _Container_decorators, _Container);
|
|
1622
|
+
__runInitializers(_init, 1, _Container);
|
|
1623
|
+
var Container = _Container;
|
|
1624
|
+
|
|
1625
|
+
export { BaseInstanceHolderManager, BoundInjectionToken, Container, DefaultRequestContextHolder, Deferred, ErrorsEnum, FactoryInjectionToken, FactoryNotFound, FactoryTokenNotResolved, Injectable, InjectableScope, InjectableTokenMeta, InjectableType, InjectionToken, InstanceDestroying, InstanceExpired, InstanceNotFound, Registry, ServiceInstantiator, ServiceLocator, ServiceLocatorEventBus, ServiceLocatorInstanceHolderStatus, ServiceLocatorManager, UnknownError, __decorateElement, __decoratorStart, __runInitializers, asyncInject, createDeferred, createRequestContextHolder, defaultInjectors, getInjectableToken, getInjectors, globalRegistry, inject, provideFactoryContext, wrapSyncInit };
|
|
1626
|
+
//# sourceMappingURL=chunk-3NLYPYBY.mjs.map
|
|
1627
|
+
//# sourceMappingURL=chunk-3NLYPYBY.mjs.map
|