@whil/guardrails 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.
Files changed (141) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +208 -2
  3. package/catalog-assets/claude-hooks/guardrails-check.sh +37 -0
  4. package/catalog-assets/eslint-guardrails/config.mjs +21 -0
  5. package/catalog-assets/eslint-rules/_rule-tester.mjs +21 -0
  6. package/catalog-assets/eslint-rules/cache-policy-constant.mjs +35 -0
  7. package/catalog-assets/eslint-rules/client-imports-server.mjs +26 -0
  8. package/catalog-assets/eslint-rules/effects-in-hooks.mjs +46 -0
  9. package/catalog-assets/eslint-rules/env-through-config.mjs +26 -0
  10. package/catalog-assets/eslint-rules/hook-body-order.mjs +169 -0
  11. package/catalog-assets/eslint-rules/import-boundaries.mjs +97 -0
  12. package/catalog-assets/eslint-rules/no-comments.mjs +35 -0
  13. package/catalog-assets/eslint-rules/no-default-export.mjs +20 -0
  14. package/catalog-assets/eslint-rules/no-delete.mjs +16 -0
  15. package/catalog-assets/eslint-rules/no-enum.mjs +14 -0
  16. package/catalog-assets/eslint-rules/no-heavy-inline-styles.mjs +20 -0
  17. package/catalog-assets/eslint-rules/no-let.mjs +14 -0
  18. package/catalog-assets/eslint-rules/no-logic-in-jsx.mjs +23 -0
  19. package/catalog-assets/eslint-rules/no-manual-memoization.mjs +45 -0
  20. package/catalog-assets/eslint-rules/no-member-assignment.mjs +28 -0
  21. package/catalog-assets/eslint-rules/no-module-cache.mjs +40 -0
  22. package/catalog-assets/eslint-rules/no-mutating-array-methods.mjs +85 -0
  23. package/catalog-assets/eslint-rules/no-process-exit.mjs +15 -0
  24. package/catalog-assets/eslint-rules/no-state-mutation.mjs +62 -0
  25. package/catalog-assets/eslint-rules/no-unnecessary-use-client.mjs +40 -0
  26. package/catalog-assets/eslint-rules/pure-components.mjs +48 -0
  27. package/catalog-assets/eslint-rules/query-key-constant.mjs +54 -0
  28. package/catalog-assets/eslint-rules/require-disable-reason.mjs +29 -0
  29. package/catalog-assets/eslint-rules/restrict-timers.mjs +35 -0
  30. package/catalog-assets/eslint-rules/rules-of-hooks.mjs +51 -0
  31. package/catalog-assets/eslint-rules/thin-api-routes.mjs +18 -0
  32. package/catalog-assets/eslint-rules/thin-routes.mjs +18 -0
  33. package/catalog-assets/eslint-rules/virtualized-lists.mjs +32 -0
  34. package/catalog-assets/githooks/commit-msg +13 -0
  35. package/catalog-assets/githooks/pre-commit +26 -0
  36. package/catalog-assets/scripts/check-exact-deps.mjs +26 -0
  37. package/dist/cli.js +54 -0
  38. package/dist/core/app/analysis.js +6 -0
  39. package/dist/core/app/args.js +44 -0
  40. package/dist/core/app/catalog.js +20 -0
  41. package/dist/core/app/ci-plan.js +14 -0
  42. package/dist/core/app/claude.js +37 -0
  43. package/dist/core/app/commands/add-rule.js +32 -0
  44. package/dist/core/app/commands/agents-md.js +13 -0
  45. package/dist/core/app/commands/apply.js +74 -0
  46. package/dist/core/app/commands/audit.js +38 -0
  47. package/dist/core/app/commands/check.js +33 -0
  48. package/dist/core/app/commands/detect.js +16 -0
  49. package/dist/core/app/commands/init.js +124 -0
  50. package/dist/core/app/commands/learn.js +48 -0
  51. package/dist/core/app/commands/plan.js +40 -0
  52. package/dist/core/app/commands/pr-status.js +66 -0
  53. package/dist/core/app/commands/self-check.js +17 -0
  54. package/dist/core/app/git.js +75 -0
  55. package/dist/core/app/github.js +146 -0
  56. package/dist/core/app/hooks-script.js +27 -0
  57. package/dist/core/app/output.js +17 -0
  58. package/dist/core/app/run.js +32 -0
  59. package/dist/core/app/session.js +18 -0
  60. package/dist/core/app/timing.js +11 -0
  61. package/dist/core/domain/agents-md.js +92 -0
  62. package/dist/core/domain/audit-report.js +7 -0
  63. package/dist/core/domain/changes.js +8 -0
  64. package/dist/core/domain/check-report.js +23 -0
  65. package/dist/core/domain/claude-settings.js +42 -0
  66. package/dist/core/domain/constraint.js +7 -0
  67. package/dist/core/domain/diagnostics.js +3 -0
  68. package/dist/core/domain/errors.js +20 -0
  69. package/dist/core/domain/facts.js +18 -0
  70. package/dist/core/domain/init-report.js +28 -0
  71. package/dist/core/domain/json.js +43 -0
  72. package/dist/core/domain/learn.js +78 -0
  73. package/dist/core/domain/log-parse.js +99 -0
  74. package/dist/core/domain/pack-defaults.js +17 -0
  75. package/dist/core/domain/pack.js +1 -0
  76. package/dist/core/domain/pr-comment.js +45 -0
  77. package/dist/core/domain/pr-loop.js +85 -0
  78. package/dist/core/domain/profile.js +25 -0
  79. package/dist/core/domain/protection.js +43 -0
  80. package/dist/core/domain/ratchet.js +40 -0
  81. package/dist/core/domain/registry.js +32 -0
  82. package/dist/core/domain/remote.js +4 -0
  83. package/dist/core/domain/result.js +25 -0
  84. package/dist/core/domain/thresholds.js +9 -0
  85. package/dist/core/domain/types.js +1 -0
  86. package/dist/core/domain/workflows.js +252 -0
  87. package/dist/core/infra/assets.js +7 -0
  88. package/dist/core/infra/backup.js +31 -0
  89. package/dist/core/infra/baseline.js +8 -0
  90. package/dist/core/infra/changes.js +17 -0
  91. package/dist/core/infra/exec.js +14 -0
  92. package/dist/core/infra/facts.js +61 -0
  93. package/dist/core/infra/fs.js +87 -0
  94. package/dist/core/infra/gh.js +32 -0
  95. package/dist/core/infra/hooks.js +31 -0
  96. package/dist/core/infra/learn-sources.js +40 -0
  97. package/dist/core/infra/pr.js +48 -0
  98. package/dist/packs/index.js +6 -0
  99. package/dist/packs/js-ts/app/add-rule.js +116 -0
  100. package/dist/packs/js-ts/app/analysis.js +104 -0
  101. package/dist/packs/js-ts/app/bootstrap.js +16 -0
  102. package/dist/packs/js-ts/app/eslint-constraints.js +155 -0
  103. package/dist/packs/js-ts/app/eslint-files.js +56 -0
  104. package/dist/packs/js-ts/app/fixes.js +3 -0
  105. package/dist/packs/js-ts/app/pr-rules.js +30 -0
  106. package/dist/packs/js-ts/app/project.js +87 -0
  107. package/dist/packs/js-ts/app/tests.js +63 -0
  108. package/dist/packs/js-ts/domain/catalog-specs.js +147 -0
  109. package/dist/packs/js-ts/domain/ci.js +47 -0
  110. package/dist/packs/js-ts/domain/data.js +34 -0
  111. package/dist/packs/js-ts/domain/diagnostics-js.js +17 -0
  112. package/dist/packs/js-ts/domain/disables.js +11 -0
  113. package/dist/packs/js-ts/domain/eslint-output.js +46 -0
  114. package/dist/packs/js-ts/domain/eslint-state.js +80 -0
  115. package/dist/packs/js-ts/domain/hooks.js +49 -0
  116. package/dist/packs/js-ts/domain/pr-diagnostics.js +33 -0
  117. package/dist/packs/js-ts/domain/pr-tests.js +27 -0
  118. package/dist/packs/js-ts/domain/profile-pure.js +51 -0
  119. package/dist/packs/js-ts/domain/profile.js +112 -0
  120. package/dist/packs/js-ts/domain/report.js +74 -0
  121. package/dist/packs/js-ts/domain/rule-templates.js +44 -0
  122. package/dist/packs/js-ts/domain/signals.js +14 -0
  123. package/dist/packs/js-ts/domain/testing.js +33 -0
  124. package/dist/packs/js-ts/domain/ts-options.js +13 -0
  125. package/dist/packs/js-ts/index.js +50 -0
  126. package/dist/packs/js-ts/infra/eslint.js +50 -0
  127. package/dist/packs/js-ts/infra/scan.js +25 -0
  128. package/dist/packs/js-ts/infra/tsc.js +21 -0
  129. package/dist/packs/nextjs/domain/data.js +9 -0
  130. package/dist/packs/nextjs/domain/profile.js +21 -0
  131. package/dist/packs/nextjs/domain/specs.js +33 -0
  132. package/dist/packs/nextjs/index.js +23 -0
  133. package/dist/packs/node/domain/specs.js +23 -0
  134. package/dist/packs/node/index.js +26 -0
  135. package/dist/packs/react/domain/data.js +9 -0
  136. package/dist/packs/react/domain/specs.js +63 -0
  137. package/dist/packs/react/index.js +30 -0
  138. package/dist/packs/react-native/domain/specs.js +29 -0
  139. package/dist/packs/react-native/domain/testing.js +20 -0
  140. package/dist/packs/react-native/index.js +30 -0
  141. package/package.json +60 -4
@@ -0,0 +1,17 @@
1
+ const GENERIC_ESLINT_FIX = "Change the code so the rule passes. Do not add eslint-disable, @ts-ignore or any to silence it.";
2
+ const TSC_FIX = "Fix the type error at its source (correct the type or the value). Do not cast through any or use @ts-ignore.";
3
+ export function eslintDiagnostic(violation, fixes) {
4
+ return { ...violation, tool: "eslint", fix: fixes[violation.rule] ?? GENERIC_ESLINT_FIX };
5
+ }
6
+ export function tscDiagnostic(diagnostic) {
7
+ return { file: diagnostic.file, line: diagnostic.line, column: diagnostic.column, tool: "tsc", rule: diagnostic.code, message: diagnostic.message, severity: "error", fix: TSC_FIX };
8
+ }
9
+ const TSC_LINE = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/;
10
+ export function parseTscOutput(output) {
11
+ return output.split("\n").flatMap((raw) => {
12
+ const match = TSC_LINE.exec(raw.trim());
13
+ if (match === null)
14
+ return [];
15
+ return [{ file: match[1] ?? "", line: Number(match[2]), column: Number(match[3]), code: match[4] ?? "", message: match[5] ?? "" }];
16
+ });
17
+ }
@@ -0,0 +1,11 @@
1
+ const DIRECTIVE = /eslint-disable(?:-next-line|-line)?\b/;
2
+ const REASON = /\s--\s+\S/;
3
+ const TOKEN = /"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`|\/\/([^\n]*)|\/\*([\s\S]*?)\*\//g;
4
+ export function findDisableDirectives(text) {
5
+ return [...text.matchAll(TOKEN)].flatMap((match) => {
6
+ const body = match[1] ?? match[2];
7
+ if (body === undefined || !DIRECTIVE.test(body))
8
+ return [];
9
+ return [{ line: text.slice(0, match.index).split("\n").length, hasReason: REASON.test(body) }];
10
+ });
11
+ }
@@ -0,0 +1,46 @@
1
+ import { isRecord, parseStrictJson } from "../../../core/domain/json.js";
2
+ export const UNUSED_DIRECTIVE_RULE = "unused-disable-directive";
3
+ export const LINT_NOT_RUN = (error) => ({ ran: false, error, violations: [], fatal: [] });
4
+ function relative(root, file) {
5
+ return file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file;
6
+ }
7
+ function entryOf(file, message) {
8
+ const text = typeof message["message"] === "string" ? message["message"] : "";
9
+ const rule = typeof message["ruleId"] === "string" ? message["ruleId"] : text.startsWith("Unused eslint-disable directive") ? UNUSED_DIRECTIVE_RULE : null;
10
+ return {
11
+ rule,
12
+ violation: {
13
+ file,
14
+ line: typeof message["line"] === "number" ? message["line"] : 0,
15
+ column: typeof message["column"] === "number" ? message["column"] : 0,
16
+ rule: rule ?? "parse-error",
17
+ message: text,
18
+ severity: message["severity"] === 1 ? "warn" : "error",
19
+ },
20
+ };
21
+ }
22
+ function entriesOf(root, result) {
23
+ if (!isRecord(result) || typeof result["filePath"] !== "string" || !Array.isArray(result["messages"]))
24
+ return [];
25
+ const file = relative(root, result["filePath"]);
26
+ return result["messages"].filter(isRecord).map((message) => entryOf(file, message));
27
+ }
28
+ export function parseEslintJson(root, stdout) {
29
+ const parsed = parseStrictJson(stdout);
30
+ if (!parsed.ok || !Array.isArray(parsed.value))
31
+ return null;
32
+ const entries = parsed.value.flatMap((result) => entriesOf(root, result));
33
+ return {
34
+ violations: entries.filter((entry) => entry.rule !== null).map((entry) => entry.violation),
35
+ fatal: entries.filter((entry) => entry.rule === null).map((entry) => entry.violation),
36
+ };
37
+ }
38
+ export function violationsOf(outcome, rule) {
39
+ return outcome.violations.filter((violation) => violation.rule === rule);
40
+ }
41
+ export function severityOf(configured) {
42
+ const value = Array.isArray(configured) ? configured[0] : configured;
43
+ if (value === 2 || value === "error")
44
+ return "error";
45
+ return value === 1 || value === "warn" ? "warn" : "off";
46
+ }
@@ -0,0 +1,80 @@
1
+ import { GUARDRAILS_CONFIG_IMPORT } from "./profile.js";
2
+ import { isRecord, parseRecordStrict, stringifyJson } from "../../../core/domain/json.js";
3
+ import { err, ok } from "../../../core/domain/result.js";
4
+ export const PLUGIN_DIR = "eslint/guardrails";
5
+ export const RULES_JSON = `${PLUGIN_DIR}/rules.json`;
6
+ export const EMPTY_STATE = Object.freeze({ version: 1, typedParser: false, linterOptions: Object.freeze({}), rules: Object.freeze({}) });
7
+ function isLevel(value) {
8
+ return value === "error" || value === "warn" || value === "off";
9
+ }
10
+ function strings(value) {
11
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : undefined;
12
+ }
13
+ function parseEntry(value) {
14
+ if (!isRecord(value) || !isLevel(value["level"]))
15
+ return null;
16
+ const ignores = strings(value["ignores"]);
17
+ const options = Array.isArray(value["options"]) ? value["options"] : undefined;
18
+ return {
19
+ level: value["level"],
20
+ files: strings(value["files"]) ?? [],
21
+ ...(ignores === undefined ? {} : { ignores }),
22
+ ...(options === undefined ? {} : { options }),
23
+ ...(value["typed"] === true ? { typed: true } : {}),
24
+ };
25
+ }
26
+ function parseState(parsed) {
27
+ const rules = isRecord(parsed["rules"]) ? parsed["rules"] : {};
28
+ const entries = Object.entries(rules).flatMap(([name, value]) => {
29
+ const entry = parseEntry(value);
30
+ return entry === null ? [] : [[name, entry]];
31
+ });
32
+ const linter = isRecord(parsed["linterOptions"]) ? parsed["linterOptions"] : {};
33
+ const unused = linter["reportUnusedDisableDirectives"];
34
+ return {
35
+ version: 1,
36
+ typedParser: parsed["typedParser"] === true,
37
+ linterOptions: unused === "error" || unused === "warn" ? { reportUnusedDisableDirectives: unused } : {},
38
+ rules: Object.fromEntries(entries),
39
+ };
40
+ }
41
+ export function parseRulesState(text) {
42
+ if (text === null)
43
+ return ok(EMPTY_STATE);
44
+ const parsed = parseRecordStrict(text);
45
+ return parsed.ok ? ok(parseState(parsed.value)) : err(parsed.error);
46
+ }
47
+ export function serializeState(state) {
48
+ const sorted = Object.fromEntries(Object.entries(state.rules).toSorted(([a], [b]) => a.localeCompare(b)));
49
+ return stringifyJson({ ...state, rules: sorted });
50
+ }
51
+ export function withRule(state, name, entry) {
52
+ return { ...state, rules: { ...state.rules, [name]: entry } };
53
+ }
54
+ export function withLevel(state, name, level) {
55
+ const entry = state.rules[name];
56
+ return entry === undefined ? state : withRule(state, name, { ...entry, level });
57
+ }
58
+ export function renderPluginIndex(ruleIds) {
59
+ const sorted = ruleIds.toSorted();
60
+ const imports = sorted.map((id, index) => `import * as rule${index} from "./rules/${id}.mjs";`);
61
+ const entries = sorted.map((id, index) => ` ${JSON.stringify(id)}: Object.values(rule${index})[0],`);
62
+ return [...imports, "", "export const guardrailsPlugin = {", ' meta: { name: "guardrails" },', " rules: {", ...entries, " },", "};", ""].join("\n");
63
+ }
64
+ const FLAT_ARRAY_START = /export default\s+(?:[A-Za-z_$][\w$.]*\()?\s*\[/;
65
+ const WIRING_IMPORT = `import { guardrailsConfig } from "./${GUARDRAILS_CONFIG_IMPORT}";\n`;
66
+ export function wireConfigText(source) {
67
+ const match = FLAT_ARRAY_START.exec(source);
68
+ if (match === null)
69
+ return null;
70
+ const at = match.index + match[0].length;
71
+ return `${WIRING_IMPORT}${source.slice(0, at)}\n ...guardrailsConfig,${source.slice(at)}`;
72
+ }
73
+ export function newConfigText(data) {
74
+ return data.eslint.typescriptEslintPackage
75
+ ? `import tseslint from "typescript-eslint";\n${WIRING_IMPORT}\nexport default [tseslint.configs.base, ...guardrailsConfig];\n`
76
+ : null;
77
+ }
78
+ export function userConfigHasTypedParser(configText) {
79
+ return configText.includes("projectService") || /\bproject\s*:/.test(configText);
80
+ }
@@ -0,0 +1,49 @@
1
+ const PRE_COMMIT = `if [ -f pnpm-lock.yaml ]; then pm=pnpm
2
+ elif [ -f yarn.lock ]; then pm=yarn
3
+ elif [ -f bun.lock ] || [ -f bun.lockb ]; then pm=bun
4
+ else pm=npm
5
+ fi
6
+ run_exec() { if [ "$pm" = npm ]; then npx --no-install "$@"; else "$pm" exec "$@"; fi; }
7
+ has_script() { node -e 'process.exit(require("./package.json").scripts?.[process.argv[1]] ? 0 : 1)' "$1" 2>/dev/null; }
8
+
9
+ if [ -f scripts/check-exact-deps.mjs ] && git diff --cached --name-only | grep -qx 'package.json'; then
10
+ node scripts/check-exact-deps.mjs || exit 1
11
+ fi
12
+
13
+ files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^(src|app|scripts)/.*\\.(ts|tsx|js|jsx|mjs)$')
14
+
15
+ if [ -n "$files" ] && [ -f package.json ]; then
16
+ echo "pre-commit: eslint on staged files"
17
+ # shellcheck disable=SC2086
18
+ run_exec eslint $files || exit 1
19
+ fi
20
+
21
+ if has_script typecheck; then
22
+ echo "pre-commit: typecheck"
23
+ "$pm" run typecheck || exit 1
24
+ fi`;
25
+ const CLAUDE_EDIT = `if [ -f pnpm-lock.yaml ]; then pm=pnpm
26
+ elif [ -f yarn.lock ]; then pm=yarn
27
+ elif [ -f bun.lock ] || [ -f bun.lockb ]; then pm=bun
28
+ else pm=npm
29
+ fi
30
+ has_script() { node -e 'process.exit(require("./package.json").scripts?.[process.argv[1]] ? 0 : 1)' "$1" 2>/dev/null; }
31
+
32
+ if [ -x node_modules/.bin/eslint ]; then
33
+ if ! output=$(./node_modules/.bin/eslint "$file" 2>&1); then
34
+ printf 'guardrails: eslint found problems in %s. Fix the cause (each message says how). Do not add eslint-disable, @ts-ignore or any to silence it:\\n%s\\n' "$file" "$output" >&2
35
+ exit 2
36
+ fi
37
+ fi
38
+
39
+ if has_script typecheck; then
40
+ if ! output=$("$pm" run --silent typecheck 2>&1); then
41
+ printf 'guardrails: typecheck failed after editing %s. Fix the type errors below at their source:\\n%s\\n' "$file" "$output" >&2
42
+ exit 2
43
+ fi
44
+ fi`;
45
+ export const JS_TS_HOOKS = {
46
+ editPatterns: ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs"],
47
+ preCommit: () => PRE_COMMIT,
48
+ claudeEdit: () => CLAUDE_EDIT,
49
+ };
@@ -0,0 +1,33 @@
1
+ import { testCandidates } from "./pr-tests.js";
2
+ const base = { line: 1, column: 1, severity: "error", tool: "tests" };
3
+ export const MISSING_TEST_RULE = "test-next-to-logic";
4
+ export const COVERAGE_RULE = "coverage-floor";
5
+ export const COVERAGE_LOWERED_RULE = "coverage-floor-lowered";
6
+ export function missingTestDiagnostic(file) {
7
+ const [first] = testCandidates(file);
8
+ return {
9
+ ...base,
10
+ file,
11
+ rule: MISSING_TEST_RULE,
12
+ message: `${file} changed in this PR and has no test next to it`,
13
+ fix: `Create ${first ?? "<name>.test.ts"} next to ${file} covering its exported functions. Components and styles are exempt; if this file is only wiring, move the logic to a pure module.`,
14
+ };
15
+ }
16
+ export function coverageDiagnostic(floor, measured, file) {
17
+ return {
18
+ ...base,
19
+ file,
20
+ rule: COVERAGE_RULE,
21
+ message: `line coverage ${String(measured)}% is below the floor ${String(floor)}%`,
22
+ fix: "Add tests for the code you changed until coverage is back at or above the floor. The floor only goes up: never lower it.",
23
+ };
24
+ }
25
+ export function loweredDiagnostic(before, after, file) {
26
+ return {
27
+ ...base,
28
+ file,
29
+ rule: COVERAGE_LOWERED_RULE,
30
+ message: `the coverage floor went from ${String(before)}% to ${after === undefined ? "nothing" : `${String(after)}%`} in this PR`,
31
+ fix: `Restore "coverage": ${String(before)} (or higher) in ${file}. Raise coverage with tests instead of lowering the floor.`,
32
+ };
33
+ }
@@ -0,0 +1,27 @@
1
+ const LOGIC_EXTENSIONS = ["ts", "mts", "cts", "js", "mjs", "cjs"];
2
+ const EXEMPT_DIRS = ["infra", "app", "node_modules", "dist", "scripts", "eslint", "catalog-assets", "fixtures", "__mocks__", "__tests__", ".guardrails", ".github", ".claude", ".githooks"];
3
+ const EXEMPT_NAMES = ["index", "cli", "main", "types", "styles", "style", "theme"];
4
+ const nameOf = (path) => path.slice(path.lastIndexOf("/") + 1);
5
+ const extensionOf = (name) => name.slice(name.lastIndexOf(".") + 1);
6
+ const stemOf = (name) => name.slice(0, name.indexOf("."));
7
+ function isExempt(path) {
8
+ const name = nameOf(path);
9
+ const stem = stemOf(name);
10
+ const dirs = path.split("/").slice(0, -1);
11
+ return (name.endsWith(".d.ts") ||
12
+ /\.(test|spec|config|types|styles|style)\./.test(name) ||
13
+ EXEMPT_NAMES.includes(stem) ||
14
+ dirs.some((dir) => EXEMPT_DIRS.includes(dir)));
15
+ }
16
+ export function isLogicFile(path) {
17
+ return LOGIC_EXTENSIONS.includes(extensionOf(nameOf(path))) && !isExempt(path);
18
+ }
19
+ export function testCandidates(path) {
20
+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";
21
+ const stem = nameOf(path).slice(0, nameOf(path).lastIndexOf("."));
22
+ return ["test", "spec"].flatMap((kind) => [...LOGIC_EXTENSIONS, "tsx", "jsx"].map((ext) => `${dir}${stem}.${kind}.${ext}`));
23
+ }
24
+ export const isTypeOnly = (source) => !/\b(function|class|const|let|var|enum)\b|=>/.test(source.replace(/^\s*import .*$/gm, ""));
25
+ export function missingTests(changed, present, source) {
26
+ return changed.filter((path) => isLogicFile(path) && !testCandidates(path).some(present) && !isTypeOnly(source(path)));
27
+ }
@@ -0,0 +1,51 @@
1
+ const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
2
+ const EXACT_VERSION = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
3
+ const PROTOCOL_VERSION = /^(workspace|link|file|npm|catalog):/;
4
+ const ROOT_SOURCE_DIRS = ["app", "pages", "components", "lib", "hooks", "utils"];
5
+ export const HOOK_GLOBS = Object.freeze(["**/hooks/**", "**/use*.{ts,tsx}"]);
6
+ export function findLooseDependencies(pkg) {
7
+ return DEPENDENCY_FIELDS.flatMap((field) => {
8
+ const group = pkg[field];
9
+ if (typeof group !== "object" || group === null)
10
+ return [];
11
+ return Object.entries(group)
12
+ .filter(([, range]) => typeof range === "string" && !EXACT_VERSION.test(range) && !PROTOCOL_VERSION.test(range))
13
+ .map(([name, range]) => `${field}.${name}@${String(range)}`);
14
+ });
15
+ }
16
+ export function pickPackageManager(lockfiles, packageManagerField) {
17
+ if (lockfiles.includes("pnpm-lock.yaml"))
18
+ return "pnpm";
19
+ if (lockfiles.includes("yarn.lock"))
20
+ return "yarn";
21
+ if (lockfiles.includes("bun.lock") || lockfiles.includes("bun.lockb"))
22
+ return "bun";
23
+ if (lockfiles.includes("package-lock.json"))
24
+ return "npm";
25
+ const named = packageManagerField?.split("@")[0];
26
+ return named === "pnpm" || named === "yarn" || named === "bun" ? named : "npm";
27
+ }
28
+ export function cleanVersion(range) {
29
+ return range === undefined ? null : (/\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?/.exec(range)?.[0] ?? null);
30
+ }
31
+ export function sourceGlobsFor(topLevelDirs) {
32
+ if (topLevelDirs.includes("src"))
33
+ return { srcDir: "src", globs: ["src/**/*.{ts,tsx}"] };
34
+ return { srcDir: null, globs: ROOT_SOURCE_DIRS.filter((dir) => topLevelDirs.includes(dir)).map((dir) => `${dir}/**/*.{ts,tsx}`) };
35
+ }
36
+ export function packageRunCommand(pm, script) {
37
+ return pm === "npm" ? `npm run ${script}` : `${pm} run ${script}`;
38
+ }
39
+ const INSTALL_DEV = Object.freeze({
40
+ pnpm: "pnpm add -D --save-exact",
41
+ yarn: "yarn add -D --exact",
42
+ bun: "bun add -d --exact",
43
+ npm: "npm install -D --save-exact",
44
+ });
45
+ export function installDevCommand(pm, packages) {
46
+ return `${INSTALL_DEV[pm]} ${packages.join(" ")}`;
47
+ }
48
+ export function execCommand(pm, bin, args) {
49
+ const prefix = { pnpm: "pnpm exec", yarn: "yarn", bun: "bun x", npm: "npx --no-install" };
50
+ return `${prefix[pm]} ${bin} ${args}`;
51
+ }
@@ -0,0 +1,112 @@
1
+ import { isRecord, objectAt } from "../../../core/domain/json.js";
2
+ import { HOOK_GLOBS, cleanVersion, findLooseDependencies, pickPackageManager, sourceGlobsFor } from "./profile-pure.js";
3
+ export const GUARDRAILS_CONFIG_IMPORT = "eslint/guardrails/config.mjs";
4
+ export const ESLINT_FLAT_CONFIGS = ["eslint.config.mjs", "eslint.config.js", "eslint.config.cjs", "eslint.config.ts", "eslint.config.mts", "eslint.config.cts"];
5
+ const ESLINT_LEGACY_CONFIGS = [".eslintrc", ".eslintrc.json", ".eslintrc.js", ".eslintrc.cjs", ".eslintrc.yml", ".eslintrc.yaml"];
6
+ const LOCKFILES = ["pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb", "package-lock.json"];
7
+ export const LAYERS_FILE = ".guardrails/layers.json";
8
+ const VERSION_PACKAGES = ["typescript", "eslint"];
9
+ export const JS_TS_PROBE = {
10
+ paths: [
11
+ "src", "app", "pages", "src/features", "scripts/check-exact-deps.mjs", "node_modules/.bin/eslint", "node_modules/.bin/guardrails", "node_modules/.bin/tsc",
12
+ ...LOCKFILES, ...ESLINT_FLAT_CONFIGS, ...ESLINT_LEGACY_CONFIGS,
13
+ ],
14
+ json: ["package.json", "tsconfig.json", LAYERS_FILE, ...VERSION_PACKAGES.map((name) => `node_modules/${name}/package.json`)],
15
+ text: ESLINT_FLAT_CONFIGS,
16
+ tree: [{ root: "src", depth: 3 }],
17
+ };
18
+ function stringRecord(value) {
19
+ if (!isRecord(value))
20
+ return {};
21
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
22
+ }
23
+ export function installedVersion(facts, name) {
24
+ const version = facts.json[`node_modules/${name}/package.json`]?.["version"];
25
+ return typeof version === "string" ? version : null;
26
+ }
27
+ function typescriptOf(facts, deps) {
28
+ const tsconfig = facts.json["tsconfig.json"];
29
+ const options = tsconfig === undefined ? null : objectAt(tsconfig, "compilerOptions");
30
+ const strictValue = options?.["strict"];
31
+ const strict = typeof strictValue === "boolean" ? strictValue : tsconfig !== undefined && tsconfig["extends"] === undefined ? false : null;
32
+ return {
33
+ present: "typescript" in deps || tsconfig !== undefined,
34
+ version: installedVersion(facts, "typescript") ?? cleanVersion(deps["typescript"]),
35
+ tsconfig: tsconfig === undefined ? null : "tsconfig.json",
36
+ strict,
37
+ };
38
+ }
39
+ function eslintOf(facts, deps) {
40
+ const flat = ESLINT_FLAT_CONFIGS.find((file) => facts.present.includes(file)) ?? null;
41
+ const legacy = ESLINT_LEGACY_CONFIGS.find((file) => facts.present.includes(file)) ?? null;
42
+ const configText = flat === null ? "" : (facts.text[flat] ?? "");
43
+ return {
44
+ installed: facts.present.includes("node_modules/.bin/eslint"),
45
+ version: installedVersion(facts, "eslint") ?? cleanVersion(deps["eslint"]),
46
+ config: flat ?? legacy,
47
+ flat: flat !== null,
48
+ typescriptPlugin: ["typescript-eslint", "@typescript-eslint/eslint-plugin", "eslint-config-next"].some((name) => name in deps),
49
+ typescriptEslintPackage: "typescript-eslint" in deps,
50
+ guardrailsWired: configText.includes(GUARDRAILS_CONFIG_IMPORT),
51
+ };
52
+ }
53
+ function layerRoots(tree) {
54
+ const roots = tree.filter((dir) => dir.endsWith("/domain")).map((dir) => dir.slice(0, -"/domain".length));
55
+ return roots.filter((root) => tree.includes(`${root}/app`) && tree.includes(`${root}/infra`));
56
+ }
57
+ function layerRulesOf(facts) {
58
+ const rules = facts.json[LAYERS_FILE]?.["forbid"];
59
+ if (!Array.isArray(rules))
60
+ return [];
61
+ return rules.flatMap((rule) => {
62
+ if (!isRecord(rule))
63
+ return [];
64
+ const { files, source, message } = rule;
65
+ return typeof files === "string" && typeof source === "string" && typeof message === "string" ? [{ files, source, message }] : [];
66
+ });
67
+ }
68
+ function pathsOf(facts) {
69
+ const globs = sourceGlobsFor(facts.topLevel);
70
+ return {
71
+ srcDir: globs.srcDir,
72
+ featuresDir: facts.present.includes("src/features") ? "src/features" : null,
73
+ layerRoots: layerRoots(facts.tree),
74
+ sourceGlobs: globs.globs,
75
+ routeGlobs: ["**/*.config.{ts,mjs,js,cjs,mts}"],
76
+ hookGlobs: HOOK_GLOBS,
77
+ };
78
+ }
79
+ export function deriveJsTs(facts) {
80
+ const pkg = facts.json["package.json"] ?? {};
81
+ const deps = { ...stringRecord(pkg["dependencies"]), ...stringRecord(pkg["devDependencies"]) };
82
+ const scripts = stringRecord(pkg["scripts"]);
83
+ const loose = findLooseDependencies(pkg);
84
+ return {
85
+ name: typeof pkg["name"] === "string" ? pkg["name"] : "unnamed",
86
+ packageManager: pickPackageManager(facts.topLevel.filter((name) => LOCKFILES.includes(name)), typeof pkg["packageManager"] === "string" ? pkg["packageManager"] : null),
87
+ packageManagerPinned: typeof pkg["packageManager"] === "string",
88
+ typescript: typescriptOf(facts, deps),
89
+ eslint: eslintOf(facts, deps),
90
+ dependencies: Object.keys(deps),
91
+ tests: { runner: "vitest" in deps ? "vitest" : "jest" in deps ? "jest" : null },
92
+ paths: pathsOf(facts),
93
+ scripts: { lint: "lint" in scripts, typecheck: "typecheck" in scripts, test: "test" in scripts, build: "build" in scripts },
94
+ guardrails: { installed: "@whil/guardrails" in deps || facts.present.includes("node_modules/.bin/guardrails") },
95
+ exactDeps: { ok: loose.length === 0, loose, script: facts.present.includes("scripts/check-exact-deps.mjs") },
96
+ layerRules: layerRulesOf(facts),
97
+ };
98
+ }
99
+ export function describeJsTs(data) {
100
+ return [
101
+ `${data.name}: ${data.packageManager}, typescript ${data.typescript.present ? `${data.typescript.version ?? "?"}, strict ${String(data.typescript.strict)}` : "absent"}`,
102
+ `eslint: ${data.eslint.config ?? "no config"}${data.eslint.flat ? "" : " (not flat config)"}${data.eslint.installed ? "" : ", not installed"}`,
103
+ `exact deps: ${data.exactDeps.ok ? "ok" : `${data.exactDeps.loose.length} loose`}`,
104
+ ];
105
+ }
106
+ export function dependenciesOf(facts) {
107
+ const pkg = facts.json["package.json"] ?? {};
108
+ return new Set([...Object.keys(stringRecord(pkg["dependencies"])), ...Object.keys(stringRecord(pkg["devDependencies"])), ...Object.keys(stringRecord(pkg["peerDependencies"]))]);
109
+ }
110
+ export function packageField(facts, field) {
111
+ return facts.json["package.json"]?.[field];
112
+ }
@@ -0,0 +1,74 @@
1
+ import { eslintDiagnostic, tscDiagnostic } from "./diagnostics-js.js";
2
+ import { installDevCommand } from "./profile-pure.js";
3
+ export const EXACT_DEPS_RULE = "exact-deps";
4
+ export const REASON_RULE = "guardrails/require-disable-reason";
5
+ export function skippedTools(lint, tsc) {
6
+ const eslint = lint === null ? [{ tool: "eslint", reason: "eslint is not installed" }] : lint.ran ? [] : [{ tool: "eslint", reason: lint.error ?? "eslint failed to run" }];
7
+ const types = tsc === null ? [{ tool: "tsc", reason: "TypeScript not detected" }] : tsc.ran ? [] : [{ tool: "tsc", reason: tsc.error ?? "tsc failed to run" }];
8
+ return [...eslint, ...types];
9
+ }
10
+ export function dependencyDiagnostics(data) {
11
+ if (!data.exactDeps.script)
12
+ return [];
13
+ return data.exactDeps.loose.map((entry) => ({
14
+ file: "package.json",
15
+ line: 0,
16
+ column: 0,
17
+ tool: "exact-deps",
18
+ rule: EXACT_DEPS_RULE,
19
+ message: `${entry} is not an exact version`,
20
+ severity: "warn",
21
+ fix: `Pin it to the exact version in the lockfile (no ^ or ~): ${installDevCommand(data.packageManager, ["<pkg>@<exact version>"])}.`,
22
+ }));
23
+ }
24
+ export function disableDiagnostics(findings, handled) {
25
+ return findings
26
+ .filter((found) => !found.hasReason && !handled.has(`${found.file}:${found.line}`))
27
+ .map((found) => ({
28
+ file: found.file,
29
+ line: found.line,
30
+ column: 1,
31
+ tool: "disable-reason",
32
+ rule: "eslint-disable-without-reason",
33
+ message: "eslint-disable without a reason",
34
+ severity: "error",
35
+ fix: "Write `eslint-disable-next-line <rule> -- <why the rule cannot be satisfied here>`, or fix the code so no disable is needed.",
36
+ }));
37
+ }
38
+ export function toolDiagnostics(lint, tsc, fixes) {
39
+ const eslint = lint?.ran === true ? [...lint.violations, ...lint.fatal].map((violation) => eslintDiagnostic(violation, fixes)) : [];
40
+ const types = tsc?.ran === true ? tsc.diagnostics.map(tscDiagnostic) : [];
41
+ return [...eslint, ...types];
42
+ }
43
+ export function topRules(violations) {
44
+ const counts = violations.reduce((acc, violation) => ({ ...acc, [violation.rule]: (acc[violation.rule] ?? 0) + 1 }), {});
45
+ return Object.entries(counts)
46
+ .toSorted((a, b) => b[1] - a[1])
47
+ .slice(0, 15)
48
+ .map(([rule, count]) => ({ rule, count }));
49
+ }
50
+ export function rulesAt(state, level) {
51
+ return Object.entries(state.rules)
52
+ .filter(([, entry]) => entry.level === level)
53
+ .map(([name]) => name);
54
+ }
55
+ export function failingReasons(input) {
56
+ return [
57
+ ...(input.errors > 0 ? [`${input.errors} lint errors`] : []),
58
+ ...input.regressions.map((entry) => `ratchet: ${entry}`),
59
+ ...(input.disablesWithoutReason > 0 ? [`${input.disablesWithoutReason} eslint-disable without a reason`] : []),
60
+ ...(input.typeErrors !== null && input.typeErrors > 0 ? [`${input.typeErrors} type errors`] : []),
61
+ ];
62
+ }
63
+ export function ratchetDiagnostic(entry) {
64
+ return {
65
+ file: "eslint/guardrails/rules.json",
66
+ line: 0,
67
+ column: 0,
68
+ tool: "ratchet",
69
+ rule: `ratchet/${entry.rule}`,
70
+ message: `${entry.rule} has ${String(entry.count)} violations, the baseline allows ${String(entry.baseline)}. Violations of a rule at warn can only go down.`,
71
+ severity: "error",
72
+ fix: `Fix the new ${entry.rule} violations listed above (they are the warnings for this rule). When the count reaches 0 the rule is promoted to error by itself.`,
73
+ };
74
+ }
@@ -0,0 +1,44 @@
1
+ export const UNIMPLEMENTED_MARKER = "IMPLEMENTED = false";
2
+ export function renderRule(spec) {
3
+ const message = JSON.stringify(spec.message);
4
+ if (spec.selector === null) {
5
+ return [
6
+ "const IMPLEMENTED = false;",
7
+ "",
8
+ "export const rule = {",
9
+ ' meta: { type: "problem", schema: [], messages: { violation: ' + message + " } },",
10
+ " create() {",
11
+ " return IMPLEMENTED ? {} : {};",
12
+ " },",
13
+ "};",
14
+ "",
15
+ ].join("\n");
16
+ }
17
+ return [
18
+ "export const rule = {",
19
+ ' meta: { type: "problem", schema: [], messages: { violation: ' + message + " } },",
20
+ " create(context) {",
21
+ " return {",
22
+ ` ${JSON.stringify(spec.selector)}: (node) => context.report({ node, messageId: "violation" }),`,
23
+ " };",
24
+ " },",
25
+ "};",
26
+ "",
27
+ ].join("\n");
28
+ }
29
+ export function renderRuleTest(spec) {
30
+ const valid = JSON.stringify(spec.good ?? "export const ok = 1;\n");
31
+ const invalid = spec.bad === null ? "" : `\n { code: ${JSON.stringify(spec.bad)}, errors: [{ messageId: "violation" }] },\n `;
32
+ return [
33
+ 'import { rule } from "./' + spec.name + '.mjs";',
34
+ 'import { makeTester } from "./_rule-tester.mjs";',
35
+ "",
36
+ "const tester = await makeTester();",
37
+ "",
38
+ `tester.run(${JSON.stringify(spec.name)}, rule, {`,
39
+ ` valid: [{ code: ${valid} }],`,
40
+ ` invalid: [${invalid}],`,
41
+ "});",
42
+ "",
43
+ ].join("\n");
44
+ }
@@ -0,0 +1,14 @@
1
+ export const JS_TS_SIGNALS = [
2
+ { pattern: "\\bany\\b|as any", constraint: "no-any" },
3
+ { pattern: "non-null|null assertion|cannot read propert|undefined is not|of undefined|of null", constraint: "no-non-null-assertion" },
4
+ { pattern: "floating promise|unhandled (promise|rejection)|missing await|forgot to await|\\bawait\\b", constraint: "no-floating-promises" },
5
+ { pattern: "mutat|in place|side effect", constraint: "no-mutation" },
6
+ { pattern: "console\\.(log|error)|leftover log|debug log", constraint: "no-console" },
7
+ { pattern: "ts-ignore|ts-expect-error|suppress", constraint: "no-ts-ignore" },
8
+ { pattern: "type error|TS\\d{4}|typecheck|tsc", constraint: "ts-strict-max" },
9
+ { pattern: "circular|cyclic|import cycle|layer|boundar", constraint: "import-boundaries" },
10
+ { pattern: "default export", constraint: "no-default-export" },
11
+ { pattern: "too long|too complex|split (this|the) function|refactor.*function", constraint: "max-function-length" },
12
+ { pattern: "eslint-disable", constraint: "require-disable-reason" },
13
+ { pattern: "\\benum\\b", constraint: "no-enum" },
14
+ ];
@@ -0,0 +1,33 @@
1
+ import { isRecord, parseStrictJson } from "../../../core/domain/json.js";
2
+ import { jsTs } from "./data.js";
3
+ export const VITEST_SPEC = {
4
+ runner: "vitest",
5
+ packages: ["vitest", "@vitest/coverage-v8"],
6
+ configFile: "vitest.config.ts",
7
+ script: "vitest run --coverage",
8
+ coverageSummary: "coverage/coverage-summary.json",
9
+ config: (profile) => {
10
+ const dir = jsTs(profile).paths.srcDir ?? ".";
11
+ return [
12
+ 'import { defineConfig } from "vitest/config";',
13
+ "",
14
+ "export default defineConfig({",
15
+ " test: {",
16
+ ` include: ["${dir}/**/*.test.{ts,tsx}"],`,
17
+ ` coverage: { provider: "v8", reporter: ["json-summary", "text-summary"], reportsDirectory: "coverage", include: ["${dir}/**/*.{ts,tsx}"] },`,
18
+ " },",
19
+ "});",
20
+ "",
21
+ ].join("\n");
22
+ },
23
+ };
24
+ export function pickTesting(packs) {
25
+ return packs.flatMap((pack) => (pack.testing === undefined ? [] : [pack.testing])).at(-1) ?? null;
26
+ }
27
+ export function measuredLines(summary) {
28
+ const parsed = summary === null ? null : parseStrictJson(summary);
29
+ const total = parsed !== null && parsed.ok && isRecord(parsed.value) ? parsed.value["total"] : null;
30
+ const lines = isRecord(total) ? total["lines"] : null;
31
+ const pct = isRecord(lines) ? lines["pct"] : null;
32
+ return typeof pct === "number" ? pct : null;
33
+ }
@@ -0,0 +1,13 @@
1
+ export const STRICT_OPTIONS = Object.freeze({
2
+ strict: true,
3
+ noUncheckedIndexedAccess: true,
4
+ exactOptionalPropertyTypes: true,
5
+ noImplicitOverride: true,
6
+ noImplicitReturns: true,
7
+ noFallthroughCasesInSwitch: true,
8
+ });
9
+ export function missingStrictOptions(compilerOptions) {
10
+ return Object.entries(STRICT_OPTIONS)
11
+ .filter(([name, value]) => compilerOptions[name] !== value)
12
+ .map(([name]) => name);
13
+ }