@vibecheckai/cli 3.2.5 → 3.3.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.
Files changed (197) hide show
  1. package/bin/.generated +25 -25
  2. package/bin/dev/run-v2-torture.js +30 -30
  3. package/bin/registry.js +192 -5
  4. package/bin/runners/lib/__tests__/entitlements-v2.test.js +295 -295
  5. package/bin/runners/lib/agent-firewall/change-packet/builder.js +280 -6
  6. package/bin/runners/lib/agent-firewall/critic/index.js +151 -0
  7. package/bin/runners/lib/agent-firewall/critic/judge.js +432 -0
  8. package/bin/runners/lib/agent-firewall/critic/prompts.js +305 -0
  9. package/bin/runners/lib/agent-firewall/lawbook/distributor.js +465 -0
  10. package/bin/runners/lib/agent-firewall/lawbook/evaluator.js +604 -0
  11. package/bin/runners/lib/agent-firewall/lawbook/index.js +304 -0
  12. package/bin/runners/lib/agent-firewall/lawbook/registry.js +514 -0
  13. package/bin/runners/lib/agent-firewall/lawbook/schema.js +420 -0
  14. package/bin/runners/lib/agent-firewall/logger.js +141 -0
  15. package/bin/runners/lib/agent-firewall/policy/loader.js +312 -4
  16. package/bin/runners/lib/agent-firewall/policy/rules/ghost-env.js +113 -1
  17. package/bin/runners/lib/agent-firewall/policy/rules/ghost-route.js +133 -6
  18. package/bin/runners/lib/agent-firewall/proposal/extractor.js +394 -0
  19. package/bin/runners/lib/agent-firewall/proposal/index.js +212 -0
  20. package/bin/runners/lib/agent-firewall/proposal/schema.js +251 -0
  21. package/bin/runners/lib/agent-firewall/proposal/validator.js +386 -0
  22. package/bin/runners/lib/agent-firewall/reality/index.js +332 -0
  23. package/bin/runners/lib/agent-firewall/reality/state.js +625 -0
  24. package/bin/runners/lib/agent-firewall/reality/watcher.js +322 -0
  25. package/bin/runners/lib/agent-firewall/risk/index.js +173 -0
  26. package/bin/runners/lib/agent-firewall/risk/scorer.js +328 -0
  27. package/bin/runners/lib/agent-firewall/risk/thresholds.js +321 -0
  28. package/bin/runners/lib/agent-firewall/risk/vectors.js +421 -0
  29. package/bin/runners/lib/agent-firewall/simulator/diff-simulator.js +472 -0
  30. package/bin/runners/lib/agent-firewall/simulator/import-resolver.js +346 -0
  31. package/bin/runners/lib/agent-firewall/simulator/index.js +181 -0
  32. package/bin/runners/lib/agent-firewall/simulator/route-validator.js +380 -0
  33. package/bin/runners/lib/agent-firewall/time-machine/incident-correlator.js +661 -0
  34. package/bin/runners/lib/agent-firewall/time-machine/index.js +267 -0
  35. package/bin/runners/lib/agent-firewall/time-machine/replay-engine.js +436 -0
  36. package/bin/runners/lib/agent-firewall/time-machine/state-reconstructor.js +490 -0
  37. package/bin/runners/lib/agent-firewall/time-machine/timeline-builder.js +530 -0
  38. package/bin/runners/lib/analyzers.js +81 -18
  39. package/bin/runners/lib/api-client.js +269 -0
  40. package/bin/runners/lib/auth-truth.js +193 -193
  41. package/bin/runners/lib/authority-badge.js +425 -0
  42. package/bin/runners/lib/backup.js +62 -62
  43. package/bin/runners/lib/billing.js +107 -107
  44. package/bin/runners/lib/claims.js +118 -118
  45. package/bin/runners/lib/cli-output.js +7 -1
  46. package/bin/runners/lib/cli-ui.js +540 -540
  47. package/bin/runners/lib/contracts/auth-contract.js +202 -202
  48. package/bin/runners/lib/contracts/env-contract.js +181 -181
  49. package/bin/runners/lib/contracts/external-contract.js +206 -206
  50. package/bin/runners/lib/contracts/guard.js +168 -168
  51. package/bin/runners/lib/contracts/index.js +89 -89
  52. package/bin/runners/lib/contracts/plan-validator.js +311 -311
  53. package/bin/runners/lib/contracts/route-contract.js +199 -199
  54. package/bin/runners/lib/contracts.js +804 -804
  55. package/bin/runners/lib/detect.js +89 -89
  56. package/bin/runners/lib/doctor/autofix.js +254 -254
  57. package/bin/runners/lib/doctor/index.js +37 -37
  58. package/bin/runners/lib/doctor/modules/dependencies.js +325 -325
  59. package/bin/runners/lib/doctor/modules/index.js +46 -46
  60. package/bin/runners/lib/doctor/modules/network.js +250 -250
  61. package/bin/runners/lib/doctor/modules/project.js +312 -312
  62. package/bin/runners/lib/doctor/modules/runtime.js +224 -224
  63. package/bin/runners/lib/doctor/modules/security.js +348 -348
  64. package/bin/runners/lib/doctor/modules/system.js +213 -213
  65. package/bin/runners/lib/doctor/modules/vibecheck.js +394 -394
  66. package/bin/runners/lib/doctor/reporter.js +262 -262
  67. package/bin/runners/lib/doctor/service.js +262 -262
  68. package/bin/runners/lib/doctor/types.js +113 -113
  69. package/bin/runners/lib/doctor/ui.js +263 -263
  70. package/bin/runners/lib/doctor-v2.js +608 -608
  71. package/bin/runners/lib/drift.js +425 -425
  72. package/bin/runners/lib/enforcement.js +72 -72
  73. package/bin/runners/lib/enterprise-detect.js +603 -603
  74. package/bin/runners/lib/enterprise-init.js +942 -942
  75. package/bin/runners/lib/env-resolver.js +417 -417
  76. package/bin/runners/lib/env-template.js +66 -66
  77. package/bin/runners/lib/env.js +189 -189
  78. package/bin/runners/lib/error-handler.js +16 -9
  79. package/bin/runners/lib/exit-codes.js +275 -0
  80. package/bin/runners/lib/extractors/client-calls.js +990 -990
  81. package/bin/runners/lib/extractors/fastify-route-dump.js +573 -573
  82. package/bin/runners/lib/extractors/fastify-routes.js +426 -426
  83. package/bin/runners/lib/extractors/index.js +363 -363
  84. package/bin/runners/lib/extractors/next-routes.js +524 -524
  85. package/bin/runners/lib/extractors/proof-graph.js +431 -431
  86. package/bin/runners/lib/extractors/route-matcher.js +451 -451
  87. package/bin/runners/lib/extractors/truthpack-v2.js +377 -377
  88. package/bin/runners/lib/extractors/ui-bindings.js +547 -547
  89. package/bin/runners/lib/findings-schema.js +281 -281
  90. package/bin/runners/lib/firewall-prompt.js +50 -50
  91. package/bin/runners/lib/global-flags.js +37 -0
  92. package/bin/runners/lib/graph/graph-builder.js +265 -265
  93. package/bin/runners/lib/graph/html-renderer.js +413 -413
  94. package/bin/runners/lib/graph/index.js +32 -32
  95. package/bin/runners/lib/graph/runtime-collector.js +215 -215
  96. package/bin/runners/lib/graph/static-extractor.js +518 -518
  97. package/bin/runners/lib/help-formatter.js +413 -0
  98. package/bin/runners/lib/html-report.js +650 -650
  99. package/bin/runners/lib/llm.js +75 -75
  100. package/bin/runners/lib/logger.js +38 -0
  101. package/bin/runners/lib/meter.js +61 -61
  102. package/bin/runners/lib/missions/evidence.js +126 -126
  103. package/bin/runners/lib/patch.js +40 -40
  104. package/bin/runners/lib/permissions/auth-model.js +213 -213
  105. package/bin/runners/lib/permissions/idor-prover.js +205 -205
  106. package/bin/runners/lib/permissions/index.js +45 -45
  107. package/bin/runners/lib/permissions/matrix-builder.js +198 -198
  108. package/bin/runners/lib/pkgjson.js +28 -28
  109. package/bin/runners/lib/policy.js +295 -295
  110. package/bin/runners/lib/preflight.js +142 -142
  111. package/bin/runners/lib/reality/correlation-detectors.js +359 -359
  112. package/bin/runners/lib/reality/index.js +318 -318
  113. package/bin/runners/lib/reality/request-hashing.js +416 -416
  114. package/bin/runners/lib/reality/request-mapper.js +453 -453
  115. package/bin/runners/lib/reality/safety-rails.js +463 -463
  116. package/bin/runners/lib/reality/semantic-snapshot.js +408 -408
  117. package/bin/runners/lib/reality/toast-detector.js +393 -393
  118. package/bin/runners/lib/reality-findings.js +84 -84
  119. package/bin/runners/lib/receipts.js +179 -179
  120. package/bin/runners/lib/redact.js +29 -29
  121. package/bin/runners/lib/replay/capsule-manager.js +154 -154
  122. package/bin/runners/lib/replay/index.js +263 -263
  123. package/bin/runners/lib/replay/player.js +348 -348
  124. package/bin/runners/lib/replay/recorder.js +331 -331
  125. package/bin/runners/lib/report.js +135 -135
  126. package/bin/runners/lib/route-detection.js +1140 -1140
  127. package/bin/runners/lib/sandbox/index.js +59 -59
  128. package/bin/runners/lib/sandbox/proof-chain.js +399 -399
  129. package/bin/runners/lib/sandbox/sandbox-runner.js +205 -205
  130. package/bin/runners/lib/sandbox/worktree.js +174 -174
  131. package/bin/runners/lib/schema-validator.js +350 -350
  132. package/bin/runners/lib/schemas/contracts.schema.json +160 -160
  133. package/bin/runners/lib/schemas/finding.schema.json +100 -100
  134. package/bin/runners/lib/schemas/mission-pack.schema.json +206 -206
  135. package/bin/runners/lib/schemas/proof-graph.schema.json +176 -176
  136. package/bin/runners/lib/schemas/reality-report.schema.json +162 -162
  137. package/bin/runners/lib/schemas/share-pack.schema.json +180 -180
  138. package/bin/runners/lib/schemas/ship-report.schema.json +117 -117
  139. package/bin/runners/lib/schemas/truthpack-v2.schema.json +303 -303
  140. package/bin/runners/lib/schemas/validator.js +438 -438
  141. package/bin/runners/lib/score-history.js +282 -282
  142. package/bin/runners/lib/share-pack.js +239 -239
  143. package/bin/runners/lib/snippets.js +67 -67
  144. package/bin/runners/lib/unified-cli-output.js +604 -0
  145. package/bin/runners/lib/upsell.js +658 -510
  146. package/bin/runners/lib/usage.js +153 -153
  147. package/bin/runners/lib/validate-patch.js +156 -156
  148. package/bin/runners/lib/verdict-engine.js +628 -628
  149. package/bin/runners/reality/engine.js +917 -917
  150. package/bin/runners/reality/flows.js +122 -122
  151. package/bin/runners/reality/report.js +378 -378
  152. package/bin/runners/reality/session.js +193 -193
  153. package/bin/runners/runAgent.d.ts +5 -0
  154. package/bin/runners/runApprove.js +1200 -0
  155. package/bin/runners/runAuth.js +324 -95
  156. package/bin/runners/runCheckpoint.js +39 -21
  157. package/bin/runners/runClassify.js +859 -0
  158. package/bin/runners/runContext.js +136 -24
  159. package/bin/runners/runDoctor.js +108 -68
  160. package/bin/runners/runFirewall.d.ts +5 -0
  161. package/bin/runners/runFirewallHook.d.ts +5 -0
  162. package/bin/runners/runFix.js +6 -5
  163. package/bin/runners/runGuard.js +262 -168
  164. package/bin/runners/runInit.js +3 -2
  165. package/bin/runners/runMcp.js +130 -52
  166. package/bin/runners/runPolish.js +43 -20
  167. package/bin/runners/runProve.js +1 -2
  168. package/bin/runners/runReport.js +3 -2
  169. package/bin/runners/runScan.js +145 -44
  170. package/bin/runners/runShip.js +3 -4
  171. package/bin/runners/runTruth.d.ts +5 -0
  172. package/bin/runners/runValidate.js +19 -2
  173. package/bin/runners/runWatch.js +104 -53
  174. package/bin/vibecheck.js +106 -19
  175. package/mcp-server/HARDENING_SUMMARY.md +299 -0
  176. package/mcp-server/agent-firewall-interceptor.js +367 -31
  177. package/mcp-server/authority-tools.js +569 -0
  178. package/mcp-server/conductor/conflict-resolver.js +588 -0
  179. package/mcp-server/conductor/execution-planner.js +544 -0
  180. package/mcp-server/conductor/index.js +377 -0
  181. package/mcp-server/conductor/lock-manager.js +615 -0
  182. package/mcp-server/conductor/request-queue.js +550 -0
  183. package/mcp-server/conductor/session-manager.js +500 -0
  184. package/mcp-server/conductor/tools.js +510 -0
  185. package/mcp-server/index.js +1199 -208
  186. package/mcp-server/lib/api-client.cjs +305 -0
  187. package/mcp-server/lib/logger.cjs +30 -0
  188. package/mcp-server/logger.js +173 -0
  189. package/mcp-server/package.json +2 -2
  190. package/mcp-server/premium-tools.js +2 -2
  191. package/mcp-server/tier-auth.js +351 -136
  192. package/mcp-server/tools/index.js +72 -72
  193. package/mcp-server/truth-firewall-tools.js +145 -15
  194. package/mcp-server/vibecheck-tools.js +2 -2
  195. package/package.json +2 -3
  196. package/mcp-server/index.old.js +0 -4137
  197. package/mcp-server/package-lock.json +0 -165
@@ -1,524 +1,524 @@
1
- /**
2
- * Next.js Route Extractor v2
3
- *
4
- * Spec-compliant extraction for App Router + Pages Router API routes.
5
- * Handles dynamic segments, route groups, catch-alls, and method detection.
6
- *
7
- * Canonical path format:
8
- * - Static: /api/billing/portal
9
- * - Params: /api/users/{id}
10
- * - Catch-all: /api/files/{*path}
11
- * - Optional catch-all: /api/blog/{*slug?}
12
- */
13
-
14
- "use strict";
15
-
16
- const fs = require("fs");
17
- const path = require("path");
18
- const fg = require("fast-glob");
19
- const crypto = require("crypto");
20
-
21
- const NEXT_HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"];
22
-
23
- /**
24
- * Detect Next.js mode and roots
25
- */
26
- function detectNextMode(projectRoot) {
27
- const result = {
28
- present: false,
29
- router: "unknown",
30
- appDir: null,
31
- pagesDir: null,
32
- middlewareFile: null,
33
- basePath: "",
34
- trailingSlash: false,
35
- rewrites: [],
36
- };
37
-
38
- // Check for Next.js presence
39
- const pkgPath = path.join(projectRoot, "package.json");
40
- if (fs.existsSync(pkgPath)) {
41
- try {
42
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
43
- if (pkg.dependencies?.next || pkg.devDependencies?.next) {
44
- result.present = true;
45
- }
46
- } catch {}
47
- }
48
-
49
- // Check for next.config
50
- const configFiles = ["next.config.js", "next.config.mjs", "next.config.ts"];
51
- for (const configFile of configFiles) {
52
- const configPath = path.join(projectRoot, configFile);
53
- if (fs.existsSync(configPath)) {
54
- result.present = true;
55
- parseNextConfig(configPath, result);
56
- break;
57
- }
58
- }
59
-
60
- // Check for app/ and pages/ directories
61
- const appDir = path.join(projectRoot, "app");
62
- const srcAppDir = path.join(projectRoot, "src", "app");
63
- const pagesDir = path.join(projectRoot, "pages");
64
- const srcPagesDir = path.join(projectRoot, "src", "pages");
65
-
66
- if (fs.existsSync(appDir)) {
67
- result.appDir = appDir;
68
- result.present = true;
69
- } else if (fs.existsSync(srcAppDir)) {
70
- result.appDir = srcAppDir;
71
- result.present = true;
72
- }
73
-
74
- if (fs.existsSync(pagesDir)) {
75
- result.pagesDir = pagesDir;
76
- result.present = true;
77
- } else if (fs.existsSync(srcPagesDir)) {
78
- result.pagesDir = srcPagesDir;
79
- result.present = true;
80
- }
81
-
82
- // Determine router mode
83
- if (result.appDir && result.pagesDir) {
84
- result.router = "mixed";
85
- } else if (result.appDir) {
86
- result.router = "app";
87
- } else if (result.pagesDir) {
88
- result.router = "pages";
89
- }
90
-
91
- // Find middleware
92
- const middlewareLocations = [
93
- path.join(projectRoot, "middleware.ts"),
94
- path.join(projectRoot, "middleware.js"),
95
- path.join(projectRoot, "src", "middleware.ts"),
96
- path.join(projectRoot, "src", "middleware.js"),
97
- ];
98
- for (const loc of middlewareLocations) {
99
- if (fs.existsSync(loc)) {
100
- result.middlewareFile = loc;
101
- break;
102
- }
103
- }
104
-
105
- return result;
106
- }
107
-
108
- /**
109
- * Parse next.config for basePath, trailingSlash, rewrites
110
- */
111
- function parseNextConfig(configPath, result) {
112
- try {
113
- const content = fs.readFileSync(configPath, "utf8");
114
-
115
- // Extract basePath
116
- const basePathMatch = content.match(/basePath\s*:\s*['"`]([^'"`]+)['"`]/);
117
- if (basePathMatch) {
118
- result.basePath = basePathMatch[1];
119
- }
120
-
121
- // Extract trailingSlash
122
- if (/trailingSlash\s*:\s*true/.test(content)) {
123
- result.trailingSlash = true;
124
- }
125
-
126
- // Extract rewrites (basic pattern matching)
127
- const rewriteMatches = content.matchAll(/source\s*:\s*['"`]([^'"`]+)['"`][\s\S]*?destination\s*:\s*['"`]([^'"`]+)['"`]/g);
128
- for (const match of rewriteMatches) {
129
- result.rewrites.push({
130
- source: match[1],
131
- destination: match[2],
132
- isExternal: match[2].startsWith("http"),
133
- });
134
- }
135
- } catch {}
136
- }
137
-
138
- /**
139
- * Extract App Router API routes from app/api directory
140
- */
141
- function extractAppRouterRoutes(appDir, projectRoot) {
142
- const routes = [];
143
-
144
- if (!appDir || !fs.existsSync(appDir)) return routes;
145
-
146
- // Find all route handlers
147
- const pattern = path.join(appDir, "api", "**", "route.{js,jsx,ts,tsx}").replace(/\\/g, "/");
148
- const files = fg.sync(pattern, { onlyFiles: true, absolute: true });
149
-
150
- for (const file of files) {
151
- const route = extractAppRouteHandler(file, appDir, projectRoot);
152
- if (route) {
153
- routes.push(route);
154
- }
155
- }
156
-
157
- return routes;
158
- }
159
-
160
- /**
161
- * Extract a single App Router route handler
162
- */
163
- function extractAppRouteHandler(file, appDir, projectRoot) {
164
- const content = fs.readFileSync(file, "utf8");
165
- const relPath = path.relative(appDir, file).replace(/\\/g, "/");
166
-
167
- // Build canonical path from file path
168
- // Strip api/ prefix and route.* suffix
169
- let urlPath = relPath
170
- .replace(/^api\//, "/api/")
171
- .replace(/\/route\.(js|jsx|ts|tsx)$/, "")
172
- .replace(/^\/api/, "/api"); // Ensure /api prefix
173
-
174
- // Handle special segments
175
- urlPath = convertNextPathToCanonical(urlPath);
176
-
177
- // Extract HTTP methods from exports
178
- const methods = extractExportedMethods(content);
179
- const confidence = methods.length > 0 && !methods.includes("UNKNOWN") ? "high" : "low";
180
-
181
- // Build evidence
182
- const evidence = [];
183
- for (const method of methods) {
184
- const methodMatch = content.match(new RegExp(`export\\s+(async\\s+)?function\\s+${method}|export\\s+const\\s+${method}\\s*=`, "m"));
185
- if (methodMatch) {
186
- const lineNum = content.substring(0, methodMatch.index).split("\n").length;
187
- evidence.push({
188
- id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
189
- kind: "file",
190
- reason: `${method} handler export`,
191
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
192
- lines: `${lineNum}-${lineNum + 5}`,
193
- snippetHash: hashSnippet(methodMatch[0]),
194
- });
195
- }
196
- }
197
-
198
- // If no methods found, add generic evidence
199
- if (evidence.length === 0) {
200
- evidence.push({
201
- id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
202
- kind: "file",
203
- reason: "Route handler file",
204
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
205
- lines: "1-10",
206
- });
207
- }
208
-
209
- return {
210
- id: `R_NEXT_APP_${hashPath(urlPath)}`,
211
- kind: "next_route_handler",
212
- methods: methods.length > 0 ? methods : ["UNKNOWN"],
213
- rawPath: relPath,
214
- path: urlPath,
215
- canonicalPath: urlPath,
216
- authRequired: "unknown",
217
- confidence,
218
- handler: {
219
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
220
- export: methods[0] || "handler",
221
- },
222
- evidence,
223
- };
224
- }
225
-
226
- /**
227
- * Extract Pages Router API routes (pages/api/**)
228
- */
229
- function extractPagesRouterRoutes(pagesDir, projectRoot) {
230
- const routes = [];
231
-
232
- if (!pagesDir || !fs.existsSync(pagesDir)) return routes;
233
-
234
- const apiDir = path.join(pagesDir, "api");
235
- if (!fs.existsSync(apiDir)) return routes;
236
-
237
- // Find all API files
238
- const pattern = path.join(apiDir, "**", "*.{js,jsx,ts,tsx}").replace(/\\/g, "/");
239
- const files = fg.sync(pattern, { onlyFiles: true, absolute: true });
240
-
241
- for (const file of files) {
242
- const route = extractPagesApiHandler(file, pagesDir, projectRoot);
243
- if (route) {
244
- routes.push(route);
245
- }
246
- }
247
-
248
- return routes;
249
- }
250
-
251
- /**
252
- * Extract a single Pages API handler
253
- */
254
- function extractPagesApiHandler(file, pagesDir, projectRoot) {
255
- const content = fs.readFileSync(file, "utf8");
256
- const relPath = path.relative(pagesDir, file).replace(/\\/g, "/");
257
-
258
- // Build URL path
259
- let urlPath = "/" + relPath
260
- .replace(/^api\//, "api/")
261
- .replace(/\.(js|jsx|ts|tsx)$/, "")
262
- .replace(/\/index$/, "");
263
-
264
- // Ensure /api prefix
265
- if (!urlPath.startsWith("/api")) {
266
- urlPath = "/api" + urlPath;
267
- }
268
-
269
- // Convert dynamic segments
270
- urlPath = convertNextPathToCanonical(urlPath);
271
-
272
- // Extract methods from req.method checks
273
- const methods = extractReqMethodChecks(content);
274
- const confidence = methods.length > 0 && !methods.includes("UNKNOWN") ? "medium" : "low";
275
-
276
- // Build evidence
277
- const evidence = [{
278
- id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
279
- kind: "file",
280
- reason: "Pages API handler",
281
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
282
- lines: "1-20",
283
- }];
284
-
285
- // Add evidence for method checks
286
- const methodCheckMatch = content.match(/req\.method\s*===?\s*['"`](\w+)['"`]/);
287
- if (methodCheckMatch) {
288
- const lineNum = content.substring(0, methodCheckMatch.index).split("\n").length;
289
- evidence.push({
290
- id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
291
- kind: "file",
292
- reason: "Method check",
293
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
294
- lines: `${lineNum}-${lineNum}`,
295
- snippetHash: hashSnippet(methodCheckMatch[0]),
296
- });
297
- }
298
-
299
- return {
300
- id: `R_NEXT_PAGES_${hashPath(urlPath)}`,
301
- kind: "next_pages_api",
302
- methods: methods.length > 0 ? methods : ["UNKNOWN"],
303
- rawPath: relPath,
304
- path: urlPath,
305
- canonicalPath: urlPath,
306
- authRequired: "unknown",
307
- confidence,
308
- handler: {
309
- file: path.relative(projectRoot, file).replace(/\\/g, "/"),
310
- export: "default",
311
- },
312
- evidence,
313
- };
314
- }
315
-
316
- /**
317
- * Convert Next.js path segments to canonical format
318
- * [id] → {id}
319
- * [...slug] → {*slug}
320
- * [[...slug]] → {*slug?}
321
- * (group) → removed
322
- */
323
- function convertNextPathToCanonical(urlPath) {
324
- return urlPath
325
- // Remove route groups (parentheses)
326
- .replace(/\/\([^)]+\)/g, "")
327
- // Remove parallel routes (@)
328
- .replace(/\/@[^/]+/g, "")
329
- // Optional catch-all [[...slug]]
330
- .replace(/\[\[\.\.\.([^\]]+)\]\]/g, "{*$1?}")
331
- // Catch-all [...slug]
332
- .replace(/\[\.\.\.([^\]]+)\]/g, "{*$1}")
333
- // Dynamic segment [id]
334
- .replace(/\[([^\]]+)\]/g, "{$1}")
335
- // Clean up double slashes
336
- .replace(/\/+/g, "/")
337
- // Remove trailing slash except root
338
- .replace(/(.)\/$/, "$1");
339
- }
340
-
341
- /**
342
- * Extract exported HTTP methods from App Router file
343
- */
344
- function extractExportedMethods(content) {
345
- const methods = [];
346
-
347
- for (const method of NEXT_HTTP_METHODS) {
348
- // export async function GET
349
- // export function GET
350
- // export const GET =
351
- const patterns = [
352
- new RegExp(`export\\s+async\\s+function\\s+${method}\\s*\\(`, "m"),
353
- new RegExp(`export\\s+function\\s+${method}\\s*\\(`, "m"),
354
- new RegExp(`export\\s+const\\s+${method}\\s*=`, "m"),
355
- ];
356
-
357
- for (const pattern of patterns) {
358
- if (pattern.test(content)) {
359
- methods.push(method);
360
- break;
361
- }
362
- }
363
- }
364
-
365
- return methods;
366
- }
367
-
368
- /**
369
- * Extract methods from req.method checks in Pages API
370
- */
371
- function extractReqMethodChecks(content) {
372
- const methods = new Set();
373
-
374
- // Match patterns like: req.method === "POST" or req.method === 'GET'
375
- const matches = content.matchAll(/req\.method\s*===?\s*['"`](\w+)['"`]/g);
376
- for (const match of matches) {
377
- const method = match[1].toUpperCase();
378
- if (NEXT_HTTP_METHODS.includes(method)) {
379
- methods.add(method);
380
- }
381
- }
382
-
383
- // Match switch case patterns
384
- const caseMatches = content.matchAll(/case\s*['"`](\w+)['"`]\s*:/g);
385
- for (const match of caseMatches) {
386
- const method = match[1].toUpperCase();
387
- if (NEXT_HTTP_METHODS.includes(method)) {
388
- methods.add(method);
389
- }
390
- }
391
-
392
- return [...methods];
393
- }
394
-
395
- /**
396
- * Extract middleware matchers for auth hints
397
- */
398
- function extractMiddlewareMatchers(middlewareFile, projectRoot) {
399
- const result = {
400
- matchers: [],
401
- protectedHints: [],
402
- };
403
-
404
- if (!middlewareFile || !fs.existsSync(middlewareFile)) return result;
405
-
406
- const content = fs.readFileSync(middlewareFile, "utf8");
407
-
408
- // Extract config.matcher
409
- const matcherMatch = content.match(/export\s+const\s+config\s*=\s*\{[^}]*matcher\s*:\s*(\[[^\]]+\]|['"`][^'"`]+['"`])/s);
410
- if (matcherMatch) {
411
- const matcherValue = matcherMatch[1];
412
-
413
- // Parse array
414
- if (matcherValue.startsWith("[")) {
415
- const patterns = matcherValue.matchAll(/['"`]([^'"`]+)['"`]/g);
416
- for (const p of patterns) {
417
- result.matchers.push(p[1]);
418
- }
419
- } else {
420
- // Single string
421
- const singleMatch = matcherValue.match(/['"`]([^'"`]+)['"`]/);
422
- if (singleMatch) {
423
- result.matchers.push(singleMatch[1]);
424
- }
425
- }
426
- }
427
-
428
- // Detect auth signals (protected hints)
429
- const authSignals = [
430
- /getToken\s*\(/,
431
- /getServerSession\s*\(/,
432
- /auth\s*\(\s*\)/,
433
- /cookies\(\)\.get\s*\(/,
434
- /NextResponse\.redirect.*login/i,
435
- /clerk/i,
436
- /supabase.*auth/i,
437
- ];
438
-
439
- for (const signal of authSignals) {
440
- if (signal.test(content)) {
441
- result.protectedHints.push({
442
- signal: signal.toString(),
443
- file: path.relative(projectRoot, middlewareFile).replace(/\\/g, "/"),
444
- });
445
- }
446
- }
447
-
448
- return result;
449
- }
450
-
451
- /**
452
- * Main extraction function
453
- */
454
- function extractNextRoutes(projectRoot) {
455
- const mode = detectNextMode(projectRoot);
456
-
457
- if (!mode.present) {
458
- return {
459
- present: false,
460
- router: "unknown",
461
- routes: [],
462
- middleware: { matchers: [], protectedHints: [] },
463
- };
464
- }
465
-
466
- const routes = [];
467
-
468
- // Extract App Router routes
469
- if (mode.appDir) {
470
- const appRoutes = extractAppRouterRoutes(mode.appDir, projectRoot);
471
- routes.push(...appRoutes);
472
- }
473
-
474
- // Extract Pages Router routes
475
- if (mode.pagesDir) {
476
- const pagesRoutes = extractPagesRouterRoutes(mode.pagesDir, projectRoot);
477
- routes.push(...pagesRoutes);
478
- }
479
-
480
- // Apply basePath to all routes
481
- if (mode.basePath) {
482
- for (const route of routes) {
483
- route.path = mode.basePath + route.path;
484
- route.canonicalPath = mode.basePath + route.canonicalPath;
485
- }
486
- }
487
-
488
- // Extract middleware
489
- const middleware = extractMiddlewareMatchers(mode.middlewareFile, projectRoot);
490
-
491
- return {
492
- present: true,
493
- router: mode.router,
494
- appDir: mode.appDir ? path.relative(projectRoot, mode.appDir) : null,
495
- pagesDir: mode.pagesDir ? path.relative(projectRoot, mode.pagesDir) : null,
496
- basePath: mode.basePath,
497
- trailingSlash: mode.trailingSlash,
498
- rewrites: mode.rewrites,
499
- middlewareFile: mode.middlewareFile ? path.relative(projectRoot, mode.middlewareFile) : null,
500
- routes,
501
- middleware,
502
- };
503
- }
504
-
505
- // Helpers
506
- function hashSnippet(text) {
507
- return `sha256:${crypto.createHash("sha256").update(text).digest("hex")}`;
508
- }
509
-
510
- function hashPath(urlPath) {
511
- return crypto.createHash("sha256").update(urlPath).digest("hex").slice(0, 12).toUpperCase();
512
- }
513
-
514
- module.exports = {
515
- detectNextMode,
516
- extractNextRoutes,
517
- extractAppRouterRoutes,
518
- extractPagesRouterRoutes,
519
- extractMiddlewareMatchers,
520
- convertNextPathToCanonical,
521
- extractExportedMethods,
522
- extractReqMethodChecks,
523
- NEXT_HTTP_METHODS,
524
- };
1
+ /**
2
+ * Next.js Route Extractor v2
3
+ *
4
+ * Spec-compliant extraction for App Router + Pages Router API routes.
5
+ * Handles dynamic segments, route groups, catch-alls, and method detection.
6
+ *
7
+ * Canonical path format:
8
+ * - Static: /api/billing/portal
9
+ * - Params: /api/users/{id}
10
+ * - Catch-all: /api/files/{*path}
11
+ * - Optional catch-all: /api/blog/{*slug?}
12
+ */
13
+
14
+ "use strict";
15
+
16
+ const fs = require("fs");
17
+ const path = require("path");
18
+ const fg = require("fast-glob");
19
+ const crypto = require("crypto");
20
+
21
+ const NEXT_HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"];
22
+
23
+ /**
24
+ * Detect Next.js mode and roots
25
+ */
26
+ function detectNextMode(projectRoot) {
27
+ const result = {
28
+ present: false,
29
+ router: "unknown",
30
+ appDir: null,
31
+ pagesDir: null,
32
+ middlewareFile: null,
33
+ basePath: "",
34
+ trailingSlash: false,
35
+ rewrites: [],
36
+ };
37
+
38
+ // Check for Next.js presence
39
+ const pkgPath = path.join(projectRoot, "package.json");
40
+ if (fs.existsSync(pkgPath)) {
41
+ try {
42
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
43
+ if (pkg.dependencies?.next || pkg.devDependencies?.next) {
44
+ result.present = true;
45
+ }
46
+ } catch {}
47
+ }
48
+
49
+ // Check for next.config
50
+ const configFiles = ["next.config.js", "next.config.mjs", "next.config.ts"];
51
+ for (const configFile of configFiles) {
52
+ const configPath = path.join(projectRoot, configFile);
53
+ if (fs.existsSync(configPath)) {
54
+ result.present = true;
55
+ parseNextConfig(configPath, result);
56
+ break;
57
+ }
58
+ }
59
+
60
+ // Check for app/ and pages/ directories
61
+ const appDir = path.join(projectRoot, "app");
62
+ const srcAppDir = path.join(projectRoot, "src", "app");
63
+ const pagesDir = path.join(projectRoot, "pages");
64
+ const srcPagesDir = path.join(projectRoot, "src", "pages");
65
+
66
+ if (fs.existsSync(appDir)) {
67
+ result.appDir = appDir;
68
+ result.present = true;
69
+ } else if (fs.existsSync(srcAppDir)) {
70
+ result.appDir = srcAppDir;
71
+ result.present = true;
72
+ }
73
+
74
+ if (fs.existsSync(pagesDir)) {
75
+ result.pagesDir = pagesDir;
76
+ result.present = true;
77
+ } else if (fs.existsSync(srcPagesDir)) {
78
+ result.pagesDir = srcPagesDir;
79
+ result.present = true;
80
+ }
81
+
82
+ // Determine router mode
83
+ if (result.appDir && result.pagesDir) {
84
+ result.router = "mixed";
85
+ } else if (result.appDir) {
86
+ result.router = "app";
87
+ } else if (result.pagesDir) {
88
+ result.router = "pages";
89
+ }
90
+
91
+ // Find middleware
92
+ const middlewareLocations = [
93
+ path.join(projectRoot, "middleware.ts"),
94
+ path.join(projectRoot, "middleware.js"),
95
+ path.join(projectRoot, "src", "middleware.ts"),
96
+ path.join(projectRoot, "src", "middleware.js"),
97
+ ];
98
+ for (const loc of middlewareLocations) {
99
+ if (fs.existsSync(loc)) {
100
+ result.middlewareFile = loc;
101
+ break;
102
+ }
103
+ }
104
+
105
+ return result;
106
+ }
107
+
108
+ /**
109
+ * Parse next.config for basePath, trailingSlash, rewrites
110
+ */
111
+ function parseNextConfig(configPath, result) {
112
+ try {
113
+ const content = fs.readFileSync(configPath, "utf8");
114
+
115
+ // Extract basePath
116
+ const basePathMatch = content.match(/basePath\s*:\s*['"`]([^'"`]+)['"`]/);
117
+ if (basePathMatch) {
118
+ result.basePath = basePathMatch[1];
119
+ }
120
+
121
+ // Extract trailingSlash
122
+ if (/trailingSlash\s*:\s*true/.test(content)) {
123
+ result.trailingSlash = true;
124
+ }
125
+
126
+ // Extract rewrites (basic pattern matching)
127
+ const rewriteMatches = content.matchAll(/source\s*:\s*['"`]([^'"`]+)['"`][\s\S]*?destination\s*:\s*['"`]([^'"`]+)['"`]/g);
128
+ for (const match of rewriteMatches) {
129
+ result.rewrites.push({
130
+ source: match[1],
131
+ destination: match[2],
132
+ isExternal: match[2].startsWith("http"),
133
+ });
134
+ }
135
+ } catch {}
136
+ }
137
+
138
+ /**
139
+ * Extract App Router API routes from app/api directory
140
+ */
141
+ function extractAppRouterRoutes(appDir, projectRoot) {
142
+ const routes = [];
143
+
144
+ if (!appDir || !fs.existsSync(appDir)) return routes;
145
+
146
+ // Find all route handlers
147
+ const pattern = path.join(appDir, "api", "**", "route.{js,jsx,ts,tsx}").replace(/\\/g, "/");
148
+ const files = fg.sync(pattern, { onlyFiles: true, absolute: true });
149
+
150
+ for (const file of files) {
151
+ const route = extractAppRouteHandler(file, appDir, projectRoot);
152
+ if (route) {
153
+ routes.push(route);
154
+ }
155
+ }
156
+
157
+ return routes;
158
+ }
159
+
160
+ /**
161
+ * Extract a single App Router route handler
162
+ */
163
+ function extractAppRouteHandler(file, appDir, projectRoot) {
164
+ const content = fs.readFileSync(file, "utf8");
165
+ const relPath = path.relative(appDir, file).replace(/\\/g, "/");
166
+
167
+ // Build canonical path from file path
168
+ // Strip api/ prefix and route.* suffix
169
+ let urlPath = relPath
170
+ .replace(/^api\//, "/api/")
171
+ .replace(/\/route\.(js|jsx|ts|tsx)$/, "")
172
+ .replace(/^\/api/, "/api"); // Ensure /api prefix
173
+
174
+ // Handle special segments
175
+ urlPath = convertNextPathToCanonical(urlPath);
176
+
177
+ // Extract HTTP methods from exports
178
+ const methods = extractExportedMethods(content);
179
+ const confidence = methods.length > 0 && !methods.includes("UNKNOWN") ? "high" : "low";
180
+
181
+ // Build evidence
182
+ const evidence = [];
183
+ for (const method of methods) {
184
+ const methodMatch = content.match(new RegExp(`export\\s+(async\\s+)?function\\s+${method}|export\\s+const\\s+${method}\\s*=`, "m"));
185
+ if (methodMatch) {
186
+ const lineNum = content.substring(0, methodMatch.index).split("\n").length;
187
+ evidence.push({
188
+ id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
189
+ kind: "file",
190
+ reason: `${method} handler export`,
191
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
192
+ lines: `${lineNum}-${lineNum + 5}`,
193
+ snippetHash: hashSnippet(methodMatch[0]),
194
+ });
195
+ }
196
+ }
197
+
198
+ // If no methods found, add generic evidence
199
+ if (evidence.length === 0) {
200
+ evidence.push({
201
+ id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
202
+ kind: "file",
203
+ reason: "Route handler file",
204
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
205
+ lines: "1-10",
206
+ });
207
+ }
208
+
209
+ return {
210
+ id: `R_NEXT_APP_${hashPath(urlPath)}`,
211
+ kind: "next_route_handler",
212
+ methods: methods.length > 0 ? methods : ["UNKNOWN"],
213
+ rawPath: relPath,
214
+ path: urlPath,
215
+ canonicalPath: urlPath,
216
+ authRequired: "unknown",
217
+ confidence,
218
+ handler: {
219
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
220
+ export: methods[0] || "handler",
221
+ },
222
+ evidence,
223
+ };
224
+ }
225
+
226
+ /**
227
+ * Extract Pages Router API routes (pages/api/**)
228
+ */
229
+ function extractPagesRouterRoutes(pagesDir, projectRoot) {
230
+ const routes = [];
231
+
232
+ if (!pagesDir || !fs.existsSync(pagesDir)) return routes;
233
+
234
+ const apiDir = path.join(pagesDir, "api");
235
+ if (!fs.existsSync(apiDir)) return routes;
236
+
237
+ // Find all API files
238
+ const pattern = path.join(apiDir, "**", "*.{js,jsx,ts,tsx}").replace(/\\/g, "/");
239
+ const files = fg.sync(pattern, { onlyFiles: true, absolute: true });
240
+
241
+ for (const file of files) {
242
+ const route = extractPagesApiHandler(file, pagesDir, projectRoot);
243
+ if (route) {
244
+ routes.push(route);
245
+ }
246
+ }
247
+
248
+ return routes;
249
+ }
250
+
251
+ /**
252
+ * Extract a single Pages API handler
253
+ */
254
+ function extractPagesApiHandler(file, pagesDir, projectRoot) {
255
+ const content = fs.readFileSync(file, "utf8");
256
+ const relPath = path.relative(pagesDir, file).replace(/\\/g, "/");
257
+
258
+ // Build URL path
259
+ let urlPath = "/" + relPath
260
+ .replace(/^api\//, "api/")
261
+ .replace(/\.(js|jsx|ts|tsx)$/, "")
262
+ .replace(/\/index$/, "");
263
+
264
+ // Ensure /api prefix
265
+ if (!urlPath.startsWith("/api")) {
266
+ urlPath = "/api" + urlPath;
267
+ }
268
+
269
+ // Convert dynamic segments
270
+ urlPath = convertNextPathToCanonical(urlPath);
271
+
272
+ // Extract methods from req.method checks
273
+ const methods = extractReqMethodChecks(content);
274
+ const confidence = methods.length > 0 && !methods.includes("UNKNOWN") ? "medium" : "low";
275
+
276
+ // Build evidence
277
+ const evidence = [{
278
+ id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
279
+ kind: "file",
280
+ reason: "Pages API handler",
281
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
282
+ lines: "1-20",
283
+ }];
284
+
285
+ // Add evidence for method checks
286
+ const methodCheckMatch = content.match(/req\.method\s*===?\s*['"`](\w+)['"`]/);
287
+ if (methodCheckMatch) {
288
+ const lineNum = content.substring(0, methodCheckMatch.index).split("\n").length;
289
+ evidence.push({
290
+ id: `E_${crypto.randomBytes(4).toString("hex").toUpperCase()}`,
291
+ kind: "file",
292
+ reason: "Method check",
293
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
294
+ lines: `${lineNum}-${lineNum}`,
295
+ snippetHash: hashSnippet(methodCheckMatch[0]),
296
+ });
297
+ }
298
+
299
+ return {
300
+ id: `R_NEXT_PAGES_${hashPath(urlPath)}`,
301
+ kind: "next_pages_api",
302
+ methods: methods.length > 0 ? methods : ["UNKNOWN"],
303
+ rawPath: relPath,
304
+ path: urlPath,
305
+ canonicalPath: urlPath,
306
+ authRequired: "unknown",
307
+ confidence,
308
+ handler: {
309
+ file: path.relative(projectRoot, file).replace(/\\/g, "/"),
310
+ export: "default",
311
+ },
312
+ evidence,
313
+ };
314
+ }
315
+
316
+ /**
317
+ * Convert Next.js path segments to canonical format
318
+ * [id] → {id}
319
+ * [...slug] → {*slug}
320
+ * [[...slug]] → {*slug?}
321
+ * (group) → removed
322
+ */
323
+ function convertNextPathToCanonical(urlPath) {
324
+ return urlPath
325
+ // Remove route groups (parentheses)
326
+ .replace(/\/\([^)]+\)/g, "")
327
+ // Remove parallel routes (@)
328
+ .replace(/\/@[^/]+/g, "")
329
+ // Optional catch-all [[...slug]]
330
+ .replace(/\[\[\.\.\.([^\]]+)\]\]/g, "{*$1?}")
331
+ // Catch-all [...slug]
332
+ .replace(/\[\.\.\.([^\]]+)\]/g, "{*$1}")
333
+ // Dynamic segment [id]
334
+ .replace(/\[([^\]]+)\]/g, "{$1}")
335
+ // Clean up double slashes
336
+ .replace(/\/+/g, "/")
337
+ // Remove trailing slash except root
338
+ .replace(/(.)\/$/, "$1");
339
+ }
340
+
341
+ /**
342
+ * Extract exported HTTP methods from App Router file
343
+ */
344
+ function extractExportedMethods(content) {
345
+ const methods = [];
346
+
347
+ for (const method of NEXT_HTTP_METHODS) {
348
+ // export async function GET
349
+ // export function GET
350
+ // export const GET =
351
+ const patterns = [
352
+ new RegExp(`export\\s+async\\s+function\\s+${method}\\s*\\(`, "m"),
353
+ new RegExp(`export\\s+function\\s+${method}\\s*\\(`, "m"),
354
+ new RegExp(`export\\s+const\\s+${method}\\s*=`, "m"),
355
+ ];
356
+
357
+ for (const pattern of patterns) {
358
+ if (pattern.test(content)) {
359
+ methods.push(method);
360
+ break;
361
+ }
362
+ }
363
+ }
364
+
365
+ return methods;
366
+ }
367
+
368
+ /**
369
+ * Extract methods from req.method checks in Pages API
370
+ */
371
+ function extractReqMethodChecks(content) {
372
+ const methods = new Set();
373
+
374
+ // Match patterns like: req.method === "POST" or req.method === 'GET'
375
+ const matches = content.matchAll(/req\.method\s*===?\s*['"`](\w+)['"`]/g);
376
+ for (const match of matches) {
377
+ const method = match[1].toUpperCase();
378
+ if (NEXT_HTTP_METHODS.includes(method)) {
379
+ methods.add(method);
380
+ }
381
+ }
382
+
383
+ // Match switch case patterns
384
+ const caseMatches = content.matchAll(/case\s*['"`](\w+)['"`]\s*:/g);
385
+ for (const match of caseMatches) {
386
+ const method = match[1].toUpperCase();
387
+ if (NEXT_HTTP_METHODS.includes(method)) {
388
+ methods.add(method);
389
+ }
390
+ }
391
+
392
+ return [...methods];
393
+ }
394
+
395
+ /**
396
+ * Extract middleware matchers for auth hints
397
+ */
398
+ function extractMiddlewareMatchers(middlewareFile, projectRoot) {
399
+ const result = {
400
+ matchers: [],
401
+ protectedHints: [],
402
+ };
403
+
404
+ if (!middlewareFile || !fs.existsSync(middlewareFile)) return result;
405
+
406
+ const content = fs.readFileSync(middlewareFile, "utf8");
407
+
408
+ // Extract config.matcher
409
+ const matcherMatch = content.match(/export\s+const\s+config\s*=\s*\{[^}]*matcher\s*:\s*(\[[^\]]+\]|['"`][^'"`]+['"`])/s);
410
+ if (matcherMatch) {
411
+ const matcherValue = matcherMatch[1];
412
+
413
+ // Parse array
414
+ if (matcherValue.startsWith("[")) {
415
+ const patterns = matcherValue.matchAll(/['"`]([^'"`]+)['"`]/g);
416
+ for (const p of patterns) {
417
+ result.matchers.push(p[1]);
418
+ }
419
+ } else {
420
+ // Single string
421
+ const singleMatch = matcherValue.match(/['"`]([^'"`]+)['"`]/);
422
+ if (singleMatch) {
423
+ result.matchers.push(singleMatch[1]);
424
+ }
425
+ }
426
+ }
427
+
428
+ // Detect auth signals (protected hints)
429
+ const authSignals = [
430
+ /getToken\s*\(/,
431
+ /getServerSession\s*\(/,
432
+ /auth\s*\(\s*\)/,
433
+ /cookies\(\)\.get\s*\(/,
434
+ /NextResponse\.redirect.*login/i,
435
+ /clerk/i,
436
+ /supabase.*auth/i,
437
+ ];
438
+
439
+ for (const signal of authSignals) {
440
+ if (signal.test(content)) {
441
+ result.protectedHints.push({
442
+ signal: signal.toString(),
443
+ file: path.relative(projectRoot, middlewareFile).replace(/\\/g, "/"),
444
+ });
445
+ }
446
+ }
447
+
448
+ return result;
449
+ }
450
+
451
+ /**
452
+ * Main extraction function
453
+ */
454
+ function extractNextRoutes(projectRoot) {
455
+ const mode = detectNextMode(projectRoot);
456
+
457
+ if (!mode.present) {
458
+ return {
459
+ present: false,
460
+ router: "unknown",
461
+ routes: [],
462
+ middleware: { matchers: [], protectedHints: [] },
463
+ };
464
+ }
465
+
466
+ const routes = [];
467
+
468
+ // Extract App Router routes
469
+ if (mode.appDir) {
470
+ const appRoutes = extractAppRouterRoutes(mode.appDir, projectRoot);
471
+ routes.push(...appRoutes);
472
+ }
473
+
474
+ // Extract Pages Router routes
475
+ if (mode.pagesDir) {
476
+ const pagesRoutes = extractPagesRouterRoutes(mode.pagesDir, projectRoot);
477
+ routes.push(...pagesRoutes);
478
+ }
479
+
480
+ // Apply basePath to all routes
481
+ if (mode.basePath) {
482
+ for (const route of routes) {
483
+ route.path = mode.basePath + route.path;
484
+ route.canonicalPath = mode.basePath + route.canonicalPath;
485
+ }
486
+ }
487
+
488
+ // Extract middleware
489
+ const middleware = extractMiddlewareMatchers(mode.middlewareFile, projectRoot);
490
+
491
+ return {
492
+ present: true,
493
+ router: mode.router,
494
+ appDir: mode.appDir ? path.relative(projectRoot, mode.appDir) : null,
495
+ pagesDir: mode.pagesDir ? path.relative(projectRoot, mode.pagesDir) : null,
496
+ basePath: mode.basePath,
497
+ trailingSlash: mode.trailingSlash,
498
+ rewrites: mode.rewrites,
499
+ middlewareFile: mode.middlewareFile ? path.relative(projectRoot, mode.middlewareFile) : null,
500
+ routes,
501
+ middleware,
502
+ };
503
+ }
504
+
505
+ // Helpers
506
+ function hashSnippet(text) {
507
+ return `sha256:${crypto.createHash("sha256").update(text).digest("hex")}`;
508
+ }
509
+
510
+ function hashPath(urlPath) {
511
+ return crypto.createHash("sha256").update(urlPath).digest("hex").slice(0, 12).toUpperCase();
512
+ }
513
+
514
+ module.exports = {
515
+ detectNextMode,
516
+ extractNextRoutes,
517
+ extractAppRouterRoutes,
518
+ extractPagesRouterRoutes,
519
+ extractMiddlewareMatchers,
520
+ convertNextPathToCanonical,
521
+ extractExportedMethods,
522
+ extractReqMethodChecks,
523
+ NEXT_HTTP_METHODS,
524
+ };