feat(di): a read-only events token, and framework names nobody can take

Three things that turned out to be one decision.

## `@needs('events')`

`app.bus` is public and `Bus` is an exported type, but the bus was not a graph token, so
`@needs('bus')` failed at boot. There is a good reason for the difference — putting the
`Bus` in the graph hands `emit` to every node and turns a one-way observation channel into
something anything can forge events on — and it was written down nowhere, inferable only
by reading `provideBuiltins` and noticing what is absent.

The read-only half is a token now: `events`, bound to `{ on }`, the same narrowing plugins
already get. `@needs('events')` works the way `@needs('logger')` does, which is the
symmetry a reader expects, and `emit` still belongs to nobody.

A plugin remains the right home for observation and the docs say so, because it gets
`on` and `onShutdown` *together*. The token gives the subscribe half alone: a `@Provider`
that subscribes should release in `dispose()` — `on()` returns its own unsubscribe — and a
`@Step` should not subscribe at all, since it runs per request and would add a listener
each time.

## The boot error teaches it

Documenting it prevents the mistake for a reader; it does nothing for the person typing
`@needs('bus')`, which is who the issue was about. That need now fails with what it should
have used and why, rather than the generic "nothing provides it" plus a nearest-match that
has nothing near enough to suggest.

## Framework names are reserved

**Behaviour change.** Builtins were registered with `if (!runners.has(name))`, so a
provider called `logger` silently replaced the framework's own and every `@needs('logger')`
in the app got something that was not the logger core writes to — a divergence you
discover from a log line that never appeared. `logger`, `rooms`, `events` and `bus` are
reserved now, enforced in `setRunner`, which is the single point modules, plugins and mesh
exports all register through. Taking one is a boot error naming it.

`bus` is reserved without being provided, so `@needs('bus')` cannot resolve to whatever a
user happened to call `bus` and be wrong in silence.

This replaces a test that asserted the old shadowing as a feature.

Closes #67.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-01 10:57:47 -05:00
1 parent c00f714aa8
commit 1e76921d49
7 files changed
+307 -18

No files matched your search

+6 -2
View File
@@ -603,7 +603,11 @@ describe('rooms auto-provide', () => {
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
s.close();
});
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
// This used to be allowed, and the user's provider silently replaced the framework's. The same
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
// the logger core writes to — a divergence discovered from a log line that never appeared.
// Framework token names are reserved now, and taking one is a boot error.
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
@Provider({ provides: 'rooms' })
class MyRooms {
provide() {
@@ -618,7 +622,7 @@ describe('rooms auto-provide', () => {
}
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
});
});
+73
View File
@@ -0,0 +1,73 @@
// The three legitimate ways to reach the bus, exercised together in one app.
//
// `bus` became a reserved name and the `Bus` itself is still not a graph token, so this file's job
// is to prove that what closed is only the wrong door: observation from outside, from a plugin and
// from inside the graph all still work, and only `emit` stays where it was.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Route, Get, Module, needs } from '../src/index';
import type { Events, Plugin } from '../src/index';
@Route('/b')
class Ctl {
@Get('/x') x(@needs('events') events: Events) {
// Reaching it per request is allowed; *subscribing* per request is the thing the docs warn
// about, and nothing here does that.
return { hasOn: typeof events.on === 'function' };
}
}
describe('reaching the bus', () => {
it('works from outside, from a plugin and from the graph, all at once', async () => {
const fromOutside: string[] = [];
const fromPlugin: string[] = [];
const observer: Plugin = (api) => {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
// 1. from outside: the public `app.bus`, which keeps `emit` too.
app.bus.on('request:end', (e) => fromOutside.push(e.route ?? ''));
// 3. from the graph: the handler receives `events` and reports its shape.
const res = await app.fetch(new Request('http://x/b/x'));
expect(await res.json()).toEqual({ hasOn: true });
expect(fromOutside).toEqual(['/b/x']);
expect(fromPlugin).toEqual(['/b/x']);
await app.close();
});
it('keeps emit outside the graph and outside plugins, and only there', async () => {
let injected: Events | undefined;
const seen: string[] = [];
@Route('/e')
class Grab {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return {};
}
}
@Module({ mountpoint: '/', controllers: [Grab] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
// The graph's slice cannot forge an event...
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
// ...while the application that owns the app still can, which is what `app.bus` is for.
app.bus.on('plugin:mounted', (e) => seen.push(e.name));
app.bus.emit('plugin:mounted', { name: 'from the owner' });
expect(seen).toEqual(['from the owner']);
await app.close();
});
});
+141
View File
@@ -0,0 +1,141 @@
// Framework token names, and the read-only slice of the bus that `@needs` can reach.
//
// Two halves of one decision. The bus is not a graph token — a node that could reach it could also
// `emit`, and an observation channel anything can write to is not one — but `@needs('logger')`
// teaches that framework things *are* graph tokens, so reaching for `@needs('bus')` is the natural
// next move. Documenting that it does not work only reaches a reader; the boot error reaches the
// person writing it. And reserving the names stops a user's own `logger` from quietly becoming the
// one the whole app injects.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { Events } from '../src/index';
@Route('/r')
class Ctl {
@Get('/x') x() {
return { ok: true };
}
}
describe('reserved framework tokens', () => {
for (const token of ['logger', 'rooms', 'events']) {
it(`refuses a provider that declares '${token}'`, () => {
@Provider({ provides: token })
class Shadow {
provide() {
return { [token]: { mine: true } };
}
}
@Module({ mountpoint: '/', providers: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(
new RegExp(`'${token}' is reserved by the framework`),
);
});
}
it("refuses a step that declares 'bus', a name the framework reserves without providing", () => {
@Step({ provides: 'bus' })
class Shadow {
run() {
return { bus: { mine: true } };
}
}
@Module({ mountpoint: '/', steps: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/'bus' is reserved by the framework/);
});
it('leaves every other name alone', () => {
@Provider({ provides: 'buses' })
class Fine {
provide() {
return { buses: 1 };
}
}
@Module({ mountpoint: '/', providers: [Fine], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
});
});
describe("@needs('bus')", () => {
it('fails at boot naming the read-only token and the plugin, not a nearest match', () => {
@Route('/b')
class Bad {
@Get('/x') x(@needs('bus') _bus: unknown) {
return {};
}
}
@Module({ mountpoint: '/', controllers: [Bad] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/the Bus is not a graph token/);
expect(() => createApp({ modules: [M] })).toThrow(/@needs\('events'\)/);
expect(() => createApp({ modules: [M] })).toThrow(/plugin/);
});
});
describe("@needs('events')", () => {
it('hands over on() and nothing else — no emit to forge events with', async () => {
let injected: Events | undefined;
@Route('/e')
class Observer {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Observer] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
expect(typeof injected?.on).toBe('function');
expect(Object.keys(injected!)).toEqual(['on']);
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
});
it('subscribes to the same bus the framework emits on, and hands back an unsubscribe', async () => {
const seen: string[] = [];
@Provider({ provides: 'watcher', needs: ['events'] })
class Watcher {
#off?: () => void;
provide(ctx: { events: Events }) {
this.#off = ctx.events.on('request:end', (e) => seen.push(e.route ?? ''));
return { watcher: true };
}
dispose() {
this.#off?.();
}
}
@Route('/e')
class Observed {
@Get('/y') y(@needs('watcher') _w: unknown) {
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [Watcher], controllers: [Observed] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/y'));
expect(seen).toEqual(['/e/y']);
// dispose() releases it, which is the half a plugin gets for free with onShutdown. Asserted by
// emitting after close and watching nothing arrive — clearing the array and finding it empty
// would prove only that clearing works.
await app.close();
seen.length = 0;
app.bus.emit('request:end', { name: 'after close', route: '/after' });
expect(seen).toEqual([]);
});
});