routecall-audit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 routecall-audit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # routecall-audit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Catch mismatches between local `/api` calls and your actual Next.js API route files **before deploying**. Zero runtime dependencies. Offline static analysis.
4
+
5
+ This is a new experimental package; it is not currently published by this project. Before publishing, verify that the package name is available: `npm view routecall-audit version` (a 404 typically means that name isn't published, but also verify on npmjs.com).
6
+
7
+ ## Why?
8
+
9
+ Your frontend calls `fetch('/api/payments')`, but your backend route is actually `/api/payment`. Or the frontend sends `DELETE /api/users/42`, but the route only exports `GET`. Both bugs can make it through a TypeScript build. `routecall-audit` catches detectable cases without running the website.
10
+
11
+ ## Install
12
+
13
+ After publishing:
14
+
15
+ ```bash
16
+ npm install --save-dev routecall-audit
17
+ ```
18
+
19
+ Or run a local clone without publishing:
20
+
21
+ ```bash
22
+ node bin/routecall-audit.js ./examples/next-app
23
+ ```
24
+
25
+ ## Use
26
+
27
+ ```bash
28
+ npx routecall-audit .
29
+ npx routecall-audit . --json
30
+ npx routecall-audit . --report-unused
31
+ npx routecall-audit . --fail-on-unused
32
+ ```
33
+
34
+ Example output:
35
+
36
+ ```text
37
+ 3 source files | 2 API routes | 5 calls
38
+ FAIL MISSING_ROUTE src/components/Example.tsx:5
39
+ GET /api/payments has no matching local Next.js API route
40
+ FAIL METHOD_MISMATCH src/components/Example.tsx:6
41
+ DELETE /api/users/123 is not handled by src/app/api/users/[id]/route.ts (GET, HEAD, OPTIONS)
42
+ ```
43
+
44
+ Integrate it into your app's `package.json`:
45
+
46
+ ```json
47
+ {
48
+ "scripts": {
49
+ "check:api": "routecall-audit .",
50
+ "prebuild": "npm run check:api"
51
+ }
52
+ }
53
+ ```
54
+
55
+ > Only add `prebuild` once you have reviewed any false positives and confirmed your app uses supported patterns.
56
+
57
+ ### Programmatic API
58
+
59
+ ```js
60
+ import { scanProject } from 'routecall-audit';
61
+
62
+ const report = scanProject(process.cwd());
63
+ console.log(report.stats);
64
+ for (const issue of report.issues) {
65
+ console.log(issue.code, issue.file, issue.line, issue.message);
66
+ }
67
+ ```
68
+
69
+ TypeScript declaration file included.
70
+
71
+ ## Supported in v0.1.0
72
+
73
+ - Node.js 20+
74
+ - `app/api/**/route.{js,jsx,ts,tsx,mjs,mts}` or `src/app/api/**/route.*`
75
+ - `pages/api/**/*.{js,jsx,ts,tsx,mjs,mts}` or `src/pages/api/**/*`
76
+ - App Router named exports: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`; auto-HEAD/OPTIONS recognized.
77
+ - Pages Router handlers treated as supporting any method (method conditions can't be safely inferred in v0.1.0).
78
+ - String or simple template-literal calls: `fetch('/api/users')`, `fetch(`/api/users/${id}`)`, `fetch('/api/users', {method:'POST'})`, and `axios.get/post/put/patch/delete/head/options('/api/users')`.
79
+ - App Router dynamic routes: `[id]`, `[...slug]`, `[[...slug]]`; route groups `(group)` are ignored when constructing URLs.
80
+ - Optional report for routes not referenced by statically detected calls; such routes may be intentionally used by external clients.
81
+ - JSON reports and predictable CI exit codes: 0 success, 1 issues, 2 error.
82
+
83
+ ## Explicit limitations (important)
84
+
85
+ This tool is **conservative and regex-based**, not a JS/TS parser, and cannot guarantee correctness. It does not detect all calls. Some edge cases may yield false positives (e.g. matches in commented-out code) and false negatives.
86
+
87
+ - Dynamic URL construction like `fetch(baseUrl + '/users')`, variable URL arguments, axios instances, wrappers, aliases, and `new URL(...)` are **not resolved**.
88
+ - External URLs and URLs without a literal local `/api` prefix are intentionally skipped.
89
+ - Computed HTTP methods are skipped; only literal methods or the default GET can be validated.
90
+ - It does not analyze Next.js rewrites, `basePath`, external services, middleware, authentication, runtime responses, or API contracts.
91
+ - It does not fully model intercepted, parallel, or optional complex routing features, nor a custom `pageExtensions` configuration.
92
+ - Source directories like `node_modules`, `.next`, `dist`, `test`, `tests`, and `e2e` are skipped; files over 1 MiB are skipped.
93
+ - An App Router route with no recognized method exports is treated as unknown rather than automatically flagged.
94
+ - Dynamic routes are matched structurally; dynamic segment values are not type-checked.
95
+
96
+ If your application uses API wrappers or a separate server, a future version could support user-configured patterns, OpenAPI integration and an AST parser.
97
+
98
+ ## Develop
99
+
100
+ ```bash
101
+ npm test
102
+ npm run audit:example # intentionally exits 1: demo has two errors
103
+ npm run pack:check
104
+ ```
105
+
106
+ ## Publish
107
+
108
+ 1. Check name availability: `npm view routecall-audit version` (if taken, change `name` and references in your package).
109
+ 2. Create an npmjs.com account and enable 2FA.
110
+ 3. Run `npm login` then `npm whoami`.
111
+ 4. Run `npm test` and `npm pack --dry-run`.
112
+ 5. Run `npm publish --access public` for a public package. Do this yourself from your machine. New npm accounts/packages require appropriate publishing authentication.
113
+ 6. For later changes, run `npm version patch`, test and publish again. npm will not let you overwrite an existing published version.
114
+
115
+ Security: avoid committing npm tokens into your GitHub repo. For future CI publishing, use npm's trusted publishing (OIDC).
116
+
117
+ ## Contributing
118
+
119
+ Issues and pull requests are welcome. Provide a tiny example project reproducing the bug. Do not upload real `.env` files or credentials.
120
+
121
+ ## License
122
+
123
+ MIT
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { scanProject } from '../src/index.js';
6
+
7
+ const args = process.argv.slice(2);
8
+ const pkgPath = new URL('../package.json', import.meta.url);
9
+ const version = JSON.parse(fs.readFileSync(fileURLToPath(pkgPath), 'utf8')).version;
10
+ const usage = `routecall-audit v${version}
11
+
12
+ Usage: routecall-audit [project-dir] [options]
13
+
14
+ Options:
15
+ --json Print JSON report (good for CI integration)
16
+ --report-unused List API routes with no detected local callers
17
+ --fail-on-unused Fail when unused routes exist (also reports them)
18
+ --help, -h Show help
19
+ --version, -v Show version
20
+
21
+ Exit codes: 0 = no issues, 1 = audit issues, 2 = invalid usage / runtime error.
22
+
23
+ Notes: only local /api fetch(...) and axios.get/post/etc. calls are inspected.
24
+ This is static analysis, not a guarantee of runtime API correctness.`;
25
+
26
+ function cli() {
27
+ if (args.includes('--help') || args.includes('-h')) {
28
+ console.log(usage);
29
+ return 0;
30
+ }
31
+ if (args.includes('--version') || args.includes('-v')) {
32
+ console.log(version);
33
+ return 0;
34
+ }
35
+ const flags = new Set(['--json', '--report-unused', '--fail-on-unused']);
36
+ const positionals = [];
37
+ for (const arg of args) {
38
+ if (arg.startsWith('-') && !flags.has(arg)) {
39
+ console.error(`Unknown option: ${arg}\n\n${usage}`);
40
+ return 2;
41
+ }
42
+ if (!arg.startsWith('-')) positionals.push(arg);
43
+ }
44
+ if (positionals.length > 1) {
45
+ console.error(`Expected at most one project directory.\n\n${usage}`);
46
+ return 2;
47
+ }
48
+ const report = scanProject(positionals[0] ?? process.cwd());
49
+ const wantUnused = args.includes('--report-unused') || args.includes('--fail-on-unused');
50
+ if (args.includes('--json')) {
51
+ console.log(JSON.stringify(report, null, 2));
52
+ } else {
53
+ console.log(`\nroutecall-audit — ${path.resolve(report.root)}`);
54
+ console.log(`${report.stats.filesScanned} source files | ${report.stats.routesFound} API routes | ${report.stats.callsFound} calls`);
55
+ if (!report.issues.length) console.log('PASS: no detectable API route mismatches.');
56
+ for (const issue of report.issues) {
57
+ console.log(`FAIL ${issue.code} ${issue.file}:${issue.line}`);
58
+ console.log(` ${issue.message}`);
59
+ }
60
+ if (wantUnused && report.unusedRoutes.length) {
61
+ console.log('\nUnused local API routes (these might be called externally):');
62
+ for (const route of report.unusedRoutes) console.log(` ${route.path} (${route.file})`);
63
+ }
64
+ if (report.skippedCalls) {
65
+ console.log(`Skipped ${report.skippedCalls} calls that could not be checked statically.`);
66
+ }
67
+ console.log('');
68
+ }
69
+ return (report.issues.length || (args.includes('--fail-on-unused') && report.unusedRoutes.length)) ? 1 : 0;
70
+ }
71
+
72
+ try {
73
+ process.exitCode = cli();
74
+ } catch (error) {
75
+ console.error(`routecall-audit: ${error.message}`);
76
+ process.exitCode = 2;
77
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "routecall-audit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Offline static audit of Next.js API route handlers against frontend fetch and Axios calls",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "bin": {
11
+ "routecall-audit": "./bin/routecall-audit.js"
12
+ },
13
+ "main": "./src/index.js",
14
+ "types": "./src/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./src/index.d.ts",
18
+ "import": "./src/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "bin/",
23
+ "src/",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "scripts": {
28
+ "test": "node --test",
29
+ "audit:example": "node bin/routecall-audit.js examples/next-app",
30
+ "audit:example:json": "node bin/routecall-audit.js examples/next-app --json",
31
+ "pack:check": "npm pack --dry-run"
32
+ },
33
+ "keywords": [
34
+ "nextjs",
35
+ "api",
36
+ "static-analysis",
37
+ "routes",
38
+ "fetch",
39
+ "axios",
40
+ "cli",
41
+ "ci",
42
+ "developer-tools"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
2
+ export type Route = {
3
+ path: string;
4
+ file: string;
5
+ methods: string[];
6
+ router: 'app' | 'pages';
7
+ };
8
+ export type ApiCall = {
9
+ method: HttpMethod;
10
+ url: string;
11
+ file: string;
12
+ line: number;
13
+ client: 'fetch' | 'axios';
14
+ };
15
+ export type AuditIssue = ApiCall & {
16
+ code: 'MISSING_ROUTE' | 'METHOD_MISMATCH';
17
+ message: string;
18
+ routeFile?: string;
19
+ };
20
+ export type AuditReport = {
21
+ root: string;
22
+ routes: Route[];
23
+ calls: ApiCall[];
24
+ issues: AuditIssue[];
25
+ unusedRoutes: Route[];
26
+ skippedCalls: number;
27
+ stats: {
28
+ filesScanned: number;
29
+ routesFound: number;
30
+ callsFound: number;
31
+ issuesFound: number;
32
+ unusedRoutes: number;
33
+ skippedCalls: number;
34
+ };
35
+ };
36
+ /** Run a conservative, offline audit of local /api fetch and axios calls against Next.js API routes. */
37
+ export declare function scanProject(root?: string): AuditReport;
package/src/index.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * routecall-audit: a conservative, offline checker for Next.js API routes.
3
+ * It only reports confidently identified local API calls. No code executes.
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ const SOURCE_EXT = /\.(?:[cm]?[jt]sx?)$/i;
9
+ const NEXT_ROUTE_EXT = /\.(?:[cm]?[jt]sx?)$/i;
10
+ const IGNORED_DIRS = new Set([
11
+ '.git', '.next', '.nuxt', '.output', '.turbo', '.vercel', 'node_modules',
12
+ 'dist', 'build', 'coverage', 'out', 'test', 'tests', '__tests__',
13
+ 'e2e', 'cypress', 'playwright', '.storybook'
14
+ ]);
15
+ const METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
16
+ const MAX_SOURCE_BYTES = 1024 * 1024;
17
+
18
+ function walk(root) {
19
+ const found = [];
20
+ function visit(current) {
21
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
22
+ if (entry.isSymbolicLink()) continue;
23
+ const full = path.join(current, entry.name);
24
+ if (entry.isDirectory()) {
25
+ if (!IGNORED_DIRS.has(entry.name)) visit(full);
26
+ } else if (entry.isFile() && SOURCE_EXT.test(entry.name) &&
27
+ !entry.name.endsWith('.d.ts') && fs.statSync(full).size <= MAX_SOURCE_BYTES) {
28
+ found.push(full);
29
+ }
30
+ }
31
+ }
32
+ visit(root);
33
+ return found.sort();
34
+ }
35
+
36
+ function toPosix(file) {
37
+ return file.split(path.sep).join('/');
38
+ }
39
+
40
+ function routeSegments(relativeFile) {
41
+ const parts = toPosix(relativeFile).split('/');
42
+ let start = -1;
43
+ let mode = '';
44
+ if (parts[0] === 'src' && (parts[1] === 'app' || parts[1] === 'pages')) {
45
+ start = 2;
46
+ mode = parts[1];
47
+ } else if (parts[0] === 'app' || parts[0] === 'pages') {
48
+ start = 1;
49
+ mode = parts[0];
50
+ }
51
+ if (start === -1) return null;
52
+
53
+ const filename = parts.at(-1);
54
+ let segments;
55
+ if (mode === 'app' && /^route\.[cm]?[jt]sx?$/i.test(filename)) {
56
+ segments = parts.slice(start, -1).filter((seg) => !/^\(.*\)$/.test(seg) && !seg.startsWith('@'));
57
+ } else if (mode === 'pages' && parts[start] === 'api' && NEXT_ROUTE_EXT.test(filename) &&
58
+ !/^_/.test(filename)) {
59
+ segments = parts.slice(start);
60
+ segments[segments.length - 1] = filename.replace(NEXT_ROUTE_EXT, '');
61
+ if (segments.at(-1) === 'index') segments.pop();
62
+ } else {
63
+ return null;
64
+ }
65
+ if (segments[0] !== 'api') return null;
66
+ return { mode, routePath: '/' + segments.join('/') };
67
+ }
68
+
69
+ function appRouteMethods(source) {
70
+ const methods = new Set();
71
+ // App Router: export function GET(), export async function POST(),
72
+ // export const PUT = async ..., export { GET, POST }.
73
+ const direct = /\bexport\s+(?:(?:default|declare)\s+)?(?:async\s+)?(?:function|const|let)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;
74
+ for (const match of source.matchAll(direct)) methods.add(match[1]);
75
+ const namedExports = /\bexport\s*\{([^}]+)\}/g;
76
+ for (const match of source.matchAll(namedExports)) {
77
+ for (const entry of match[1].split(',')) {
78
+ const exportedName = entry.trim().split(/\s+as\s+/i).at(-1)?.trim();
79
+ if (METHODS.has(exportedName)) methods.add(exportedName);
80
+ }
81
+ }
82
+ // Next.js supplies HEAD for GET and auto-implements OPTIONS.
83
+ if (methods.has('GET')) methods.add('HEAD');
84
+ if (methods.size) methods.add('OPTIONS');
85
+ return [...methods].sort();
86
+ }
87
+
88
+ function discoverRoutes(files, root) {
89
+ const routes = [];
90
+ for (const file of files) {
91
+ const relative = toPosix(path.relative(root, file));
92
+ const info = routeSegments(relative);
93
+ if (!info) continue;
94
+ const source = fs.readFileSync(file, 'utf8');
95
+ const methods = info.mode === 'pages' ? ['*'] : appRouteMethods(source);
96
+ routes.push({ path: info.routePath, file: relative, methods, router: info.mode });
97
+ }
98
+ return routes.sort((a, b) => a.path.localeCompare(b.path) || a.file.localeCompare(b.file));
99
+ }
100
+
101
+ /**
102
+ * Extract a balanced JS invocation, ignoring parentheses inside quoted strings.
103
+ * Deliberately conservative: an incomplete call is skipped.
104
+ */
105
+ function invocationBody(text, openIndex) {
106
+ let depth = 0;
107
+ let quote = null;
108
+ let escaped = false;
109
+ for (let i = openIndex; i < text.length; i++) {
110
+ const char = text[i];
111
+ if (quote !== null) {
112
+ if (escaped) escaped = false;
113
+ else if (char === '\\') escaped = true;
114
+ else if (char === quote) quote = null;
115
+ continue;
116
+ }
117
+ if (char === '"' || char === "'" || char === '`') {
118
+ quote = char;
119
+ } else if (char === '(') {
120
+ depth++;
121
+ } else if (char === ')') {
122
+ depth--;
123
+ if (depth === 0) return text.slice(openIndex + 1, i);
124
+ }
125
+ }
126
+ return null;
127
+ }
128
+
129
+ function literalFirstArgument(body) {
130
+ const trimmed = body.trimStart();
131
+ const quote = trimmed[0];
132
+ if (quote !== '"' && quote !== "'" && quote !== '`') return null;
133
+ let escaped = false;
134
+ for (let i = 1; i < trimmed.length; i++) {
135
+ const ch = trimmed[i];
136
+ if (escaped) { escaped = false; continue; }
137
+ if (ch === '\\') { escaped = true; continue; }
138
+ if (ch === quote) {
139
+ const rest = trimmed.slice(i + 1).trimStart();
140
+ if (rest && !rest.startsWith(',')) return null;
141
+ return { rawUrl: trimmed.slice(1, i), rest, quote };
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ function normalizeCallPath(rawUrl, quote) {
148
+ let pathname = rawUrl;
149
+ if (quote === '`') {
150
+ // Accept one interpolated expression per entire path segment.
151
+ pathname = pathname.replace(/\$\{[^{}]*\}/g, '__dynamic__');
152
+ if (pathname.includes('${')) return null;
153
+ }
154
+ if (!pathname.startsWith('/api') || (pathname.length > 4 && !['/', '?', '#'].includes(pathname[4]))) return null;
155
+ pathname = pathname.split(/[?#]/, 1)[0].replace(/\/+$/, '') || '/';
156
+ if (!pathname.split('/').every((segment) => !segment.includes('__dynamic__') || segment === '__dynamic__')) return null;
157
+ if (pathname.includes('\\')) return null;
158
+ return pathname;
159
+ }
160
+
161
+ function fetchMethod(rest) {
162
+ if (!rest) return 'GET';
163
+ const match = rest.match(/\bmethod\s*:\s*(['"`])([A-Za-z]+)\1/);
164
+ if (match) return match[2].toUpperCase();
165
+ // If the HTTP method is computed we must not guess GET.
166
+ if (/\bmethod\b/.test(rest)) return null;
167
+ return 'GET';
168
+ }
169
+
170
+ function sourceLine(text, offset) {
171
+ return text.slice(0, offset).split('\n').length;
172
+ }
173
+
174
+ function collectCalls(files, root) {
175
+ const calls = [];
176
+ let skippedCalls = 0;
177
+ for (const file of files) {
178
+ const relative = toPosix(path.relative(root, file));
179
+ const source = fs.readFileSync(file, 'utf8');
180
+ // axios and global fetch only. No user-controlled modules execute.
181
+ const pattern = /\b(fetch|axios\s*\.\s*(?:get|post|put|patch|delete|head|options))\s*\(/g;
182
+ for (const match of source.matchAll(pattern)) {
183
+ const open = match.index + match[0].length - 1;
184
+ const body = invocationBody(source, open);
185
+ if (body === null) { skippedCalls++; continue; }
186
+ const arg = literalFirstArgument(body);
187
+ if (!arg) { skippedCalls++; continue; }
188
+ const url = normalizeCallPath(arg.rawUrl, arg.quote);
189
+ if (!url) { skippedCalls++; continue; }
190
+ const method = match[1].startsWith('axios')
191
+ ? match[1].split('.').at(-1).trim().toUpperCase()
192
+ : fetchMethod(arg.rest);
193
+ if (!method || !METHODS.has(method)) { skippedCalls++; continue; }
194
+ calls.push({ method, url, file: relative, line: sourceLine(source, match.index),
195
+ client: match[1].startsWith('axios') ? 'axios' : 'fetch' });
196
+ }
197
+ }
198
+ return { calls, skippedCalls };
199
+ }
200
+
201
+ function matchesRoute(patternPath, actualPath) {
202
+ const expected = patternPath.split('/').filter(Boolean);
203
+ const actual = actualPath.split('/').filter(Boolean);
204
+ function matches(i, j) {
205
+ if (i === expected.length) return j === actual.length;
206
+ const segment = expected[i];
207
+ if (/^\[\[\.\.\.[^\]]+\]\]$/.test(segment)) {
208
+ if (i === expected.length - 1) return true;
209
+ for (let k = j; k <= actual.length; k++) if (matches(i + 1, k)) return true;
210
+ return false;
211
+ }
212
+ if (/^\[\.\.\.[^\]]+\]$/.test(segment)) {
213
+ if (i === expected.length - 1) return j < actual.length;
214
+ for (let k = j + 1; k <= actual.length; k++) if (matches(i + 1, k)) return true;
215
+ return false;
216
+ }
217
+ if (j >= actual.length) return false;
218
+ if (segment === actual[j] || /^\[[^\]]+\]$/.test(segment)) return matches(i + 1, j + 1);
219
+ return false;
220
+ }
221
+ return matches(0, 0);
222
+ }
223
+
224
+ function specificity(patternPath) {
225
+ return patternPath.split('/').filter(Boolean).reduce((score, seg) => {
226
+ if (/^\[\[\.\.\./.test(seg)) return score + 1;
227
+ if (/^\[\.\.\./.test(seg)) return score + 2;
228
+ if (/^\[/.test(seg)) return score + 10;
229
+ return score + 100;
230
+ }, 0);
231
+ }
232
+
233
+ /**
234
+ * Scan a Next.js project without installing its dependencies or running its code.
235
+ * @param {string} root project folder (defaults to current working directory)
236
+ * @returns {AuditReport} routes, calls, issues, unusedRoutes, stats
237
+ */
238
+ export function scanProject(root = process.cwd()) {
239
+ const absolute = path.resolve(root);
240
+ if (!fs.existsSync(absolute) || !fs.statSync(absolute).isDirectory()) {
241
+ throw new Error(`Project directory does not exist: ${absolute}`);
242
+ }
243
+ const files = walk(absolute);
244
+ const routes = discoverRoutes(files, absolute);
245
+ const { calls, skippedCalls } = collectCalls(files, absolute);
246
+ const issues = [];
247
+ const used = new Set();
248
+ for (const call of calls) {
249
+ const matches = routes.filter((route) => matchesRoute(route.path, call.url))
250
+ .sort((a, b) => specificity(b.path) - specificity(a.path));
251
+ const best = matches[0];
252
+ if (!best) {
253
+ issues.push({ code: 'MISSING_ROUTE', ...call,
254
+ message: `${call.method} ${call.url} has no matching local Next.js API route` });
255
+ continue;
256
+ }
257
+ used.add(best.file);
258
+ // An app route with no recognizable methods is skipped rather than assumed broken.
259
+ if (best.methods.length && !best.methods.includes('*') && !best.methods.includes(call.method)) {
260
+ issues.push({ code: 'METHOD_MISMATCH', ...call, routeFile: best.file,
261
+ message: `${call.method} ${call.url} is not handled by ${best.file} (${best.methods.join(', ')})` });
262
+ }
263
+ }
264
+ const unusedRoutes = routes.filter((route) => !used.has(route.file));
265
+ return {
266
+ root: absolute, routes, calls, issues, unusedRoutes, skippedCalls,
267
+ stats: { filesScanned: files.length, routesFound: routes.length,
268
+ callsFound: calls.length, issuesFound: issues.length,
269
+ unusedRoutes: unusedRoutes.length, skippedCalls }
270
+ };
271
+ }