diff --git a/src/app.ts b/src/app.ts index 97afff6..3ca3b38 100644 --- a/src/app.ts +++ b/src/app.ts @@ -130,8 +130,9 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me orderedProviders = ordered.filter((n) => providerNodes.includes(n)); orderedSteps = ordered.filter((n) => stepNodes.includes(n)); const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0); // side-effect/observer steps (plugins) + const alwaysNeeds = alwaysSteps.flatMap((n) => n.needs); // pull observers' deps into every route for (const plan of routePlans) { - const closure = subgraphFor(plan.needs, ordered); + const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered); plan.providers = closure.filter((n) => providerNodes.includes(n)); const sliced = new Set([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]); plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n)); // topo order, deduped diff --git a/test/app.test.ts b/test/app.test.ts index 38e04b9..b1feb59 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -191,6 +191,22 @@ describe('per-route subgraph slicing', () => { expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing server.close(); }); + + it('an always-run observer step receives its declared needs even when the route does not need them', async () => { + let seen: any; + const observer = (api: any) => api.scope.add({ kind: 'step', name: 'audit', needs: ['user'], provides: [], run: (ctx: any) => { seen = ctx.user; return {}; } }); + @Step({ provides: 'user', needs: [] }) + class Auth { run() { return { user: { id: 'u1' } }; } } + @Route('/') + class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user') + @Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M], plugins: [observer] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); + expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined + server.close(); + }); }); describe('graceful shutdown', () => {