diff --git a/CHANGELOG.md b/CHANGELOG.md index f88177e..84a650e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) + [Semantic Ver ## [Unreleased] ### Added +- Express routers defined in one file and mounted in another now get their + mount prefix and mount middleware: `app.use("/p", mw, importedRouter)` + with relative ESM or CommonJS imports (`./x.js`, `./x`, `./dir`), nested + across files, and one route per prefix when a router is mounted twice. + `parserCapabilities.express.crossFileMountPrefix` is now `true`. - NestJS global guards: `{ provide: APP_GUARD, useClass|useExisting: X }` providers and `useGlobalGuards(new X())` calls add the guard class name as an auth marker to every Nest endpoint in the scan. An endpoint is GUARDED @@ -24,11 +29,18 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) + [Semantic Ver matrix runs Node 20, 22, 24 and 26. - Bumped `acorn` to 8.19 and `yaml` to 2.9.1. Dev tooling moved to ESLint 10, `@eslint/js` 10 and `globals` 17; `npm audit` is clean again. +- An exported `Router()` that no resolved mount reaches (alias or package + imports, mounts in `.ts/.tsx` files, scans of a sub-directory, factory + exports, mount cycles) is now `UNRESOLVED` with the new reason + `mount-prefix-cross-file` instead of a resolved bare path. An `express()` + app stays a root. - `parserCapabilities.nest.globalGuardDetection` is now `true`, with new keys `globalGuardRules`, `globalPrefix` and `publicDecorators`. The report limitation about global guards describes what is and is not detected. ### Fixed +- Endpoint sorting is a total order when unresolved endpoints (path `null`) + are mixed with resolved ones, so output no longer depends on input order. - Nest: decorators on the same line before `@Get(...)` are now read, and a method declared on the anchor line (`@Get() list() {}`) no longer takes the decorators of the next method. diff --git a/README.md b/README.md index 80a115e..1ce1c3d 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ The bounded scan builds one sorted candidate-file index and shares it across all | Framework | Detection | |------------|--------------------------------------------------------------------------------------------------------------------------| -| **Express** | acorn AST for `.js/.mjs/.cjs`; regex fallback for `.ts/.tsx`. Resolves `app.use('/prefix', router)` mounts in same file. AST files also track any variable assigned from `express()` / `express.Router()` / `Router()` whatever its name, and parse `app.route('/x').get(...).post(...)` chains. Path-less `router.use(requireAuth)` guards routes registered on that router after it only when `router` is a `const/let/var` declared once from a router factory, never reassigned, and the `use()` is a plain statement in the same block as the declaration. These `use()` calls are ignored (routes stay OPEN): `this.router.use(...)`, a router received as a parameter, a `use()` inside `if` or a helper function, `X.use(someCall(), auth)`, and wrappers like `jwt(...).unless(...)`. Not resolved: routers imported from another file, path-less `app.use(auth)` flowing into routers mounted on `app`, `route('/x').all(auth)` guarding the other verbs of the chain, and all of the above in `.ts/.tsx` files. Routers created in factory functions or received as parameters are parsed (routes and mounts), with the `use()` limits above. | +| **Express** | acorn AST for `.js/.mjs/.cjs`; regex fallback for `.ts/.tsx`. Resolves `app.use('/prefix', router)` mounts in the same file and across files: `app.use('/p', mw, importedRouter)` (the last argument is the router) follows relative imports (`./x.js`, `./x`, `./dir` to `dir/index.js`; ESM default, named and namespace imports; CommonJS `require`) to a router the file exports (`export default r`, `export { r }`, `export const r`, `module.exports = r`, `module.exports = { r }`, `exports.x = r`), including routers that mount other routers in other files. Mount middleware is added to the route's auth markers, and a router mounted twice yields one route per prefix. An exported `Router()` that no resolved mount reaches (alias or package imports such as `@/routes/x`, mounts in `.ts/.tsx` files, scans of a sub-directory, factory exports like `module.exports = function build() {...}`, cycles, more than 64 prefixes, routers nested inside a mounted file, a router mounted both in its own file and from another file, a router whose mount owner is nested on another local Router(), a router whose same-file owner sits on an `express()` app that is itself mounted) is `UNRESOLVED` with reason `mount-prefix-cross-file`; an `express()` app stays a root. A path-less mount middleware must be a function defined in the mounting file, otherwise the prefix counts as dynamic. `.ts/.tsx` files are never rewritten across files, so their routers keep their own path. AST files also track any variable assigned from `express()` / `express.Router()` / `Router()` whatever its name, and parse `app.route('/x').get(...).post(...)` chains. Path-less `router.use(requireAuth)` guards routes registered on that router after it only when `router` is a `const/let/var` declared once from a router factory, never reassigned, and the `use()` is a plain statement in the same block as the declaration. These `use()` calls are ignored (routes stay OPEN): `this.router.use(...)`, a router received as a parameter, a `use()` inside `if` or a helper function, `X.use(someCall(), auth)`, and wrappers like `jwt(...).unless(...)`. Not resolved: re-export barrels, aliases and package imports (see above), path-less `app.use(auth)` flowing into routers mounted on `app`, `route('/x').all(auth)` guarding the other verbs of the chain, and all of the above in `.ts/.tsx` files. Routers created in factory functions or received as parameters are parsed (routes and mounts), with the `use()` limits above. | | **Fastify** | acorn AST for `.js/.mjs/.cjs`; regex extractor for `.ts/.mts/.cts` (no TypeScript dependency, `fastify.delete<{ Params: ... }>(...)` generics are skipped). Handles `fastify.(...)` and `fastify.route({ method, url, preHandler })`. | | **NestJS** | Decorator extraction over `.ts/.js`. Pairs `@Controller(...)` with method decorators `@Get / @Post / @Put / @Patch / @Delete / @Options / @Head / @All`. Captures class- and method-level guards (`@UseGuards`, `@Auth`, `@Roles`, `@ApiBearerAuth`), global guards (`APP_GUARD` providers, `useGlobalGuards`) and a literal `setGlobalPrefix()`; see [NestJS global guards and prefix](#nestjs-global-guards-and-prefix). | | **OpenAPI** | Parses `*.yaml`/`*.yml`/`*.json` with `swagger:` (2.0) or `openapi:` (3.x) root. Honors operation-level `security` and root inheritance. | @@ -505,7 +505,7 @@ Each run writes: "frameworksDetected": ["express", "openapi"], "specsDetected": ["openapi.yaml"], "parserCapabilities": { - "express": { "sameFileMountPrefix": true, "crossFileMountPrefix": false, "dynamicMountPrefix": "UNRESOLVED", "routeChains": "AST files: ...", "routerLevelMiddleware": "AST files: ..." }, + "express": { "sameFileMountPrefix": true, "crossFileMountPrefix": true, "dynamicMountPrefix": "UNRESOLVED", "routeChains": "AST files: ...", "routerLevelMiddleware": "AST files: ..." }, "fastify": { "registerPrefixPropagation": false, "routeOptionsParsed": true }, "nest": { "controllerObjectArg": "path field only", "classLevelGuards": true }, "openapi": { "missingSecurity": "UNKNOWN (conservative)", "operationSecurityEmptyArray": "OPEN" } diff --git a/lib/capabilities.mjs b/lib/capabilities.mjs index feb8f5f..ab613b1 100644 --- a/lib/capabilities.mjs +++ b/lib/capabilities.mjs @@ -16,7 +16,8 @@ export const PARSER_CAPABILITIES = Object.freeze({ language: "js, mjs, cjs (AST) · ts, tsx (regex fallback)", httpMethods: "get/post/put/delete/patch/head/options/all", sameFileMountPrefix: true, - crossFileMountPrefix: false, + crossFileMountPrefix: true, + crossFileMounts: "AST files: X.use([prefix, ...mw,] importedRouter) where the LAST argument is the router, imported by a relative specifier (./x.js, ./x, ./dir -> dir/index.js) through ESM default/named/namespace import or CommonJS require, and the file exports it as `export default r`, `export { r }`, `export const r`, `module.exports = r`, `module.exports = { r }`, `module.exports.x = r` or `exports.x = r`. Nesting across files works, a router mounted twice yields one route per prefix, and mount middleware (identifiers between prefix and router, same rules as router-level use) is added to the route markers. A path-less mount middleware must be a function defined in the mounting file, otherwise the prefix counts as dynamic. An exported Router() that no resolved mount reaches (alias or package imports, mounts in .ts/.tsx files, scans of a sub-directory), a mount chain with a cycle or over 64 prefixes, a mount target whose export is not a Router() binding (factories, re-exports, `export default makeRouter()`) routers nested inside a mounted file and a router mounted both in its own file and from another file, a router whose mount owner is itself nested on another local Router(), and a router whose same-file owner sits on an express() app that is itself mounted (in its own file or from another file) are UNRESOLVED (mount-prefix-cross-file); a dynamic prefix keeps mount-prefix-not-static. An express() app stays a root. Parameter or this.app owners are treated as roots. .ts/.tsx files (regex fallback) are never rewritten, so their routers keep their own path", routerVariableTracking: "AST files: any same-file name assigned from express() / express.Router() / Router() (renamed imports included); the name heuristic (app, server, router, api, r, *router, *app) also applies, and is the only rule in the .ts/.tsx regex fallback", routeChains: "AST files: X.route(path).get(...).post(...) with per-method middleware; route(path).all(mw) is its own ALL endpoint and does not guard the other verbs of the chain; not in the .ts/.tsx regex fallback", routerLevelMiddleware: "AST files: path-less X.use(mw) adds markers to routes registered on X later, only when X is a const/let/var declared once from a router factory and never reassigned, the use() is an unconditional statement in the block that declares X, and the route is in that block outside nested functions; markers come from the direct argument or its callee only. Ignored (routes stay OPEN): this.router, parameters, use() inside if/loops/helper functions, X.use(, mw), skip wrappers (.unless/.optional/.skip/...). Not propagated into routers mounted on X", @@ -82,6 +83,7 @@ export const KNOWN_UNRESOLVED_REASONS = Object.freeze([ "global-prefix-not-static-string", "method-or-url-missing", "method-path-not-static-string", + "mount-prefix-cross-file", "mount-prefix-not-static", "path-not-static-string", "route-opts-not-object-literal" diff --git a/lib/parsers/express-modules.mjs b/lib/parsers/express-modules.mjs new file mode 100644 index 0000000..d5f2496 --- /dev/null +++ b/lib/parsers/express-modules.mjs @@ -0,0 +1,214 @@ +import path from "path"; + +/** + * Cross-file Express mount resolution. Pure graph code: it never touches an + * AST. `parseExpress` extracts, per file, the exported router bindings and the + * `X.use(prefix, ...mw, importedRouter)` calls; this module links them by + * module specifier and rewrites route paths with the mount prefixes found. + * + * Results depend only on complete maps keyed by absolute path, never on file + * order, so forward and reversed candidate lists give the same output. + */ + +const SPEC_EXTS = [".js", ".mjs", ".cjs", ".ts", ".tsx"]; +const MAX_CHAINS = 64; +export const REASON_CROSS_FILE = "mount-prefix-cross-file"; +export const REASON_NOT_STATIC = "mount-prefix-not-static"; + +const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k); + +export function joinPath(prefix, suffix) { + if (!prefix) return suffix || "/"; + if (!suffix || suffix === "/") return prefix.replace(/\/$/, "") || "/"; + const a = prefix.replace(/\/$/, ""); + const b = suffix.startsWith("/") ? suffix : "/" + suffix; + const joined = a + b; + return joined || "/"; +} + +/** Join two mount prefixes where an empty one means "no prefix". */ +function composePrefix(a, b) { + if (!a) return b; + if (!b) return a; + return joinPath(a, b); +} + +function unionMarkers(a, b) { + return [...new Set([...a, ...b])].sort(); +} + +/** + * Absolute path of the scanned file a relative specifier points at, or null. + * Tries the path as written, then each extension, then `/index`, + * in a fixed order. Package names and aliases are never resolved. + */ +export function resolveSpecifier(fromAbs, spec, fileSet) { + if (typeof spec !== "string") return null; + if (!(spec.startsWith("./") || spec.startsWith("../") || spec === "." || spec === "..")) return null; + const base = path.resolve(path.dirname(fromAbs), spec); + if (SPEC_EXTS.includes(path.extname(base).toLowerCase()) && fileSet.has(base)) return base; + for (const ext of SPEC_EXTS) if (fileSet.has(base + ext)) return base + ext; + for (const ext of SPEC_EXTS) { + const idx = path.join(base, "index" + ext); + if (fileSet.has(idx)) return idx; + } + return null; +} + +function createResolver(modules, fileSet) { + const incoming = new Map(); + const mountTargets = new Set(); + const tainted = new Set(); + + for (const abs of [...modules.keys()].sort()) { + const mod = modules.get(abs); + for (const m of [...mod.mounts].sort((x, y) => x.start - y.start)) { + const targetAbs = resolveSpecifier(abs, m.spec, fileSet); + if (!targetAbs) continue; + mountTargets.add(targetAbs); + const id = targetAbs + "\0" + m.key; + if (!incoming.has(id)) incoming.set(id, []); + incoming.get(id).push(m); + const target = modules.get(targetAbs); + if (target && (target.isTs || !target.exports.has(m.key))) tainted.add(targetAbs); + } + } + + const fail = (reason) => ({ fail: reason }); + + // Chains `{prefix, markers}` for routes owned by the exported binding + // `name` of `abs`; null when nothing mounts it; `{fail}` when the prefix + // cannot be composed (all-or-nothing, never a partial path). + const chainsFor = (abs, name, visiting = new Set()) => { + const mod = modules.get(abs); + const mounts = []; + for (const [key, bound] of mod.exports) { + if (bound === name) mounts.push(...(incoming.get(abs + "\0" + key) || [])); + } + if (mounts.length === 0) return null; + mounts.sort((x, y) => (x.file < y.file ? -1 : x.file > y.file ? 1 : x.start - y.start)); + + const id = abs + "\0" + name; + if (visiting.has(id)) return fail(REASON_CROSS_FILE); + visiting.add(id); + try { + const out = new Map(); + for (const m of mounts) { + if (m.prefix === null) return fail(REASON_NOT_STATIC); + const owner = modules.get(m.file); + if (m.ownerName && owner.routerUnresolved.has(m.ownerName)) return fail(REASON_NOT_STATIC); + const sameFile = m.ownerName && hasOwn(owner.routerMounts, m.ownerName); + const rooted = m.ownerName && owner.rootMounted.has(m.ownerName); + // `rooted` only says the owner router sits on an `express()` app. The + // prefix is complete only if that app is itself a root: not mounted + // in its own file and not mounted from another file. + if (sameFile && rooted) { + const app = owner.rootMounted.get(m.ownerName); + if (hasOwn(owner.routerMounts, app) || owner.routerUnresolved.has(app)) return fail(REASON_CROSS_FILE); + const appUp = chainsFor(m.file, app, visiting); + if (appUp) return fail(REASON_CROSS_FILE); + } + // A same-file mount on another Router() is not chained, so the full + // prefix is unknown. Only a mount straight on an app is complete. + if (sameFile && !rooted) return fail(REASON_CROSS_FILE); + const local = sameFile ? owner.routerMounts[m.ownerName] : ""; + const base = composePrefix(local, m.prefix); + let ups = null; + if (m.ownerLinked) { + const up = chainsFor(m.file, m.ownerLinked, visiting); + if (up && up.fail) return up; + if (up) { + // Mounted in its own file and from another file: separate + // mounts of one router, so the prefixes must not be stacked. + if (sameFile) return fail(REASON_CROSS_FILE); + ups = up.chains; + } + // An exported Router() nothing reaches is not a root: its own + // prefix lives in a file we cannot see. + else if (!m.ownerIsApp && !rooted && isExported(owner, m.ownerLinked)) return fail(REASON_CROSS_FILE); + } + if (!ups) ups = [{ prefix: "", markers: [] }]; + for (const u of ups) { + const prefix = composePrefix(u.prefix, base); + const markers = unionMarkers(u.markers, m.markers); + out.set(prefix + "\0" + markers.join(","), { prefix, markers }); + if (out.size > MAX_CHAINS) return fail(REASON_CROSS_FILE); + } + } + const chains = [...out.values()].sort((x, y) => { + if (x.prefix !== y.prefix) return x.prefix < y.prefix ? -1 : 1; + const xm = x.markers.join(","), ym = y.markers.join(","); + return xm < ym ? -1 : xm > ym ? 1 : 0; + }); + return { chains }; + } finally { + visiting.delete(id); + } + }; + + return { chainsFor, mountTargets, tainted }; +} + +function isExported(mod, name) { + for (const bound of mod.exports.values()) if (bound === name) return true; + return false; +} + +// True when the file exports a Router() that no resolved chain reaches. +function hasUnreachedExportedRouter(mod, abs, resolver) { + for (const name of new Set(mod.exports.values())) { + if (mod.apps && mod.apps.has(name)) continue; + if (mod.rootMounted.has(name)) continue; + if (resolver.chainsFor(abs, name) === null) return true; + } + return false; +} + +function unresolvedCopy(ep, reason) { + return { ...ep, path: null, resolved: false, unresolvedReason: reason }; +} + +/** + * Rewrite the endpoints emitted per file with the prefixes and middleware of + * the mounts that lead to them. `pending` maps each endpoint object to + * `{abs, ownerName, linked, isRouter}`; `linked` is the Program-level router + * binding that owns the route, or null, and `isRouter` tells `Router()` from + * an `express()` app. An exported router no resolved chain reaches becomes + * unresolved; an app stays a root. + */ +export function applyCrossFileMounts(endpoints, modules, pending, fileSet) { + const resolver = createResolver(modules, fileSet); + + const out = []; + for (const ep of endpoints) { + const p = pending.get(ep); + if (!p || ep.resolved === false) { + out.push(ep); + continue; + } + const res = p.linked ? resolver.chainsFor(p.abs, p.linked) : null; + if (res && res.fail) { + out.push(unresolvedCopy(ep, res.fail)); + } else if (res && hasOwn(modules.get(p.abs).routerMounts, p.linked)) { + // Mounted in its own file and from another file: those are separate + // mounts of the same router, so the two prefixes must not be stacked. + out.push(unresolvedCopy(ep, REASON_CROSS_FILE)); + } else if (res) { + for (const c of res.chains) { + out.push({ ...ep, path: joinPath(c.prefix, ep.path), authMarkers: unionMarkers(ep.authMarkers, c.markers) }); + } + } else if (p.linked && p.isRouter && isExported(modules.get(p.abs), p.linked) && + !modules.get(p.abs).rootMounted.has(p.linked)) { + // An exported Router() nothing in the scan reaches: its real prefix + // lives in a file we cannot see (alias, package, .ts, sub-directory). + out.push(unresolvedCopy(ep, REASON_CROSS_FILE)); + } else if (resolver.tainted.has(p.abs) || + (p.ownerName && hasOwn(modules.get(p.abs).routerMounts, p.ownerName) && + (resolver.mountTargets.has(p.abs) || hasUnreachedExportedRouter(modules.get(p.abs), p.abs, resolver)))) { + out.push(unresolvedCopy(ep, REASON_CROSS_FILE)); + } else { + out.push(ep); + } + } + return out; +} diff --git a/lib/parsers/express.mjs b/lib/parsers/express.mjs index eb848da..cc07698 100644 --- a/lib/parsers/express.mjs +++ b/lib/parsers/express.mjs @@ -2,6 +2,7 @@ import path from "path"; import * as acorn from "acorn"; import * as walk from "acorn-walk"; import { readTextFile, walkFiles, filterFilesByExtension, relPath } from "../utils.mjs"; +import { joinPath, applyCrossFileMounts } from "./express-modules.mjs"; const HTTP_METHODS = new Set([ "get", "post", "put", "delete", "patch", "head", "options", "all" @@ -24,8 +25,10 @@ const TS_EXTS = new Set([".ts", ".tsx"]); * routers received as parameters (`module.exports = (app) => ...`) or * via `this.router` keep working. * 4. Detect mount calls: `app.use('/prefix', r)` — record prefix→routerVar - * bindings inside the SAME file (cross-file router import resolution is - * not attempted; dynamic prefixes are flagged UNRESOLVED). + * bindings inside the SAME file; dynamic prefixes are flagged + * UNRESOLVED. Cross-file mounts (`app.use('/p', mw, importedRouter)`) + * are recorded per file and linked after the loop by + * express-modules.mjs (relative specifiers only; see step 8). * 5. Detect path-less middleware `X.use(mw, ...)`: its identifiers become * auth markers for every route registered on X LATER in source order. * Keyed on the binding (scope + name), never the bare name, and only @@ -40,13 +43,22 @@ const TS_EXTS = new Set([".ts", ".tsx"]); * 7. Collect middleware identifiers from the handler args, by Identifier * name + MemberExpression last-property name + property names of inline * array elements. Stored as `authMarkers` for the auth classifier. + * 8. After all files are read, prefix routes of exported Program-level + * routers with the mounts that reach them, across files (nested too), + * and add the mount middleware to their markers. An exported + * `Router()` no resolved mount reaches, or whose chain cannot be + * composed, is UNRESOLVED `mount-prefix-cross-file`; an `express()` app + * stays a root. `.ts/.tsx` files (regex) are never rewritten. */ export function parseExpress(targetDir, excludePaths = [], scanOptions = {}, candidateFiles = null) { const files = candidateFiles === null ? walkFiles(targetDir, EXTS, excludePaths, scanOptions) : filterFilesByExtension(candidateFiles, EXTS); - const endpoints = []; + let endpoints = []; const warnings = []; + const modules = new Map(); + const pending = new Map(); + const fileSet = new Set(files.map(f => path.resolve(f))); for (const file of files) { const rel = relPath(targetDir, file); @@ -59,9 +71,15 @@ export function parseExpress(targetDir, excludePaths = [], scanOptions = {}, can if (!hasExpressSignal(src)) continue; const ext = path.extname(file).toLowerCase(); + const abs = path.resolve(file); if (TS_EXTS.has(ext)) { + const from = endpoints.length; parseTsRegex(src, rel, endpoints); + modules.set(abs, { isTs: true, exports: new Map(), mounts: [], routerMounts: {}, rootMounted: new Map(), routerUnresolved: new Set() }); + for (let i = from; i < endpoints.length; i++) { + pending.set(endpoints[i], { abs, ownerName: null, linked: null, isRouter: false }); + } continue; } @@ -94,8 +112,19 @@ export function parseExpress(targetDir, excludePaths = [], scanOptions = {}, can const isRouter = (name) => isRouterRef(name, ctx); const routerMounts = {}; const routerUnresolved = new Set(); + const rootMounted = new Map(); const routerUses = new Map(); - collectMounts(ast, routerMounts, routerUnresolved, routerUses, ctx, isRouter); + collectMounts(ast, routerMounts, routerUnresolved, routerUses, ctx, isRouter, rootMounted); + const exportsMap = collectModuleExports(ast, ctx); + modules.set(abs, { + isTs: false, + exports: exportsMap, + apps: new Set([...exportsMap.values()].filter(n => ctx.scopes.get(ast)?.get(n)?.decls[0]?.isApp)), + mounts: collectCrossMounts(ast, ctx, isRouter, collectModuleImports(ast)).map(m => ({ ...m, file: abs })), + routerMounts, + rootMounted, + routerUnresolved + }); traverse(ast, (node, parents) => { if (node.type !== "CallExpression") return; @@ -154,7 +183,7 @@ export function parseExpress(targetDir, excludePaths = [], scanOptions = {}, can for (const m of inheritedUseMarkers(ownerNode, position, parents, routerUses, ctx)) markerSet.add(m); const authMarkers = [...markerSet].sort(); - endpoints.push({ + const ep = { method: method === "all" ? "ALL" : method.toUpperCase(), path: finalPath, file: rel, @@ -163,10 +192,19 @@ export function parseExpress(targetDir, excludePaths = [], scanOptions = {}, can resolved, authMarkers, unresolvedReason: reason + }; + endpoints.push(ep); + const linked = linkedRouterName(ownerNode, parents, ctx); + pending.set(ep, { + abs, + ownerName: objName, + linked, + isRouter: !!linked && !resolveBinding(linked, parents, ctx).decls[0].isApp }); }); } + endpoints = applyCrossFileMounts(endpoints, modules, pending, fileSet); return { endpoints, warnings }; } @@ -278,16 +316,7 @@ function stringValue(node) { return null; } -function joinPath(prefix, suffix) { - if (!prefix) return suffix || "/"; - if (!suffix || suffix === "/") return prefix.replace(/\/$/, "") || "/"; - const a = prefix.replace(/\/$/, ""); - const b = suffix.startsWith("/") ? suffix : "/" + suffix; - const joined = a + b; - return joined || "/"; -} - -function collectMounts(ast, routerMounts, routerUnresolved, routerUses, ctx, isRouter) { +function collectMounts(ast, routerMounts, routerUnresolved, routerUses, ctx, isRouter, rootMounted) { traverse(ast, (node, parents) => { if (node.type !== "CallExpression") return; const callee = node.callee; @@ -319,6 +348,9 @@ function collectMounts(ast, routerMounts, routerUnresolved, routerUses, ctx, isR if (!refName || !isRouter(refName)) continue; if (prefix !== null) { routerMounts[refName] = prefix; + const mountOwner = identName(callee.object); + if (mountOwner && resolveBinding(mountOwner, parents, ctx)?.decls?.[0]?.isApp) rootMounted.set(refName, mountOwner); + else rootMounted.delete(refName); } else { routerUnresolved.add(refName); } @@ -448,6 +480,16 @@ function analyzeBindings(ast) { return false; }; + // `express()` / `require("express")()`: an app (a root), not a Router(). + const isAppFactory = (init) => { + let n = init; + while (n?.type === "AssignmentExpression") n = n.right; + const c = n?.callee; + if (n?.type !== "CallExpression") return false; + if (c?.type === "Identifier") return expressNames.has(c.name); + return c?.type === "CallExpression" && isRequireExpress(c); + }; + // Pass 2: router instance names (scope-insensitive, used to decide which // `X.(...)` calls are routes). walk.simple(ast, { @@ -478,8 +520,9 @@ function analyzeBindings(ast) { const container = (list?.type === "Program" || list?.type === "BlockStatement") ? list : null; for (const d of node.declarations) { const isRouterDecl = d.id?.type === "Identifier" && isRouterFactory(d.init); + const isApp = isRouterDecl && isAppFactory(d.init); for (const name of patternNames(d.id)) { - declare(scope, name, { kind: "var", init: d.init || null, isRouter: isRouterDecl, container }); + declare(scope, name, { kind: "var", init: d.init || null, isRouter: isRouterDecl, container, isApp }); } } } else if (FUNCTION_TYPES.has(node.type)) { @@ -702,3 +745,169 @@ function visitMarker(node, out) { return; } } + +/** + * Name of the Program-level router binding `ownerNode` refers to, or null. + * Only these can be exported and linked across files (never parameters, + * `this.router` or factory-local routers). + */ +function linkedRouterName(ownerNode, parents, ctx) { + if (ownerNode?.type !== "Identifier") return null; + const b = resolveBinding(ownerNode.name, parents, ctx); + return isStableRouterBinding(b) && b.decls[0].container.type === "Program" ? ownerNode.name : null; +} + +const exportKey = (n) => (n?.type === "Identifier" ? n.name : n?.type === "Literal" ? String(n.value) : null); + +/** + * Exported router bindings of a file: export key -> Program-level binding + * name, from top-level statements only. ESM: `export default r`, + * `export { r, r as x }`, `export const r = Router()`. CJS: + * `module.exports = r`, `module.exports = { r, x: r }`, + * `module.exports.x = r`, `exports.x = r`. + */ +function collectModuleExports(ast, ctx) { + const top = ctx.scopes.get(ast); + const out = new Map(); + const add = (key, name) => { + const b = top?.get(name); + if (key !== null && isStableRouterBinding(b) && b.decls[0].container.type === "Program") out.set(key, name); + }; + const isMember = (n, obj, prop) => + n?.type === "MemberExpression" && !n.computed && n.object?.type === "Identifier" && + n.object.name === obj && n.property?.type === "Identifier" && n.property.name === prop; + for (const st of ast.body) { + if (st.type === "ExportDefaultDeclaration" && st.declaration?.type === "Identifier") { + add("default", st.declaration.name); + } else if (st.type === "ExportNamedDeclaration" && !st.source) { + if (st.declaration?.type === "VariableDeclaration") { + for (const d of st.declaration.declarations) if (d.id?.type === "Identifier") add(d.id.name, d.id.name); + } + for (const sp of st.specifiers || []) add(exportKey(sp.exported), sp.local?.name); + } else if (st.type === "ExpressionStatement" && st.expression.type === "AssignmentExpression" && + st.expression.operator === "=") { + const { left, right } = st.expression; + if (isMember(left, "module", "exports")) { + if (right.type === "Identifier") add("default", right.name); + else if (right.type === "ObjectExpression") { + for (const p of right.properties) { + if (p.type === "Property" && !p.computed && p.value?.type === "Identifier") add(exportKey(p.key), p.value.name); + } + } + } else if (left?.type === "MemberExpression" && !left.computed && left.property?.type === "Identifier" && + (isMember(left.object, "module", "exports") || (left.object?.type === "Identifier" && left.object.name === "exports")) && + right.type === "Identifier") { + add(left.property.name, right.name); + } + } + } + return out; +} + +/** `require("")` with one string argument -> spec, else null. */ +function requireSpec(node) { + if (node?.type !== "CallExpression" || node.callee?.type !== "Identifier" || node.callee.name !== "require") return null; + if ((node.arguments || []).length !== 1) return null; + return stringValue(node.arguments[0]); +} + +/** + * Top-level import bindings: local name -> `{spec, key}` (one export of the + * module), `{spec, ns: true}` (namespace import) or `{spec, whole: true}` + * (`const m = require(spec)`: the module value and its namespace). + */ +function collectModuleImports(ast) { + const out = new Map(); + for (const st of ast.body) { + if (st.type === "ImportDeclaration") { + const spec = stringValue(st.source); + for (const sp of st.specifiers || []) { + if (sp.type === "ImportDefaultSpecifier") out.set(sp.local.name, { spec, key: "default" }); + else if (sp.type === "ImportNamespaceSpecifier") out.set(sp.local.name, { spec, ns: true }); + else if (sp.type === "ImportSpecifier") out.set(sp.local.name, { spec, key: exportKey(sp.imported) }); + } + } else if (st.type === "VariableDeclaration") { + for (const d of st.declarations) { + const whole = requireSpec(d.init); + if (whole !== null) { + if (d.id?.type === "Identifier") out.set(d.id.name, { spec: whole, whole: true }); + else if (d.id?.type === "ObjectPattern") { + for (const p of d.id.properties) { + if (p.type === "Property" && !p.computed && p.value?.type === "Identifier") { + out.set(p.value.name, { spec: whole, key: exportKey(p.key) }); + } + } + } + } else if (d.init?.type === "MemberExpression" && !d.init.computed && d.id?.type === "Identifier" && + d.init.property?.type === "Identifier" && requireSpec(d.init.object) !== null) { + out.set(d.id.name, { spec: requireSpec(d.init.object), key: d.init.property.name }); + } + } + } + } + return out; +} + +/** `{spec, key}` when `node` is an imported module value, else null. */ +function importRef(node, parents, ctx, imports) { + const info = (name) => { + const b = resolveBinding(name, parents, ctx); + if (!b || b !== ctx.scopes.get(parents[0])?.get(name) || b.decls.length !== 1 || b.reassigned) return null; + return imports.get(name) || null; + }; + if (node?.type === "Identifier") { + const i = info(node.name); + if (!i) return null; + if (i.key !== undefined) return { spec: i.spec, key: i.key }; + return i.whole ? { spec: i.spec, key: "default" } : null; + } + const spec = requireSpec(node); + if (spec !== null) return { spec, key: "default" }; + if (node?.type === "MemberExpression" && !node.computed && node.property?.type === "Identifier") { + const objSpec = requireSpec(node.object); + if (objSpec !== null) return { spec: objSpec, key: node.property.name }; + if (node.object?.type === "Identifier") { + const i = info(node.object.name); + if (i && (i.ns || i.whole)) return { spec: i.spec, key: node.property.name }; + } + } + return null; +} + +/** + * `X.use([prefix, ...mw,] importedRouter)` calls whose LAST argument is an + * imported module value. Earlier arguments are middleware, so an imported + * `requireAuth` is never read as the router. `prefix` is "" for a path-less + * use, null when the prefix is not static. + */ +function collectCrossMounts(ast, ctx, isRouter, imports) { + const out = []; + traverse(ast, (node, parents) => { + if (node.type !== "CallExpression") return; + const callee = node.callee; + if (callee?.type !== "MemberExpression" || callee.computed || callee.property?.type !== "Identifier" || + callee.property.name !== "use") return; + const ownerName = identName(callee.object); + if (!ownerName || ownerName === "this" || !isRouter(ownerName)) return; + const args = node.arguments || []; + if (args.length === 0) return; + const ref = importRef(args[args.length - 1], parents, ctx, imports); + if (!ref) return; + let prefix = null; + let mw = []; + if (args.length === 1) prefix = ""; + else if (stringValue(args[0]) !== null) { prefix = stringValue(args[0]); mw = args.slice(1, -1); } + else if (isPathlessUse(args, parents, ctx)) { prefix = ""; mw = args.slice(0, -1); } + out.push({ + start: node.start, + ownerName, + ownerLinked: linkedRouterName(callee.object, parents, ctx), + ownerIsApp: !!resolveBinding(ownerName, parents, ctx)?.decls?.[0]?.isApp, + spec: ref.spec, + key: ref.key, + prefix, + markers: prefix === null ? [] : collectUseMarkers(mw) + }); + }); + return out; +} diff --git a/lib/utils.mjs b/lib/utils.mjs index 4f3d80d..182427a 100644 --- a/lib/utils.mjs +++ b/lib/utils.mjs @@ -213,12 +213,18 @@ export function normalizeMethod(m) { } /** - * Stable endpoint sort key: method, path, file, line. + * Stable endpoint sort key: method, path (null last), file, line. */ export function sortEndpoints(arr) { return [...arr].sort((a, b) => { if (a.method !== b.method) return a.method < b.method ? -1 : 1; - if (a.path !== b.path) return a.path < b.path ? -1 : 1; + // Unresolved endpoints have path null: sort them after resolved ones so + // the comparator stays a total order (null < "/x" is false both ways). + if (a.path !== b.path) { + if (a.path === null || a.path === undefined) return 1; + if (b.path === null || b.path === undefined) return -1; + return a.path < b.path ? -1 : 1; + } if ((a.file || "") !== (b.file || "")) return (a.file || "") < (b.file || "") ? -1 : 1; return (a.line || 0) - (b.line || 0); }); diff --git a/test/capabilities.mjs b/test/capabilities.mjs index 2295d2e..143655b 100644 --- a/test/capabilities.mjs +++ b/test/capabilities.mjs @@ -16,14 +16,14 @@ t.test("PARSER_CAPABILITIES.express child is frozen", () => { t.test("Express: declares regex TS fallback, no TS AST, dynamic mount UNRESOLVED", () => { const e = PARSER_CAPABILITIES.express; assertEq(e.sameFileMountPrefix, true); - assertEq(e.crossFileMountPrefix, false); + assertEq(e.crossFileMountPrefix, true); assertEq(e.dynamicMountPrefix, "UNRESOLVED"); assertEq(e.typeScriptAst, false); }); t.test("Express: router tracking, route() chains and router-level middleware are declared AST-only", () => { const e = PARSER_CAPABILITIES.express; - for (const k of ["routerVariableTracking", "routeChains", "routerLevelMiddleware"]) { + for (const k of ["routerVariableTracking", "routeChains", "routerLevelMiddleware", "crossFileMounts"]) { if (typeof e[k] !== "string" || !e[k].startsWith("AST files:")) throw new Error(`express.${k} missing or not AST-scoped`); } }); diff --git a/test/determinism.mjs b/test/determinism.mjs index f3f46bc..a31a7e8 100644 --- a/test/determinism.mjs +++ b/test/determinism.mjs @@ -12,6 +12,8 @@ import { computeScore } from "../lib/score.mjs"; import { renderHtml } from "../lib/report.mjs"; import { annotateRisk } from "../lib/risk.mjs"; import { parseFilter, applyFilter } from "../lib/filter.mjs"; +import { parseExpress } from "../lib/parsers/express.mjs"; +import { walkFiles, sortEndpoints } from "../lib/utils.mjs"; import { runner, assertEq } from "./_runner.mjs"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -127,4 +129,10 @@ t.test("applyFilter: filtered HTML byte-equal across two runs", () => { assertEq(a, b); }); +t.test("parseExpress: cross-file mounts give identical output for forward and reversed file lists", () => { + const multi = path.join(__dirname, "fixtures", "express-multifile"); + const files = walkFiles(multi, [".js", ".mjs", ".cjs", ".ts", ".tsx"], [], {}); + const run = (list) => JSON.stringify(sortEndpoints(parseExpress(multi, [], {}, list).endpoints)); + assertEq(run(files), run([...files].reverse())); +}); t.finish(); diff --git a/test/fixtures/express-multifile/app.js b/test/fixtures/express-multifile/app.js new file mode 100644 index 0000000..e51af38 --- /dev/null +++ b/test/fixtures/express-multifile/app.js @@ -0,0 +1,19 @@ +import express from "express"; +import usersRouter from "./routes/users.js"; +import adminRouter from "./routes/admin"; +import apiRouter from "./routes/api"; +import legacy from "./routes/legacy"; +import dynRouter from "./routes/dyn.js"; +import ghost from "@/routes/ghost"; +import { requireAuth } from "./auth.js"; + +const app = express(); + +app.use("/api/users", usersRouter); +app.use("/admin", requireAuth, adminRouter); +app.use("/v1", apiRouter); +app.use("/legacy", legacy); +app.use(process.env.DYN, dynRouter); +app.use("/ghost", ghost); + +export default app; diff --git a/test/fixtures/express-multifile/auth.js b/test/fixtures/express-multifile/auth.js new file mode 100644 index 0000000..4701807 --- /dev/null +++ b/test/fixtures/express-multifile/auth.js @@ -0,0 +1,3 @@ +export function requireAuth(req, res, next) { + next(); +} diff --git a/test/fixtures/express-multifile/cycle/a.js b/test/fixtures/express-multifile/cycle/a.js new file mode 100644 index 0000000..dbf9eea --- /dev/null +++ b/test/fixtures/express-multifile/cycle/a.js @@ -0,0 +1,7 @@ +import { Router } from "express"; +import { bRouter } from "./b.js"; + +export const aRouter = Router(); + +aRouter.use("/b", bRouter); +aRouter.get("/x", (req, res) => res.end()); diff --git a/test/fixtures/express-multifile/cycle/b.js b/test/fixtures/express-multifile/cycle/b.js new file mode 100644 index 0000000..08195cc --- /dev/null +++ b/test/fixtures/express-multifile/cycle/b.js @@ -0,0 +1,7 @@ +import { Router } from "express"; +import { aRouter } from "./a.js"; + +export const bRouter = Router(); + +bRouter.use("/a", aRouter); +bRouter.get("/y", (req, res) => res.end()); diff --git a/test/fixtures/express-multifile/multi/inline.js b/test/fixtures/express-multifile/multi/inline.js new file mode 100644 index 0000000..d08a94a --- /dev/null +++ b/test/fixtures/express-multifile/multi/inline.js @@ -0,0 +1,5 @@ +const router = require("express").Router(); + +router.get("/i", (req, res) => res.end()); + +module.exports = router; diff --git a/test/fixtures/express-multifile/multi/main.js b/test/fixtures/express-multifile/multi/main.js new file mode 100644 index 0000000..64f7f2b --- /dev/null +++ b/test/fixtures/express-multifile/multi/main.js @@ -0,0 +1,12 @@ +import express from "express"; +import { sharedRouter as shared } from "./shared.js"; +import * as named from "./named.js"; + +const app = express(); + +app.use("/a", shared); +app.use("/b", shared); +app.use("/ns", named.nsRouter); +app.use("/inline", require("./inline.js")); + +export default app; diff --git a/test/fixtures/express-multifile/multi/named.js b/test/fixtures/express-multifile/multi/named.js new file mode 100644 index 0000000..8cab3a1 --- /dev/null +++ b/test/fixtures/express-multifile/multi/named.js @@ -0,0 +1,7 @@ +import { Router } from "express"; + +const nsRouter = Router(); + +nsRouter.get("/n", (req, res) => res.end()); + +export { nsRouter }; diff --git a/test/fixtures/express-multifile/multi/shared.js b/test/fixtures/express-multifile/multi/shared.js new file mode 100644 index 0000000..6e2914e --- /dev/null +++ b/test/fixtures/express-multifile/multi/shared.js @@ -0,0 +1,5 @@ +import { Router } from "express"; + +export const sharedRouter = Router(); + +sharedRouter.get("/ping", (req, res) => res.end()); diff --git a/test/fixtures/express-multifile/routes/admin.js b/test/fixtures/express-multifile/routes/admin.js new file mode 100644 index 0000000..6ea2ccc --- /dev/null +++ b/test/fixtures/express-multifile/routes/admin.js @@ -0,0 +1,5 @@ +const router = require("express").Router(); + +router.delete("/wipe", (req, res) => res.end()); + +module.exports = router; diff --git a/test/fixtures/express-multifile/routes/api/index.js b/test/fixtures/express-multifile/routes/api/index.js new file mode 100644 index 0000000..b831c0f --- /dev/null +++ b/test/fixtures/express-multifile/routes/api/index.js @@ -0,0 +1,9 @@ +const express = require("express"); +const { itemsRouter } = require("./items"); + +const router = express.Router(); + +router.use("/items", itemsRouter); +router.get("/ping", (req, res) => res.end("pong")); + +module.exports = router; diff --git a/test/fixtures/express-multifile/routes/api/items.js b/test/fixtures/express-multifile/routes/api/items.js new file mode 100644 index 0000000..b9645f5 --- /dev/null +++ b/test/fixtures/express-multifile/routes/api/items.js @@ -0,0 +1,7 @@ +const express = require("express"); + +const router = express.Router(); + +router.get("/:id", (req, res) => res.json({})); + +exports.itemsRouter = router; diff --git a/test/fixtures/express-multifile/routes/dyn.js b/test/fixtures/express-multifile/routes/dyn.js new file mode 100644 index 0000000..123696e --- /dev/null +++ b/test/fixtures/express-multifile/routes/dyn.js @@ -0,0 +1,7 @@ +import { Router } from "express"; + +const router = Router(); + +router.get("/x", (req, res) => res.end()); + +export default router; diff --git a/test/fixtures/express-multifile/routes/ghost.js b/test/fixtures/express-multifile/routes/ghost.js new file mode 100644 index 0000000..6950199 --- /dev/null +++ b/test/fixtures/express-multifile/routes/ghost.js @@ -0,0 +1,7 @@ +import { Router } from "express"; + +const router = Router(); + +router.get("/g", (req, res) => res.end()); + +export default router; diff --git a/test/fixtures/express-multifile/routes/legacy.js b/test/fixtures/express-multifile/routes/legacy.js new file mode 100644 index 0000000..3c02fb2 --- /dev/null +++ b/test/fixtures/express-multifile/routes/legacy.js @@ -0,0 +1,7 @@ +const { Router } = require("express"); + +module.exports = function build() { + const r = Router(); + r.get("/old", (req, res) => res.end()); + return r; +}; diff --git a/test/fixtures/express-multifile/routes/users.js b/test/fixtures/express-multifile/routes/users.js new file mode 100644 index 0000000..26b223b --- /dev/null +++ b/test/fixtures/express-multifile/routes/users.js @@ -0,0 +1,8 @@ +import { Router } from "express"; + +const router = Router(); + +router.get("/", (req, res) => res.json([])); +router.post("/", (req, res) => res.status(201).end()); + +export default router; diff --git a/test/fixtures/express-multifile/samefile/server.js b/test/fixtures/express-multifile/samefile/server.js new file mode 100644 index 0000000..da6e004 --- /dev/null +++ b/test/fixtures/express-multifile/samefile/server.js @@ -0,0 +1,6 @@ +const express = require("express"); +const app = express(); +const router = express.Router(); +router.get("/u", (q, s) => s.end()); +app.use("/api", router); +module.exports = { app, router }; diff --git a/test/fixtures/express-multifile/samefile2/other.js b/test/fixtures/express-multifile/samefile2/other.js new file mode 100644 index 0000000..611737b --- /dev/null +++ b/test/fixtures/express-multifile/samefile2/other.js @@ -0,0 +1,4 @@ +const express = require("express"); +const { router } = require("./server"); +const main = express(); +main.use("/x", router); diff --git a/test/fixtures/express-multifile/samefile2/server.js b/test/fixtures/express-multifile/samefile2/server.js new file mode 100644 index 0000000..da6e004 --- /dev/null +++ b/test/fixtures/express-multifile/samefile2/server.js @@ -0,0 +1,6 @@ +const express = require("express"); +const app = express(); +const router = express.Router(); +router.get("/u", (q, s) => s.end()); +app.use("/api", router); +module.exports = { app, router }; diff --git a/test/fixtures/express-multifile/samefile3/leaf.js b/test/fixtures/express-multifile/samefile3/leaf.js new file mode 100644 index 0000000..086c0ec --- /dev/null +++ b/test/fixtures/express-multifile/samefile3/leaf.js @@ -0,0 +1,4 @@ +const express = require("express"); +const r2 = express.Router(); +r2.get("/z", (q, s) => s.end()); +module.exports = r2; diff --git a/test/fixtures/express-multifile/samefile3/other.js b/test/fixtures/express-multifile/samefile3/other.js new file mode 100644 index 0000000..198d8ea --- /dev/null +++ b/test/fixtures/express-multifile/samefile3/other.js @@ -0,0 +1,4 @@ +const express = require("express"); +const { r } = require("./server"); +const main = express(); +main.use("/c", r); diff --git a/test/fixtures/express-multifile/samefile3/server.js b/test/fixtures/express-multifile/samefile3/server.js new file mode 100644 index 0000000..da62a6c --- /dev/null +++ b/test/fixtures/express-multifile/samefile3/server.js @@ -0,0 +1,6 @@ +const express = require("express"); +const app = express(); +const r = express.Router(); +r.use("/x", require("./leaf")); +app.use("/api", r); +module.exports = { app, r }; diff --git a/test/fixtures/express-multifile/samefile4/leaf.js b/test/fixtures/express-multifile/samefile4/leaf.js new file mode 100644 index 0000000..086c0ec --- /dev/null +++ b/test/fixtures/express-multifile/samefile4/leaf.js @@ -0,0 +1,4 @@ +const express = require("express"); +const r2 = express.Router(); +r2.get("/z", (q, s) => s.end()); +module.exports = r2; diff --git a/test/fixtures/express-multifile/samefile4/server.js b/test/fixtures/express-multifile/samefile4/server.js new file mode 100644 index 0000000..9a4de04 --- /dev/null +++ b/test/fixtures/express-multifile/samefile4/server.js @@ -0,0 +1,9 @@ +const express = require("express"); +const app = express(); +const r0 = express.Router(); +const r = express.Router(); +r.get("/own", (q, s) => s.end()); +r.use("/x", require("./leaf")); +r0.use("/r", r); +app.use("/api", r0); +app.listen(3000); diff --git a/test/fixtures/express-multifile/samefile5/leaf.js b/test/fixtures/express-multifile/samefile5/leaf.js new file mode 100644 index 0000000..086c0ec --- /dev/null +++ b/test/fixtures/express-multifile/samefile5/leaf.js @@ -0,0 +1,4 @@ +const express = require("express"); +const r2 = express.Router(); +r2.get("/z", (q, s) => s.end()); +module.exports = r2; diff --git a/test/fixtures/express-multifile/samefile5/server.js b/test/fixtures/express-multifile/samefile5/server.js new file mode 100644 index 0000000..da62a6c --- /dev/null +++ b/test/fixtures/express-multifile/samefile5/server.js @@ -0,0 +1,6 @@ +const express = require("express"); +const app = express(); +const r = express.Router(); +r.use("/x", require("./leaf")); +app.use("/api", r); +module.exports = { app, r }; diff --git a/test/fixtures/express-multifile/samefile6/leaf.js b/test/fixtures/express-multifile/samefile6/leaf.js new file mode 100644 index 0000000..086c0ec --- /dev/null +++ b/test/fixtures/express-multifile/samefile6/leaf.js @@ -0,0 +1,4 @@ +const express = require("express"); +const r2 = express.Router(); +r2.get("/z", (q, s) => s.end()); +module.exports = r2; diff --git a/test/fixtures/express-multifile/samefile6/server.js b/test/fixtures/express-multifile/samefile6/server.js new file mode 100644 index 0000000..121d78b --- /dev/null +++ b/test/fixtures/express-multifile/samefile6/server.js @@ -0,0 +1,8 @@ +const express = require("express"); +const main = express(); +const sub = express(); +const r = express.Router(); +r.use("/x", require("./leaf")); +sub.use("/r", r); +main.use("/v", sub); +main.listen(3000); diff --git a/test/fixtures/express-multifile/samefile7/app.js b/test/fixtures/express-multifile/samefile7/app.js new file mode 100644 index 0000000..f8486fb --- /dev/null +++ b/test/fixtures/express-multifile/samefile7/app.js @@ -0,0 +1,6 @@ +const express = require("express"); +const app = express(); +const r = express.Router(); +r.use("/x", require("./leaf")); +app.use("/r", r); +module.exports = app; diff --git a/test/fixtures/express-multifile/samefile7/leaf.js b/test/fixtures/express-multifile/samefile7/leaf.js new file mode 100644 index 0000000..086c0ec --- /dev/null +++ b/test/fixtures/express-multifile/samefile7/leaf.js @@ -0,0 +1,4 @@ +const express = require("express"); +const r2 = express.Router(); +r2.get("/z", (q, s) => s.end()); +module.exports = r2; diff --git a/test/fixtures/express-multifile/samefile7/main.js b/test/fixtures/express-multifile/samefile7/main.js new file mode 100644 index 0000000..b5fe041 --- /dev/null +++ b/test/fixtures/express-multifile/samefile7/main.js @@ -0,0 +1,4 @@ +const express = require("express"); +const main = express(); +main.use("/v", require("./app")); +main.listen(3000); diff --git a/test/fixtures/express-multifile/unmounted/nested.js b/test/fixtures/express-multifile/unmounted/nested.js new file mode 100644 index 0000000..fda2c6b --- /dev/null +++ b/test/fixtures/express-multifile/unmounted/nested.js @@ -0,0 +1,7 @@ +const { Router } = require("express"); +const router = Router(); +const sub = Router(); +sub.get("/x", (req, res) => res.json({})); +router.use("/sub", sub); +router.get("/top", (req, res) => res.json({})); +module.exports = router; diff --git a/test/fixtures/express-router-negatives/conditional-use.js b/test/fixtures/express-router-negatives/conditional-use.js index 8b4a9cb..1d2bfd9 100644 --- a/test/fixtures/express-router-negatives/conditional-use.js +++ b/test/fixtures/express-router-negatives/conditional-use.js @@ -12,5 +12,3 @@ function protect() { } router.post("/open", (req, res) => res.end()); // -> OPEN (registered before protect()) protect(); - -module.exports = { r2, router }; diff --git a/test/fixtures/express-router-negatives/unless.js b/test/fixtures/express-router-negatives/unless.js index 26873e3..ccf3e75 100644 --- a/test/fixtures/express-router-negatives/unless.js +++ b/test/fixtures/express-router-negatives/unless.js @@ -10,5 +10,3 @@ app.post("/webhook", (req, res) => res.end()); // -> OPEN const api = express.Router(); api.use(jwt({ secret })); api.post("/guarded", (req, res) => res.end()); // -> GUARDED (control) - -module.exports = { app, api }; diff --git a/test/parser-express.mjs b/test/parser-express.mjs index 0ef0a0b..0ff2d70 100644 --- a/test/parser-express.mjs +++ b/test/parser-express.mjs @@ -133,4 +133,79 @@ t.test("use(): express.json(), imported router and error handler are not auth", assertDeepEq(summarizeNeg("harmless-use.js"), ["POST /items OPEN"]); }); +// Issue #8: routers defined in one file and mounted in another. +const multiFixture = path.join(__dirname, "fixtures", "express-multifile"); +const multiEndpoints = parseExpress(multiFixture, []).endpoints; +const multi = classifyAll(multiEndpoints, CONFIG_DEFAULTS); +const summarizeMulti = (prefix) => multi + .filter(e => e.file.startsWith(prefix)) + .map(e => `${e.method} ${e.path} ${e.posture}${e.unresolvedReason ? " " + e.unresolvedReason : ""}`) + .sort(); +t.test("multifile: default-imported ESM router gets its mount prefix", () => { + assertDeepEq(summarizeMulti("routes/users.js"), ["GET /api/users OPEN", "POST /api/users OPEN"]); +}); +t.test("multifile: mount middleware guards the routes of an extension-less CJS import", () => { + assertDeepEq(summarizeMulti("routes/admin.js"), ["DELETE /admin/wipe GUARDED"]); + const e = multi.find(x => x.file === "routes/admin.js"); + assertEq(e.matchedAuthMarker, "requireAuth"); +}); +t.test("multifile: ./dir resolves index.js and nested mounts compose across files", () => { + assertDeepEq(summarizeMulti("routes/api/"), ["GET /v1/items/:id OPEN", "GET /v1/ping OPEN"]); +}); +t.test("multifile: named, namespace, renamed and inline require forms; one router mounted twice", () => { + assertDeepEq(summarizeMulti("multi/"), [ + "GET /a/ping OPEN", "GET /b/ping OPEN", "GET /inline/i OPEN", "GET /ns/n OPEN" + ]); +}); +t.test("multifile: factory export is unresolved mount-prefix-cross-file, never a bare path", () => { + assertDeepEq(summarizeMulti("routes/legacy.js"), ["GET null UNKNOWN mount-prefix-cross-file"]); +}); +t.test("multifile: dynamic prefix on a cross-file mount stays mount-prefix-not-static", () => { + assertDeepEq(summarizeMulti("routes/dyn.js"), ["GET null UNKNOWN mount-prefix-not-static"]); +}); +t.test("multifile: exported router reached only through an alias import is unresolved", () => { + assertDeepEq(summarizeMulti("routes/ghost.js"), ["GET null UNKNOWN mount-prefix-cross-file"]); +}); +t.test("multifile: mount cycle is unresolved, not a partial path", () => { + assertDeepEq(summarizeMulti("cycle/"), [ + "GET null UNKNOWN mount-prefix-cross-file", "GET null UNKNOWN mount-prefix-cross-file" + ]); +}); +t.test("multifile: no unresolved endpoint carries a path", () => { + for (const e of multiEndpoints) if (e.resolved === false && e.path !== null) throw new Error(`${e.file} has path ${e.path}`); +}); +t.test("multifile: scanning a sub-directory never reports half a prefix as resolved", () => { + const sub = classifyAll(parseExpress(path.join(multiFixture, "routes", "api"), []).endpoints, CONFIG_DEFAULTS) + .map(e => `${e.file} ${e.method} ${e.path} ${e.unresolvedReason || ""}`).sort(); + assertDeepEq(sub, [ + "index.js GET null mount-prefix-cross-file", + "items.js GET null mount-prefix-cross-file" + ]); +}); +t.test("multifile: nested local router inside an exported router nothing mounts is unresolved", () => { + assertDeepEq(summarizeMulti("unmounted/"), [ + "GET null UNKNOWN mount-prefix-cross-file", "GET null UNKNOWN mount-prefix-cross-file" + ]); +}); +t.test("multifile: exported router mounted on an app in its own file keeps its resolved path", () => { + assertDeepEq(summarizeMulti("samefile/"), ["GET /api/u OPEN"]); +}); +t.test("multifile: router mounted in its own file and from another file is unresolved, not stacked", () => { + assertDeepEq(summarizeMulti("samefile2/server.js"), ["GET null UNKNOWN mount-prefix-cross-file"]); +}); +t.test("multifile: dual-mounted middle router does not stack prefixes onto its child", () => { + assertDeepEq(summarizeMulti("samefile3/leaf.js"), ["GET null UNKNOWN mount-prefix-cross-file"]); +}); +t.test("multifile: child of a router nested on another local Router() stays unresolved", () => { + assertDeepEq(summarizeMulti("samefile4/leaf.js"), ["GET null UNKNOWN mount-prefix-cross-file"]); +}); +t.test("multifile: child of an exported router mounted straight on an app resolves with the full prefix", () => { + assertDeepEq(summarizeMulti("samefile5/leaf.js"), ["GET /api/x/z OPEN"]); +}); +t.test("multifile: router on an express() app that is mounted in the same file is unresolved", () => { + assertDeepEq(summarizeMulti("samefile6/leaf.js"), ["GET null UNKNOWN mount-prefix-cross-file"]); +}); +t.test("multifile: router on an express() app that is mounted from another file is unresolved", () => { + assertDeepEq(summarizeMulti("samefile7/leaf.js"), ["GET null UNKNOWN mount-prefix-cross-file"]); +}); t.finish();