prodlint 0.10.4 → 0.10.5

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/dist/mcp.js CHANGED
@@ -90,7 +90,8 @@ function isLineSuppressed(lines, lineIndex, ruleId) {
90
90
  return false;
91
91
  }
92
92
  function isTestFile(relativePath) {
93
- return /\.(test|spec)\.[jt]sx?$/.test(relativePath) || /(?:^|\/)__tests__\//.test(relativePath) || /(?:^|\/)tests?\//.test(relativePath) || /(?:^|\/)fixtures?\//.test(relativePath) || /(?:^|\/)mocks?\//.test(relativePath);
93
+ return /\.(test|spec)\.[jt]sx?$/.test(relativePath) || // Jest's __tests__ and __mocks__, jscodeshift's __testfixtures__
94
+ /(?:^|\/)__(?:tests|testfixtures|fixtures|mocks)__\//.test(relativePath) || /(?:^|\/)tests?\//.test(relativePath) || /(?:^|\/)fixtures?\//.test(relativePath) || /(?:^|\/)mocks?\//.test(relativePath);
94
95
  }
95
96
  function isScriptFile(relativePath) {
96
97
  if (/(?:^|\/)scripts?\//.test(relativePath)) return true;
@@ -404,6 +405,263 @@ var DEPENDENCY_TO_FRAMEWORK = {
404
405
  var SQL_SAFE_ORMS = /* @__PURE__ */ new Set(["prisma", "drizzle", "knex", "typeorm", "sequelize"]);
405
406
  var RATE_LIMIT_FRAMEWORKS = /* @__PURE__ */ new Set(["upstash-ratelimit", "express-rate-limit", "rate-limiter-flexible"]);
406
407
 
408
+ // src/utils/middleware-matcher.ts
409
+ function matcherExcludesApi(content, fileName) {
410
+ const sources = matcherSources(content, fileName);
411
+ if (!sources || sources.length === 0) return false;
412
+ return sources.every((source) => {
413
+ const matcher = compile(source);
414
+ return matcher !== null && !matcher.patterns.some(namesApi) && !apiPaths(matcher.literals).some((path) => matcher.regexp.test(path));
415
+ });
416
+ }
417
+ function matcherExcludesPages(content, fileName) {
418
+ const sources = matcherSources(content, fileName);
419
+ if (!sources || sources.length === 0) return false;
420
+ return sources.every((source) => {
421
+ const matcher = compile(source);
422
+ return matcher !== null && underApi(matcher.tokens);
423
+ });
424
+ }
425
+ function underApi(tokens) {
426
+ const [head, ...rest] = tokens;
427
+ if (typeof head !== "string") return false;
428
+ if (head.startsWith("/api/")) return true;
429
+ if (head !== "/api") return false;
430
+ for (const token of rest) {
431
+ const start = typeof token === "string" ? token : token.pattern ? prefixOf(token) : token.prefix + token.suffix;
432
+ if (!start.startsWith("/")) return false;
433
+ if (typeof token === "string" || token.modifier !== "?" && token.modifier !== "*") return true;
434
+ }
435
+ return true;
436
+ }
437
+ function apiPaths(literals) {
438
+ const paths = ["/api/x", "/api/x/y"];
439
+ for (const literal2 of literals) {
440
+ for (const head of ["", "/api", "/api/x"]) {
441
+ for (const tail of ["", "/x"]) paths.push(head + literal2 + tail);
442
+ }
443
+ }
444
+ return paths.filter((path) => path.startsWith("/api/"));
445
+ }
446
+ function matcherSources(content, fileName) {
447
+ const ast = parseFile(content, fileName);
448
+ if (!ast) return null;
449
+ for (const st of ast.program.body) {
450
+ if (st.type !== "ExportNamedDeclaration" || st.declaration?.type !== "VariableDeclaration") continue;
451
+ if (st.declaration.kind !== "const") continue;
452
+ for (const d of st.declaration.declarations) {
453
+ if (d.id.type !== "Identifier" || d.id.name !== "config" || !d.init) continue;
454
+ const config = unwrap(d.init);
455
+ if (config.type !== "ObjectExpression") return null;
456
+ if (config.properties.some((p) => p.type !== "ObjectProperty")) return null;
457
+ const matcher = property(config, "matcher");
458
+ if (!matcher) return void 0;
459
+ const values = matcher.type === "ArrayExpression" ? matcher.elements : [matcher];
460
+ const sources = [];
461
+ for (const value of values) {
462
+ const element = value ? unwrap(value) : null;
463
+ const source = element?.type === "ObjectExpression" ? property(element, "source") : element;
464
+ const text = source ? literal(source) : null;
465
+ if (text === null) return null;
466
+ sources.push(text);
467
+ }
468
+ return sources;
469
+ }
470
+ }
471
+ return void 0;
472
+ }
473
+ function unwrap(node) {
474
+ while (node.type === "TSSatisfiesExpression" || node.type === "TSAsExpression") node = node.expression;
475
+ return node;
476
+ }
477
+ function property(object, name) {
478
+ if (object.type !== "ObjectExpression") return void 0;
479
+ let value;
480
+ for (const p of object.properties) {
481
+ if (p.type !== "ObjectProperty" || p.computed) continue;
482
+ const key = p.key.type === "Identifier" ? p.key.name : p.key.type === "StringLiteral" ? p.key.value : null;
483
+ if (key === name) value = unwrap(p.value);
484
+ }
485
+ return value;
486
+ }
487
+ function literal(node) {
488
+ if (node.type === "StringLiteral") return node.value;
489
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked ?? null;
490
+ return null;
491
+ }
492
+ function namesApi(pattern) {
493
+ let kept = "";
494
+ const negative = [];
495
+ for (let i = 0; i < pattern.length; i++) {
496
+ const c = pattern[i];
497
+ const skipping = negative.includes(true);
498
+ if (c === "\\") {
499
+ if (!skipping) kept += pattern.slice(i, i + 2);
500
+ i++;
501
+ } else if (c === "(") {
502
+ negative.push(pattern.startsWith("(?!", i) || pattern.startsWith("(?<!", i));
503
+ if (!skipping) kept += c;
504
+ } else if (c === ")") {
505
+ negative.pop();
506
+ if (!negative.includes(true)) kept += c;
507
+ } else if (!skipping) {
508
+ kept += c;
509
+ }
510
+ }
511
+ return /\bapi\b/i.test(kept);
512
+ }
513
+ var DELIMITER = "/#?";
514
+ var PREFIXES = "./";
515
+ var escape = (s) => s.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
516
+ var prefixOf = (token) => (token.modifier === "*" || token.modifier === "+") && !token.prefix && !token.suffix ? "/" : token.prefix;
517
+ function lex(source) {
518
+ const tokens = [];
519
+ let i = 0;
520
+ while (i < source.length) {
521
+ const c = source[i];
522
+ if (c === "*" || c === "+" || c === "?") {
523
+ tokens.push({ type: "MODIFIER", value: source[i++] });
524
+ } else if (c === "\\") {
525
+ tokens.push({ type: "ESCAPED_CHAR", value: source[i + 1] });
526
+ i += 2;
527
+ } else if (c === "{" || c === "}") {
528
+ tokens.push({ type: c === "{" ? "OPEN" : "CLOSE", value: source[i++] });
529
+ } else if (c === ":") {
530
+ const name = /^\w+/.exec(source.slice(i + 1))?.[0];
531
+ if (!name) throw new TypeError(`Missing parameter name at ${i}`);
532
+ tokens.push({ type: "NAME", value: name });
533
+ i += 1 + name.length;
534
+ } else if (c === "(") {
535
+ let depth = 1;
536
+ let pattern = "";
537
+ let j = i + 1;
538
+ if (source[j] === "?") throw new TypeError(`Pattern cannot start with "?" at ${j}`);
539
+ while (j < source.length) {
540
+ if (source[j] === "\\") {
541
+ pattern += source[j++] + source[j++];
542
+ continue;
543
+ }
544
+ if (source[j] === ")") {
545
+ if (--depth === 0) {
546
+ j++;
547
+ break;
548
+ }
549
+ } else if (source[j] === "(") {
550
+ depth++;
551
+ if (source[j + 1] !== "?") throw new TypeError(`Capturing groups are not allowed at ${j}`);
552
+ }
553
+ pattern += source[j++];
554
+ }
555
+ if (depth) throw new TypeError(`Unbalanced pattern at ${i}`);
556
+ if (!pattern) throw new TypeError(`Missing pattern at ${i}`);
557
+ tokens.push({ type: "PATTERN", value: pattern });
558
+ i = j;
559
+ } else {
560
+ tokens.push({ type: "CHAR", value: source[i++] });
561
+ }
562
+ }
563
+ tokens.push({ type: "END", value: "" });
564
+ return tokens;
565
+ }
566
+ function parse2(source) {
567
+ const tokens = lex(source);
568
+ const result = [];
569
+ let i = 0;
570
+ let path = "";
571
+ const tryConsume = (type) => i < tokens.length && tokens[i].type === type ? tokens[i++].value : void 0;
572
+ const mustConsume = (type) => {
573
+ const value = tryConsume(type);
574
+ if (value === void 0) throw new TypeError(`Unexpected ${tokens[i].type}, expected ${type}`);
575
+ return value;
576
+ };
577
+ const consumeText = () => {
578
+ let text = "";
579
+ let value;
580
+ while (value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR")) text += value;
581
+ return text;
582
+ };
583
+ const safePattern = (prefix) => {
584
+ const prev = result[result.length - 1];
585
+ const prevText = prefix || (typeof prev === "string" ? prev : "");
586
+ if (prev && !prevText) throw new TypeError("Must have text between two parameters");
587
+ if (!prevText || [...DELIMITER].some((c) => prevText.includes(c))) return `[^${escape(DELIMITER)}]+?`;
588
+ return `(?:(?!${escape(prevText)})[^${escape(DELIMITER)}])+?`;
589
+ };
590
+ while (i < tokens.length) {
591
+ const char = tryConsume("CHAR");
592
+ const name = tryConsume("NAME");
593
+ const pattern = tryConsume("PATTERN");
594
+ if (name || pattern) {
595
+ let prefix = char || "";
596
+ if (!PREFIXES.includes(prefix)) {
597
+ path += prefix;
598
+ prefix = "";
599
+ }
600
+ if (path) {
601
+ result.push(path);
602
+ path = "";
603
+ }
604
+ result.push({ prefix, suffix: "", pattern: pattern || safePattern(prefix), modifier: tryConsume("MODIFIER") || "" });
605
+ continue;
606
+ }
607
+ const value = char || tryConsume("ESCAPED_CHAR");
608
+ if (value) {
609
+ path += value;
610
+ continue;
611
+ }
612
+ if (path) {
613
+ result.push(path);
614
+ path = "";
615
+ }
616
+ if (tryConsume("OPEN")) {
617
+ const prefix = consumeText();
618
+ const name2 = tryConsume("NAME") || "";
619
+ const pattern2 = tryConsume("PATTERN") || "";
620
+ const suffix = consumeText();
621
+ mustConsume("CLOSE");
622
+ result.push({ prefix, suffix, pattern: name2 && !pattern2 ? safePattern(prefix) : pattern2, modifier: tryConsume("MODIFIER") || "" });
623
+ continue;
624
+ }
625
+ mustConsume("END");
626
+ }
627
+ return result;
628
+ }
629
+ function compile(source) {
630
+ if (!source.startsWith("/")) return null;
631
+ try {
632
+ const tokens = parse2(source);
633
+ let route = "^";
634
+ for (const token of tokens) {
635
+ if (typeof token === "string") {
636
+ route += escape(token);
637
+ continue;
638
+ }
639
+ if (!token.pattern) {
640
+ route += `(?:${escape(token.prefix)}${escape(token.suffix)})${token.modifier}`;
641
+ continue;
642
+ }
643
+ const repeat = token.modifier === "*" || token.modifier === "+";
644
+ const prefix = escape(prefixOf(token));
645
+ const suffix = escape(token.suffix);
646
+ if (!prefix && !suffix) {
647
+ route += `(${token.pattern})${token.modifier}`;
648
+ } else if (repeat) {
649
+ route += `(?:${prefix}((?:${token.pattern})(?:${suffix}${prefix}(?:${token.pattern}))*)${suffix})${token.modifier === "*" ? "?" : ""}`;
650
+ } else {
651
+ route += `(?:${prefix}(${token.pattern})${suffix})${token.modifier}`;
652
+ }
653
+ }
654
+ return {
655
+ regexp: new RegExp(`${route}[${escape(DELIMITER)}]?$`),
656
+ tokens,
657
+ literals: tokens.filter((token) => typeof token === "string"),
658
+ patterns: tokens.flatMap((token) => typeof token === "string" ? [] : [token.pattern])
659
+ };
660
+ } catch {
661
+ return null;
662
+ }
663
+ }
664
+
407
665
  // src/utils/file-walker.ts
408
666
  var DEFAULT_IGNORES = [
409
667
  "**/node_modules/**",
@@ -433,6 +691,37 @@ var SCAN_EXTENSIONS = [
433
691
  ];
434
692
  var AST_EXTENSIONS = /* @__PURE__ */ new Set(["ts", "tsx", "js", "jsx", "mjs", "cjs"]);
435
693
  var MAX_FILE_SIZE = 1024 * 1024;
694
+ var MIDDLEWARE_FILES = [
695
+ "middleware.ts",
696
+ "middleware.js",
697
+ "src/middleware.ts",
698
+ "src/middleware.js",
699
+ "proxy.ts",
700
+ "proxy.js",
701
+ "src/proxy.ts",
702
+ "src/proxy.js"
703
+ ];
704
+ var MIDDLEWARE_AUTH_PATTERNS = [
705
+ /getSession/i,
706
+ /getUser/i,
707
+ /auth\(\)/,
708
+ /withAuth/i,
709
+ /clerkMiddleware/i,
710
+ /authMiddleware/i,
711
+ /NextAuth/i,
712
+ /supabase.*auth/i,
713
+ /createMiddlewareClient/i,
714
+ /getToken/i,
715
+ /verifyToken/i,
716
+ /jwt/i,
717
+ /updateSession/i,
718
+ // Auth.js: export { auth as proxy } from '@/auth', export default auth((req) => …)
719
+ /\bauth\s+as\s+(?:proxy|middleware|default)\b/,
720
+ /\bauth\(/,
721
+ // NextAuth v4: export { default } from 'next-auth/middleware'
722
+ /['"]next-auth\/middleware['"]/
723
+ ];
724
+ var MIDDLEWARE_RATE_LIMIT_PATTERNS = [/rateLimit/i, /throttle/i];
436
725
  async function walkFiles(root, extraIgnores = []) {
437
726
  const patterns = SCAN_EXTENSIONS.map((ext) => `**/*.${ext}`);
438
727
  patterns.push("**/.env", "**/.env.*");
@@ -571,6 +860,8 @@ async function buildProjectContext(root, files) {
571
860
  let declaredDependencies = /* @__PURE__ */ new Set();
572
861
  let tsconfigPaths = /* @__PURE__ */ new Set();
573
862
  let hasAuthMiddleware = false;
863
+ let authMiddlewareExcludesApi = false;
864
+ let authMiddlewareExcludesPages = false;
574
865
  let hasRateLimiting = false;
575
866
  const detectedFrameworks = /* @__PURE__ */ new Set();
576
867
  let gitignoreContent = null;
@@ -622,45 +913,19 @@ async function buildProjectContext(root, files) {
622
913
  }
623
914
  } catch {
624
915
  }
625
- try {
626
- for (const name of ["middleware.ts", "middleware.js", "src/middleware.ts", "src/middleware.js"]) {
627
- try {
628
- const content = await readFile(resolve(root, name), "utf-8");
629
- const authPatterns = [
630
- /getSession/i,
631
- /getUser/i,
632
- /auth\(\)/,
633
- /withAuth/i,
634
- /clerkMiddleware/i,
635
- /authMiddleware/i,
636
- /NextAuth/i,
637
- /supabase.*auth/i,
638
- /createMiddlewareClient/i,
639
- /getToken/i,
640
- /verifyToken/i,
641
- /jwt/i,
642
- /updateSession/i
643
- ];
644
- if (authPatterns.some((p) => p.test(content))) {
645
- hasAuthMiddleware = true;
646
- break;
647
- }
648
- } catch {
649
- }
916
+ for (const name of MIDDLEWARE_FILES) {
917
+ let content;
918
+ try {
919
+ content = await readFile(resolve(root, name), "utf-8");
920
+ } catch {
921
+ continue;
650
922
  }
651
- } catch {
652
- }
653
- if (!hasRateLimiting) {
654
- for (const name of ["middleware.ts", "middleware.js", "src/middleware.ts", "src/middleware.js"]) {
655
- try {
656
- const content = await readFile(resolve(root, name), "utf-8");
657
- if (/rateLimit/i.test(content) || /throttle/i.test(content)) {
658
- hasRateLimiting = true;
659
- break;
660
- }
661
- } catch {
662
- }
923
+ if (MIDDLEWARE_AUTH_PATTERNS.some((p) => p.test(content))) {
924
+ authMiddlewareExcludesApi = (!hasAuthMiddleware || authMiddlewareExcludesApi) && matcherExcludesApi(content, name);
925
+ authMiddlewareExcludesPages = (!hasAuthMiddleware || authMiddlewareExcludesPages) && matcherExcludesPages(content, name);
926
+ hasAuthMiddleware = true;
663
927
  }
928
+ if (MIDDLEWARE_RATE_LIMIT_PATTERNS.some((p) => p.test(content))) hasRateLimiting = true;
664
929
  }
665
930
  try {
666
931
  gitignoreContent = await readFile(resolve(root, ".gitignore"), "utf-8");
@@ -673,6 +938,8 @@ async function buildProjectContext(root, files) {
673
938
  declaredDependencies,
674
939
  tsconfigPaths,
675
940
  hasAuthMiddleware,
941
+ authMiddlewareExcludesApi,
942
+ authMiddlewareExcludesPages,
676
943
  hasRateLimiting,
677
944
  detectedFrameworks,
678
945
  gitignoreContent,
@@ -990,6 +1257,15 @@ var AUTH_PATTERNS = [
990
1257
  var MUTATION_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
991
1258
  var HANDLER_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
992
1259
  var TRPC_ROUTE = /['"]@trpc\/server\/adapters\//;
1260
+ function servedUnderApi(relativePath) {
1261
+ const pages = /(?:^|\/)pages\/api\/(.+)$/.exec(relativePath);
1262
+ if (pages) return !/^index\.\w+$/.test(pages[1]);
1263
+ const segments = relativePath.split("/");
1264
+ const app = segments.indexOf("app");
1265
+ if (app === -1) return false;
1266
+ const url = segments.slice(app + 1, -1).filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith("@"));
1267
+ return url[0] === "api" && url.length > 1;
1268
+ }
993
1269
  var AUTH_WORD = /^(?:auth(?!or(?:s|ed|ing|ship)?$)|session)/i;
994
1270
  var NO_AUTH_WORD = /^(?:without|no|non|skip|bypass|optional|public|anon|anonymous|guest)$/i;
995
1271
  function words(name) {
@@ -1198,8 +1474,10 @@ var authChecksRule = {
1198
1474
  const handlers = file.ast ? handlersFromAst(file.ast.program) : handlersFromText(file);
1199
1475
  const exposed = handlers.filter((h) => !h.authed);
1200
1476
  if (handlers.length > 0 && exposed.length === 0) return [];
1477
+ const middlewareSkipsRoute = project.hasAuthMiddleware && project.authMiddlewareExcludesApi === true && servedUnderApi(file.relativePath);
1478
+ const middlewareAuth = project.hasAuthMiddleware && !middlewareSkipsRoute;
1201
1479
  let severity;
1202
- if (project.hasAuthMiddleware) {
1480
+ if (middlewareAuth) {
1203
1481
  severity = "info";
1204
1482
  } else if (exposed.some((h) => h.local && MUTATION_METHODS.has(h.method)) && !TRPC_ROUTE.test(file.content)) {
1205
1483
  severity = "critical";
@@ -1207,7 +1485,7 @@ var authChecksRule = {
1207
1485
  severity = "info";
1208
1486
  }
1209
1487
  const handlerLine = exposed[0]?.line ?? 1;
1210
- const message = project.hasAuthMiddleware ? "API route has no inline auth check (middleware auth detected \u2014 verify coverage)" : "API route has no authentication check";
1488
+ const message = middlewareAuth ? "API route has no inline auth check (middleware auth detected \u2014 verify coverage)" : middlewareSkipsRoute ? "API route has no authentication check (middleware auth detected, but its matcher excludes /api)" : "API route has no authentication check";
1211
1489
  return [{
1212
1490
  ruleId: "auth-checks",
1213
1491
  file: file.relativePath,
@@ -2611,16 +2889,190 @@ var codebaseConsistencyRule = {
2611
2889
  };
2612
2890
 
2613
2891
  // src/rules/dead-exports.ts
2614
- function isEntryPoint(relativePath) {
2892
+ function isEntryPoint(relativePath, appRoots, routeModules) {
2615
2893
  const name = relativePath.split("/").pop() ?? "";
2616
- return /^(page|layout|loading|error|not-found|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)\.(tsx?|jsx?)$/.test(name) || /^index\.(tsx?|jsx?)$/.test(name) || name === "global-error.tsx" || name === "global-error.jsx";
2894
+ return /^(page|layout|loading|error|not-found|route|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)\.(tsx?|jsx?)$/.test(name) || isBarrel(relativePath) || name === "global-error.tsx" || name === "global-error.jsx" || // SvelteKit's route files: +page.ts, +page.server.ts, +layout.ts, +server.ts
2895
+ /^\+(page|layout|server)(\.server)?\.(ts|js)$/.test(name) || // Storybook's stories: it reads a CSF file's default export as the meta, and each named
2896
+ // export as a story
2897
+ /\.stories\.(tsx?|jsx?|mjs)$/.test(name) || isNextRootFile(relativePath, appRoots) || isPagesRoute(relativePath, appRoots) || routeModules.has(relativePath);
2898
+ }
2899
+ function isBarrel(relativePath) {
2900
+ return /(?:^|\/)index\.(tsx?|jsx?)$/.test(relativePath);
2901
+ }
2902
+ function isAppFolder(dir, appRoots) {
2903
+ return appRoots.has(dir) || appRoots.has(dir.replace(/(?:^|\/)src$/, ""));
2904
+ }
2905
+ function isNextRootFile(relativePath, appRoots) {
2906
+ const match = /^(?:(.*)\/)?(?:middleware|proxy|instrumentation|instrumentation-client)\.(tsx?|jsx?)$/.exec(relativePath);
2907
+ return match !== null && isAppFolder(match[1] ?? "", appRoots);
2908
+ }
2909
+ function isPagesRoute(relativePath, appRoots) {
2910
+ if (!/\.(tsx?|jsx?)$/.test(relativePath)) return false;
2911
+ const parts = relativePath.split("/");
2912
+ return parts.some((part, i) => part === "pages" && isAppFolder(parts.slice(0, i).join("/"), appRoots));
2913
+ }
2914
+ function findAppRoots(paths) {
2915
+ const roots = /* @__PURE__ */ new Set([""]);
2916
+ for (const path of paths) {
2917
+ const match = /^(?:(.*)\/)?package\.json$/.exec(path);
2918
+ if (match) roots.add(match[1] ?? "");
2919
+ }
2920
+ return roots;
2921
+ }
2922
+ function findRouteModules(files, paths, appRoots) {
2923
+ const appFolders = [];
2924
+ for (const path of paths) {
2925
+ const match = /^(?:(.*)\/)?app\/root\.(tsx?|jsx?)$/.exec(path);
2926
+ if (match && appRoots.has(match[1] ?? "")) appFolders.push(path.slice(0, path.lastIndexOf("/")));
2927
+ }
2928
+ const modules = /* @__PURE__ */ new Set();
2929
+ for (const { relativePath, content } of files) {
2930
+ const folder = appFolders.find((f) => relativePath.startsWith(`${f}/`));
2931
+ if (folder === void 0) continue;
2932
+ const path = relativePath.slice(folder.length + 1);
2933
+ if (/^(?:root|entry\.server|routes\/.+)\.(tsx?|jsx?)$/.test(path)) {
2934
+ modules.add(relativePath);
2935
+ } else if (/^routes\.(?:[cm]?[jt]s|[jt]sx)$/.test(path)) {
2936
+ for (const match of content.matchAll(/['"`]([^'"`\n]+\.(?:tsx?|jsx?))['"`]/g)) {
2937
+ const module = normalizePath(`${folder}/${match[1]}`);
2938
+ if (module !== null) modules.add(module);
2939
+ }
2940
+ }
2941
+ }
2942
+ return modules;
2617
2943
  }
2618
2944
  var IMPORT_NAMED = /\bimport\s*(?:type\s*)?(?:[\w$]+\s*,\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g;
2619
2945
  var IMPORT_DEFAULT = /\bimport\s+([\w$]+)\s*(?:,\s*\{[^}]*\}\s*)?from\s*['"]([^'"]+)['"]/g;
2620
2946
  var IMPORT_NAMESPACE = /\bimport\s+(?:[\w$]+\s*,\s*)?\*\s*as\s+[\w$]+\s+from\s*['"]([^'"]+)['"]/g;
2621
- var FROM_SOURCE = /from\s+['"]([^'"]+)['"]/g;
2622
- function sourceBasename(source) {
2623
- return source.split("/").pop()?.replace(/\.\w+$/, "") ?? "";
2947
+ var DYNAMIC_IMPORT = /(\btypeof\s+)?(?:\{([^{}]*)\}\s*=\s*await\s+)?\bimport\s*\(\s*['"`]([^'"`]+)['"`]\s*\)(?:\s*\.\s*([\w$]+))?/g;
2948
+ var REQUIRE = /(?:\{([^{}]*)\}\s*=\s*)?\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)(?:\s*\.\s*([\w$]+))?/g;
2949
+ var REEXPORT_NAMED = /\bexport\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g;
2950
+ var REEXPORT_ALL = /\bexport\s*\*\s*(?:as\s+([\w$]+)\s*)?from\s*['"]([^'"]+)['"]/g;
2951
+ var MODULE_EXTENSIONS = ["ts", "tsx", "js", "jsx", "mjs", "cjs"];
2952
+ var MODULE_EXTENSION = /\.(?:[cm]?[jt]s|[jt]sx)$/;
2953
+ function parseSpecifiers(list) {
2954
+ return list.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").split(",").map((s) => s.trim().replace(/^type\s+/, "")).filter(Boolean).map((s) => {
2955
+ const [name, alias] = s.split(/\s+as\s+/).map((part) => part.trim());
2956
+ return [name, alias ?? name];
2957
+ });
2958
+ }
2959
+ function normalizePath(path) {
2960
+ const parts = [];
2961
+ for (const part of path.split("/")) {
2962
+ if (part === "..") {
2963
+ if (parts.length === 0) return null;
2964
+ parts.pop();
2965
+ } else if (part && part !== ".") {
2966
+ parts.push(part);
2967
+ }
2968
+ }
2969
+ return parts.join("/");
2970
+ }
2971
+ var EXTERNAL = { files: [], folders: [] };
2972
+ var UNKNOWN = { files: [], folders: [""] };
2973
+ function isAsset(source) {
2974
+ const name = source.slice(source.lastIndexOf("/") + 1);
2975
+ return /^[^.].*\.\w+$/.test(name) && !MODULE_EXTENSION.test(name);
2976
+ }
2977
+ function stringsIn(value) {
2978
+ if (typeof value === "string") return [value];
2979
+ if (Array.isArray(value)) return value.flatMap(stringsIn);
2980
+ if (value && typeof value === "object") return Object.values(value).flatMap(stringsIn);
2981
+ return [];
2982
+ }
2983
+ function createResolver(files, project) {
2984
+ const modules = new Set(files.filter((f) => MODULE_EXTENSIONS.includes(f.ext)).map((f) => f.relativePath));
2985
+ const byName = /* @__PURE__ */ new Map();
2986
+ for (const path of modules) {
2987
+ const key = path.replace(/\.\w+$/, "").replace(/(?:^|\/)index$/, "");
2988
+ const name = key.slice(key.lastIndexOf("/") + 1);
2989
+ const list = byName.get(name);
2990
+ if (list) list.push({ path, key });
2991
+ else byName.set(name, [{ path, key }]);
2992
+ }
2993
+ const manifests = [];
2994
+ for (const file of files) {
2995
+ if (!/(?:^|\/)package\.json$/.test(file.relativePath)) continue;
2996
+ try {
2997
+ const json = JSON.parse(file.content);
2998
+ if (json && typeof json === "object") manifests.push({ folder: file.relativePath.replace(/\/?package\.json$/, ""), json });
2999
+ } catch {
3000
+ }
3001
+ }
3002
+ const packages = /* @__PURE__ */ new Map();
3003
+ for (const { folder, json } of manifests) {
3004
+ if (typeof json.name === "string" && json.name) packages.set(json.name, [...packages.get(json.name) ?? [], folder]);
3005
+ }
3006
+ const findModule = (path) => {
3007
+ const stem = path.replace(/\.(?:[cm]?js|jsx)$/, "");
3008
+ const index = path ? `${path}/index` : "index";
3009
+ return [
3010
+ path,
3011
+ // TypeScript's ESM style names the compiled file: ./format.js for format.ts
3012
+ ...stem === path ? [] : [`${stem}.ts`, `${stem}.tsx`],
3013
+ ...MODULE_EXTENSIONS.map((ext) => `${path}.${ext}`),
3014
+ ...MODULE_EXTENSIONS.map((ext) => `${index}.${ext}`)
3015
+ ].find((candidate) => modules.has(candidate));
3016
+ };
3017
+ const packageEntries = /* @__PURE__ */ new Set();
3018
+ for (const { folder, json } of manifests) {
3019
+ if (json.private === true) continue;
3020
+ for (const target of stringsIn([json.main, json.module, json.types, json.typings, json.exports, json.bin])) {
3021
+ const isSource = /\.(?:[cm]?ts|tsx)$/.test(target) && !/\.d\.[cm]?ts$/.test(target);
3022
+ const path = isSource || target.includes("*") ? null : normalizePath(`${folder}/${target}`);
3023
+ if (path === null) continue;
3024
+ const stem = path.replace(/\.d\.ts$/, "").replace(MODULE_EXTENSION, "");
3025
+ const entry = findModule(path) ?? findModule(stem) ?? findModule(stem.replace(/(^|\/)(?:dist|build|lib|out|esm|cjs)\//, "$1src/"));
3026
+ if (entry) packageEntries.add(entry);
3027
+ }
3028
+ }
3029
+ const resolveRelative = (path) => {
3030
+ const normalized = normalizePath(path);
3031
+ if (normalized?.includes("${")) {
3032
+ const parts = normalized.split(/\$\{[^}]*\}/).map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3033
+ const pattern = new RegExp(`^${parts.join(".*")}(?:\\.\\w+)?$`);
3034
+ return { files: [...modules].filter((m) => pattern.test(m)), folders: [] };
3035
+ }
3036
+ const module = normalized === null ? void 0 : findModule(normalized);
3037
+ if (module) return { files: [module], folders: [] };
3038
+ return isAsset(path) ? EXTERNAL : UNKNOWN;
3039
+ };
3040
+ const resolveBare = (source) => {
3041
+ if (/^[a-z][\w+.-]*:/i.test(source)) return EXTERNAL;
3042
+ const name = source.startsWith("@") ? source.split("/").slice(0, 2).join("/") : source.split("/")[0];
3043
+ const folders = packages.get(name);
3044
+ if (folders) {
3045
+ const subpath = source.slice(name.length + 1);
3046
+ const found = folders.map((folder) => {
3047
+ const base = folder ? `${folder}/` : "";
3048
+ return subpath ? findModule(base + subpath) ?? findModule(`${base}src/${subpath}`) : findModule(folder) ?? findModule(`${base}src`);
3049
+ });
3050
+ return { files: found.filter((f) => f !== void 0), folders };
3051
+ }
3052
+ if (NODE_BUILTINS.has(name) || project.declaredDependencies.has(name)) return EXTERNAL;
3053
+ const segments = source.replace(MODULE_EXTENSION, "").split("/").filter(Boolean);
3054
+ const named = byName.get(segments[segments.length - 1] ?? "") ?? [];
3055
+ for (let i = 0; i < segments.length; i++) {
3056
+ const path = segments.slice(i).join("/");
3057
+ const matches = named.filter((m) => m.key === path || m.key.endsWith(`/${path}`));
3058
+ if (matches.length > 0) return i <= 1 ? { files: matches.map((m) => m.path), folders: [] } : UNKNOWN;
3059
+ }
3060
+ return isAsset(source) ? EXTERNAL : UNKNOWN;
3061
+ };
3062
+ const cache = /* @__PURE__ */ new Map();
3063
+ const resolve5 = (source, from) => {
3064
+ const clean = source.replace(/\?.*$/, "");
3065
+ const relative = /^\.\.?(?:\/|$)/.test(clean);
3066
+ const dir = relative ? from.slice(0, from.lastIndexOf("/") + 1) : "";
3067
+ const key = `${dir}\0${clean}`;
3068
+ let target = cache.get(key);
3069
+ if (!target) {
3070
+ target = relative ? resolveRelative(dir + clean) : resolveBare(clean);
3071
+ cache.set(key, target);
3072
+ }
3073
+ return target;
3074
+ };
3075
+ return { resolve: resolve5, packageEntries };
2624
3076
  }
2625
3077
  var THRESHOLD = 5;
2626
3078
  var deadExportsRule = {
@@ -2633,17 +3085,16 @@ var deadExportsRule = {
2633
3085
  check() {
2634
3086
  return [];
2635
3087
  },
2636
- checkProject(files, _project) {
3088
+ checkProject(files, project) {
2637
3089
  const sourceFiles = files.filter(
2638
3090
  (f) => ["ts", "tsx", "js", "jsx"].includes(f.ext) && !isTestFile(f.relativePath) && !isScriptFile(f.relativePath)
2639
3091
  );
3092
+ const appRoots = findAppRoots(project.allFiles);
3093
+ const routeModules = findRouteModules(files, project.allFiles, appRoots);
3094
+ const { resolve: resolve5, packageEntries } = createResolver(files, project);
2640
3095
  const exports = /* @__PURE__ */ new Map();
2641
- const imports = /* @__PURE__ */ new Map();
2642
- const allImportedSymbols = /* @__PURE__ */ new Set();
2643
- const importedFiles = /* @__PURE__ */ new Set();
2644
- const namespaceImported = /* @__PURE__ */ new Set();
2645
3096
  for (const file of sourceFiles) {
2646
- if (isEntryPoint(file.relativePath)) continue;
3097
+ if (isEntryPoint(file.relativePath, appRoots, routeModules) || packageEntries.has(file.relativePath)) continue;
2647
3098
  let inTemplateLiteral = false;
2648
3099
  for (let i = 0; i < file.lines.length; i++) {
2649
3100
  const line = file.lines[i];
@@ -2684,38 +3135,92 @@ var deadExportsRule = {
2684
3135
  }
2685
3136
  }
2686
3137
  }
2687
- const addImport = (sym, source) => {
2688
- allImportedSymbols.add(sym);
2689
- const fromBasename = sourceBasename(source);
2690
- if (fromBasename) {
2691
- const set = imports.get(fromBasename) ?? /* @__PURE__ */ new Set();
2692
- set.add(sym);
2693
- imports.set(fromBasename, set);
3138
+ const contents = new Map(files.map((f) => [f.relativePath, f.content]));
3139
+ const used = /* @__PURE__ */ new Set();
3140
+ const usedInFolder = /* @__PURE__ */ new Map();
3141
+ const reexports = /* @__PURE__ */ new Map();
3142
+ const reexportsOf = (file) => {
3143
+ let list = reexports.get(file);
3144
+ if (!list) {
3145
+ list = [];
3146
+ const content = contents.get(file) ?? "";
3147
+ for (const match of content.matchAll(REEXPORT_NAMED)) {
3148
+ for (const [imported, exported] of parseSpecifiers(match[1])) list.push({ source: match[2], imported, exported });
3149
+ }
3150
+ for (const match of content.matchAll(REEXPORT_ALL)) {
3151
+ list.push(match[1] ? { source: match[2], imported: "*", exported: match[1] } : { source: match[2], imported: "", exported: "*" });
3152
+ }
3153
+ reexports.set(file, list);
3154
+ }
3155
+ return list;
3156
+ };
3157
+ const use = (target, name) => {
3158
+ if (name !== "*" && name !== "default") {
3159
+ for (const folder of target.folders) {
3160
+ const names = usedInFolder.get(folder) ?? /* @__PURE__ */ new Set();
3161
+ names.add(name);
3162
+ usedInFolder.set(folder, names);
3163
+ }
3164
+ }
3165
+ for (const file of target.files) {
3166
+ const key = `${file}::${name}`;
3167
+ if (used.has(key)) continue;
3168
+ used.add(key);
3169
+ for (const { source, imported, exported } of reexportsOf(file)) {
3170
+ if (exported === "*") {
3171
+ if (name !== "default") use(resolve5(source, file), name);
3172
+ } else if (name === "*" || name === exported) {
3173
+ use(resolve5(source, file), imported);
3174
+ }
3175
+ }
3176
+ }
3177
+ };
3178
+ const useLoaded = (target, destructured, member, typeOnly) => {
3179
+ if (member && !["then", "catch", "finally"].includes(member)) {
3180
+ use(target, member);
3181
+ } else if (typeOnly) {
3182
+ return;
3183
+ } else if (destructured !== void 0 && !destructured.includes("...")) {
3184
+ for (const name of destructured.split(",").map((s) => s.split(/[:=]/)[0].trim()).filter(Boolean)) use(target, name);
3185
+ } else {
3186
+ use(target, "*");
2694
3187
  }
2695
3188
  };
2696
3189
  for (const file of files) {
3190
+ const from = file.relativePath;
2697
3191
  for (const match of file.content.matchAll(IMPORT_NAMED)) {
2698
- const symbols = match[1].replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").split(",").map((s) => s.trim().replace(/^type\s+/, "").split(/\s+as\s+/)[0].trim()).filter(Boolean);
2699
- for (const sym of symbols) addImport(sym, match[2]);
3192
+ for (const [name] of parseSpecifiers(match[1])) use(resolve5(match[2], from), name);
2700
3193
  }
2701
3194
  for (const match of file.content.matchAll(IMPORT_DEFAULT)) {
2702
- addImport(match[1], match[2]);
3195
+ const target = resolve5(match[2], from);
3196
+ use(target, "default");
3197
+ use(target, match[1]);
2703
3198
  }
2704
- for (const match of file.content.matchAll(IMPORT_NAMESPACE)) {
2705
- namespaceImported.add(sourceBasename(match[1]));
3199
+ for (const match of file.content.matchAll(IMPORT_NAMESPACE)) use(resolve5(match[1], from), "*");
3200
+ for (const match of file.content.matchAll(DYNAMIC_IMPORT)) {
3201
+ const [, typeOnly, destructured, source, member] = match;
3202
+ useLoaded(resolve5(source, from), destructured, member, Boolean(typeOnly));
2706
3203
  }
2707
- for (const match of file.content.matchAll(FROM_SOURCE)) {
2708
- importedFiles.add(match[1]);
3204
+ for (const match of file.content.matchAll(REQUIRE)) {
3205
+ const [, destructured, source, member] = match;
3206
+ useLoaded(resolve5(source, from), destructured, member, false);
2709
3207
  }
3208
+ if (isEntryPoint(from, appRoots, routeModules) && !isBarrel(from)) use({ files: [from], folders: [] }, "*");
2710
3209
  }
3210
+ for (const entry of packageEntries) use({ files: [entry], folders: [] }, "*");
3211
+ const usedInAFolderOf = (file, name) => {
3212
+ let folder = file;
3213
+ while (folder) {
3214
+ folder = folder.slice(0, Math.max(folder.lastIndexOf("/"), 0));
3215
+ if (usedInFolder.get(folder)?.has(name)) return true;
3216
+ }
3217
+ return false;
3218
+ };
2711
3219
  const deadByFile = /* @__PURE__ */ new Map();
2712
3220
  for (const [key, loc] of exports) {
2713
3221
  const symbolName = key.split("::")[1];
2714
- const exportFileBasename = loc.file.split("/").pop()?.replace(/\.\w+$/, "") ?? "";
2715
- if (namespaceImported.has(exportFileBasename)) continue;
2716
- const importSet = imports.get(exportFileBasename);
2717
- const isImported = importSet?.has(symbolName) ?? false;
2718
- if (!isImported && !allImportedSymbols.has(symbolName)) {
3222
+ const isUsed = used.has(key) || used.has(`${loc.file}::*`) || usedInAFolderOf(loc.file, symbolName);
3223
+ if (!isUsed) {
2719
3224
  deadByFile.set(loc.file, (deadByFile.get(loc.file) ?? 0) + 1);
2720
3225
  }
2721
3226
  }
@@ -3829,7 +4334,6 @@ var serverActionAuthRule = {
3829
4334
  check(file, project) {
3830
4335
  if (isTestFile(file.relativePath)) return [];
3831
4336
  if (!USE_SERVER3.test(file.content)) return [];
3832
- if (project.hasAuthMiddleware) return [];
3833
4337
  for (const p of PUBLIC_ACTION_NAMES) {
3834
4338
  if (p.test(file.relativePath)) return [];
3835
4339
  }
@@ -3844,15 +4348,17 @@ var serverActionAuthRule = {
3844
4348
  break;
3845
4349
  }
3846
4350
  }
4351
+ const middlewareSkipsPages = project.hasAuthMiddleware && project.authMiddlewareExcludesPages === true;
4352
+ const middleware = project.hasAuthMiddleware && !middlewareSkipsPages;
3847
4353
  return [{
3848
4354
  ruleId: "server-action-auth",
3849
4355
  file: file.relativePath,
3850
4356
  line: reportLine,
3851
4357
  column: 1,
3852
- message: "Server action performs mutations without any authentication check \u2014 anyone can call this action",
3853
- severity: "warning",
4358
+ message: middleware ? "Server action performs mutations without an inline auth check (middleware auth detected \u2014 verify coverage)" : middlewareSkipsPages ? "Server action performs mutations without any authentication check (middleware auth detected, but its matcher doesn't cover pages)" : "Server action performs mutations without any authentication check \u2014 anyone can call this action",
4359
+ severity: middleware ? "info" : "warning",
3854
4360
  category: "security",
3855
- fix: 'Add auth check: const session = await auth(); if (!session) throw new Error("Unauthorized")'
4361
+ fix: middleware ? 'Check the user in the action too, not only in middleware: const session = await auth(); if (!session) throw new Error("Unauthorized")' : 'Add auth check: const session = await auth(); if (!session) throw new Error("Unauthorized")'
3856
4362
  }];
3857
4363
  }
3858
4364
  };
@@ -5029,9 +5535,9 @@ function ipv6Groups(address) {
5029
5535
  const quad = address.match(/^(.*:)(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
5030
5536
  const hex = quad ? `${quad[1]}${(+quad[2] << 8 | +quad[3]).toString(16)}:${(+quad[4] << 8 | +quad[5]).toString(16)}` : address;
5031
5537
  const [head, tail] = hex.split("::");
5032
- const parse2 = (part) => part ? part.split(":").map((g) => parseInt(g, 16)) : [];
5033
- const front = parse2(head);
5034
- const back = parse2(tail);
5538
+ const parse3 = (part) => part ? part.split(":").map((g) => parseInt(g, 16)) : [];
5539
+ const front = parse3(head);
5540
+ const back = parse3(tail);
5035
5541
  return tail === void 0 ? front : [...front, ...Array(8 - front.length - back.length).fill(0), ...back];
5036
5542
  }
5037
5543
  function embeddedIPv4(address) {