From a88cb530c97faa2879fc7511b422a6f4d07021ec Mon Sep 17 00:00:00 2001 From: Vadim Date: Mon, 23 Nov 2026 17:31:36 +0000 Subject: [PATCH] Fail the contract test when a route is not documented test/openapi.test.ts caught documented routes the app does not have, but not the reverse: a new endpoint left out of buildOpenApiDocument() passed CI, and the frontend got no types for it. The new test lists every route of the app and checks that each one is in the contract. Express 5 does not keep a router's mount path, so a spy on Router.prototype.use records where each router was mounted; the routes come from router.stack and layer.route. Those are Express internals, so the test also requires a known route to be listed: if an upgrade changes them, it fails instead of passing on an empty list. --- .claude/skills/add-endpoint/SKILL.md | 2 +- AGENTS.md | 2 +- test/openapi.test.ts | 64 ++++++++++++++++++++++++++-- 3 files changed, 63 insertions(+), 5 deletions(-) diff --git a/.claude/skills/add-endpoint/SKILL.md b/.claude/skills/add-endpoint/SKILL.md index b168ef9..256817d 100644 --- a/.claude/skills/add-endpoint/SKILL.md +++ b/.claude/skills/add-endpoint/SKILL.md @@ -16,7 +16,7 @@ Follow the layers in order. Look at `src/modules/elements/` as the reference mod 7. **Tests** - HTTP: `test/app.test.ts` with Supertest — success status and body, 400 for invalid input, 404/409 where they apply, and that `db.json` changed as expected. - Pure logic (helpers): `*.test.ts` next to the code. - - `test/openapi.test.ts` fails until `openapi.json` is regenerated and catches documented routes that do not exist. + - `test/openapi.test.ts` fails until `openapi.json` is regenerated, catches documented routes that do not exist, and catches routes missing from `buildOpenApiDocument()`. 8. **Docs** — the endpoint table in `README.md`. 9. **Frontend** — if the shape or path changed, the frontend's `src/api/main.ts` and `main.types.ts` need a matching PR in `email-template-editor-reactjs`. diff --git a/AGENTS.md b/AGENTS.md index 80ec329..742498f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ request → helmet → cors → request-id → pino-http → json → static ## API contract -- **Source of truth:** [`openapi.json`](openapi.json), generated from the zod schemas and served at `GET /openapi.json`. `test/openapi.test.ts` fails if the committed file is stale or documents a route the app does not have. +- **Source of truth:** [`openapi.json`](openapi.json), generated from the zod schemas and served at `GET /openapi.json`. `test/openapi.test.ts` fails if the committed file is stale, documents a route the app does not have, or misses a route the app has. - The frontend's request types (`src/api/main.types.ts` in the frontend repo) must match it. A breaking change here needs a matching frontend PR. - Errors are always `{ error: { code, message, details?, requestId } }` (see `src/common/middleware/error-handler.ts`). - Keys in paths are URL-encoded by the client. diff --git a/test/openapi.test.ts b/test/openapi.test.ts index 97920c1..96c43c2 100644 --- a/test/openapi.test.ts +++ b/test/openapi.test.ts @@ -1,9 +1,9 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import type { Express } from "express"; +import { Router, type Express } from "express"; import request from "supertest"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest"; import { createApp } from "../src/app.js"; import { createLogger } from "../src/common/logger.js"; import { loadConfig } from "../src/config/env.js"; @@ -15,6 +15,7 @@ const METHODS = ["get", "post", "put", "patch", "delete"] as const; let dir: string; let app: Express; +let buildApp: () => Express; beforeAll(async () => { dir = await mkdtemp(path.join(tmpdir(), "openapi-test-")); @@ -26,9 +27,52 @@ beforeAll(async () => { DB_FILE: dbFile, PUBLIC_DIR: dir, }); - app = createApp({ config, store: new JsonFileStore(dbFile), logger: createLogger(config) }); + buildApp = () => + createApp({ config, store: new JsonFileStore(dbFile), logger: createLogger(config) }); + app = buildApp(); }); +interface RouteLayer { + route?: { path: string; methods: Record }; + handle: unknown; +} +interface RouterLike { + stack: RouteLayer[]; +} +const isRouter = (handle: unknown): handle is RouterLike => + typeof handle === "function" && Array.isArray((handle as Partial).stack); + +/** + * Lists every route as "METHOD /path" in OpenAPI form (`:key` → `{key}`). + * Express 5 does not keep a router's mount path, so `use` records which router was mounted where. + * Reads `router.stack` and `layer.route` (Express internals, unchanged since Express 4): if an + * Express upgrade changes them, the sanity check in the test below fails instead of passing empty. + */ +function listRoutes(root: RouterLike, use: MockInstance): string[] { + const mountPath = (parent: RouterLike, child: RouterLike): string => { + const i = use.mock.calls.findIndex( + (args, n) => use.mock.contexts[n] === parent && args.includes(child), + ); + const path: unknown = use.mock.calls[i]?.[0]; + return typeof path === "string" ? path : "/"; + }; + const join = (...parts: string[]) => + `/${parts.join("/")}`.replace(/\/+/g, "/").replace(/(.)\/$/, "$1"); + + const walk = (router: RouterLike, prefix: string): string[] => + router.stack.flatMap((layer) => { + if (layer.route) { + const path = join(prefix, layer.route.path).replace(/:(\w+)/g, "{$1}"); + return Object.keys(layer.route.methods).map((method) => `${method.toUpperCase()} ${path}`); + } + return isRouter(layer.handle) + ? walk(layer.handle, join(prefix, mountPath(router, layer.handle))) + : []; + }); + + return walk(root, "/"); +} + afterAll(async () => { await rm(dir, { recursive: true, force: true }); }); @@ -65,4 +109,18 @@ describe("OpenAPI contract", () => { } } }); + + it("documents every route the app has (add new routes to buildOpenApiDocument())", () => { + const use = vi.spyOn(Router.prototype as { use: (...args: unknown[]) => unknown }, "use"); + const routes = listRoutes((buildApp() as unknown as { router: RouterLike }).router, use); + + const { paths } = buildOpenApiDocument(); + const documented = Object.entries(paths).flatMap(([route, item]) => + METHODS.filter((m) => m in item).map((m) => `${m.toUpperCase()} ${route}`), + ); + + // Sanity check: an empty or wrong list means Express internals changed, not that all is well. + expect(routes).toContain("PATCH /tree/nodes/{key}"); + expect(routes.filter((route) => !documented.includes(route))).toEqual([]); + }); });