feat(plugin)!: a plugin is a named object, not a function
BREAKING CHANGE: `Plugin` is now `{ name, mount(api) }`. `fn.name` was the only
source for the name that plugin:mounted reports, and it is empty for a returned
arrow, "plugin" for a const, and whatever a minifier decides. A failed mount now
names the plugin and keeps the original error as its cause, and two plugins with
the same name fail createApp.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+152
-6
No files matched your search
+12
-1
@@ -600,8 +600,19 @@ function buildTeardownRegistry(
|
||||
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void {
|
||||
const extraSteps: ScopeNode[] = [];
|
||||
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
|
||||
// The name is the plugin's identity in `plugin:mounted` and in a mount failure, so two of them
|
||||
// make both ambiguous. Two instances of one plugin are legitimate — they differ by `provides`,
|
||||
// and the convention derives the name from it (.specs/2026-09-15, rule 2).
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
|
||||
for (const plugin of plugins ?? []) {
|
||||
if (seen.has(plugin.name)) {
|
||||
throw new Error(`two plugins are named "${plugin.name}" — pass a different \`provides\` to one of them`);
|
||||
}
|
||||
|
||||
seen.add(plugin.name);
|
||||
mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
|
||||
}
|
||||
|
||||
for (const scopeNode of extraSteps) {
|
||||
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
|
||||
|
||||
+22
-4
@@ -37,8 +37,18 @@ export interface PluginApi {
|
||||
*/
|
||||
onShutdown(fn: TeardownFn): void;
|
||||
}
|
||||
/** A plugin: a function that wires itself up through the provided PluginApi. */
|
||||
export type Plugin = (api: PluginApi) => void;
|
||||
/**
|
||||
* A plugin: a named object that wires itself up through the provided PluginApi.
|
||||
*
|
||||
* The name is a field rather than `fn.name` because `fn.name` cannot be relied on: an arrow
|
||||
* returned straight from a factory has `""`, `const plugin = …` reports `"plugin"`, and a minifier
|
||||
* rewrites both. The name is what `plugin:mounted` reports and what a failed mount is blamed on, so
|
||||
* it has to be the author's word, not the bundler's.
|
||||
*/
|
||||
export interface Plugin {
|
||||
readonly name: string;
|
||||
mount(api: PluginApi): void;
|
||||
}
|
||||
|
||||
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
|
||||
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
|
||||
@@ -53,6 +63,14 @@ export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdow
|
||||
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still
|
||||
// caps the whole shutdown.
|
||||
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
|
||||
plugin(api);
|
||||
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
|
||||
|
||||
try {
|
||||
plugin.mount(api);
|
||||
} catch (error) {
|
||||
// Without the name this surfaces as somebody else's stack trace: mounting happens inside
|
||||
// createApp, so the application sees a throw from a line it never wrote.
|
||||
throw new Error(`plugin "${plugin.name}" failed to mount: ${(error as Error).message}`, { cause: error });
|
||||
}
|
||||
|
||||
bus.emit('plugin:mounted', { name: plugin.name });
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// test/plugin-contract.test.ts
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { createApp, Get, Module, Route, needs } from '../src/index';
|
||||
import type { Plugin } from '../src/index';
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/who')
|
||||
who(@needs('who') who: string) {
|
||||
return { who };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const provides = (name: string, value: string): Plugin => ({
|
||||
name,
|
||||
mount({ scope }) {
|
||||
scope.add({ kind: 'provider', name, needs: [], provides: [name], run: async () => ({ [name]: value }) });
|
||||
},
|
||||
});
|
||||
|
||||
describe('the plugin contract', () => {
|
||||
it('mounts an object plugin and its node reaches a handler', async () => {
|
||||
const app = createApp({ modules: [M], plugins: [provides('who', 'jwt')] });
|
||||
|
||||
const response = await app.fetch(new Request('http://x/who'));
|
||||
|
||||
expect(await response.json()).toEqual({ who: 'jwt' });
|
||||
});
|
||||
|
||||
it('names the plugin whose mount threw', () => {
|
||||
const boom: Plugin = {
|
||||
name: 'boom',
|
||||
mount() {
|
||||
throw new Error('no key');
|
||||
},
|
||||
};
|
||||
|
||||
expect(() => createApp({ modules: [M], plugins: [boom] })).toThrow(
|
||||
/plugin "boom" failed to mount: no key/,
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the original error as the cause', () => {
|
||||
const original = new Error('no key');
|
||||
const boom: Plugin = {
|
||||
name: 'boom',
|
||||
mount() {
|
||||
throw original;
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
createApp({ modules: [M], plugins: [boom] });
|
||||
expect.unreachable('createApp should have thrown');
|
||||
} catch (error) {
|
||||
expect((error as Error).cause).toBe(original);
|
||||
}
|
||||
});
|
||||
|
||||
// The two plugins provide *different* tokens, so nothing but the duplicate-name check can fail
|
||||
// this. Two plugins providing the same token would also collide inside `setRunner`, which
|
||||
// enforces unique node names already — and the test would pass without the new code.
|
||||
it('refuses two plugins with the same name, even when they provide different tokens', () => {
|
||||
const twin = (token: string): Plugin => ({
|
||||
name: 'twin',
|
||||
mount({ scope }) {
|
||||
scope.add({ kind: 'provider', name: token, needs: [], provides: [token], run: async () => ({ [token]: 1 }) });
|
||||
},
|
||||
});
|
||||
|
||||
expect(() => createApp({ modules: [M], plugins: [twin('a'), twin('b')] })).toThrow(
|
||||
/two plugins are named "twin"/,
|
||||
);
|
||||
});
|
||||
|
||||
// `plugin:mounted` means "this plugin is in". A plugin whose mount threw is not, and announcing
|
||||
// it would put a name in the lifecycle stream for something that never registered anything.
|
||||
it('does not announce a plugin whose mount threw', () => {
|
||||
const seen = vi.fn();
|
||||
const observer: Plugin = {
|
||||
name: 'observer',
|
||||
mount({ bus }) {
|
||||
bus.on('plugin:mounted', seen);
|
||||
},
|
||||
};
|
||||
const boom: Plugin = {
|
||||
name: 'boom',
|
||||
mount() {
|
||||
throw new Error('no key');
|
||||
},
|
||||
};
|
||||
|
||||
expect(() => createApp({ modules: [M], plugins: [observer, boom] })).toThrow(/failed to mount/);
|
||||
expect(seen).not.toHaveBeenCalledWith(expect.objectContaining({ name: 'boom' }));
|
||||
});
|
||||
|
||||
it('reports the name on plugin:mounted', () => {
|
||||
const seen = vi.fn();
|
||||
// `createApp` takes no `bus` option, and the event
|
||||
// fires during construction — so the observer has to be a plugin, listed first, because
|
||||
// plugins mount in the order they are given.
|
||||
const observer: Plugin = {
|
||||
name: 'observer',
|
||||
mount({ bus }) {
|
||||
bus.on('plugin:mounted', seen);
|
||||
},
|
||||
};
|
||||
|
||||
createApp({ modules: [M], plugins: [observer, provides('who', 'jwt')] });
|
||||
|
||||
expect(seen).toHaveBeenCalledWith(expect.objectContaining({ name: 'who' }));
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
"target": "es2017",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"lib": ["es2020"],
|
||||
"lib": ["es2020", "es2022.error"],
|
||||
"declaration": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": ".",
|
||||
|
||||
Reference in new issue
Block a user