Skip to content

DI Bag API / index / DiBagApi

Interface: DiBagApi ​

Defined in: di-bag.ts:607

The immutable public entry surface used by DiBag and derived facades.

See ​

https://dany-fedorov.github.io/di-bag/agent/api-card.html#dibag-facade

Properties ​

all ​

ts
all: <T extends TokenBase>(token: T & TokenTupleAdmission<readonly [T]>, ...invalid: [T] extends [never] ? [TokenTupleAdmission<readonly [T]>] : []) => CollectionDependency<T>;

Defined in: di-bag.ts:695

Create a positional dependency containing every contribution to a collection token, in order.

Describe a positional dependency containing every contribution for a token.

Type Parameters ​

Type ParameterDescription
T-

Parameters ​

ParameterDescription
tokenThe genuine collection token.
...invalid-

Returns ​

An immutable reference that supplies a fresh frozen array, including when empty.

Throws ​

DI_BAG_INVALID_TOKEN for a value that is not a genuine token.

Example ​

ts
const toolsKey = Symbol('tools');
const tools = DiBag.token(toolsKey).of<string>();
const menu = DiBag.fromFunction([DiBag.all(tools)], names => names.join(', '));

createBuilder ​

ts
createBuilder: () => Builder<never>;

Defined in: di-bag.ts:741

Begin an empty immutable graph; build creates its owning bag, buildModule seals a reusable module.

Example ​

ts
const bag = DiBag.createBuilder().register({ greeting: () => 'hello' }).build();

fromAsyncFactory ​

ts
fromAsyncFactory: {
    <F extends (this: void, deps: never, factoryCtx: AcquisitionContext) => Promise<unknown>>(callback: F, options: ContextualPortableFactoryOptions): Provider<ContextualFactory<F>, Readonly<{}>, readonly [], TokenDependencyContract, Awaited<ReturnType<F>>>;
    <F extends Factory>(callback: F & AsyncOutput<ReturnType<NoInfer<F>>>, options?: PortableFactoryOptions): Provider<F, Readonly<{}>, readonly [], TokenDependencyContract, Awaited<ReturnType<F>>>;
};

Defined in: di-bag.ts:652

Describe an asynchronous factory that runs on every host: the service is the returned native Promise and withDisposal receives its fulfilled value. A non-Promise output is rejected at compile time; a thenable that is not a native Promise fails the acquisition with a TypeError.

Call Signature ​

ts
<F extends (this: void, deps: never, factoryCtx: AcquisitionContext) => Promise<unknown>>(callback: F, options: ContextualPortableFactoryOptions): Provider<ContextualFactory<F>, Readonly<{}>, readonly [], TokenDependencyContract, Awaited<ReturnType<F>>>;

Describe an asynchronous named-dependency factory that runs on every host: a nativePromise stage whose service is the returned Promise and whose owners receive the fulfilled value.

Type Parameters ​
Type ParameterDescription
FThe complete callback signature, retaining dependency and output inference.
Parameters ​
ParameterDescription
callbackA receiver-free async factory taking its named dependency object and the acquisition context.
optionscontext: 'acquisition'; the acquisition mode is fixed and acquisitionMode is rejected.
Returns ​

A lazy provider exposing the factory's own Promise; adds no ownership.

Call Signature ​

ts
<F extends Factory>(callback: F & AsyncOutput<ReturnType<NoInfer<F>>>, options?: PortableFactoryOptions): Provider<F, Readonly<{}>, readonly [], TokenDependencyContract, Awaited<ReturnType<F>>>;

Describe an asynchronous named-dependency factory that runs on every host: a nativePromise stage whose service is the returned Promise and whose owners receive the fulfilled value. A non-Promise output is rejected at compile time; a thenable that is not a native Promise fails the acquisition with a TypeError.

Type Parameters ​
Type ParameterDescription
FThe exact factory signature and exposed Promise.
Parameters ​
ParameterDescription
callbackA receiver-free factory returning a native Promise.
options?Optional; acquisitionMode is rejected because the helper fixes it.
Returns ​

A lazy provider exposing the factory's own Promise; withDisposal receives its fulfilled value.

Throws ​

DI_BAG_INVALID_FACTORY for a non-function, an unknown context, or an acquisitionMode option.

Example ​

ts
const db = DiBag.withDisposal(
  DiBag.fromAsyncFactory(async ({ config }: { config: { url: string } }) => ({ url: config.url, end: async () => {} })),
  db => db.end(),
);

fromClass ​

ts
fromClass: <const T extends readonly DependencyReference[], C extends new (...args: TokenArguments<NoInfer<T>>) => unknown, M extends AcquisitionMode = 'auto'>(tokens: T & DependencyTupleAdmission<T>, constructor: C & CompositionArguments<TokenArguments<NoInfer<T>>, ConstructorParameters<NoInfer<C>>> & NativeOutput<InstanceType<NoInfer<C>>, NoInfer<M>> & AutoOutput<InstanceType<NoInfer<C>>, NoInfer<M>>, ...modeOptions: StageOptions<M>) => Provider<() => InstanceType<C>, Readonly<{}>, readonly [], ReferenceGraph<T>, Acquired<InstanceType<C>, M>>;

Defined in: di-bag.ts:733

Adapt a class whose constructor parameters receive the listed tokens' services.

Adapt a concrete constructor while preserving its prototype, private fields, and new.target.

Type Parameters ​

Type ParameterDescription
T-
C-
M-

Parameters ​

ParameterDescription
tokensA finite tuple whose dependency values match the constructor parameters.
constructorThe concrete class or constructable function to instantiate.
...modeOptionsOptional acquisition mode for the constructed result.

Returns ​

A lazy provider that constructs one instance per acquisition attempt.

Throws ​

When the supplied runtime value is not constructable.

Throws ​

DI_BAG_INVALID_TOKEN for a malformed token tuple; DI_BAG_INVALID_CONSTRUCTOR for a non-constructable value; DI_BAG_INVALID_ACQUISITION_MODE for an unknown mode.

Example ​

ts
class Greeter { constructor(readonly greeting: string) {} }
const greetingKey = Symbol('greeting');
const greeter = DiBag.fromClass([DiBag.token(greetingKey).of<string>()], Greeter);

fromFactory ​

ts
fromFactory: {
    <F extends (this: void, deps: never, factoryCtx: AcquisitionContext) => ('nativePromise' extends M ? Promise<unknown> : unknown), M extends AcquisitionMode = 'auto'>(callback: F & AutoOutput<ReturnType<NoInfer<F>>, NoInfer<M>>, options: {
        readonly context: 'acquisition';
    } & ModeOptions<M>): Provider<ContextualFactory<F>, Readonly<{}>, readonly [], TokenDependencyContract, Acquired<ReturnType<F>, M>>;
    <F extends Factory, M extends AcquisitionMode = 'auto'>(callback: F & NativeOutput<ReturnType<NoInfer<F>>, NoInfer<M>> & AutoOutput<ReturnType<NoInfer<F>>, NoInfer<M>>, ...options: FactoryOptions<M>): Provider<F, Readonly<{}>, readonly [], TokenDependencyContract, Acquired<ReturnType<F>, M>>;
};

Defined in: di-bag.ts:629

Describe a named-dependency factory with an explicit acquisition mode or the acquisition's abort signal. A factory that returns a non-Promise object with a then method needs acquisitionMode: 'raw' or must return Promise.resolve(value).

Call Signature ​

ts
<F extends (this: void, deps: never, factoryCtx: AcquisitionContext) => ('nativePromise' extends M ? Promise<unknown> : unknown), M extends AcquisitionMode = 'auto'>(callback: F & AutoOutput<ReturnType<NoInfer<F>>, NoInfer<M>>, options: {
    readonly context: 'acquisition';
} & ModeOptions<M>): Provider<ContextualFactory<F>, Readonly<{}>, readonly [], TokenDependencyContract, Acquired<ReturnType<F>, M>>;

Describe a named-dependency factory receiving its acquisition owner's cancellation signal. Context allocation is opt-in through context: 'acquisition', independent of callback arity.

Type Parameters ​
Type ParameterDescription
FThe complete callback signature, retaining dependency and output inference.
MThe raw, nativePromise, or configured auto acquisition policy.
Parameters ​
ParameterDescription
callbackA receiver-free factory taking dependencies and acquisition context.
optionsContext selection and result policy; acquisitionMode defaults to auto.
Returns ​

A lazy provider preserving exact output and named dependencies; adds no ownership.

Call Signature ​

ts
<F extends Factory, M extends AcquisitionMode = 'auto'>(callback: F & NativeOutput<ReturnType<NoInfer<F>>, NoInfer<M>> & AutoOutput<ReturnType<NoInfer<F>>, NoInfer<M>>, ...options: FactoryOptions<M>): Provider<F, Readonly<{}>, readonly [], TokenDependencyContract, Acquired<ReturnType<F>, M>>;

Describe a named-dependency factory with explicit or automatic result acquisition. Raw mode preserves the exact acquired value; nativePromise observes Promise fulfillment.

Type Parameters ​
Type ParameterDescription
FThe exact factory signature and exposed result.
MThe raw, nativePromise, or configured auto acquisition policy.
Parameters ​
ParameterDescription
callbackA receiver-free factory taking its named dependency object.
...optionsOptional result acquisitionMode, defaulting to auto.
Returns ​

A lazy provider retaining exact output and dependency types without adding ownership.

Throws ​

DI_BAG_INVALID_FACTORY for a non-function or an unknown context; DI_BAG_INVALID_ACQUISITION_MODE for an unknown mode.

Example ​

ts
type Query = { then(done: (rows: string[]) => void): void };
const query = DiBag.fromFactory((): Query => ({ then: done => done([]) }), { acquisitionMode: 'raw' });

fromFunction ​

ts
fromFunction: {
    <const T extends readonly DependencyReference[], F extends CompositionFunction<NoInfer<T>, 'nativePromise' extends M ? Promise<unknown> : unknown>, M extends AcquisitionMode = 'auto'>(tokens: T & DependencyTupleAdmission<T>, callback: F & CompositionArguments<TokenArguments<NoInfer<T>>, Parameters<NoInfer<F>>> & NativeOutput<ReturnType<NoInfer<F>>, NoInfer<M>> & AutoOutput<ReturnType<NoInfer<F>>, NoInfer<M>>, ...modeOptions: StageOptions<M>): Provider<OutputFactory<ReturnType<F>>, Readonly<{}>, readonly [], ReferenceGraph<T>, Acquired<ReturnType<F>, M>>;
    <const T extends readonly DependencyReference[], F extends CompositionFunction<NoInfer<T>>, M extends AcquisitionMode = 'auto'>(tokens: T & DependencyTupleAdmission<T>, callback: F & CompositionArguments<TokenArguments<NoInfer<T>>, Parameters<NoInfer<F>>> & NativeOutput<ReturnType<NoInfer<F>>, NoInfer<M>> & AutoOutput<ReturnType<NoInfer<F>>, NoInfer<M>>, ...modeOptions: StageOptions<M>): Provider<OutputFactory<ReturnType<F>>, Readonly<{}>, readonly [], ReferenceGraph<T>, Acquired<ReturnType<F>, M>>;
};

Defined in: di-bag.ts:721

Adapt a positional function whose parameters receive the listed tokens' services.

Call Signature ​

ts
<const T extends readonly DependencyReference[], F extends CompositionFunction<NoInfer<T>, 'nativePromise' extends M ? Promise<unknown> : unknown>, M extends AcquisitionMode = 'auto'>(tokens: T & DependencyTupleAdmission<T>, callback: F & CompositionArguments<TokenArguments<NoInfer<T>>, Parameters<NoInfer<F>>> & NativeOutput<ReturnType<NoInfer<F>>, NoInfer<M>> & AutoOutput<ReturnType<NoInfer<F>>, NoInfer<M>>, ...modeOptions: StageOptions<M>): Provider<OutputFactory<ReturnType<F>>, Readonly<{}>, readonly [], ReferenceGraph<T>, Acquired<ReturnType<F>, M>>;

Adapt a positional function without awaiting its arguments or return value.

Type Parameters ​
Type ParameterDescription
T-
FThe exact positional function signature retained by the provider.
M-
Parameters ​
ParameterDescription
tokensA finite tuple of typed tokens and dependency references.
callbackThe receiver-free function to call in tuple order.
...modeOptionsOptional acquisition mode for the function result.
Returns ​

A lazy provider retaining the dependency graph and exact return type.

Call Signature ​

ts
<const T extends readonly DependencyReference[], F extends CompositionFunction<NoInfer<T>>, M extends AcquisitionMode = 'auto'>(tokens: T & DependencyTupleAdmission<T>, callback: F & CompositionArguments<TokenArguments<NoInfer<T>>, Parameters<NoInfer<F>>> & NativeOutput<ReturnType<NoInfer<F>>, NoInfer<M>> & AutoOutput<ReturnType<NoInfer<F>>, NoInfer<M>>, ...modeOptions: StageOptions<M>): Provider<OutputFactory<ReturnType<F>>, Readonly<{}>, readonly [], ReferenceGraph<T>, Acquired<ReturnType<F>, M>>;

Adapt a positional function whose parameters exactly match the selected dependency values.

Type Parameters ​
Type ParameterDescription
T-
FThe exact positional function signature retained by the provider.
M-
Parameters ​
ParameterDescription
tokensA finite tuple of typed tokens and dependency references.
callbackThe function invoked once per provider acquisition with no receiver.
...modeOptionsOptional auto, raw, or nativePromise result classification.
Returns ​

A reusable provider; no dependency or result is implicitly awaited.

Throws ​

DI_BAG_INVALID_TOKEN for a malformed token tuple; DI_BAG_INVALID_FUNCTION for a non-function; DI_BAG_INVALID_ACQUISITION_MODE for an unknown mode.

Example ​

ts
const clockKey = Symbol('clock');
const clock = DiBag.token(clockKey).of<{ now(): number }>();
const stamp = DiBag.fromFunction([clock], source => new Date(source.now()).toISOString());

fromPlugin ​

ts
fromPlugin: PluginProviderFactory;

Defined in: di-bag.ts:709

Validate an unknown plugin descriptor now and its acquired output at acquisition.

Throws ​

DI_BAG_INVALID_TOKEN for a malformed dependency tuple; DI_BAG_INVALID_PLUGIN_OPTIONS for malformed options; DiBagPluginValidationError (DI_BAG_PLUGIN_VALIDATION) for an invalid descriptor, or at acquisition for rejected output.

Example ​

ts
declare const descriptor: unknown;
const greeter = DiBag.fromPlugin([], descriptor, {
  acquisitionMode: 'raw',
  validate: (value): value is () => string => typeof value === 'function',
});

fromSyncFactory ​

ts
fromSyncFactory: {
    <F extends ContextFactory>(callback: F & SyncOutput<ReturnType<NoInfer<F>>>, options: ContextualPortableFactoryOptions): Provider<ContextualFactory<F>, Readonly<{}>, readonly [], TokenDependencyContract, ReturnType<F>>;
    <F extends Factory>(callback: F & SyncOutput<ReturnType<NoInfer<F>>>, options?: PortableFactoryOptions): Provider<F, Readonly<{}>, readonly [], TokenDependencyContract, ReturnType<F>>;
};

Defined in: di-bag.ts:639

Describe a synchronous factory that runs on every host: the exact return value is the service and then is never read. A Promise or thenable output is rejected at compile time; use fromAsyncFactory, or fromFactory with acquisitionMode: 'raw' when the Promise object itself is the service.

Call Signature ​

ts
<F extends ContextFactory>(callback: F & SyncOutput<ReturnType<NoInfer<F>>>, options: ContextualPortableFactoryOptions): Provider<ContextualFactory<F>, Readonly<{}>, readonly [], TokenDependencyContract, ReturnType<F>>;

Describe a synchronous named-dependency factory that runs on every host: a raw stage whose exact return value is the service, so then is never read and no Promise classifier is needed.

Type Parameters ​
Type ParameterDescription
FThe complete callback signature, retaining dependency and output inference.
Parameters ​
ParameterDescription
callbackA receiver-free factory taking its named dependency object and the acquisition context.
optionscontext: 'acquisition'; the acquisition mode is fixed and acquisitionMode is rejected.
Returns ​

A lazy provider preserving exact output and named dependencies; adds no ownership.

Call Signature ​

ts
<F extends Factory>(callback: F & SyncOutput<ReturnType<NoInfer<F>>>, options?: PortableFactoryOptions): Provider<F, Readonly<{}>, readonly [], TokenDependencyContract, ReturnType<F>>;

Describe a synchronous named-dependency factory that runs on every host: a raw stage whose exact return value is the service. A Promise or thenable output is rejected at compile time; use fromAsyncFactory, or fromFactory with acquisitionMode: 'raw' when the Promise object is the service.

Type Parameters ​
Type ParameterDescription
FThe exact factory signature and exposed result.
Parameters ​
ParameterDescription
callbackA receiver-free factory taking its named dependency object.
options?Optional; acquisitionMode is rejected because the helper fixes it.
Returns ​

A lazy provider retaining exact output and dependency types without adding ownership.

Throws ​

DI_BAG_INVALID_FACTORY for a non-function, an unknown context, or an acquisitionMode option.

Example ​

ts
const config = DiBag.fromSyncFactory(() => ({ url: 'memory:' }));

lazy ​

ts
lazy: <T extends TokenBase>(token: T & TokenTupleAdmission<readonly [T]>, ...invalid: [T] extends [never] ? [TokenTupleAdmission<readonly [T]>] : []) => LazyDependency<T>;

Defined in: di-bag.ts:684

Create a positional dependency supplied as a function that resolves the token when called.

Describe a positional dependency supplied as an on-demand lookup function. Each invocation follows the target lifetime and records its dependency edge then.

Type Parameters ​

Type ParameterDescription
T-

Parameters ​

ParameterDescription
tokenThe genuine typed token to resolve lazily.
...invalid-

Returns ​

An immutable lazy reference accepted by positional provider adapters.

Throws ​

DI_BAG_INVALID_TOKEN for a value that is not a genuine token.

Example ​

ts
const clockKey = Symbol('clock');
const clock = DiBag.token(clockKey).of<{ now(): number }>();
const stamp = DiBag.fromFunction([DiBag.lazy(clock)], getClock => () => getClock().now());

optional ​

ts
optional: <T extends TokenBase>(token: T & TokenTupleAdmission<readonly [T]>, ...invalid: [T] extends [never] ? [TokenTupleAdmission<readonly [T]>] : []) => OptionalDependency<T>;

Defined in: di-bag.ts:673

Create a positional dependency that yields undefined only when the token is unregistered.

Describe a positional dependency that supplies undefined only when the token is unbound. A present undefined value and acquisition failures remain present dependency results.

Type Parameters ​

Type ParameterDescription
T-

Parameters ​

ParameterDescription
tokenThe genuine typed token to read optionally.
...invalid-

Returns ​

An immutable reference accepted by positional provider adapters.

Throws ​

DI_BAG_INVALID_TOKEN for a value that is not a genuine token.

Example ​

ts
const clockKey = Symbol('clock');
const clock = DiBag.token(clockKey).of<{ now(): number }>();
const stamp = DiBag.fromFunction([DiBag.optional(clock)], source => source?.now() ?? 0);

token ​

ts
token: <const K extends symbol>(key: K & TokenKeyAdmission<K>, ...invalid: [K] extends [never] ? [TokenKeyAdmission<K>] : []) => {
    readonly of: <S>() => Token<K, S>;
};

Defined in: di-bag.ts:662

Create a typed token from a unique symbol; .of<Service>() fixes its service type.

Create a typed-token factory from the caller's canonical unique symbol. Reusing the same key and service type produces compatible handles; copied or fabricated objects are rejected at runtime.

Type Parameters ​

Type ParameterDescription
K-

Parameters ​

ParameterDescription
keyAn individually known unique symbol used as the runtime binding identity.
...invalid-

Returns ​

An object whose of<Service>() method creates an immutable typed token.

Example ​

ts
const clockKey = Symbol('clock');
const clock = DiBag.token(clockKey).of<{ now(): number }>();

Throws ​

DI_BAG_INVALID_TOKEN when the key is not a symbol.

Example ​

ts
const clockKey = Symbol('clock');
const clock = DiBag.token(clockKey).of<{ now(): number }>();

transformService ​

ts
transformService: {
    <R extends Registration, P extends (this: void, value: ProviderOutput<NoInfer<R>>) => ('nativePromise' extends M ? Promise<unknown> : unknown), M extends AcquisitionMode = 'auto'>(registration: R & Registration, options: {
        readonly mode: 'direct';
        readonly transform: P;
    } & ModeOptions<M>): Provider<MappedFactory<R, ReturnType<P>>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, ProviderGraphContract<R>, Acquired<ReturnType<P>, M>>;
    <R extends Registration, P extends (this: void, value: Awaited<ProviderOutput<NoInfer<R>>>) => unknown>(registration: R & Registration, options: {
        readonly mode: 'awaited';
        readonly transform: P;
        readonly acquisitionMode?: never;
    }): Provider<MappedFactory<R, Promise<Awaited<ReturnType<P>>>>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, ProviderGraphContract<R>>;
};

Defined in: di-bag.ts:786

Transform the exposed service while retaining dependencies, metadata, lifetime, and existing ownership.

Call Signature ​

ts
<R extends Registration, P extends (this: void, value: ProviderOutput<NoInfer<R>>) => ('nativePromise' extends M ? Promise<unknown> : unknown), M extends AcquisitionMode = 'auto'>(registration: R & Registration, options: {
    readonly mode: 'direct';
    readonly transform: P;
} & ModeOptions<M>): Provider<MappedFactory<R, ReturnType<P>>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, ProviderGraphContract<R>, Acquired<ReturnType<P>, M>>;

Transform the exact exposed service without awaiting the input or callback result. Retains dependencies, lifetime, metadata, and earlier cleanup; the result adds no ownership.

Type Parameters ​
Type ParameterDescription
RThe source registration and its retained contracts.
PThe exact transform callback signature and output.
MThe result's auto, raw, or nativePromise acquisition policy.
Parameters ​
ParameterDescription
registrationThe source registration whose exact output is transformed.
optionsDirect mode, a transform callback, and optional output acquisitionMode (auto by default).
Returns ​

A provider exposing the callback's exact result, with the selected output acquisition policy.

Call Signature ​

ts
<R extends Registration, P extends (this: void, value: Awaited<ProviderOutput<NoInfer<R>>>) => unknown>(registration: R & Registration, options: {
    readonly mode: 'awaited';
    readonly transform: P;
    readonly acquisitionMode?: never;
}): Provider<MappedFactory<R, Promise<Awaited<ReturnType<P>>>>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, ProviderGraphContract<R>>;

Await the input and adopt the transformed result into a native Promise stage. Retains dependencies, lifetime, metadata, and existing cleanup; adds no result ownership.

Type Parameters ​
Type ParameterDescription
RThe source registration and retained contracts.
PThe callback signature; its result may itself be a Promise.
Parameters ​
ParameterDescription
registrationThe source registration whose fulfilled value is transformed.
optionsAwaited mode and a transform callback; acquisitionMode cannot be overridden.
Returns ​

A provider exposing a Promise of the awaited transform result.

Throws ​

DI_BAG_INVALID_TRANSFORM for a bad mode or callback; DI_BAG_INVALID_ACQUISITION_MODE for an unknown mode; DI_BAG_INVALID_REGISTRATION for an invalid registration.

Example ​

ts
const shout = DiBag.transformService(() => 'hello', { mode: 'direct', transform: text => text.toUpperCase() });

withConfiguration ​

ts
withConfiguration: (options: ConfigurationOptions) => DiBagApi;

Defined in: di-bag.ts:618

Return a facade with inherited runtime settings and appended observers.

Parameters ​

ParameterDescription
options-

Throws ​

DI_BAG_INVALID_CONFIGURATION for a non-object, a runtime without isNativePromise, or malformed observers.

Example ​

ts
const Observed = DiBag.withConfiguration({
  observers: [{ onEvent: event => console.log(event.kind), onError: failure => console.error(failure.error) }],
});

withDisposal ​

ts
withDisposal: {
    <F extends Factory>(create: F, dispose: (this: void, value: Awaited<ReturnType<NoInfer<F>>>) => void | Promise<void>): FactoryWithDisposal<F>;
    <R extends Registration>(provider: R & Registration, dispose: (this: void, value: ProviderAcquiredValue<NoInfer<R>>) => void | Promise<void>): Provider<ProviderFactory<R>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, ProviderGraphContract<R>, ProviderAcquiredValue<R>>;
};

Defined in: di-bag.ts:754

Make the bag own a factory's value and run dispose on it when the bag closes. close() runs disposers, dependents first; close every scope and fork you create.

Call Signature ​

ts
<F extends Factory>(create: F, dispose: (this: void, value: Awaited<ReturnType<NoInfer<F>>>) => void | Promise<void>): FactoryWithDisposal<F>;

Declare that each acquiring bag owns a factory's fulfilled value. Neither callback runs until acquisition; cleanup runs once after dependent resources.

Type Parameters ​
Type ParameterDescription
F-
Parameters ​
ParameterDescription
createThe receiver-free service factory.
disposeCleanup for its fulfilled value; it may complete synchronously or asynchronously.
Returns ​

A nominal disposable registration preserving the factory's exact output.

Call Signature ​

ts
<R extends Registration>(provider: R & Registration, dispose: (this: void, value: ProviderAcquiredValue<NoInfer<R>>) => void | Promise<void>): Provider<ProviderFactory<R>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, ProviderGraphContract<R>, ProviderAcquiredValue<R>>;

Add an ownership stage to an existing registration. Earlier disposal stages remain attached and run after this stage in reverse order.

Type Parameters ​
Type ParameterDescription
R-
Parameters ​
ParameterDescription
providerThe registration whose acquired value becomes owned at this stage.
disposeCleanup for the registration's acquired value.
Returns ​

A provider retaining output, dependencies, metadata, frames, and earlier ownership.

Throws ​

DI_BAG_INVALID_REGISTRATION when the registration is neither a function nor a provider.

Example ​

ts
const bag = DiBag.createBuilder()
  .register({ controller: DiBag.withDisposal(() => new AbortController(), controller => controller.abort()) })
  .build();
await bag.close();

withLifetime ​

ts
withLifetime: {
    <R extends Registration, const L extends Lifetime>(registration: R & Registration, lifetime: L & Admission<L>): Provider<ProviderFactory<R>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, LifetimeGraph<ProviderGraphContract<R>, L, undefined>, ProviderAcquiredValue<R>>;
    <R extends Registration, const L extends Lifetime, const O extends object | undefined>(registration: R & Registration, lifetime: L & Admission<L>, options: O & Options<NoInfer<L>, NoInfer<O>>): Provider<ProviderFactory<R>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, LifetimeGraph<ProviderGraphContract<R>, L, O>, ProviderAcquiredValue<R>>;
};

Defined in: di-bag.ts:766

Select root, scoped (the default), or transient caching for a registration. Mark a shared client root only when nothing it depends on is scoped.

Call Signature ​

ts
<R extends Registration, const L extends Lifetime>(registration: R & Registration, lifetime: L & Admission<L>): Provider<ProviderFactory<R>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, LifetimeGraph<ProviderGraphContract<R>, L, undefined>, ProviderAcquiredValue<R>>;

Select family-root caching, per-scope caching, or a fresh owned attempt per read. Strict roots cannot capture scoped dependencies. Wrapping preserves the factory, acquired value, metadata, frames, and ownership stages.

Type Parameters ​
Type ParameterDescription
R-
L-
Parameters ​
ParameterDescription
registrationThe registration whose caching policy to replace.
lifetimeAn individually known root, scoped, or transient literal.
Returns ​

A provider with the selected lifetime policy.

Call Signature ​

ts
<R extends Registration, const L extends Lifetime, const O extends object | undefined>(registration: R & Registration, lifetime: L & Admission<L>, options: O & Options<NoInfer<L>, NoInfer<O>>): Provider<ProviderFactory<R>, RetainedMetadata<R>, ProviderAcquisitionMetadata<R>, LifetimeGraph<ProviderGraphContract<R>, L, O>, ProviderAcquiredValue<R>>;

Select a lifetime and optionally permit a root provider to capture scoped dependencies.

Type Parameters ​
Type ParameterDescription
R-
L-
O-
Parameters ​
ParameterDescription
registrationThe registration whose caching policy to replace.
lifetimeAn individually known root, scoped, or transient literal.
optionsRoot-only { allowScopedDependencies: boolean } admission.
Returns ​

A provider preserving factory, output, metadata, frames, and ownership stages.

Throws ​

DI_BAG_INVALID_LIFETIME for an unknown lifetime or malformed options; DI_BAG_INVALID_REGISTRATION for an invalid registration.

Example ​

ts
const bag = DiBag.createBuilder()
  .register({ cache: DiBag.withLifetime(() => new Map<string, string>(), 'root') })
  .build();

withMetadata ​

ts
withMetadata: {
    <R extends Registration, M extends object>(registration: R & Registration, options: {
        readonly static: M & MetadataKeys<NoInfer<R>, M>;
        readonly dynamic?: never;
    }): Provider<ProviderFactory<R>, Readonly<RetainedMetadata<R> & M>, ProviderAcquisitionMetadata<R>, ProviderGraphContract<R>, ProviderAcquiredValue<R>>;
    <R extends Registration, P extends (this: void, value: ProviderOutput<NoInfer<R>>) => object, M extends object = {}>(registration: R & Registration, options: {
        readonly static: M & MetadataKeys<NoInfer<R>, M>;
        readonly dynamic: {
            readonly mode: 'direct';
            readonly describe: P & AcquisitionMetadataAdmission<ReturnType<P>>;
        };
    }): Provider<ProviderFactory<R>, Readonly<RetainedMetadata<R> & M>, AcquisitionFrames<R, ReturnType<P>>, ProviderGraphContract<R>, ProviderAcquiredValue<R>>;
    <R extends Registration, P extends (this: void, value: ProviderOutput<NoInfer<R>>) => object, M extends object = {}>(registration: R & Registration, options: {
        readonly static?: M & MetadataKeys<NoInfer<R>, M>;
        readonly dynamic: {
            readonly mode: 'direct';
            readonly describe: P & AcquisitionMetadataAdmission<ReturnType<P>>;
        };
    }): Provider<ProviderFactory<R>, Readonly<RetainedMetadata<R> & Partial<M>>, AcquisitionFrames<R, ReturnType<P>>, ProviderGraphContract<R>, ProviderAcquiredValue<R>>;
    <R extends Registration, P extends (this: void, value: Awaited<ProviderOutput<NoInfer<R>>>) => object, M extends object = {}>(registration: R & Registration, options: {
        readonly static: M & MetadataKeys<NoInfer<R>, M>;
        readonly dynamic: {
            readonly mode: 'awaited';
            readonly describe: P & AcquisitionMetadataAdmission<ReturnType<P>>;
        };
    }): Provider<MappedFactory<R, Promise<Awaited<ProviderOutput<R>>>>, Readonly<RetainedMetadata<R> & M>, AcquisitionFrames<R, ReturnType<P>>, ProviderGraphContract<R>, Awaited<ProviderOutput<R>>>;
    <R extends Registration, P extends (this: void, value: Awaited<ProviderOutput<NoInfer<R>>>) => object, M extends object = {}>(registration: R & Registration, options: {
        readonly static?: M & MetadataKeys<NoInfer<R>, M>;
        readonly dynamic: {
            readonly mode: 'awaited';
            readonly describe: P & AcquisitionMetadataAdmission<ReturnType<P>>;
        };
    }): Provider<MappedFactory<R, Promise<Awaited<ProviderOutput<R>>>>, Readonly<RetainedMetadata<R> & Partial<M>>, AcquisitionFrames<R, ReturnType<P>>, ProviderGraphContract<R>, Awaited<ProviderOutput<R>>>;
};

Defined in: di-bag.ts:776

Attach static registration metadata, or per-acquisition metadata in direct or awaited mode.

Call Signature ​

ts
<R extends Registration, M extends object>(registration: R & Registration, options: {
    readonly static: M & MetadataKeys<NoInfer<R>, M>;
    readonly dynamic?: never;
}): Provider<ProviderFactory<R>, Readonly<RetainedMetadata<R> & M>, ProviderAcquisitionMetadata<R>, ProviderGraphContract<R>, ProviderAcquiredValue<R>>;

Attach registration metadata without evaluating the source or changing ownership. Own keys are copied and frozen; static key collisions reject before getters run.

Type Parameters ​
Type ParameterDescription
RThe source registration and retained contracts.
MThe additional static registration metadata record.
Parameters ​
ParameterDescription
registrationThe source registration to describe.
optionsA static record with finite noncolliding string or unique-symbol keys.
Returns ​

A provider preserving exact output, acquisition policy, and ordered dynamic frames.

Call Signature ​

ts
<R extends Registration, P extends (this: void, value: ProviderOutput<NoInfer<R>>) => object, M extends object = {}>(registration: R & Registration, options: {
    readonly static: M & MetadataKeys<NoInfer<R>, M>;
    readonly dynamic: {
        readonly mode: 'direct';
        readonly describe: P & AcquisitionMetadataAdmission<ReturnType<P>>;
    };
}): Provider<ProviderFactory<R>, Readonly<RetainedMetadata<R> & M>, AcquisitionFrames<R, ReturnType<P>>, ProviderGraphContract<R>, ProviderAcquiredValue<R>>;

Describe the exact exposed service with a synchronous plain metadata record. Direct mode preserves Promise identity and source acquisition policy, adding no ownership.

Type Parameters ​
Type ParameterDescription
RThe source registration and retained contracts.
PThe synchronous describe callback and its record result.
MThe required static metadata record.
Parameters ​
ParameterDescription
registrationThe source registration whose exact output is described.
optionsRequired static metadata and mandatory direct dynamic mode with a synchronous describe callback.
Returns ​

A provider with merged registration metadata and one appended acquisition metadata frame.

Call Signature ​

ts
<R extends Registration, P extends (this: void, value: ProviderOutput<NoInfer<R>>) => object, M extends object = {}>(registration: R & Registration, options: {
    readonly static?: M & MetadataKeys<NoInfer<R>, M>;
    readonly dynamic: {
        readonly mode: 'direct';
        readonly describe: P & AcquisitionMetadataAdmission<ReturnType<P>>;
    };
}): Provider<ProviderFactory<R>, Readonly<RetainedMetadata<R> & Partial<M>>, AcquisitionFrames<R, ReturnType<P>>, ProviderGraphContract<R>, ProviderAcquiredValue<R>>;

Describe the exact exposed service with a synchronous plain metadata record. Direct mode preserves Promise identity and source acquisition policy, adding no ownership.

Type Parameters ​
Type ParameterDescription
RThe source registration and retained contracts.
PThe synchronous describe callback and its record result.
MThe optional static metadata record.
Parameters ​
ParameterDescription
registrationThe source registration whose exact output is described.
optionsOptional static metadata and mandatory direct dynamic mode with a synchronous describe callback.
If the static level may be absent, its added keys remain optional in inspection.
Returns ​

A provider with merged registration metadata and one appended acquisition metadata frame.

Call Signature ​

ts
<R extends Registration, P extends (this: void, value: Awaited<ProviderOutput<NoInfer<R>>>) => object, M extends object = {}>(registration: R & Registration, options: {
    readonly static: M & MetadataKeys<NoInfer<R>, M>;
    readonly dynamic: {
        readonly mode: 'awaited';
        readonly describe: P & AcquisitionMetadataAdmission<ReturnType<P>>;
    };
}): Provider<MappedFactory<R, Promise<Awaited<ProviderOutput<R>>>>, Readonly<RetainedMetadata<R> & M>, AcquisitionFrames<R, ReturnType<P>>, ProviderGraphContract<R>, Awaited<ProviderOutput<R>>>;

Await the source and append a synchronous metadata record through a native Promise stage. Existing ownership and metadata frames remain ordered; annotation adds no ownership.

Type Parameters ​
Type ParameterDescription
RThe source registration and retained contracts.
PThe synchronous describe callback and its record result.
MThe required static metadata record.
Parameters ​
ParameterDescription
registrationThe source registration whose fulfilled value is described.
optionsRequired static metadata and mandatory awaited mode with a synchronous describe callback.
Returns ​

A provider exposing a Promise of the source value with one appended metadata frame.

Call Signature ​

ts
<R extends Registration, P extends (this: void, value: Awaited<ProviderOutput<NoInfer<R>>>) => object, M extends object = {}>(registration: R & Registration, options: {
    readonly static?: M & MetadataKeys<NoInfer<R>, M>;
    readonly dynamic: {
        readonly mode: 'awaited';
        readonly describe: P & AcquisitionMetadataAdmission<ReturnType<P>>;
    };
}): Provider<MappedFactory<R, Promise<Awaited<ProviderOutput<R>>>>, Readonly<RetainedMetadata<R> & Partial<M>>, AcquisitionFrames<R, ReturnType<P>>, ProviderGraphContract<R>, Awaited<ProviderOutput<R>>>;

Await the source and append a synchronous metadata record through a native Promise stage. Existing ownership and metadata frames remain ordered; annotation adds no ownership.

Type Parameters ​
Type ParameterDescription
RThe source registration and retained contracts.
PThe synchronous describe callback and its record result.
MThe optional static metadata record.
Parameters ​
ParameterDescription
registrationThe source registration whose fulfilled value is described.
optionsOptional static metadata and mandatory awaited mode with a synchronous describe callback.
If the static level may be absent, its added keys remain optional in inspection.
Returns ​

A provider exposing a Promise of the source value with one appended metadata frame.

Throws ​

DI_BAG_INVALID_METADATA for malformed options or, at acquisition, a describe result that is not a plain record; DI_BAG_DUPLICATE_METADATA for a repeated key; DI_BAG_INVALID_REGISTRATION for an invalid registration.

Example ​

ts
const greeting = DiBag.withMetadata(() => 'hello', { static: { owner: 'greeting' } });

Ordinary services. Checked composition. Explicit ownership.