knaxuslearn · build · ship

Projects / DI container / Phase 4

Phase 4 of 4 · about 2.5 hours

A typed API, tests and a package

You end with a typed way to list dependencies, tests that include compile errors, and a package you install from another folder.

Step 4.1: Say what you need, once (about 30 minutes)

Writing (c) => new Database(c.resolve(Config), c.resolve(Logger)) repeats ourselves. Better:

.singleton(Db, [Config, Logger], (config, logger) => new Database(config, logger))

The list of tokens is on the left, and the function receives their values in the same order. The hard part is typing it: config must be a Config and logger a Logger, inferred. We need a type that turns a list of tokens into a list of values:

export type Values<D extends readonly Token<unknown>[]> = {
  -readonly [K in keyof D]: D[K] extends Token<infer V> ? V : never;
};

Values maps over each position of a list of tokens, and for each one takes out the T of Token<T>. The -readonly strips the read-only marker that a const type parameter adds. Then each registration method gets two forms, written as overloads: the original factory form, and the new list form:

  singleton<T>(token: Token<T>, factory: Factory<T>): this;
  singleton<T, const D extends readonly Token<unknown>[]>(
    token: Token<T>,
    deps: D,
    make: (...args: Values<D>) => T,
  ): this;
  singleton(token: Token<unknown>, a: unknown, b?: unknown): this {
    return this.#add(token, { factory: toFactory(a, b), lifetime: 'singleton' });
  }

const D tells TypeScript to keep the exact list you wrote (as a fixed-length tuple) instead of widening it to an array of tokens. That is what lets the compiler know the function takes exactly two values. At runtime one small helper converts both forms into a plain factory:

// Accepts either (container) => value, or a list of tokens plus a function that takes their values.
const toFactory = (a: unknown, b: unknown): Factory<unknown> => {
  if (typeof a === 'function') return a as Factory<unknown>;
  const deps = a as readonly Token<unknown>[];
  const make = b as (...args: unknown[]) => unknown;
  return (container) => make(...deps.map((dep) => container.resolve(dep)));
};

scoped and transient get the same pair of overloads. Create src/index.ts, the package's public face. It exports the classes and the types, and nothing else:

export { Container, Token } from './container.js';
export type { Factory, Lifetime, Values } from './container.js';

Try it. Create src/try_typed.ts:

import { Container, Token } from './index.js';

type Config = { dbUrl: string; level: 'info' | 'debug' };
const ConfigT = new Token<Config>('Config');
const LevelT = new Token<string>('Level');
const NameT = new Token<string>('Name');
const BannerT = new Token<string>('Banner');

const container = new Container()
  .singleton(ConfigT, () => ({ dbUrl: 'postgres://localhost/app', level: 'debug' }))
  .singleton(LevelT, [ConfigT], (config) => config.level)
  .singleton(NameT, () => 'orders')
  // `level` and `name` are inferred as string, in the order of the list
  .singleton(BannerT, [LevelT, NameT], (level, name) => `${name} running at ${level}`);

console.log(container.resolve(BannerT));
orders running at debug

Hover over level and name in your editor: both are string, inferred from the tokens. No annotations.

Step 4.2: Tests that are compile errors (about 40 minutes)

The main promise of this library is "the compiler stops you". A runtime test cannot check that. A @ts-expect-error can. Create src/try_wrong.ts:

import { Container, Token } from './index.js';

const Port = new Token<number>('Port');
const Name = new Token<string>('Name');
const Banner = new Token<string>('Banner');

const container = new Container();

// @ts-expect-error the function treats Port as a string
container.singleton(Banner, [Port], (port: string) => port.toUpperCase());

// @ts-expect-error the function takes two values but the list has one token
container.singleton(Banner, [Name], (name, extra) => `${name}${extra}`);

// @ts-expect-error the result must be a string, not a number
container.singleton(Banner, [Name, Port], (name, port) => port);

console.log('three wiring mistakes were caught by the compiler');
three wiring mistakes were caught by the compiler

Three mistakes: a function that treats a number as a string, one that takes more values than the list gives, and one that returns the wrong type. Each one is a compile error, and the directive turns "this must not compile" into something tsc verifies. If a future change to Values quietly loosens the types, this file stops compiling.

Step 4.3: Runtime tests (about 40 minutes)

Node has a test runner built in. Create src/container.test.ts. Each test states one promise:

import assert from 'node:assert/strict';
import { test } from 'node:test';
import { Container, Token } from './index.js';

const N = new Token<number>('N');
const Double = new Token<number>('Double');
const A = new Token<string>('A');
const B = new Token<string>('B');

test('singleton is built once, transient every time', () => {
  let built = 0;
  const c = new Container().singleton(N, () => ++built);
  c.resolve(N);
  c.resolve(N);
  assert.equal(built, 1);
  let made = 0;
  const t = new Container().transient(N, () => ++made);
  t.resolve(N);
  t.resolve(N);
  assert.equal(made, 2);
});

test('dependencies are resolved and typed', () => {
  const c = new Container().singleton(N, () => 21).singleton(Double, [N], (n) => n * 2);
  assert.equal(c.resolve(Double), 42);
});

test('a missing token names the whole path', () => {
  const c = new Container().singleton(A, (x) => x.resolve(B));
  assert.throws(
    () => c.resolve(A),
    /Nothing is registered for Token\(B\).*Token\(A\) -> Token\(B\)/,
  );
});

test('a cycle is reported with its path', () => {
  const c = new Container().singleton(A, (x) => x.resolve(B)).singleton(B, (x) => x.resolve(A));
  assert.throws(() => c.resolve(A), /Circular dependency: Token\(A\) -> Token\(B\) -> Token\(A\)/);
});

test('a failed resolve leaves the container usable', () => {
  const c = new Container().singleton(A, (x) => x.resolve(B));
  assert.throws(() => c.resolve(A));
  c.singleton(B, () => 'ok');
  assert.equal(c.resolve(A), 'ok');
});

test('replacing a registration drops the cached singleton', () => {
  const c = new Container().singleton(A, () => 'real');
  assert.equal(c.resolve(A), 'real');
  c.singleton(A, () => 'fake');
  assert.equal(c.resolve(A), 'fake');
});

test('scoped services are per scope, singletons are shared', () => {
  let ids = 0;
  const root = new Container().singleton(A, () => 'shared').scoped(N, () => ++ids);
  const s1 = root.createScope();
  const s2 = root.createScope();
  assert.equal(s1.resolve(N), s1.resolve(N));
  assert.notEqual(s1.resolve(N), s2.resolve(N));
  assert.equal(s1.resolve(A), s2.resolve(A));
});

test('a singleton cannot capture a scoped service', () => {
  const root = new Container().scoped(N, () => 1).singleton(Double, (c) => c.resolve(N) * 2);
  assert.throws(() => root.createScope().resolve(Double), /is scoped, so it needs a scope/);
});

test('scoped services cannot be resolved from the root', () => {
  const root = new Container().scoped(N, () => 1);
  assert.throws(() => root.resolve(N), /needs a scope/);
});

test('dispose runs in reverse order and reports every failure', () => {
  const order: string[] = [];
  const mk = (name: string, fail = false) => ({
    dispose: () => {
      order.push(name);
      if (fail) throw new Error(`${name} failed`);
    },
  });
  const First = new Token<{ dispose(): void }>('First');
  const Second = new Token<{ dispose(): void }>('Second');
  const c = new Container()
    .singleton(First, () => mk('first', true))
    .singleton(Second, () => mk('second', true));
  c.resolve(First);
  c.resolve(Second);
  assert.throws(() => c.dispose(), AggregateError);
  assert.deepEqual(order, ['second', 'first']);
});

test('a transient service is not tracked for disposal', () => {
  let closed = 0;
  const T = new Token<{ dispose(): void }>('T');
  const c = new Container().transient(T, () => ({ dispose: () => closed++ }));
  c.resolve(T);
  c.dispose();
  assert.equal(closed, 0);
});
npx tsc && node --test --test-reporter=spec dist/container.test.js
✔ singleton is built once, transient every time (0.752196ms)
✔ dependencies are resolved and typed (0.274218ms)
✔ a missing token names the whole path (0.331645ms)
✔ a cycle is reported with its path (0.097412ms)
✔ a failed resolve leaves the container usable (0.178085ms)
✔ replacing a registration drops the cached singleton (0.125288ms)
✔ scoped services are per scope, singletons are shared (0.211843ms)
✔ a singleton cannot capture a scoped service (0.101145ms)
✔ scoped services cannot be resolved from the root (0.166447ms)
✔ dispose runs in reverse order and reports every failure (0.734715ms)
✔ a transient service is not tracked for disposal (0.119122ms)
ℹ tests 11
ℹ pass 11
ℹ fail 0

Every promise from the first three phases is now a test, including the unhappy ones: the missing-token path, the cycle, a failed resolve that leaves the container usable, a singleton that tries to capture a scoped service, and cleanup that fails halfway. (The Node test runner is documented on nodejs.org.)

Step 4.4: Package it and measure it (about 40 minutes)

A package says what its entry point is and which files belong to it. Replace package.json:

{
  "name": "tiny-di",
  "version": "0.1.0",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    }
  },
  "files": ["dist/index.js", "dist/index.d.ts", "dist/container.js", "dist/container.d.ts"],
  "scripts": {
    "build": "tsc",
    "test": "tsc && node --test dist/container.test.js"
  },
  "license": "MIT"
}

exports is what import 'tiny-di' loads, and its types entry tells TypeScript where the declarations are. files lists exactly what is published: the compiled library and its type files, not tests, benchmarks or experiments. (The exports field is documented in the Node.js packages page.) Build and pack:

npx tsc
npm pack

Then use it from somewhere else. In a new folder, install the tarball (plus the compiler and Node types) and write src/app.ts:

mkdir ../app && cd ../app
npm init -y
npm install --save-dev typescript @types/node
npm install ../tiny-di/tiny-di-0.1.0.tgz

Use the same tsconfig.json as before, but add "type": "module" to this folder's package.json.

import { Container, Token } from 'tiny-di';

const Port = new Token<number>('Port');
const Url = new Token<string>('Url');

const container = new Container()
  .singleton(Port, () => 8080)
  .singleton(Url, [Port], (port) => `http://localhost:${port}`);

console.log(container.resolve(Url));
http://localhost:8080

The import resolved, the compiler found the types, and the tokens kept their inferred types across the package boundary. Choose your own package name before you ever publish: tiny-di may belong to someone else.

Last, a number. src/bench.ts times three things:

import { Container, Token } from './index.js';

const A = new Token<number>('A');
const B = new Token<number>('B');
const C = new Token<number>('C');

const time = (label: string, run: () => void) => {
  const start = performance.now();
  run();
  console.log(`${label.padEnd(44)} ${(performance.now() - start).toFixed(0).padStart(5)} ms`);
};

const container = new Container()
  .singleton(A, () => 1)
  .transient(B, [A], (a) => a + 1)
  .transient(C, [A, B], (a, b) => a + b);

time('1,000,000 resolves of a singleton', () => {
  for (let i = 0; i < 1_000_000; i++) container.resolve(A);
});
time('1,000,000 resolves of a 3 deep transient', () => {
  for (let i = 0; i < 1_000_000; i++) container.resolve(C);
});
time('100,000 scopes, one scoped service each', () => {
  const root = new Container().scoped(A, () => 1);
  for (let i = 0; i < 100_000; i++) root.createScope().resolve(A);
});
1,000,000 resolves of a singleton               26 ms
1,000,000 resolves of a 3 deep transient       160 ms
100,000 scopes, one scoped service each         18 ms

A million singleton lookups in tens of milliseconds, and a million builds of a three-deep transient chain in a couple of hundred. Your numbers will differ. The cost per resolve is a map lookup, a path push and pop, and the factory call, so this is plenty for web requests.

Phase 4 done

You wrote about 150 lines of library, 11 runtime tests, three compile-time tests and a benchmark, and installed it like any dependency.