navi-di 1.1.1 → 1.1.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/README.md CHANGED
@@ -55,6 +55,9 @@ Runtime exports:
55
55
  - `Inject`
56
56
  - `Token`
57
57
 
58
+ `Container` exposes the runtime API for resolution and low-level registration,
59
+ including `of()`, `get()`, `set()`, `has()`, `remove()`, and `reset()`.
60
+
58
61
  Type-only exports:
59
62
 
60
63
  - `Constructable` / `AbstractConstructable`
@@ -209,6 +212,9 @@ handler.logger.log('hello from token injection');
209
212
 
210
213
  Returns the default container or a named container.
211
214
 
215
+ Calling `Container.of(id)` with the same identifier reuses the same container
216
+ instance until that instance is disposed.
217
+
212
218
  ### `container.get(id)`
213
219
 
214
220
  Resolves a service by class or service identifier.
@@ -218,6 +224,15 @@ Throws:
218
224
  - `ServiceNotFoundError` when no registration exists;
219
225
  - `CircularDependencyError` when the current resolution path loops back to an in-progress dependency.
220
226
 
227
+ ### `container.tryGet(id)`
228
+
229
+ Resolves a service by class or service identifier and returns `undefined` when
230
+ no registration exists.
231
+
232
+ Unlike `get()`, this only returns `undefined` when the requested identifier is
233
+ not registered anywhere in the current resolution path. Other failures, such as
234
+ circular dependencies or missing nested dependencies, still throw.
235
+
221
236
  ### `container.has(id)`
222
237
 
223
238
  Checks whether the current container has a local registration.
@@ -235,12 +250,80 @@ Supported strategies:
235
250
 
236
251
  This is especially useful in tests.
237
252
 
238
- ### `container.set(metadata)`
253
+ ### `await container.dispose()`
254
+
255
+ Disposes the current container instance explicitly.
256
+
257
+ - clears local registrations, bindings, and cached service instances;
258
+ - awaits any bound value or cached service instance that exposes a `dispose()` method;
259
+ - makes the disposed container instance unusable for future operations.
260
+
261
+ After disposal, calling `Container.of(id)` again creates a fresh container for
262
+ that identifier. The same applies to the default container: after disposal, the
263
+ next `Container.of()` or named-container fallback access recreates a fresh
264
+ default container with no previous registrations or cached instances.
265
+
266
+ ### `container.set(id, valueOrProvider)`
267
+
268
+ Registers or replaces a bound value or provider for a service identifier.
269
+
270
+ Use `set()` when you want manual registration without decorating a class.
271
+ This is the supported low-level API for values, classes, and factories.
272
+
273
+ Supported forms today:
274
+
275
+ - `container.set(id, value)`
276
+ - `container.set(id, { useValue: value })`
277
+ - `container.set(id, { useClass: Class, scope?, injections? })`
278
+ - `container.set(id, { useFactory: (container) => value, scope? })`
279
+
280
+ This is the low-level API for manual value, class, and factory registration.
281
+ For decorator-driven classes, prefer `@Service()`.
282
+
283
+ Value example:
284
+
285
+ ```ts
286
+ const REQUEST_ID = 'request-id';
287
+
288
+ Container.of().set(REQUEST_ID, { useValue: crypto.randomUUID() });
289
+
290
+ const requestId = Container.of().get<string>(REQUEST_ID);
291
+ ```
239
292
 
240
- Registers or replaces service metadata for a service identifier.
293
+ Class example:
294
+
295
+ ```ts
296
+ interface Logger {
297
+ log(message: string): void;
298
+ }
299
+
300
+ class ConsoleLogger implements Logger {
301
+ public log(message: string) {
302
+ console.log(message);
303
+ }
304
+ }
305
+
306
+ Container.of().set<Logger>('logger', { useClass: ConsoleLogger, scope: 'singleton' });
307
+ ```
308
+
309
+ Factory example:
310
+
311
+ ```ts
312
+ class Connection {
313
+ constructor(public readonly requestId: string) {}
314
+ }
315
+
316
+ Container.of().set('request-id', { useValue: 'request-1' });
317
+ Container.of().set(Connection, {
318
+ useFactory: (container) => new Connection(container.get('request-id')),
319
+ scope: 'container',
320
+ });
321
+ ```
241
322
 
242
- This is a low-level API that powers manual registration scenarios and internal tests.
243
- For application-facing code, prefer `@Service()` unless you specifically need to construct metadata yourself.
323
+ For named containers, values bound in the default container are available through
324
+ fallback. Provider objects are detected structurally, so plain object values that
325
+ contain `useValue`, `useClass`, or `useFactory` should be wrapped with
326
+ `{ useValue: value }` if you want them treated as values.
244
327
 
245
328
  ## Internal architecture
246
329
 
@@ -1,4 +1,4 @@
1
- import type { ContainerIdentifier, Metadata, ServiceIdentifier } from '../types';
1
+ import type { ContainerIdentifier, Metadata, ServiceIdentifier, ServiceProvider } from '../types';
2
2
  /**
3
3
  * Resolves services and stores container-local bindings.
4
4
  *
@@ -17,12 +17,22 @@ export declare class Container {
17
17
  private bindingMap;
18
18
  private resolving;
19
19
  private resolvingPath;
20
+ private disposed;
20
21
  constructor(id: ContainerIdentifier);
22
+ private ensureNotDisposed;
23
+ private isDisposable;
24
+ private canResolveLocally;
25
+ private canResolve;
26
+ private isValueProvider;
27
+ private isClassProvider;
28
+ private isFactoryProvider;
29
+ private getClassProviderMetadata;
30
+ private getFactoryProviderMetadata;
21
31
  /**
22
32
  * Returns the default container or a named container.
23
33
  *
24
- * Calling this method with the same identifier always returns the same
25
- * container instance.
34
+ * Calling this method with the same identifier returns the same container
35
+ * instance until that instance is disposed.
26
36
  *
27
37
  * @param id The container identifier. Omit this to use the default container.
28
38
  * @returns The matching container instance.
@@ -50,16 +60,17 @@ export declare class Container {
50
60
  */
51
61
  has(id: ServiceIdentifier): boolean;
52
62
  /**
53
- * Binds a concrete value to this container.
63
+ * Registers a value or provider for a service identifier.
54
64
  *
55
- * Bound values are returned as-is when the same identifier is requested from
56
- * this container.
65
+ * Use a plain value to bind an explicit instance, or a provider object to
66
+ * resolve by class or factory.
57
67
  *
58
- * @param id The service identifier to bind.
59
- * @param value The value to return for that identifier.
68
+ * @param id The service identifier to register.
69
+ * @param valueOrProvider The bound value or provider definition.
60
70
  * @returns The current container.
61
71
  */
62
72
  set<T>(id: ServiceIdentifier<T>, value: T): this;
73
+ set<T>(id: ServiceIdentifier<T>, provider: ServiceProvider<T>): this;
63
74
  /**
64
75
  * Removes a local binding or registration from this container.
65
76
  *
@@ -91,6 +102,24 @@ export declare class Container {
91
102
  * @throws {CircularDependencyError} If the dependency graph contains a cycle.
92
103
  */
93
104
  get<T>(id: ServiceIdentifier<T>): T;
105
+ /**
106
+ * Resolves a service if it exists, otherwise returns `undefined`.
107
+ *
108
+ * Unlike `get()`, this only suppresses `ServiceNotFoundError`. Other errors,
109
+ * such as circular dependencies or disposed-container access, still surface.
110
+ *
111
+ * @param id The service identifier to resolve.
112
+ * @returns The resolved value, or `undefined` when the service is missing.
113
+ */
114
+ tryGet<T>(id: ServiceIdentifier<T>): T | undefined;
115
+ /**
116
+ * Disposes this container instance and clears all local registrations.
117
+ *
118
+ * The container becomes unusable after disposal. Cached service instances and
119
+ * bound values that expose an async or sync `dispose()` method are awaited in
120
+ * the order they were discovered.
121
+ */
122
+ dispose(): Promise<void>;
94
123
  private isDefault;
95
124
  /**
96
125
  * Resets a container by its identifier.
@@ -1,4 +1,4 @@
1
- import { CircularDependencyError, ServiceNotFoundError } from '../errors';
1
+ import { CircularDependencyError, ContainerDisposedError, ServiceNotFoundError } from '../errors';
2
2
  import { EMPTY_VALUE } from '../types';
3
3
  import { ContainerRegistry } from './registry';
4
4
  /**
@@ -19,14 +19,67 @@ export class Container {
19
19
  bindingMap = new Map();
20
20
  resolving = new Set();
21
21
  resolvingPath = [];
22
+ disposed = false;
22
23
  constructor(id) {
23
24
  this.id = id;
24
25
  }
26
+ ensureNotDisposed() {
27
+ if (this.disposed) {
28
+ throw new ContainerDisposedError(this.id);
29
+ }
30
+ }
31
+ isDisposable(value) {
32
+ return typeof value === 'object' && value !== null && 'dispose' in value && typeof value.dispose === 'function';
33
+ }
34
+ canResolveLocally(id) {
35
+ return this.bindingMap.has(id) || this.metadataMap.has(id);
36
+ }
37
+ canResolve(id) {
38
+ if (this.canResolveLocally(id)) {
39
+ return true;
40
+ }
41
+ if (this.isDefault()) {
42
+ return false;
43
+ }
44
+ return ContainerRegistry.defaultContainer.canResolveLocally(id);
45
+ }
46
+ isValueProvider(provider) {
47
+ return typeof provider === 'object' && provider !== null && 'useValue' in provider;
48
+ }
49
+ isClassProvider(provider) {
50
+ return typeof provider === 'object' && provider !== null && 'useClass' in provider;
51
+ }
52
+ isFactoryProvider(provider) {
53
+ return typeof provider === 'object' && provider !== null && 'useFactory' in provider;
54
+ }
55
+ getClassProviderMetadata(id, provider) {
56
+ const existingMetadata = this.metadataMap.get(provider.useClass) ?? ContainerRegistry.defaultContainer.metadataMap.get(provider.useClass);
57
+ const inheritedInjections = existingMetadata?.Class === provider.useClass ? [...existingMetadata.injections] : [];
58
+ const inheritedScope = existingMetadata?.Class === provider.useClass ? existingMetadata.scope : 'container';
59
+ return {
60
+ id,
61
+ Class: provider.useClass,
62
+ name: provider.useClass.name || String(id),
63
+ injections: provider.injections ?? inheritedInjections,
64
+ scope: provider.scope ?? inheritedScope,
65
+ value: EMPTY_VALUE,
66
+ };
67
+ }
68
+ getFactoryProviderMetadata(id, provider) {
69
+ return {
70
+ id,
71
+ name: typeof id === 'function' ? id.name : String(id),
72
+ injections: [],
73
+ scope: provider.scope ?? 'container',
74
+ value: EMPTY_VALUE,
75
+ factory: provider.useFactory,
76
+ };
77
+ }
25
78
  /**
26
79
  * Returns the default container or a named container.
27
80
  *
28
- * Calling this method with the same identifier always returns the same
29
- * container instance.
81
+ * Calling this method with the same identifier returns the same container
82
+ * instance until that instance is disposed.
30
83
  *
31
84
  * @param id The container identifier. Omit this to use the default container.
32
85
  * @returns The matching container instance.
@@ -53,6 +106,7 @@ export class Container {
53
106
  * @returns The current container.
54
107
  */
55
108
  register(metadata) {
109
+ this.ensureNotDisposed();
56
110
  if (metadata.scope === 'singleton' && !this.isDefault()) {
57
111
  ContainerRegistry.defaultContainer.register(metadata);
58
112
  this.metadataMap.delete(metadata.id);
@@ -80,20 +134,26 @@ export class Container {
80
134
  * @returns `true` when the current container has a local registration.
81
135
  */
82
136
  has(id) {
83
- return this.metadataMap.has(id);
137
+ this.ensureNotDisposed();
138
+ return this.bindingMap.has(id) || this.metadataMap.has(id);
84
139
  }
85
- /**
86
- * Binds a concrete value to this container.
87
- *
88
- * Bound values are returned as-is when the same identifier is requested from
89
- * this container.
90
- *
91
- * @param id The service identifier to bind.
92
- * @param value The value to return for that identifier.
93
- * @returns The current container.
94
- */
95
- set(id, value) {
96
- this.bindingMap.set(id, value);
140
+ set(id, valueOrProvider) {
141
+ this.ensureNotDisposed();
142
+ if (this.isValueProvider(valueOrProvider)) {
143
+ this.bindingMap.set(id, valueOrProvider.useValue);
144
+ this.metadataMap.delete(id);
145
+ return this;
146
+ }
147
+ if (this.isClassProvider(valueOrProvider)) {
148
+ this.bindingMap.delete(id);
149
+ return this.register(this.getClassProviderMetadata(id, valueOrProvider));
150
+ }
151
+ if (this.isFactoryProvider(valueOrProvider)) {
152
+ this.bindingMap.delete(id);
153
+ return this.register(this.getFactoryProviderMetadata(id, valueOrProvider));
154
+ }
155
+ this.bindingMap.set(id, valueOrProvider);
156
+ this.metadataMap.delete(id);
97
157
  return this;
98
158
  }
99
159
  /**
@@ -103,6 +163,7 @@ export class Container {
103
163
  * @returns The current container.
104
164
  */
105
165
  remove(id) {
166
+ this.ensureNotDisposed();
106
167
  this.bindingMap.delete(id);
107
168
  this.metadataMap.delete(id);
108
169
  return this;
@@ -117,6 +178,7 @@ export class Container {
117
178
  * @returns The current container.
118
179
  */
119
180
  reset(strategy = 'value') {
181
+ this.ensureNotDisposed();
120
182
  if (strategy === 'value') {
121
183
  this.metadataMap.forEach((metadata) => {
122
184
  metadata.value = EMPTY_VALUE;
@@ -143,11 +205,15 @@ export class Container {
143
205
  * @throws {CircularDependencyError} If the dependency graph contains a cycle.
144
206
  */
145
207
  get(id) {
208
+ this.ensureNotDisposed();
146
209
  if (this.bindingMap.has(id)) {
147
210
  return this.bindingMap.get(id);
148
211
  }
149
212
  let metadata = this.metadataMap.get(id);
150
213
  if (!metadata && !this.isDefault()) {
214
+ if (ContainerRegistry.defaultContainer.bindingMap.has(id)) {
215
+ return ContainerRegistry.defaultContainer.bindingMap.get(id);
216
+ }
151
217
  const defaultMetadata = ContainerRegistry.defaultContainer.metadataMap.get(id);
152
218
  if (!defaultMetadata) {
153
219
  throw new ServiceNotFoundError(id);
@@ -179,7 +245,7 @@ export class Container {
179
245
  this.resolving.add(id);
180
246
  this.resolvingPath.push(id);
181
247
  try {
182
- const instance = new metadata.Class();
248
+ const instance = metadata.factory ? metadata.factory(this) : new metadata.Class();
183
249
  for (const injection of metadata.injections) {
184
250
  Object.defineProperty(instance, injection.name, {
185
251
  value: this.get(injection.id),
@@ -197,6 +263,54 @@ export class Container {
197
263
  this.resolvingPath.pop();
198
264
  }
199
265
  }
266
+ /**
267
+ * Resolves a service if it exists, otherwise returns `undefined`.
268
+ *
269
+ * Unlike `get()`, this only suppresses `ServiceNotFoundError`. Other errors,
270
+ * such as circular dependencies or disposed-container access, still surface.
271
+ *
272
+ * @param id The service identifier to resolve.
273
+ * @returns The resolved value, or `undefined` when the service is missing.
274
+ */
275
+ tryGet(id) {
276
+ this.ensureNotDisposed();
277
+ if (!this.canResolve(id)) {
278
+ return undefined;
279
+ }
280
+ return this.get(id);
281
+ }
282
+ /**
283
+ * Disposes this container instance and clears all local registrations.
284
+ *
285
+ * The container becomes unusable after disposal. Cached service instances and
286
+ * bound values that expose an async or sync `dispose()` method are awaited in
287
+ * the order they were discovered.
288
+ */
289
+ async dispose() {
290
+ if (this.disposed) {
291
+ return;
292
+ }
293
+ const ownedValues = new Set();
294
+ this.bindingMap.forEach((value) => {
295
+ ownedValues.add(value);
296
+ });
297
+ this.metadataMap.forEach((metadata) => {
298
+ if (metadata.value !== EMPTY_VALUE) {
299
+ ownedValues.add(metadata.value);
300
+ }
301
+ });
302
+ this.disposed = true;
303
+ ContainerRegistry.disposeContainer(this);
304
+ this.bindingMap.clear();
305
+ this.metadataMap.clear();
306
+ this.resolving.clear();
307
+ this.resolvingPath = [];
308
+ for (const value of ownedValues) {
309
+ if (this.isDisposable(value)) {
310
+ await value.dispose();
311
+ }
312
+ }
313
+ }
200
314
  isDefault() {
201
315
  return this === ContainerRegistry.defaultContainer;
202
316
  }
@@ -48,4 +48,5 @@ export declare class ContainerRegistry {
48
48
  * @throws {DefaultContainerIdError} If the reserved `default` id is used.
49
49
  */
50
50
  static removeContainer(id: ContainerIdentifier): void;
51
+ static disposeContainer(container: Container): void;
51
52
  }
@@ -74,4 +74,15 @@ export class ContainerRegistry {
74
74
  }
75
75
  this.containerMap.delete(id);
76
76
  }
77
+ static disposeContainer(container) {
78
+ if (container.id === 'default') {
79
+ if (this.defaultContainerInstance === container) {
80
+ this.defaultContainerInstance = undefined;
81
+ }
82
+ return;
83
+ }
84
+ if (this.containerMap.get(container.id) === container) {
85
+ this.containerMap.delete(container.id);
86
+ }
87
+ }
77
88
  }
@@ -0,0 +1,11 @@
1
+ import type { ContainerIdentifier } from '../types';
2
+ /**
3
+ * Thrown when an operation is attempted on a disposed container instance.
4
+ */
5
+ export declare class ContainerDisposedError extends Error {
6
+ name: string;
7
+ /**
8
+ * @param id The identifier of the disposed container.
9
+ */
10
+ constructor(id: ContainerIdentifier);
11
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Thrown when an operation is attempted on a disposed container instance.
3
+ */
4
+ export class ContainerDisposedError extends Error {
5
+ name = 'ContainerDisposedError';
6
+ /**
7
+ * @param id The identifier of the disposed container.
8
+ */
9
+ constructor(id) {
10
+ super(`Container has been disposed: ${String(id)}`);
11
+ }
12
+ }
@@ -1,4 +1,5 @@
1
1
  export { CircularDependencyError } from './circular-dependency-error';
2
2
  export { ContainerDuplicatedError } from './container-duplicated-error';
3
+ export { ContainerDisposedError } from './container-disposed-error';
3
4
  export { DefaultContainerIdError } from './default-container-id-error';
4
5
  export { ServiceNotFoundError } from './service-not-found-error';
@@ -1,4 +1,5 @@
1
1
  export { CircularDependencyError } from './circular-dependency-error';
2
2
  export { ContainerDuplicatedError } from './container-duplicated-error';
3
+ export { ContainerDisposedError } from './container-disposed-error';
3
4
  export { DefaultContainerIdError } from './default-container-id-error';
4
5
  export { ServiceNotFoundError } from './service-not-found-error';
package/dist/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export { Service, Inject } from './decorators';
3
3
  export { Token } from './tokens';
4
4
  export type { AbstractConstructable, Constructable } from './types/constructable.ts';
5
5
  export type { ServiceIdentifier } from './types/service.ts';
6
+ export type { ClassProvider, FactoryProvider, ServiceFactory, ServiceProvider, ValueProvider, } from './types/container.ts';
@@ -1,6 +1,7 @@
1
1
  import type { Constructable } from './constructable';
2
2
  import type { InjectionMetadata } from './injection';
3
3
  import type { ServiceIdentifier, ServiceScope } from './service';
4
+ import type { Container } from '../container';
4
5
  /**
5
6
  * A container identifier used to select the default container or a named container.
6
7
  */
@@ -9,6 +10,53 @@ export type ContainerIdentifier = string | symbol;
9
10
  * Sentinel value used internally to mark services that have not been instantiated yet.
10
11
  */
11
12
  export declare const EMPTY_VALUE: unique symbol;
13
+ /**
14
+ * A factory function that creates a service using the current container.
15
+ */
16
+ export type ServiceFactory<T> = (container: Container) => T;
17
+ /**
18
+ * A provider that always resolves to the same explicit value.
19
+ */
20
+ export interface ValueProvider<T> {
21
+ /**
22
+ * The value returned for the registered identifier.
23
+ */
24
+ useValue: T;
25
+ }
26
+ /**
27
+ * A provider that resolves by instantiating a class.
28
+ */
29
+ export interface ClassProvider<T> {
30
+ /**
31
+ * The class instantiated when the service is resolved.
32
+ */
33
+ useClass: Constructable<T>;
34
+ /**
35
+ * Optional property injection definitions for the registered class.
36
+ */
37
+ injections?: InjectionMetadata[];
38
+ /**
39
+ * The lifetime used when the service is resolved.
40
+ */
41
+ scope?: ServiceScope;
42
+ }
43
+ /**
44
+ * A provider that resolves by calling a factory function.
45
+ */
46
+ export interface FactoryProvider<T> {
47
+ /**
48
+ * The factory used to create the resolved value.
49
+ */
50
+ useFactory: ServiceFactory<T>;
51
+ /**
52
+ * The lifetime used when the service is resolved.
53
+ */
54
+ scope?: ServiceScope;
55
+ }
56
+ /**
57
+ * A provider object accepted by low-level container registration APIs.
58
+ */
59
+ export type ServiceProvider<T> = ValueProvider<T> | ClassProvider<T> | FactoryProvider<T>;
12
60
  /**
13
61
  * Service registration metadata stored by a container.
14
62
  *
@@ -22,7 +70,7 @@ export interface Metadata<T = unknown> {
22
70
  /**
23
71
  * The class instantiated for this service.
24
72
  */
25
- Class: Constructable<T>;
73
+ Class?: Constructable<T>;
26
74
  /**
27
75
  * The original class or member name, when available.
28
76
  */
@@ -39,4 +87,8 @@ export interface Metadata<T = unknown> {
39
87
  * The cached service instance, or `EMPTY_VALUE` when no instance is cached.
40
88
  */
41
89
  value: T | typeof EMPTY_VALUE;
90
+ /**
91
+ * An optional factory used to create the resolved value.
92
+ */
93
+ factory?: ServiceFactory<T>;
42
94
  }
@@ -1,4 +1,4 @@
1
1
  export type { AbstractConstructable, Constructable } from './constructable';
2
2
  export type { ServiceIdentifier, ServiceOption } from './service';
3
- export { type ContainerIdentifier, type Metadata, EMPTY_VALUE } from './container';
3
+ export { type ClassProvider, type ContainerIdentifier, EMPTY_VALUE, type FactoryProvider, type Metadata, type ServiceFactory, type ServiceProvider, type ValueProvider, } from './container';
4
4
  export { type InjectionMetadata, INJECTION_KEY } from './injection';
@@ -1,2 +1,2 @@
1
- export { EMPTY_VALUE } from './container';
1
+ export { EMPTY_VALUE, } from './container';
2
2
  export { INJECTION_KEY } from './injection';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "navi-di",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "Dependency injection for standard ECMAScript decorators.",
5
5
  "author": "naviary-sanctuary",
6
6
  "keywords": [