@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.
package/README.md CHANGED
@@ -1,16 +1,15 @@
1
1
  <!--suppress HtmlDeprecatedAttribute -->
2
+ <h1 align="center">di-wise-neo</h1>
3
+ <p align="center">Lightweight, type-safe, flexible dependency injection library for TypeScript and JavaScript</p>
2
4
  <div align="center">
3
- <h1>di-wise-neo</h1>
4
- <p>Lightweight, type-safe, flexible dependency injection library for TypeScript and JavaScript</p>
5
5
 
6
6
  [![test](https://img.shields.io/github/actions/workflow/status/lppedd/di-wise-neo/test.yml.svg?branch=main)](https://github.com/lppedd/di-wise-neo/actions/workflows/test.yml)
7
7
  [![npm](https://img.shields.io/npm/v/@lppedd/di-wise-neo?color=%23de1f1f&logo=npm)](https://www.npmjs.com/package/@lppedd/di-wise-neo)
8
8
  [![npm gzipped size](https://img.shields.io/bundlejs/size/@lppedd/di-wise-neo)](https://bundlejs.com/?q=@lppedd/di-wise-neo)
9
9
  [![license](https://img.shields.io/github/license/lppedd/di-wise-neo?color=blue)](https://github.com/lppedd/di-wise-neo/blob/main/LICENSE)
10
10
 
11
- <img src="./.github/images/neo-wall.jpg" alt="di-wise-neo" style="border: 3px solid black; border-radius: 15px;" />
12
- <div><sub>yes, I like The Matrix</sub></div>
13
11
  </div>
12
+ <img align="center" src="./.github/images/neo-wall.jpg" alt="di-wise-neo" style="border: 3px solid black; border-radius: 15px;" />
14
13
 
15
14
  > [!NOTE]
16
15
  >
@@ -23,7 +22,7 @@
23
22
  - [Why yet another library](#why-yet-another-library)
24
23
  - [Installation](#installation)
25
24
  - [API reference](#api-reference)
26
- - [Ergonomics](#ergonomics)
25
+ - [Ergonomics & Requirements](#ergonomics)
27
26
  - [Quickstart](#quickstart)
28
27
  - [Container scopes](#container-scopes)
29
28
  - [Token registration](#token-registration)
@@ -93,9 +92,10 @@ pnpm add @lppedd/di-wise-neo
93
92
  ```sh
94
93
  yarn add @lppedd/di-wise-neo
95
94
  ```
95
+
96
96
  ## API reference
97
97
 
98
- You can find the complete API reference at https://lppedd.github.io/di-wise-neo
98
+ You can find the complete API reference at [lppedd.github.io/di-wise-neo](https://lppedd.github.io/di-wise-neo)
99
99
 
100
100
  ## Ergonomics
101
101
 
@@ -103,6 +103,11 @@ You can find the complete API reference at https://lppedd.github.io/di-wise-neo
103
103
  - Does **not** use [reflect-metadata](https://www.npmjs.com/package/reflect-metadata) to drive decorators
104
104
  - **Can** be used from JavaScript with function-based injection
105
105
 
106
+ ### Requirements
107
+
108
+ - When using decorator-based injection, `experimentalDecorators` must be enabled in your `tsconfig.json` file
109
+ - The JavaScript environment must support features such as `Array.flat`, `WeakSet`, `WeakMap`, `Set`, and `Map`
110
+
106
111
  ## Quickstart
107
112
 
108
113
  ```ts
@@ -220,14 +225,14 @@ Alternatively, use an explicit `ClassProvider` object - useful when registering
220
225
  an interface or abstract type:
221
226
 
222
227
  ```ts
223
- const Store = createType<Store>("Store");
224
- container.register(Store, {
228
+ const IStore = createType<Store>("Store");
229
+ container.register(IStore, {
225
230
  useClass: SecretStore, // class SecretStore implements Store
226
231
  });
227
232
  ```
228
233
 
229
- Upon resolving `Store`, the container creates an instance of `SecretStore`,
230
- caching it according to the configured scope.
234
+ Upon resolving `IStore` - which represents the `Store` interface - the container
235
+ creates an instance of `SecretStore`, caching it according to the configured scope.
231
236
 
232
237
  ### FactoryProvider
233
238
 
@@ -245,7 +250,7 @@ according to the configured scope.
245
250
 
246
251
  ### ValueProvider
247
252
 
248
- A static value - always taken as-is and unaffected by scopes - can be registered using:
253
+ A fixed value - always taken as-is and unaffected by scopes - can be registered using:
249
254
 
250
255
  ```ts
251
256
  const PID = createType<number>("PID");
@@ -310,7 +315,7 @@ never been registered in the container.
310
315
 
311
316
  ```ts
312
317
  export class ExtensionContext {
313
- readonly stores /*: Store[] */ = injectAll(Store);
318
+ readonly stores /*: Store[] */ = injectAll(IStore);
314
319
 
315
320
  /* ... */
316
321
 
@@ -341,7 +346,7 @@ has never been registered in the container.
341
346
  ```ts
342
347
  export class ExtensionContext {
343
348
  // The type does not change compared to injectAll(T), but the call does not fail
344
- readonly stores /*: Store[] */ = optionalAll(Store);
349
+ readonly stores /*: Store[] */ = optionalAll(IStore);
345
350
 
346
351
  /* ... */
347
352
  }
@@ -366,7 +371,7 @@ export class ProcessManager {
366
371
  /* ... */
367
372
 
368
373
  // The method is called immediately after instance construction
369
- notifyListener(@Inject(ProcessListener) listeners: ProcessListener): void {
374
+ notifyListener(@Inject(ProcessListener) listener: ProcessListener): void {
370
375
  listener.processStarted(this.rootPID);
371
376
  }
372
377
  }
@@ -381,7 +386,7 @@ never been registered in the container.
381
386
 
382
387
  ```ts
383
388
  export class ExtensionContext {
384
- constructor(@InjectAll(Store) readonly stores: Store[]) {}
389
+ constructor(@InjectAll(IStore) readonly stores: Store[]) {}
385
390
 
386
391
  /* ... */
387
392
 
@@ -412,7 +417,7 @@ has never been registered in the container.
412
417
  ```ts
413
418
  export class ExtensionContext {
414
419
  // The type does not change compared to @InjectAll, but construction does not fail
415
- constructor(@OptionalAll(Store) readonly stores: Store[]) {}
420
+ constructor(@OptionalAll(IStore) readonly stores: Store[]) {}
416
421
 
417
422
  /* ... */
418
423
  }
@@ -423,13 +428,13 @@ export class ExtensionContext {
423
428
  Sometimes you may need to reference a token or class that is declared later in the file.
424
429
  Normally, attempting to do that would result in a `ReferenceError`:
425
430
 
426
- > ReferenceError: Cannot access 'Store' before initialization
431
+ > ReferenceError: Cannot access 'IStore' before initialization
427
432
 
428
433
  We can work around this problem by using the `forwardRef` helper function:
429
434
 
430
435
  ```ts
431
436
  export class ExtensionContext {
432
- constructor(@OptionalAll(forwardRef(() => Store)) readonly stores: Store[]) {}
437
+ constructor(@OptionalAll(forwardRef(() => IStore)) readonly stores: Store[]) {}
433
438
 
434
439
  /* ... */
435
440
  }
@@ -471,7 +476,7 @@ In this example, `ExtensionContext` will be registered with **Resolution** scope
471
476
  Enables automatic registration of the decorated class if it has not been registered explicitly.
472
477
 
473
478
  ```ts
474
- @AutoRegister()
479
+ @AutoRegister
475
480
  export class ExtensionContext {
476
481
  /* ... */
477
482
  }
@@ -480,6 +485,24 @@ export class ExtensionContext {
480
485
  container.resolve(ExtensionContext);
481
486
  ```
482
487
 
488
+ ### `@EagerInstantiate`
489
+
490
+ Marks a class for eager instantiation when registered with **Container** scope.
491
+
492
+ This causes the container to immediately create and cache the instance of the class
493
+ at registration time, instead of deferring instantiation until the first resolution.
494
+
495
+ ```ts
496
+ @EagerInstantiate
497
+ @Scoped(Scope.Container)
498
+ export class ExtensionContext {
499
+ /* ... */
500
+ }
501
+
502
+ // The container immediately creates and caches the instance
503
+ container.register(ExtensionContext);
504
+ ```
505
+
483
506
  ## Testing support
484
507
 
485
508
  Testing is an important part of software development, and dependency injection is meant to make it easier.
@@ -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 };