13 · Reference
Public API Reference
Everything dn-ioc exports comes from 'dn-ioc'—six runtime functions and fifteen TypeScript types, with zero sub-path imports or global side effects. Use this chapter whenever you want to double-check an exact parameter type, return value, or handle invariant.
1export const publicApi = {2 token: token satisfies <T>(description?: string) => Token<T>,3 provide: provide satisfies <T>(factory: Factory<T>, options?: ProviderOptions) => Ref<T>,4 provideFor: provideFor satisfies <T>(key: InjectKey<T>, factory: Factory<T>, options?: ProviderOptions) => ProviderDef<T>,5 bundleProviders: bundleProviders satisfies (...inputs: ProviderInput[]) => ProviderBundle,6 isProvideRef: isProvideRef satisfies (value: unknown) => value is Ref<unknown>,7 bootstrapApp: bootstrapApp satisfies (fn: BootstrapAppFn, options?: BootstrapAppOptions) => App,8}
Runtime Functions
token<T>(description?)
Signature: function token<T>(description?: string): Token<T>
Creates a pure dependency key carrying the TypeScript type T and zero runtime implementation.
description(optionalstring): Human-readable label shown inNo provider for token: NameandCircular dependency detected: .... When omitted or empty, diagnostics print<anonymous>. Two separatetoken('Same')calls always produce distinct keys—identity never comes from the description string.- Async contracts: Put
PromiseinsideT(token<Promise<Settings>>('Settings')) so bothinject()callers andprovideFor()implementations agree on the async return type.
provide<T>(factory, options?)
Signature: function provide<T>(factory: Factory<T>, options?: ProviderOptions): Ref<T>
Wraps factory in a self-providing Ref<T> handle.
factory:(ctx: Context) => T. If no binding for thisRefexists in the active scope or its ancestors wheninject()is called, theRefinstalls its default factory into the active scope, runs it once, and caches the result (or shares the in-flightPromisefor an async factory). Sync throws and async rejections are not cached, allowing retries while the app is running.- Diagnostic name: Taken from
factory.name(for example,const UserService = (ctx: Context) => { ... }; provide(UserService)reportsUserService, whereas an unnamed inline arrow reports<anonymous>). options?.providers: Optional private child subtree visible only tofactoryand its descendants. Snapshotted whenprovide()is called and validated lazily when that subtree is first resolved.
provideFor<T>(key, factory, options?)
Signature: function provideFor<T>(key: InjectKey<T>, factory: Factory<T>, options?: ProviderOptions): ProviderDef<T>
Binds an implementation factory to key—accepting either a Token<T> or a Ref<T>—and returns a ProviderDef<T> ready to install in { providers } or bundleProviders().
- Validates
keyimmediately whenprovideFor()is called; passing anything other than a realTokenorRefthrowsInvalid inject key received. options?.providers: Optional private child subtree visible to this boundfactoryand its descendants; snapshotted on creation.
bundleProviders(...inputs)
Signature: function bundleProviders(...inputs: ProviderInput[]): ProviderBundle
Packs any mix of Refs, ProviderDef bindings, nested arrays, and other ProviderBundles into one reusable ProviderBundle.
- Shallow-copies input arrays at creation time so later array mutations cannot alter the bundle.
- Installing a bundle flattens its items left-to-right in source order directly into the receiving scope—it does not create an isolated child scope of its own.
isProvideRef(value)
Signature: function isProvideRef(value: unknown): value is Ref<unknown>
Type guard returning true only when value is a genuine Ref returned by provide(). Returns false for Token, ProviderDef, ProviderBundle, primitives, null, and cloned objects ({ ...someRef }).
bootstrapApp(fn, options?)
Signature: function bootstrapApp(fn: BootstrapAppFn, options?: BootstrapAppOptions): App
Creates an isolated root scope, validates and installs options?.providers synchronously, and returns an App handle without executing fn or any provider factory yet.
fn:(ctx: Context) => void | Promise<void>. Runs whenapp.start()is called. Must returnvoidorPromise<void>.options?.providers: Root-level bindings, refs, arrays, and bundles. Invalid entries throwInvalid provider input receivedsynchronously before anApphandle is returned.
Context & App Lifecycle Interfaces
Context (InjectFn & OnDisposeFn)
Every provider Factory<T> and BootstrapAppFn receives a Context object with two functions:
inject: InjectFn(<T>(key: InjectKey<T>) => T) — Resolveskeystarting from the provider's owning scope upward. Returns synchronous values directly and sharedPromises for async factories. Remains callable inside returned methods after the factory finishes, up untilapp.stop()is called.onDispose: OnDisposeFn((fn: () => void | Promise<void>) => void) — Registers a cleanup hook run in LIFO (newest-first) order duringapp.stop(). Callable only while its own factory is actively running and beforestop(). Returning anything other thanvoidorPromise<void>is a TypeScript compile error—wrap non-voidteardown expressions in braces (onDispose(() => { server.close() })).
App (start, stop & AsyncDisposable)
The handle returned by bootstrapApp() exposes three members:
start(): Promise<void>— Runs the root callback once and awaits anyPromiseit returns. Concurrent or repeated calls return the exact samePromise. If startup fails,start()automatically runsstop()to roll back already-acquired resources before rejecting. Oncestop()has been called,start()rejects withCannot start an app that has been stopped.stop(): Promise<void>— Synchronously closesinject()across the entire app, then awaits registeredonDisposehooks newest-first. Idempotent across concurrent or repeated calls. Even if a hook fails, all remaining hooks still run.[Symbol.asyncDispose](): Promise<void>— Points to the exact samestopfunction soawait using app = bootstrapApp(...)tears the app down automatically at block exit. When nativeSymbol.asyncDisposeexists on the runtime,Appdefines[Symbol.asyncDispose]; on older runtimes without the native symbol (such as Node 18), it falls back to[Symbol.for('Symbol.asyncDispose')]to match TypeScript's downlevelawait usinglookup.
1export type { ProviderBundle, ProviderDef, Ref, Token }23export type RefType<T> = T extends Ref<infer U> ? U : never4export type InjectKey<T> = Token<T> | Ref<T>5export type ProviderInput = Ref<unknown> | ProviderDef<unknown> | ProviderBundle | readonly ProviderInput[]67export type ProviderOptions = {8 providers?: readonly ProviderInput[]9}1011export type InjectFn = <T>(key: InjectKey<T>) => T12export type OnDisposeFn = (fn: () => void | Promise<void>) => void1314export interface Context {15 inject: InjectFn16 onDispose: OnDisposeFn17}1819export type Factory<T> = (ctx: Context) => T20export type BootstrapAppFn = (ctx: Context) => void | Promise<void>2122export interface BootstrapAppOptions {23 providers?: readonly ProviderInput[]24}2526export interface App extends AsyncDisposable {27 start(): Promise<void> // idempotent; rejects once the app is stopped28 stop(): Promise<void> // idempotent29}
Handle & Utility Types
| Exported type | Definition / shape | Purpose |
|---|---|---|
Token<T> | Branded opaque interface carrying T | Contract key returned by token<T>(). |
Ref<T> | extends Token<T> (branded as a ref) | Self-providing handle returned by provide(). |
RefType<T> | T extends Ref<infer U> ? U : never | Extracts the resolved type U from typeof someRef—great for typing test fakes without writing duplicate interfaces. |
InjectKey<T> | Token<T> | Ref<T> | Any valid lookup or binding target accepted by inject() and provideFor(). |
ProviderDef<T> | Branded opaque interface carrying T | Explicit binding returned by provideFor(). |
ProviderBundle | Branded opaque interface | Grouped wiring handle returned by bundleProviders(). |
ProviderInput | Ref<unknown> | ProviderDef<unknown> | ProviderBundle | readonly ProviderInput[] | Any installable item or arbitrarily nested array accepted by providers and bundleProviders(). |
ProviderOptions | { providers?: readonly ProviderInput[] } | Options object for provide() and provideFor() declaring a private child subtree. |
BootstrapAppOptions | { providers?: readonly ProviderInput[] } | Options object for bootstrapApp() installing root-scope bindings. |
InjectFn | <T>(key: InjectKey<T>) => T | Type of ctx.inject passed inside Context. |
OnDisposeFn | (fn: () => void | Promise<void>) => void | Type of ctx.onDispose passed inside Context. |
Factory<T> | (ctx: Context) => T | Provider factory function signature. |
BootstrapAppFn | (ctx: Context) => void | Promise<void> | Root startup callback signature for bootstrapApp(). |
Frozen Opaque Handle Semantics
Every handle returned by token(), provide(), provideFor(), and bundleProviders() is an empty frozen object (Object.freeze({})) with zero own enumerable properties and zero own symbol keys. All internal metadata is stored inside a private WeakMap inside the kernel:
- Mutation fails: Attempting to attach or overwrite properties on a handle throws a
TypeErrorin strict mode. - Clones and forgeries are rejected: Spreading or copying a handle (
{ ...sampleRef },Object.assign({}, myToken)) creates a brand-new object reference absent from the kernel'sWeakMap. Passing that copy toisProvideRef()returnsfalse; passing it toinject()orprovideFor()throwsInvalid inject key received; passing a copied binding or bundle inprovidersthrowsInvalid provider input received.
For every runtime error message the kernel can throw—and how to fix each one—flip to Errors & Diagnostics.
1export const sampleRef = provide(() => 'ok')2export const sampleToken = token<string>('Sample')3export const sampleBinding = provideFor(sampleToken, () => 'ok')4export const sampleBundle = bundleProviders(sampleRef, sampleBinding)56console.log(isProvideRef(sampleRef)) // true7console.log(isProvideRef(sampleToken)) // false8console.log(isProvideRef(sampleBinding)) // false9console.log(isProvideRef(sampleBundle)) // false10console.log(isProvideRef({ ...sampleRef })) // false (copied object is rejected)