@vercube/di 0.0.1-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,599 @@
1
+ "use strict";
2
+
3
+ //#region packages/di/src/Common/BaseDecorators.ts
4
+ var BaseDecorator = class {
5
+ /** Holds options object that is passed as 2nd argument in createDecorator() factory */
6
+ options;
7
+ /** Holds class instance that is decorated */
8
+ instance;
9
+ /** Holds class prototype that is decorated */
10
+ prototype;
11
+ /** Holds property name that was decorated */
12
+ propertyName;
13
+ /** Holds property descriptor that was decorated */
14
+ descriptor;
15
+ /** Holds property index if decorators if for Method Property */
16
+ propertyIndex;
17
+ /**
18
+ * This method is called when decorator is created and ready to be used.
19
+ */
20
+ created() {}
21
+ /**
22
+ * This method is called when decorator is destroyed for cleanup tasks (like unregistering listeners, clearing timers).
23
+ * For standard services it is called at the end of SSR requests and for Vue components it is called when component is
24
+ * destroyed.
25
+ */
26
+ destroyed() {}
27
+ };
28
+
29
+ //#endregion
30
+ //#region packages/di/src/Types/IOCTypes.ts
31
+ let IOC;
32
+ (function(_IOC) {
33
+ let ServiceFactoryType = /* @__PURE__ */ function(ServiceFactoryType$1) {
34
+ ServiceFactoryType$1["CLASS"] = "CLASS";
35
+ ServiceFactoryType$1["CLASS_SINGLETON"] = "CLASS_SINGLETON";
36
+ ServiceFactoryType$1["INSTANCE"] = "INSTANCE";
37
+ return ServiceFactoryType$1;
38
+ }({});
39
+ _IOC.ServiceFactoryType = ServiceFactoryType;
40
+ let InjectMethod = /* @__PURE__ */ function(InjectMethod$1) {
41
+ InjectMethod$1["LAZY"] = "LAZY";
42
+ InjectMethod$1["STATIC"] = "STATIC";
43
+ return InjectMethod$1;
44
+ }({});
45
+ _IOC.InjectMethod = InjectMethod;
46
+ let DependencyType = /* @__PURE__ */ function(DependencyType$1) {
47
+ DependencyType$1[DependencyType$1["STANDARD"] = 0] = "STANDARD";
48
+ DependencyType$1[DependencyType$1["OPTIONAL"] = 1] = "OPTIONAL";
49
+ return DependencyType$1;
50
+ }({});
51
+ _IOC.DependencyType = DependencyType;
52
+ })(IOC || (IOC = {}));
53
+
54
+ //#endregion
55
+ //#region packages/di/src/Domain/Engine.ts
56
+ /**
57
+ * This map holds metadata for ALL classes in system along with their dependencies. Original idea was
58
+ * to store those informations in object prototype, but accessing this map is blazing fast with Map
59
+ * container (<1ms).
60
+ */
61
+ const classMap = new Map();
62
+ const ROOT_PROTO = Object.getPrototypeOf({});
63
+ /**
64
+ * This method registers @Inject() in particular class.
65
+ * @param prototype class prototype for which we register @Inject()
66
+ * @param propertyName name of property that is inejcted
67
+ * @param dependency what we should inject there
68
+ * @param type type of dependency (standard or optional dependency)
69
+ */
70
+ function registerInject(prototype, propertyName, dependency, type) {
71
+ let entry = classMap.get(prototype);
72
+ if (!entry) {
73
+ const newEntry = { deps: [] };
74
+ entry = newEntry;
75
+ classMap.set(prototype, entry);
76
+ }
77
+ const newDep = {
78
+ propertyName,
79
+ dependency,
80
+ type
81
+ };
82
+ entry.deps.push(newDep);
83
+ }
84
+ /**
85
+ * Returns classmap entry for particular class. It holds information about @Injects for this particular class.
86
+ * @param classType type of class to check
87
+ * @returns class map entry or null if cannot be found
88
+ */
89
+ function getEntryForClass(classType) {
90
+ const entry = classMap.get(classType.prototype);
91
+ return entry === void 0 ? null : entry;
92
+ }
93
+ /**
94
+ * Returns array of dependencies for particular class instance.
95
+ * @param instance class instance
96
+ * @returns array of @Inject dependencies defined for this class
97
+ */
98
+ function getDeps(instance) {
99
+ const prototype = Object.getPrototypeOf(instance);
100
+ if (!prototype) return [];
101
+ const entry = classMap.get(prototype);
102
+ return entry !== void 0 && entry.deps !== void 0 ? entry.deps : [];
103
+ }
104
+ /**
105
+ * This method injects stuff into class, using container passed as first argument. We need container as
106
+ * inject execution is always context based.
107
+ * @param container container instance that is providing dependencies
108
+ * @param instance class instance to inject
109
+ * @param method inject method, "lazy" queries dep during property access while "static" injects during class creation
110
+ */
111
+ function injectDeps(container, instance, method) {
112
+ let prototype = Object.getPrototypeOf(instance);
113
+ if (!prototype) return;
114
+ /**
115
+ * Here we will traverse through prototype chain until we hit dead end (ROOT_PROTO). This is because we
116
+ * must process inject for current class and also for every base class.
117
+ *
118
+ * So we will use "do" loop to iterate full prototype chain.
119
+ */
120
+ do {
121
+ const entry = classMap.get(prototype);
122
+ if (entry) for (const iter of entry.deps) {
123
+ const propertyName = iter.propertyName;
124
+ const dependency = iter.dependency;
125
+ const type = iter.type;
126
+ if (Object.prototype.hasOwnProperty.call(instance, propertyName) && instance[propertyName] !== void 0) continue;
127
+ if (type === IOC.DependencyType.OPTIONAL) {
128
+ Object.defineProperty(instance, propertyName, { get: function() {
129
+ return container.getOptional(dependency);
130
+ } });
131
+ continue;
132
+ }
133
+ switch (method) {
134
+ case IOC.InjectMethod.LAZY: {
135
+ Object.defineProperty(instance, propertyName, { get: function() {
136
+ return container.get(dependency);
137
+ } });
138
+ break;
139
+ }
140
+ case IOC.InjectMethod.STATIC: {
141
+ instance[propertyName] = container.get(dependency);
142
+ break;
143
+ }
144
+ default: throw new Error(`IOCEngine.injectDeps() - invalid inject method ${method}`);
145
+ }
146
+ }
147
+ prototype = Object.getPrototypeOf(prototype);
148
+ } while (prototype && prototype !== ROOT_PROTO);
149
+ }
150
+ const IOCEngine = {
151
+ registerInject,
152
+ getEntryForClass,
153
+ injectDeps,
154
+ getDeps
155
+ };
156
+
157
+ //#endregion
158
+ //#region packages/di/src/Decorators/Inject.ts
159
+ function Inject(key) {
160
+ return (target, propertyName) => {
161
+ IOCEngine.registerInject(target, propertyName, key, IOC.DependencyType.STANDARD);
162
+ };
163
+ }
164
+
165
+ //#endregion
166
+ //#region packages/di/src/Decorators/InjectOptional.ts
167
+ function InjectOptional(key) {
168
+ return (target, propertyName) => {
169
+ IOCEngine.registerInject(target, propertyName, key, IOC.DependencyType.OPTIONAL);
170
+ };
171
+ }
172
+
173
+ //#endregion
174
+ //#region packages/di/src/Decorators/Init.ts
175
+ var InitDecorator = class extends BaseDecorator {
176
+ /**
177
+ * Called when decorator is initialized.
178
+ */
179
+ created() {
180
+ if (typeof this.instance[this.propertyName] === "function") this.instance[this.propertyName]();
181
+ }
182
+ };
183
+ function Init() {
184
+ return createDecorator(InitDecorator, {});
185
+ }
186
+
187
+ //#endregion
188
+ //#region packages/di/src/Domain/ContainerEvents.ts
189
+ var ContainerEvents = class {
190
+ fOnExpanded = [];
191
+ /**
192
+ * Registers to container "onExpanded" event.
193
+ * @param handler event handler
194
+ */
195
+ onExpanded(handler) {
196
+ this.fOnExpanded.push(handler);
197
+ }
198
+ /**
199
+ * Calls on expanded event.
200
+ * @param serviceKeys key of service we have installed
201
+ */
202
+ callOnExpanded(serviceKeys) {
203
+ for (const handler of this.fOnExpanded) handler(serviceKeys);
204
+ }
205
+ };
206
+
207
+ //#endregion
208
+ //#region packages/di/src/Utils/Utils.ts
209
+ function Identity(name) {
210
+ return Symbol(name);
211
+ }
212
+ function createDecorator(decoratorClass, params) {
213
+ return function internalDecorator(target, propertyName, descriptor) {
214
+ if (!target.__decorators) target.__decorators = [];
215
+ target.__decorators.push({
216
+ classType: decoratorClass,
217
+ params,
218
+ target,
219
+ propertyName,
220
+ descriptor
221
+ });
222
+ };
223
+ }
224
+ /**
225
+ * This map holds map of Container:DecoratorMetadata values. For every container created,
226
+ * we must hold array of decorated instances, we realize it by holding map where key is
227
+ * container (for easier removal later) and value is IContainerDecoratorMetadataObject.
228
+ */
229
+ const containerMap = new Map();
230
+ /**
231
+ * Helper function to query data from container
232
+ * @param container container to get metadata fro
233
+ * @return metadata object
234
+ */
235
+ function getContainerMetadata(container) {
236
+ if (!containerMap.has(container)) containerMap.set(container, { decoratedInstances: new Map() });
237
+ return containerMap.get(container);
238
+ }
239
+ function initializeDecorators(target, container) {
240
+ const prototype = Object.getPrototypeOf(target);
241
+ if (prototype.__decorators) for (const entry of prototype.__decorators) {
242
+ const instance = container.resolve(entry.classType);
243
+ if (instance) {
244
+ instance.options = entry.params;
245
+ instance.instance = target;
246
+ instance.prototype = prototype;
247
+ instance.propertyName = entry.propertyName;
248
+ instance.descriptor = entry.descriptor;
249
+ instance.propertyIndex = typeof entry.descriptor === "number" ? entry.descriptor : -1;
250
+ instance.created();
251
+ }
252
+ const { decoratedInstances } = getContainerMetadata(container);
253
+ const instanceList = decoratedInstances.get(target) ?? [];
254
+ instanceList.push(instance);
255
+ decoratedInstances.set(target, instanceList);
256
+ }
257
+ }
258
+ function destroyDecorators(target, container) {
259
+ const { decoratedInstances } = getContainerMetadata(container);
260
+ const instanceList = decoratedInstances.get(target);
261
+ if (instanceList) for (const instance of instanceList) instance.destroyed();
262
+ decoratedInstances.delete(target);
263
+ }
264
+ function initializeContainer(container) {
265
+ container.flushQueue();
266
+ }
267
+ function destroyContainer(container) {
268
+ container.getAllServices().forEach((service) => destroyDecorators(service, container));
269
+ containerMap.delete(container);
270
+ }
271
+
272
+ //#endregion
273
+ //#region packages/di/src/Domain/Container.ts
274
+ var Container = class Container {
275
+ fLocked = false;
276
+ fDefaultParams = { createLocked: false };
277
+ fServices = new Map();
278
+ fNewQueue = new Map();
279
+ fSingletonInstances = new Map();
280
+ fInjectMethod = IOC.InjectMethod.STATIC;
281
+ fContainerEvents = new ContainerEvents();
282
+ /**
283
+ * Constructor for container.
284
+ * @param params initial params for container
285
+ */
286
+ constructor(params) {
287
+ this.fLocked = params?.createLocked ?? false;
288
+ this.fDefaultParams = Object.assign(this.fDefaultParams, params);
289
+ this.fInjectMethod = params?.injectMethod ?? IOC.InjectMethod.STATIC;
290
+ this.bindInstance(Container, this);
291
+ }
292
+ /**
293
+ * Returns array of all service keys. This basically returns keys from all .bindXXX calls.
294
+ * @returns {Array} array of service keys
295
+ */
296
+ get servicesKeys() {
297
+ return [...this.fServices.keys()];
298
+ }
299
+ /**
300
+ * Returns events handler.
301
+ */
302
+ get events() {
303
+ return this.fContainerEvents;
304
+ }
305
+ /**
306
+ * Binds particular key to container in singleton scope. Multiple queries/injects of this
307
+ * service will always return the same instance.
308
+ *
309
+ * @param key key of service, preferably class or abstract class
310
+ * @param value implementation
311
+ */
312
+ bind(key, value) {
313
+ const newDef = {
314
+ serviceKey: key,
315
+ serviceValue: value ?? key,
316
+ type: IOC.ServiceFactoryType.CLASS_SINGLETON
317
+ };
318
+ if (typeof key === "symbol" && !value) throw new Error("Container - provide implementation for binds with symbols.");
319
+ const existingServiceDef = this.fServices.get(key);
320
+ if (existingServiceDef) this.internalDispose(existingServiceDef);
321
+ this.fServices.set(key, newDef);
322
+ this.fNewQueue.set(key, newDef);
323
+ }
324
+ /**
325
+ * Binds particular key to container in transient scope. Every query/@Inject of this service
326
+ * will have totally brand-new instance of class.
327
+ * @param key key of service, preferably class or abstract class
328
+ * @param value implementation
329
+ */
330
+ bindTransient(key, value) {
331
+ const newDef = {
332
+ serviceKey: key,
333
+ serviceValue: value ?? key,
334
+ type: IOC.ServiceFactoryType.CLASS
335
+ };
336
+ const existingServiceDef = this.fServices.get(key);
337
+ if (existingServiceDef) this.internalDispose(existingServiceDef);
338
+ this.fServices.set(key, newDef);
339
+ this.fNewQueue.set(key, newDef);
340
+ }
341
+ /**
342
+ * Binds particular key class to an existing class instance. If you use this method,
343
+ * class wont be instantiated automatically. The common use case is to
344
+ * share single class instance between two or more containers.
345
+ *
346
+ * @param key key of service, preferably class or abstract class
347
+ * @param value instance of class to be used as resolution
348
+ */
349
+ bindInstance(key, value) {
350
+ const newDef = {
351
+ serviceKey: key,
352
+ serviceValue: value,
353
+ type: IOC.ServiceFactoryType.INSTANCE
354
+ };
355
+ const existingServiceDef = this.fServices.get(key);
356
+ if (existingServiceDef) this.internalDispose(existingServiceDef);
357
+ this.fServices.set(key, newDef);
358
+ this.fNewQueue.set(key, newDef);
359
+ }
360
+ /**
361
+ * Binds mocked instance to a particular service ID. Its designed to be used in unit tests, where you can quickly
362
+ * replace real IOC implementation with a partial stub. Please note, you are responsible to provide enough data
363
+ * for test to pass, TypeScript wont check it.
364
+ *
365
+ * Example:
366
+ *
367
+ * container.bind(HttpServer, {
368
+ * listen: jest.fn(),
369
+ * });
370
+ *
371
+ * @param key service to be replaced
372
+ * @param mockInstance mock instance
373
+ */
374
+ bindMock(key, mockInstance) {
375
+ const newDef = {
376
+ serviceKey: key,
377
+ serviceValue: mockInstance,
378
+ type: IOC.ServiceFactoryType.INSTANCE
379
+ };
380
+ const existingServiceDef = this.fServices.get(key);
381
+ if (existingServiceDef) this.internalDispose(existingServiceDef);
382
+ this.fServices.set(key, newDef);
383
+ this.fNewQueue.set(key, newDef);
384
+ }
385
+ /**
386
+ * Returns implementation for a particular key class. This is the same as @Inject,
387
+ * but triggered programitically.
388
+ * @param key key used in .bind() function to bind key class to implementation class
389
+ * @returns service for identifier
390
+ */
391
+ get(key) {
392
+ return this.internalGet(key);
393
+ }
394
+ /**
395
+ * Returns implementation for a particular key class. This is the same as @Inject,
396
+ * but triggered programitically.
397
+ * @param key key used in .bind() function to bind key class to implementation class
398
+ * @returns service for identifier
399
+ */
400
+ getOptional(key) {
401
+ return this.internalGetOptional(key);
402
+ }
403
+ /**
404
+ * Uses the container provider to register multiple things in IOC container at once.
405
+ * @param provider provider that will register new services into IOC container
406
+ */
407
+ use(provider) {
408
+ provider(this);
409
+ }
410
+ /**
411
+ * Expands container during runtime, adding new services to it.
412
+ * @param providers functor that is used to expand the container
413
+ * @param flush whether container should be flushed now or not
414
+ */
415
+ expand(providers, flush = true) {
416
+ const preLockState = this.fLocked;
417
+ const allProviders = Array.isArray(providers) ? providers : [providers];
418
+ try {
419
+ this.fLocked = false;
420
+ for (const provider of allProviders) this.use(provider);
421
+ const newKeys = [...this.fNewQueue.keys()].filter((k) => !this.fSingletonInstances.has(k));
422
+ this.fContainerEvents.callOnExpanded(newKeys);
423
+ if (flush) this.flushQueue();
424
+ } finally {
425
+ this.fLocked = preLockState;
426
+ }
427
+ }
428
+ /**
429
+ * Creates instance of particular class using, respecting all @Injects inside created class.
430
+ * @param classType type of class to instantiate
431
+ * @param method (optional) inject method
432
+ * @returns new class instance with dependencies
433
+ */
434
+ resolve(classType, method = IOC.InjectMethod.LAZY) {
435
+ const newInstance = new classType();
436
+ this.internalProcessInjects(newInstance, method);
437
+ return newInstance;
438
+ }
439
+ /**
440
+ * Returns all IOC services registered in container.
441
+ * @returns array with all registered services
442
+ */
443
+ getAllServices() {
444
+ return this.servicesKeys.map((k) => this.get(k));
445
+ }
446
+ /**
447
+ * Unlocks the container, allowing things to be retrieved and used.
448
+ */
449
+ unlock() {
450
+ this.fLocked = false;
451
+ }
452
+ /**
453
+ * Locks the container, disabling to add new services here.
454
+ */
455
+ lock() {
456
+ this.fLocked = true;
457
+ }
458
+ /**
459
+ * Flushes new services queue, registering them into container.
460
+ */
461
+ flushQueue() {
462
+ if (this.fNewQueue.size === 0) return;
463
+ const values = [...this.fNewQueue.values()];
464
+ for (const def of values) {
465
+ if (def.type !== IOC.ServiceFactoryType.CLASS_SINGLETON) continue;
466
+ const instance = this.internalResolve(def);
467
+ initializeDecorators(instance, this);
468
+ }
469
+ this.fNewQueue.clear();
470
+ }
471
+ /**
472
+ * Internally retrieve dependency from container.
473
+ * @param key key to get
474
+ * @param parent parent (for debugging purposes)
475
+ * @returns queried instance
476
+ */
477
+ internalGet(key, parent) {
478
+ const serviceDef = this.fServices.get(key);
479
+ if (!serviceDef) throw new Error(`Unresolved dependency for [${this.getKeyDescription(key)}]`);
480
+ return this.internalResolve(serviceDef);
481
+ }
482
+ /**
483
+ * Internally retrieve dependency from container.
484
+ * @param key key to get
485
+ * @param parent parent
486
+ * @returns queried instance
487
+ */
488
+ internalGetOptional(key) {
489
+ const serviceDef = this.fServices.get(key);
490
+ if (!serviceDef) return null;
491
+ return this.internalResolve(serviceDef);
492
+ }
493
+ /**
494
+ * Internally resolves service def, turning it into class instance with deps injected.
495
+ * @param serviceDef service def to resolve
496
+ * @returns class instance
497
+ */
498
+ internalResolve(serviceDef) {
499
+ switch (serviceDef.type) {
500
+ case IOC.ServiceFactoryType.INSTANCE: return serviceDef.serviceValue;
501
+ case IOC.ServiceFactoryType.CLASS_SINGLETON: {
502
+ if (!this.fSingletonInstances.has(serviceDef.serviceKey)) {
503
+ const constructor = serviceDef.serviceValue;
504
+ const instance = new constructor();
505
+ this.fSingletonInstances.set(serviceDef.serviceKey, instance);
506
+ this.internalProcessInjects(instance, this.fInjectMethod);
507
+ return instance;
508
+ }
509
+ return this.fSingletonInstances.get(serviceDef.serviceKey);
510
+ }
511
+ case IOC.ServiceFactoryType.CLASS: {
512
+ const constructor = serviceDef.serviceValue;
513
+ const instance = new constructor();
514
+ this.internalProcessInjects(instance, this.fInjectMethod);
515
+ return instance;
516
+ }
517
+ default: throw new Error(`Container - invalid factory type: ${serviceDef.type}`);
518
+ }
519
+ }
520
+ /**
521
+ * Internally inject deps for particular class..
522
+ * @param instance instance to inject
523
+ * @param method method for injecting dependencies, either lazy or static
524
+ */
525
+ internalProcessInjects(instance, method) {
526
+ if (method === IOC.InjectMethod.LAZY) {
527
+ IOCEngine.injectDeps(this, instance, IOC.InjectMethod.LAZY);
528
+ return;
529
+ }
530
+ const processQueue = [];
531
+ const elementSet = new Set();
532
+ const toProcessElements = [];
533
+ processQueue.push(instance);
534
+ toProcessElements.push(instance);
535
+ while (processQueue.length > 0) {
536
+ const element = processQueue.pop();
537
+ const deps = IOCEngine.getDeps(element);
538
+ for (const inj of deps) if (!elementSet.has(inj.dependency)) {
539
+ const isOptional = inj.type === IOC.DependencyType.OPTIONAL;
540
+ const childInstance = isOptional ? this.internalGetOptional(inj.dependency) : this.internalGet(inj.dependency, instance);
541
+ elementSet.add(inj.dependency);
542
+ if (!isOptional) {
543
+ processQueue.push(childInstance);
544
+ toProcessElements.push(childInstance);
545
+ }
546
+ }
547
+ }
548
+ for (const el of toProcessElements) IOCEngine.injectDeps(this, el, IOC.InjectMethod.STATIC);
549
+ }
550
+ /**
551
+ * Disposes a module, clearing everything allocated to it.
552
+ * @param def def that should be disposed
553
+ */
554
+ internalDispose(def) {
555
+ switch (def.type) {
556
+ case IOC.ServiceFactoryType.INSTANCE: {
557
+ destroyDecorators(def.serviceValue, this);
558
+ break;
559
+ }
560
+ case IOC.ServiceFactoryType.CLASS_SINGLETON: {
561
+ const existingInstance = this.fSingletonInstances.get(def.serviceKey);
562
+ if (existingInstance) destroyDecorators(existingInstance, this);
563
+ break;
564
+ }
565
+ case IOC.ServiceFactoryType.CLASS: break;
566
+ default: throw new Error(`Container::internalDispose() - invalid def type: ${def.type}`);
567
+ }
568
+ }
569
+ /**
570
+ * Describes particular key for better error messaging.
571
+ * @param key service key
572
+ * @returns string representation of service key
573
+ */
574
+ getKeyDescription(key) {
575
+ if (typeof key === "symbol") return key.description;
576
+ else if (typeof key === "function") return key.name;
577
+ else if (typeof key === "object") return key.constructor?.name ?? "Unknown object";
578
+ return "Unknown";
579
+ }
580
+ };
581
+
582
+ //#endregion
583
+ exports.BaseDecorator = BaseDecorator
584
+ exports.Container = Container
585
+ Object.defineProperty(exports, 'IOC', {
586
+ enumerable: true,
587
+ get: function () {
588
+ return IOC;
589
+ }
590
+ });
591
+ exports.Identity = Identity
592
+ exports.Init = Init
593
+ exports.Inject = Inject
594
+ exports.InjectOptional = InjectOptional
595
+ exports.createDecorator = createDecorator
596
+ exports.destroyContainer = destroyContainer
597
+ exports.destroyDecorators = destroyDecorators
598
+ exports.initializeContainer = initializeContainer
599
+ exports.initializeDecorators = initializeDecorators
@@ -0,0 +1,7 @@
1
+ export * from "./Common/BaseDecorators.js";
2
+ export * from "./Decorators/Inject.js";
3
+ export * from "./Decorators/InjectOptional.js";
4
+ export * from "./Decorators/Init.js";
5
+ export * from "./Domain/Container.js";
6
+ export * from "./Types/IOCTypes.js";
7
+ export * from "./Utils/Utils.js";