@lppedd/di-wise-neo 0.3.2 → 0.5.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.
@@ -3,11 +3,11 @@
3
3
  */
4
4
  interface Type<A> {
5
5
  /**
6
- * Name of the type.
6
+ * The name of the type.
7
7
  */
8
8
  readonly name: string;
9
9
  /**
10
- * Create an intersection type from another type.
10
+ * Creates an intersection type from another type.
11
11
  *
12
12
  * @example
13
13
  * ```ts
@@ -19,7 +19,7 @@ interface Type<A> {
19
19
  */
20
20
  inter<B>(typeName: string, B: Type<B>): Type<A & B>;
21
21
  /**
22
- * Create a union type from another type.
22
+ * Creates a union type from another type.
23
23
  *
24
24
  * @example
25
25
  * ```ts
@@ -37,7 +37,6 @@ interface Type<A> {
37
37
  interface Constructor<Instance extends object> {
38
38
  new (...args: any[]): Instance;
39
39
  readonly name: string;
40
- readonly length: number;
41
40
  }
42
41
  /**
43
42
  * Token type.
@@ -48,11 +47,11 @@ type Token<Value = any> = [Value] extends [object] ? Type<Value> | Constructor<V
48
47
  */
49
48
  type Tokens<Value = any> = [Token<Value>, ...Token<Value>[]];
50
49
  /**
51
- * Create a type token.
50
+ * Creates a type token.
52
51
  *
53
52
  * @example
54
53
  * ```ts
55
- * const Spell = createType<Spell>("Spell");
54
+ * const ISpell = createType<Spell>("Spell");
56
55
  * ```
57
56
  *
58
57
  * @__NO_SIDE_EFFECTS__
@@ -65,31 +64,33 @@ declare function createType<T>(typeName: string): Type<T>;
65
64
  interface ClassProvider<Instance extends object> {
66
65
  readonly useClass: Constructor<Instance>;
67
66
  }
68
- /**
69
- * Provides a value for a token via another existing token.
70
- */
71
- interface ExistingProvider<Value> {
72
- readonly useExisting: Token<Value>;
73
- }
74
67
  /**
75
68
  * Provides a value for a token via a factory function.
76
69
  *
77
- * The factory function runs inside the injection context
78
- * and can thus access dependencies via {@link inject}.
70
+ * The factory function runs inside the injection context and can
71
+ * thus access dependencies via {@link inject}-like functions.
79
72
  */
80
73
  interface FactoryProvider<Value> {
81
74
  readonly useFactory: (...args: []) => Value;
82
75
  }
83
76
  /**
84
- * Provides a direct - already constructed - value for a token.
77
+ * Provides a static - already constructed - value for a token.
85
78
  */
86
79
  interface ValueProvider<T> {
87
80
  readonly useValue: T;
88
81
  }
82
+ /**
83
+ * Aliases another registered token.
84
+ *
85
+ * Resolving this token will return the value of the aliased one.
86
+ */
87
+ interface ExistingProvider<Value> {
88
+ readonly useExisting: Token<Value>;
89
+ }
89
90
  /**
90
91
  * A token provider.
91
92
  */
92
- type Provider<Value = any> = ClassProvider<Value & object> | ExistingProvider<Value> | FactoryProvider<Value> | ValueProvider<Value>;
93
+ type Provider<Value = any> = ClassProvider<Value & object> | FactoryProvider<Value> | ValueProvider<Value> | ExistingProvider<Value>;
93
94
 
94
95
  declare const Scope: {
95
96
  readonly Inherited: "Inherited";
@@ -212,35 +213,87 @@ interface Container {
212
213
  * Returns whether the token is registered in this container or in parent containers, if any.
213
214
  */
214
215
  isRegistered(token: Token): boolean;
216
+ /**
217
+ * Registers a concrete class, where the class acts as its own token.
218
+ *
219
+ * Tokens provided via the {@link Injectable} decorator applied to the class
220
+ * are also registered as aliases.
221
+ *
222
+ * The default registration scope is determined by the {@link Scoped} decorator,
223
+ * if present.
224
+ */
225
+ registerClass<Instance extends object>(Class: Constructor<Instance>): void;
226
+ /**
227
+ * Registers a concrete class with a token.
228
+ *
229
+ * The default registration scope is determined by the {@link Scoped} decorator
230
+ * applied to the class, if present, but it can be overridden by passing explicit
231
+ * registration options.
232
+ */
233
+ registerClass<Instance extends object, ProvidedInstance extends Instance>(token: Token<Instance>, Class: Constructor<ProvidedInstance>, options?: RegistrationOptions): void;
234
+ /**
235
+ * Registers a token whose value is produced by a factory function.
236
+ *
237
+ * The factory function runs inside the injection context and can
238
+ * thus access dependencies via {@link inject}-like functions.
239
+ */
240
+ registerFactory<Value, ProvidedValue extends Value>(token: Token<Value>, factory: (...args: []) => ProvidedValue, options?: RegistrationOptions): void;
241
+ /**
242
+ * Registers a token with a fixed value.
243
+ *
244
+ * The provided value is returned as-is when the token is resolved (scopes do not apply).
245
+ */
246
+ registerValue<Value, ProvidedValue extends Value>(token: Token<Value>, value: ProvidedValue): void;
247
+ /**
248
+ * Registers one or more tokens as aliases for a target token.
249
+ *
250
+ * When an alias is resolved, the target token is resolved instead.
251
+ */
252
+ registerAlias<Value, ProvidedValue extends Value>(targetToken: Token<ProvidedValue>, aliasTokens: Tokens<Value>): void;
215
253
  /**
216
254
  * Registers a {@link ClassProvider}, using the class itself as its token.
217
255
  *
218
- * Tokens provided to the {@link Injectable} decorator applied to the class
219
- * are also registered as aliases. The scope is determined by the {@link Scoped}
220
- * decorator, if present.
256
+ * Tokens provided via the {@link Injectable} decorator applied to the class
257
+ * are also registered as aliases.
258
+ *
259
+ * The scope is determined by the {@link Scoped} decorator, if present.
260
+ *
261
+ * @see registerClass
221
262
  */
222
- register<Instance extends object>(Class: Constructor<Instance>): this;
263
+ register<Instance extends object>(Class: Constructor<Instance>): Container;
223
264
  /**
224
265
  * Registers a {@link ClassProvider} with a token.
266
+ *
267
+ * The default registration scope is determined by the {@link Scoped} decorator
268
+ * applied to the provided class, if present, but it can be overridden by
269
+ * passing explicit registration options.
270
+ *
271
+ * @see registerClass
225
272
  */
226
- register<Instance extends object, ProviderInstance extends Instance>(token: Token<Instance>, provider: ClassProvider<ProviderInstance>, options?: RegistrationOptions): this;
273
+ register<Instance extends object, ProviderInstance extends Instance>(token: Token<Instance>, provider: ClassProvider<ProviderInstance>, options?: RegistrationOptions): Container;
227
274
  /**
228
275
  * Registers a {@link FactoryProvider} with a token.
276
+ *
277
+ * @see registerFactory
229
278
  */
230
- register<Value, ProviderValue extends Value>(token: Token<Value>, provider: FactoryProvider<ProviderValue>, options?: RegistrationOptions): this;
279
+ register<Value, ProviderValue extends Value>(token: Token<Value>, provider: FactoryProvider<ProviderValue>, options?: RegistrationOptions): Container;
231
280
  /**
232
281
  * Registers an {@link ExistingProvider} with a token.
233
282
  *
234
283
  * The token will alias the one set in `useExisting`.
284
+ *
285
+ * @see registerAlias
235
286
  */
236
- register<Value, ProviderValue extends Value>(token: Token<Value>, provider: ExistingProvider<ProviderValue>): this;
287
+ register<Value, ProviderValue extends Value>(token: Token<Value>, provider: ExistingProvider<ProviderValue>): Container;
237
288
  /**
238
289
  * Registers a {@link ValueProvider} with a token.
239
290
  *
240
291
  * Values provided via `useValue` are never cached (scopes do not apply)
241
292
  * and are simply returned as-is.
293
+ *
294
+ * @see registerValue
242
295
  */
243
- register<Value, ProviderValue extends Value>(token: Token<Value>, provider: ValueProvider<ProviderValue>): this;
296
+ register<Value, ProviderValue extends Value>(token: Token<Value>, provider: ValueProvider<ProviderValue>): Container;
244
297
  /**
245
298
  * Removes all registrations for the given token from the container's internal registry.
246
299
  *
@@ -364,12 +417,12 @@ interface Container {
364
417
  declare function createContainer(options?: Partial<ContainerOptions>): Container;
365
418
 
366
419
  /**
367
- * Class decorator for enabling auto-registration of an unregistered class
368
- * when first resolving it from the container.
420
+ * Class decorator that enables auto-registration of an unregistered class,
421
+ * when the class is first resolved from the container.
369
422
  *
370
423
  * @example
371
424
  * ```ts
372
- * @AutoRegister()
425
+ * @AutoRegister
373
426
  * class Wizard {}
374
427
  *
375
428
  * const wizard = container.resolve(Wizard);
@@ -378,7 +431,28 @@ declare function createContainer(options?: Partial<ContainerOptions>): Container
378
431
  *
379
432
  * @__NO_SIDE_EFFECTS__
380
433
  */
381
- declare function AutoRegister(enable?: boolean): ClassDecorator;
434
+ declare function AutoRegister<Ctor extends Constructor<any>>(Class: Ctor): void;
435
+
436
+ /**
437
+ * Class decorator that enables eager instantiation of a class when it is registered
438
+ * in the container with `Scope.Container`.
439
+ *
440
+ * This causes the container to immediately create and cache the instance of the class,
441
+ * instead of deferring instantiation until the first resolution.
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * @EagerInstantiate
446
+ * @Scoped(Scope.Container)
447
+ * class Wizard {}
448
+ *
449
+ * // A Wizard instance is immediately created and cached by the container
450
+ * const wizard = container.register(Wizard);
451
+ * ```
452
+ *
453
+ * @__NO_SIDE_EFFECTS__
454
+ */
455
+ declare function EagerInstantiate<Ctor extends Constructor<any>>(Class: Ctor): void;
382
456
 
383
457
  interface TokensRef<Value = any> {
384
458
  readonly getRefTokens: () => Set<Token<Value>>;
@@ -387,9 +461,14 @@ interface TokenRef<Value = any> {
387
461
  readonly getRefToken: () => Token<Value>;
388
462
  }
389
463
  /**
390
- * Allows referencing a token that is declared later in the file by wrapping it in a function.
464
+ * Allows referencing tokens that are declared later in the file by wrapping them
465
+ * in a lazily evaluated function.
391
466
  */
392
467
  declare function forwardRef<Value>(token: () => Tokens<Value>): TokensRef<Value>;
468
+ /**
469
+ * Allows referencing a token that is declared later in the file by wrapping it
470
+ * in a lazily evaluated function.
471
+ */
393
472
  declare function forwardRef<Value>(token: () => Token<Value>): TokenRef<Value>;
394
473
 
395
474
  /**
@@ -424,8 +503,8 @@ declare function Inject<Value>(token: Token<Value>): ParameterDecorator;
424
503
  declare function Inject<Value>(tokens: TokenRef<Value>): ParameterDecorator;
425
504
 
426
505
  /**
427
- * Class decorator for registering additional aliasing tokens for the decorated type
428
- * when registering it.
506
+ * Class decorator that registers additional aliasing tokens for the decorated type,
507
+ * when the type is first registered in the container.
429
508
  *
430
509
  * The container uses {@link ExistingProvider} under the hood.
431
510
  *
@@ -437,8 +516,8 @@ declare function Inject<Value>(tokens: TokenRef<Value>): ParameterDecorator;
437
516
  */
438
517
  declare function Injectable<This extends object, Value extends This>(...tokens: Tokens<Value>): ClassDecorator;
439
518
  /**
440
- * Class decorator for registering additional aliasing tokens for the decorated type
441
- * when registering it.
519
+ * Class decorator that registers additional aliasing tokens for the decorated type,
520
+ * when the type is first registered in the container.
442
521
  *
443
522
  * The container uses {@link ExistingProvider} under the hood.
444
523
  *
@@ -718,7 +797,7 @@ declare const Injector: Type<Injector>;
718
797
  */
719
798
  interface MiddlewareComposer {
720
799
  /**
721
- * Add a middleware function to the composer.
800
+ * Adds a middleware function to the composer.
722
801
  */
723
802
  use<MethodKey extends keyof Container>(key: MethodKey, wrap: Container[MethodKey] extends Function ? (next: Container[MethodKey]) => Container[MethodKey] : never): MiddlewareComposer;
724
803
  }
@@ -744,7 +823,7 @@ interface Middleware {
744
823
  (composer: MiddlewareComposer, api: Readonly<Container>): void;
745
824
  }
746
825
  /**
747
- * Apply middleware functions to a container.
826
+ * Applies middleware functions to a container.
748
827
  *
749
828
  * Middlewares are applied in array order, but execute in reverse order.
750
829
  *
@@ -768,5 +847,5 @@ interface Middleware {
768
847
  */
769
848
  declare function applyMiddleware(container: Container, middlewares: Middleware[]): Container;
770
849
 
771
- export { AutoRegister, Inject, InjectAll, Injectable, Injector, Optional, OptionalAll, Scope, Scoped, applyMiddleware, build, createContainer, createType, forwardRef, inject, injectAll, injectBy };
850
+ export { AutoRegister, EagerInstantiate, Inject, InjectAll, Injectable, Injector, Optional, OptionalAll, Scope, Scoped, applyMiddleware, build, createContainer, createType, forwardRef, inject, injectAll, injectBy };
772
851
  export type { ClassProvider, Constructor, Container, ContainerOptions, ExistingProvider, FactoryProvider, Middleware, MiddlewareComposer, Provider, RegistrationOptions, Token, TokenRef, Tokens, TokensRef, Type, ValueProvider };
package/dist/es/index.mjs CHANGED
@@ -207,10 +207,6 @@ function isClassProvider(provider) {
207
207
  return "useClass" in provider;
208
208
  }
209
209
  // @internal
210
- function isExistingProvider(provider) {
211
- return "useExisting" in provider;
212
- }
213
- // @internal
214
210
  function isFactoryProvider(provider) {
215
211
  return "useFactory" in provider;
216
212
  }
@@ -218,6 +214,10 @@ function isFactoryProvider(provider) {
218
214
  function isValueProvider(provider) {
219
215
  return "useValue" in provider;
220
216
  }
217
+ // @internal
218
+ function isExistingProvider(provider) {
219
+ return "useExisting" in provider;
220
+ }
221
221
 
222
222
  const Scope = {
223
223
  Inherited: "Inherited",
@@ -229,11 +229,11 @@ const Scope = {
229
229
  /**
230
230
  * Type API.
231
231
  */ /**
232
- * Create a type token.
232
+ * Creates a type token.
233
233
  *
234
234
  * @example
235
235
  * ```ts
236
- * const Spell = createType<Spell>("Spell");
236
+ * const ISpell = createType<Spell>("Spell");
237
237
  * ```
238
238
  *
239
239
  * @__NO_SIDE_EFFECTS__
@@ -279,8 +279,8 @@ function getTypeName(value) {
279
279
  // @internal
280
280
  class TokenRegistry {
281
281
  constructor(parent){
282
- this.parent = parent;
283
282
  this.myMap = new Map();
283
+ this.myParent = parent;
284
284
  }
285
285
  get(token) {
286
286
  // To clarify, at(-1) means we take the last added registration for this token
@@ -333,7 +333,7 @@ class TokenRegistry {
333
333
  }
334
334
  getAllFromParent(token) {
335
335
  const registrations = this.myMap.get(token);
336
- return registrations || this.parent?.getAllFromParent(token);
336
+ return registrations || this.myParent?.getAllFromParent(token);
337
337
  }
338
338
  }
339
339
  // @internal
@@ -384,12 +384,11 @@ function isDisposable(value) {
384
384
 
385
385
  /**
386
386
  * The default implementation of a di-wise-neo {@link Container}.
387
- */ class DefaultContainer {
388
- constructor(myParent, options){
389
- this.myParent = myParent;
390
- // eslint-disable-next-line no-use-before-define
387
+ */ class ContainerImpl {
388
+ constructor(parent, options){
391
389
  this.myChildren = new Set();
392
390
  this.myDisposed = false;
391
+ this.myParent = parent;
393
392
  this.myOptions = {
394
393
  autoRegister: false,
395
394
  defaultScope: Scope.Inherited,
@@ -413,7 +412,7 @@ function isDisposable(value) {
413
412
  }
414
413
  createChild(options) {
415
414
  this.checkDisposed();
416
- const container = new DefaultContainer(this, {
415
+ const container = new ContainerImpl(this, {
417
416
  ...this.myOptions,
418
417
  ...options
419
418
  });
@@ -460,20 +459,51 @@ function isDisposable(value) {
460
459
  this.checkDisposed();
461
460
  return this.myTokenRegistry.get(token) !== undefined;
462
461
  }
462
+ registerClass(token, Class, options) {
463
+ // This mess will go away once/if we remove the register method
464
+ // in favor of the multiple specialized ones
465
+ if (Class) {
466
+ const ctor = Class ?? token;
467
+ this.register(token, {
468
+ useClass: ctor
469
+ }, options);
470
+ } else {
471
+ this.register(token);
472
+ }
473
+ }
474
+ registerFactory(token, factory, options) {
475
+ this.register(token, {
476
+ useFactory: factory
477
+ }, options);
478
+ }
479
+ registerValue(token, value) {
480
+ this.register(token, {
481
+ useValue: value
482
+ });
483
+ }
484
+ registerAlias(targetToken, aliasTokens) {
485
+ // De-duplicate tokens
486
+ for (const alias of new Set(aliasTokens)){
487
+ this.register(alias, {
488
+ useExisting: targetToken
489
+ });
490
+ }
491
+ }
463
492
  register(...args) {
464
493
  this.checkDisposed();
465
494
  if (args.length == 1) {
466
495
  const Class = args[0];
467
496
  const metadata = getMetadata(Class);
468
- // Register the class itself
469
- this.myTokenRegistry.set(Class, {
497
+ const registration = {
470
498
  // The provider is of type ClassProvider, initialized by getMetadata
471
499
  provider: metadata.provider,
472
500
  options: {
473
- scope: metadata.scope
501
+ scope: metadata.scope ?? this.myOptions.defaultScope
474
502
  },
475
503
  dependencies: metadata.dependencies
476
- });
504
+ };
505
+ // Register the class itself
506
+ this.myTokenRegistry.set(Class, registration);
477
507
  // Register the additional tokens specified via class decorators.
478
508
  // These tokens will point to the original Class token and will have the same scope.
479
509
  for (const token of metadata.tokensRef.getRefTokens()){
@@ -483,21 +513,29 @@ function isDisposable(value) {
483
513
  }
484
514
  });
485
515
  }
516
+ // Eager-instantiate only if the class is container-scoped
517
+ if (metadata.eagerInstantiate && registration.options?.scope === Scope.Container) {
518
+ this.resolve(Class);
519
+ }
486
520
  } else {
487
521
  const [token, provider, options] = args;
488
522
  if (isClassProvider(provider)) {
489
- const Class = provider.useClass;
490
- const metadata = getMetadata(Class);
491
- this.myTokenRegistry.set(token, {
523
+ const metadata = getMetadata(provider.useClass);
524
+ const registration = {
492
525
  provider: metadata.provider,
493
526
  options: {
494
527
  // The explicit registration options override what is specified
495
528
  // via class decorators (e.g., @Scoped)
496
- scope: metadata.scope,
529
+ scope: metadata.scope ?? this.myOptions.defaultScope,
497
530
  ...options
498
531
  },
499
532
  dependencies: metadata.dependencies
500
- });
533
+ };
534
+ this.myTokenRegistry.set(token, registration);
535
+ // Eager-instantiate only if the provided class is container-scoped
536
+ if (metadata.eagerInstantiate && registration.options?.scope === Scope.Container) {
537
+ this.resolve(token);
538
+ }
501
539
  } else {
502
540
  if (isExistingProvider(provider)) {
503
541
  assert(token !== provider.useExisting, `the useExisting token ${token.name} cannot be the same as the token being registered`);
@@ -785,16 +823,16 @@ function isDisposable(value) {
785
823
  autoRegister: false,
786
824
  defaultScope: Scope.Inherited
787
825
  }) {
788
- return new DefaultContainer(undefined, options);
826
+ return new ContainerImpl(undefined, options);
789
827
  }
790
828
 
791
829
  /**
792
- * Class decorator for enabling auto-registration of an unregistered class
793
- * when first resolving it from the container.
830
+ * Class decorator that enables auto-registration of an unregistered class,
831
+ * when the class is first resolved from the container.
794
832
  *
795
833
  * @example
796
834
  * ```ts
797
- * @AutoRegister()
835
+ * @AutoRegister
798
836
  * class Wizard {}
799
837
  *
800
838
  * const wizard = container.resolve(Wizard);
@@ -802,11 +840,32 @@ function isDisposable(value) {
802
840
  * ```
803
841
  *
804
842
  * @__NO_SIDE_EFFECTS__
805
- */ function AutoRegister(enable = true) {
806
- return function(Class) {
807
- const metadata = getMetadata(Class);
808
- metadata.autoRegister = enable;
809
- };
843
+ */ function AutoRegister(Class) {
844
+ const metadata = getMetadata(Class);
845
+ metadata.autoRegister = true;
846
+ }
847
+
848
+ /**
849
+ * Class decorator that enables eager instantiation of a class when it is registered
850
+ * in the container with `Scope.Container`.
851
+ *
852
+ * This causes the container to immediately create and cache the instance of the class,
853
+ * instead of deferring instantiation until the first resolution.
854
+ *
855
+ * @example
856
+ * ```ts
857
+ * @EagerInstantiate
858
+ * @Scoped(Scope.Container)
859
+ * class Wizard {}
860
+ *
861
+ * // A Wizard instance is immediately created and cached by the container
862
+ * const wizard = container.register(Wizard);
863
+ * ```
864
+ *
865
+ * @__NO_SIDE_EFFECTS__
866
+ */ function EagerInstantiate(Class) {
867
+ const metadata = getMetadata(Class);
868
+ metadata.eagerInstantiate = true;
810
869
  }
811
870
 
812
871
  function forwardRef(token) {
@@ -990,7 +1049,7 @@ function OptionalAll(token) {
990
1049
  });
991
1050
 
992
1051
  /**
993
- * Apply middleware functions to a container.
1052
+ * Applies middleware functions to a container.
994
1053
  *
995
1054
  * Middlewares are applied in array order, but execute in reverse order.
996
1055
  *
@@ -1033,5 +1092,5 @@ function OptionalAll(token) {
1033
1092
  return container;
1034
1093
  }
1035
1094
 
1036
- export { AutoRegister, Inject, InjectAll, Injectable, Injector, Optional, OptionalAll, Scope, Scoped, applyMiddleware, build, createContainer, createType, forwardRef, inject, injectAll, injectBy };
1095
+ export { AutoRegister, EagerInstantiate, Inject, InjectAll, Injectable, Injector, Optional, OptionalAll, Scope, Scoped, applyMiddleware, build, createContainer, createType, forwardRef, inject, injectAll, injectBy };
1037
1096
  //# sourceMappingURL=index.mjs.map