workspace-conformance 1.6.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,12 +5,13 @@ import { escapePath, glob, isDynamicPattern } from "tinyglobby";
5
5
  import { ModuleKind, ModuleResolutionKind, Node, Project, ScriptTarget, SyntaxKind, ts } from "ts-morph";
6
6
  import { createJitiLoader, validateStandard } from "cosmiconfig-extends";
7
7
  import { readFile, realpath } from "node:fs/promises";
8
+ import { Range, subset, valid, validRange } from "semver";
8
9
  import { LineCounter, isMap, isNode, isScalar, isSeq, parse, parseDocument } from "yaml";
9
10
  import { execFile } from "node:child_process";
10
11
  import { findNodeAtLocation, parse as parse$1, parseTree, printParseErrorCode } from "jsonc-parser";
11
12
  import { parse as parse$2 } from "smol-toml";
12
- import { defineSection, layoutSection, loadSection } from "@exadev/config";
13
13
  import { z } from "zod";
14
+ import { defineSection, layoutSection, loadSection } from "@exadev/config";
14
15
  //#region src/files.ts
15
16
  /**
16
17
  * Directories no check descends into: installed dependencies are not the workspace's own files.
@@ -780,6 +781,317 @@ const dockerfilePackageManager = async ({ cwd, options }) => {
780
781
  }
781
782
  return violations;
782
783
  };
784
+ /**
785
+ * What every path inside the package in `dir` starts with, relative to the workspace root: `dir` and a `/`, or nothing for the root package, which holds every path. The trailing `/` keeps `packages/a` from holding `packages/ab`.
786
+ */
787
+ function packagePathPrefix(dir) {
788
+ return dir === "." ? "" : `${dir}/`;
789
+ }
790
+ /**
791
+ * Whether `path`, relative to the workspace root, is inside the package in `dir`.
792
+ */
793
+ function isInPackage(dir, path) {
794
+ return path.startsWith(packagePathPrefix(dir));
795
+ }
796
+ function segmentsOf(path) {
797
+ return path.split("/").filter((segment) => segment !== "" && segment !== ".");
798
+ }
799
+ function groupRoot(group) {
800
+ return segmentsOf(group.path ?? group.name);
801
+ }
802
+ function startsWithSegments(segments, prefix) {
803
+ return prefix.every((segment, index) => segments[index] === segment);
804
+ }
805
+ /**
806
+ * The group whose root is the longest prefix of `dir`; the first declared wins a tie. `undefined` when no group owns the directory.
807
+ */
808
+ function owningGroup(dir, groups) {
809
+ const segments = segmentsOf(dir);
810
+ let best;
811
+ let bestLength = -1;
812
+ for (const group of groups) {
813
+ const root = groupRoot(group);
814
+ if (root.length > bestLength && startsWithSegments(segments, root)) {
815
+ best = group;
816
+ bestLength = root.length;
817
+ }
818
+ }
819
+ return best;
820
+ }
821
+ function rankOf(name, group, layout) {
822
+ if (name !== void 0) {
823
+ const rule = layout.nameRanks?.find((candidate) => new RegExp(candidate.pattern, "u").test(name));
824
+ if (rule !== void 0) return rule.rank;
825
+ }
826
+ return group.rank ?? layout.defaultRank;
827
+ }
828
+ /**
829
+ * The name without its npm scope: `@scope/store-cli` gives `store-cli`.
830
+ */
831
+ function unscoped(name) {
832
+ return name.replace(/^@[^/]+\//u, "");
833
+ }
834
+ /**
835
+ * The longest slice value that is the whole unscoped name or its prefix up to a `-`.
836
+ */
837
+ function sliceByNamePrefix(name, known) {
838
+ const bare = unscoped(name);
839
+ return [...known].filter((candidate) => bare === candidate || bare.startsWith(`${candidate}-`)).sort((a, b) => b.length - a.length)[0];
840
+ }
841
+ /**
842
+ * Classify discovered packages by the layout: group, rank and slice. Pure.
843
+ *
844
+ * A package no group owns is a configuration error, because every check would otherwise skip it without saying so. Nested package directories are one too: the checks attribute a file to the package whose directory is its prefix, which is ambiguous for a package inside another. The root package holds every other directory, so it is a package only in a single-package repository. A `namePrefix` slice takes the longest slice value that a `segment` group produced and that prefixes the package's unscoped name; a package without a name has no such slice.
845
+ */
846
+ function classifyPackages(discovered, layout) {
847
+ const owned = discovered.map((found) => {
848
+ const group = owningGroup(found.dir, layout.groups);
849
+ if (group === void 0) throw new ConformanceError(`the package directory '${found.dir}' is not under any layout group's path; add a group whose path prefixes it, or narrow the workspace package globs`);
850
+ return {
851
+ found,
852
+ group
853
+ };
854
+ });
855
+ const knownSlices = /* @__PURE__ */ new Set();
856
+ for (const { found, group } of owned) if (group.slice !== void 0 && "segment" in group.slice) {
857
+ const value = segmentsOf(found.dir).slice(groupRoot(group).length)[group.slice.segment];
858
+ if (value !== void 0) knownSlices.add(value);
859
+ }
860
+ const packages = owned.map(({ found, group }) => {
861
+ let slice;
862
+ if (group.slice !== void 0 && "segment" in group.slice) slice = segmentsOf(found.dir).slice(groupRoot(group).length)[group.slice.segment];
863
+ else if (group.slice !== void 0 && found.name !== void 0) slice = sliceByNamePrefix(found.name, knownSlices);
864
+ return {
865
+ ...found,
866
+ group: group.name,
867
+ rank: rankOf(found.name, group, layout),
868
+ slice
869
+ };
870
+ });
871
+ for (const outer of packages) {
872
+ const nested = packages.find((inner) => inner.dir !== outer.dir && isInPackage(outer.dir, inner.dir));
873
+ if (nested !== void 0) throw new ConformanceError(`the package directory '${nested.dir}' is inside the package directory '${outer.dir}'; workspace packages must not nest`);
874
+ }
875
+ return packages;
876
+ }
877
+ /**
878
+ * The workspace root: `layout.root` resolved against `cwd`, or `cwd` itself.
879
+ */
880
+ function workspaceRoot(cwd, layout) {
881
+ return layout.root === void 0 ? cwd : resolve(cwd, layout.root);
882
+ }
883
+ const PNPM_WORKSPACE_FILE = "pnpm-workspace.yaml";
884
+ /**
885
+ * The `packages` list of `pnpm-workspace.yaml` in `root`, or `undefined` when there is no such file. A file that exists but cannot be read, or has no list of strings under `packages`, is a configuration error.
886
+ */
887
+ async function pnpmWorkspacePatterns(root) {
888
+ const file = join(root, PNPM_WORKSPACE_FILE);
889
+ if (!existsSync(file)) return;
890
+ let source;
891
+ try {
892
+ source = await readFile(file, "utf8");
893
+ } catch (error) {
894
+ throw new ConformanceError(`${file} cannot be read`, { cause: error });
895
+ }
896
+ const document = parse(source);
897
+ if (typeof document !== "object" || document === null || !("packages" in document) || !Array.isArray(document.packages)) throw new ConformanceError(`${file} has no 'packages' list`);
898
+ const patterns = document.packages;
899
+ if (!patterns.every((pattern) => typeof pattern === "string")) throw new ConformanceError(`${file}: every entry of 'packages' must be a string`);
900
+ return patterns;
901
+ }
902
+ /**
903
+ * The package globs: `layout.packages`, else the `packages` list of `pnpm-workspace.yaml` in `root`.
904
+ */
905
+ async function workspacePatterns(root, layout) {
906
+ if (layout.packages !== void 0) return layout.packages;
907
+ const patterns = await pnpmWorkspacePatterns(root);
908
+ if (patterns === void 0) throw new ConformanceError(`the layout has no 'packages' and ${join(root, PNPM_WORKSPACE_FILE)} does not exist`);
909
+ return patterns;
910
+ }
911
+ async function readName(manifest) {
912
+ let content;
913
+ try {
914
+ content = JSON.parse(await readFile(manifest, "utf8"));
915
+ } catch (error) {
916
+ throw new ConformanceError(`${manifest} cannot be read as JSON`, { cause: error });
917
+ }
918
+ if (typeof content === "object" && content !== null && "name" in content && typeof content.name === "string") return content.name;
919
+ }
920
+ /**
921
+ * The directories under `root` that the pnpm-style `patterns` select and that hold a `package.json`, sorted. A `!` pattern excludes. The root package is found, as {@link ROOT_PACKAGE_DIR}, when a pattern selects it (`.`, or `**`).
922
+ */
923
+ async function discoverPackages(root, patterns) {
924
+ const manifests = patterns.map((pattern) => pattern.startsWith("!") ? `!${pattern.slice(1)}/**` : `${pattern}/package.json`);
925
+ const dirs = (await glob(manifests, {
926
+ cwd: root,
927
+ dot: true,
928
+ ignore: [INSTALLED_DEPENDENCIES_GLOB],
929
+ onlyFiles: true
930
+ })).map((manifest) => {
931
+ const dir = manifest.replace(/\/?package\.json$/u, "");
932
+ return dir === "" ? "." : dir;
933
+ });
934
+ return Promise.all([...new Set(dirs)].sort().map(async (dir) => ({
935
+ dir,
936
+ name: await readName(join(root, dir, "package.json"))
937
+ })));
938
+ }
939
+ /**
940
+ * The layout's packages found under the workspace root. Finding none is a configuration error: every check that reads the packages would otherwise look at nothing and report a clean workspace.
941
+ */
942
+ async function readWorkspacePackages(cwd, layout) {
943
+ const root = workspaceRoot(cwd, layout);
944
+ const patterns = await workspacePatterns(root, layout);
945
+ const discovered = await discoverPackages(root, patterns);
946
+ if (discovered.length === 0) throw new ConformanceError(`no workspace package found: ${patterns.length === 0 ? "the package patterns are empty, so no directory is selected" : `no directory the patterns ${patterns.join(", ")} select holds a package.json`}; for a single-package repository, set the layout's packages to ['.']`);
947
+ return classifyPackages(discovered, layout);
948
+ }
949
+ //#endregion
950
+ //#region src/checks/engines-floor.ts
951
+ /**
952
+ * The pattern that selects the root package, the `package.json` in the directory the checks run in.
953
+ */
954
+ const ROOT_PACKAGE = ".";
955
+ const MANIFEST = "package.json";
956
+ const ANY_INSTALLED_COPY = {};
957
+ const DEPENDENCY_FIELDS = [
958
+ {
959
+ field: "dependencies",
960
+ noun: "dependency",
961
+ mayBeAbsent: () => false,
962
+ judgedCopy: () => ANY_INSTALLED_COPY
963
+ },
964
+ {
965
+ field: "optionalDependencies",
966
+ noun: "optional dependency",
967
+ mayBeAbsent: () => true,
968
+ judgedCopy: () => ANY_INSTALLED_COPY
969
+ },
970
+ {
971
+ field: "peerDependencies",
972
+ noun: "peer dependency",
973
+ mayBeAbsent: (manifest, name) => {
974
+ const meta = manifest["peerDependenciesMeta"];
975
+ const entry = isRecord(meta) ? meta[name] : void 0;
976
+ return isRecord(entry) && entry["optional"] === true;
977
+ },
978
+ judgedCopy: (spec) => {
979
+ const version = onlyAdmittedVersion(spec);
980
+ return version === null ? void 0 : { version };
981
+ }
982
+ }
983
+ ];
984
+ /**
985
+ * The one version `spec` admits, when it is a semver range of a single comparator naming an exact version (`1.2.3` or `=1.2.3`); `null`, as semver gives for no version, for any other range, including one of a single major, and for a spec that is not a semver range (`workspace:^`, a tag or a URL).
986
+ */
987
+ function onlyAdmittedVersion(spec) {
988
+ if (validRange(spec) === null) return null;
989
+ const [comparators, ...others] = new Range(spec).set;
990
+ if (comparators === void 0 || others.length > 0 || comparators.length !== 1) return null;
991
+ const [comparator] = comparators;
992
+ if (comparator?.operator !== "") return null;
993
+ return valid(comparator.value);
994
+ }
995
+ async function readManifest(cwd, file) {
996
+ let content;
997
+ try {
998
+ content = JSON.parse(await readFile(resolve(cwd, file), "utf8"));
999
+ } catch (error) {
1000
+ throw new ConformanceError(`${file} cannot be read as JSON`, { cause: error });
1001
+ }
1002
+ if (!isRecord(content)) throw new ConformanceError(`${file} is not a JSON object`);
1003
+ return content;
1004
+ }
1005
+ /**
1006
+ * The `engines.node` range the manifest at `file` declares, or `undefined` when it declares none. A range semver cannot parse is a configuration error, since nothing can be said about the versions it admits.
1007
+ */
1008
+ function nodeRange(manifest, file) {
1009
+ const engines = manifest["engines"];
1010
+ if (engines === void 0) return;
1011
+ if (!isRecord(engines)) throw new ConformanceError(`${file}: engines must be an object`);
1012
+ const node = engines["node"];
1013
+ if (node === void 0) return;
1014
+ if (typeof node !== "string") throw new ConformanceError(`${file}: engines.node must be a string, not ${JSON.stringify(node)}`);
1015
+ if (validRange(node) === null) throw new ConformanceError(`${file}: engines.node '${node}' is not a valid semver range`);
1016
+ return node;
1017
+ }
1018
+ /**
1019
+ * The name and version spec of each dependency a dependency field of the manifest at `file` lists, sorted by name; none when the field is absent.
1020
+ */
1021
+ function dependencyEntries(manifest, field, file) {
1022
+ const listed = manifest[field];
1023
+ if (listed === void 0) return [];
1024
+ if (!isRecord(listed)) throw new ConformanceError(`${file}: ${field} must be an object`);
1025
+ return Object.keys(listed).sort().map((name) => {
1026
+ const spec = listed[name];
1027
+ if (typeof spec !== "string") throw new ConformanceError(`${file}: ${field}.${name} must be a string, not ${JSON.stringify(spec)}`);
1028
+ return [name, spec];
1029
+ });
1030
+ }
1031
+ /**
1032
+ * The `package.json` of the dependency `name` as installed for the package in `packageDirectory`, found the way Node finds a package directory: in `node_modules` of the package's own directory, then of each directory above it, stopping at the working directory, since a copy above the workspace is not one its install put there. A symbolic link, as pnpm installs every dependency, is followed. `undefined` when no directory has it.
1033
+ */
1034
+ function installedManifest(cwd, packageDirectory, name) {
1035
+ const top = resolve(cwd);
1036
+ for (let directory = resolve(cwd, packageDirectory);; directory = dirname(directory)) {
1037
+ const candidate = join(directory, "node_modules", name, MANIFEST);
1038
+ if (existsSync(candidate)) return relativePosix(cwd, candidate);
1039
+ if (directory === top) return;
1040
+ }
1041
+ }
1042
+ /**
1043
+ * The directories of the packages to judge: those `packages` selects, else the root package and the `packages` of `pnpm-workspace.yaml`. Selecting none is a configuration error, so a pattern that matches nothing never reads as a pass.
1044
+ */
1045
+ async function packageDirectories(cwd, options) {
1046
+ const patterns = options.packages ?? [ROOT_PACKAGE, ...await pnpmWorkspacePatterns(cwd) ?? []];
1047
+ const members = await discoverPackages(cwd, patterns.filter((pattern) => pattern !== ROOT_PACKAGE));
1048
+ const directories = [...patterns.includes(ROOT_PACKAGE) ? [ROOT_PACKAGE] : [], ...members.map((member) => member.dir)];
1049
+ if (directories.length === 0) throw new ConformanceError(`no package.json is selected by ${patterns.join(", ")}`);
1050
+ return directories;
1051
+ }
1052
+ /**
1053
+ * The `engines.node` range of each package is a subset of the `engines.node` range of each dependency and optional dependency it lists, and of each peer dependency whose range admits a single version, as installed in `node_modules`, so the package admits no Node version that something it needs at run time rejects. A package that declares no range admits every version, so it is reported for each dependency that declares one. A dependency that declares no range constrains nothing and is ignored.
1054
+ *
1055
+ * The comparison is `semver.subset(package, dependency)`: every version the package's range admits satisfies the dependency's range. A floor alone is not enough, because a range of several lines (`^20.19.0 || ^22.13.0 || >=24`) also rejects the versions between them, which `>=20.19.0` admits. semver compares a range of several comparator sets set by set, so each set of the package's range must lie within one set of the dependency's; a set that only two adjacent dependency sets cover together (`>=22` against `^22.0.0 || >=23`) is reported, and splitting it the same way (`^22.0.0 || >=23`) satisfies the check.
1056
+ *
1057
+ * A peer dependency is judged only when its range admits a single version (`1.2.3` or `=1.2.3`), and then by the copy installed, which must be that version. The consumer chooses which admitted version to install, so the package's range holds when each Node version in it is accepted by some admitted version; one installed copy that rejects a Node version does not show that every admitted version does, and the others are not on disk.
1058
+ *
1059
+ * A dependency that is not installed fails the run: its range cannot be read, and passing it unjudged would read as a pass. An optional dependency and a peer dependency marked optional in `peerDependenciesMeta` may be absent and are then skipped.
1060
+ */
1061
+ const enginesFloor = async ({ cwd, options }) => {
1062
+ const violations = [];
1063
+ for (const directory of await packageDirectories(cwd, options)) {
1064
+ const file = posix.join(directory, MANIFEST);
1065
+ const manifest = await readManifest(cwd, file);
1066
+ const own = nodeRange(manifest, file);
1067
+ const seen = /* @__PURE__ */ new Set();
1068
+ for (const { field, noun, mayBeAbsent, judgedCopy } of DEPENDENCY_FIELDS) for (const [name, spec] of dependencyEntries(manifest, field, file).filter(([candidate]) => !seen.has(candidate))) {
1069
+ seen.add(name);
1070
+ const copy = judgedCopy(spec);
1071
+ if (copy === void 0) continue;
1072
+ const installed = installedManifest(cwd, directory, name);
1073
+ if (installed === void 0) {
1074
+ if (mayBeAbsent(manifest, name)) continue;
1075
+ throw new ConformanceError(`${file}: the ${noun} '${name}' is not installed (no node_modules/${name}/package.json in its directory or any directory above it up to the working directory); install the workspace before running engines-floor`);
1076
+ }
1077
+ const dependency = await readManifest(cwd, installed);
1078
+ if (copy.version !== void 0 && dependency["version"] !== copy.version) throw new ConformanceError(`${file}: the ${noun} '${name}' admits only version ${copy.version}, but ${installed} is version ${String(dependency["version"])}; install the workspace before running engines-floor`);
1079
+ const theirs = nodeRange(dependency, installed);
1080
+ if (theirs === void 0) continue;
1081
+ if (own === void 0) violations.push({
1082
+ code: "engines-floor/no-engines",
1083
+ message: `no engines.node is declared, so every Node version is admitted, but the ${noun} '${name}' requires engines.node '${theirs}'; declare a subset of that range`,
1084
+ file
1085
+ });
1086
+ else if (!subset(own, theirs)) violations.push({
1087
+ code: "engines-floor/wider-than-dependency",
1088
+ message: `engines.node '${own}' admits Node versions that the ${noun} '${name}' rejects with engines.node '${theirs}'; narrow it to a subset of that range`,
1089
+ file
1090
+ });
1091
+ }
1092
+ }
1093
+ return violations;
1094
+ };
783
1095
  //#endregion
784
1096
  //#region src/checks/eslint.ts
785
1097
  /**
@@ -886,40 +1198,61 @@ async function sampleViolations(eslint, sample, shared) {
886
1198
  function isNothingLinted(error) {
887
1199
  return error instanceof Error && isRecord(error) && (error["messageTemplate"] === "file-not-found" || error["messageTemplate"] === "all-matched-files-ignored");
888
1200
  }
1201
+ /**
1202
+ * Where a message is, or `undefined` for a message about the whole file. ESLint types `line` and `column` as numbers, but a parsing error copies them from the parser's error, which may carry none: typescript-eslint's project service reports a file outside every tsconfig that way.
1203
+ */
1204
+ function locationOf(message) {
1205
+ const line = message.line;
1206
+ const column = message.column;
1207
+ return typeof line === "number" && typeof column === "number" ? {
1208
+ line,
1209
+ column
1210
+ } : void 0;
1211
+ }
889
1212
  function messageViolation(cwd, result, message) {
890
1213
  const file = relativePosix(cwd, result.filePath);
891
- const location = {
892
- line: message.line,
893
- column: message.column
1214
+ const location = locationOf(message);
1215
+ const at = location === void 0 ? { file } : {
1216
+ file,
1217
+ location
894
1218
  };
895
1219
  if (message.ruleId !== null) {
896
1220
  const severity = message.severity === 1 ? "warn" : "error";
897
1221
  return {
898
1222
  code: `eslint/lint/${message.ruleId}`,
899
1223
  message: `${message.ruleId} (${severity}): ${message.message}`,
900
- file,
901
- location
1224
+ ...at
902
1225
  };
903
1226
  }
904
1227
  return message.fatal === true ? {
905
1228
  code: "eslint/fatal",
906
1229
  message: message.message,
907
- file,
908
- location
1230
+ ...at
909
1231
  } : {
910
1232
  code: "eslint/lint-message",
911
1233
  message: message.message,
912
- file,
913
- location
1234
+ ...at
914
1235
  };
915
1236
  }
916
1237
  function byPosition(left, right) {
917
1238
  return left.file.localeCompare(right.file) || (left.location?.line ?? 0) - (right.location?.line ?? 0) || (left.location?.column ?? 0) - (right.location?.column ?? 0) || left.code.localeCompare(right.code);
918
1239
  }
1240
+ function files(count) {
1241
+ return count === 1 ? "1 file" : `${String(count)} files`;
1242
+ }
1243
+ /**
1244
+ * The files below `cwd` that ESLint has a configuration for (not ignored, and matched by a configuration block) and that the lint did not reach: the patterns are narrower than what the config covers.
1245
+ */
1246
+ async function unreachedFiles(cwd, eslint, linted) {
1247
+ const candidates = (await findFiles(cwd, ["**"])).filter((file) => !linted.has(resolve(cwd, file)));
1248
+ const unreached = [];
1249
+ for (const file of candidates) if (!await eslint.isPathIgnored(file)) unreached.push(file);
1250
+ return unreached;
1251
+ }
919
1252
  /**
920
- * Lints the workspace through the Node API, with the repository's own config, and maps every message to a violation. A pattern that selects no linted file is itself a violation, since the workspace is then not linted at all.
1253
+ * Lints the workspace through the Node API, with the repository's own config, and maps every message to a violation. A pattern that selects no linted file is itself a violation, since the workspace is then not linted at all. It notes how many files it linted and how many files the config covers that the patterns did not reach.
921
1254
  */
922
- async function lintViolations(cwd, eslint, patterns) {
1255
+ async function lintViolations(cwd, eslint, patterns, note) {
923
1256
  const violations = [];
924
1257
  const results = /* @__PURE__ */ new Map();
925
1258
  for (const pattern of patterns) try {
@@ -933,6 +1266,10 @@ async function lintViolations(cwd, eslint, patterns) {
933
1266
  });
934
1267
  }
935
1268
  for (const result of results.values()) for (const message of result.messages) violations.push(messageViolation(cwd, result, message));
1269
+ if (note !== void 0) {
1270
+ const unreached = await unreachedFiles(cwd, eslint, new Set(results.keys()));
1271
+ note(unreached.length === 0 ? `linted ${files(results.size)}` : `linted ${files(results.size)}; ${unreached.length === 1 ? "1 other file has" : `${String(unreached.length)} other files have`} an ESLint configuration and ${unreached.length === 1 ? "was" : "were"} not reached by lintPatterns (${patterns.join(", ")})`);
1272
+ }
936
1273
  return violations.sort(byPosition);
937
1274
  }
938
1275
  /**
@@ -942,7 +1279,9 @@ async function lintViolations(cwd, eslint, patterns) {
942
1279
  *
943
1280
  * The config is a black box: the check sees which rules are active on a file, not why. It does not embed a config, so a repository without one is reported and nothing is substituted.
944
1281
  */
945
- const eslint = async ({ cwd, options }) => {
1282
+ const eslint = async (context) => {
1283
+ const { options } = context;
1284
+ const cwd = resolve(context.cwd);
946
1285
  const instance = new (loadEslint(cwd))({
947
1286
  cwd,
948
1287
  ...options.configFile === void 0 ? {} : { overrideConfigFile: resolve(cwd, options.configFile) }
@@ -950,7 +1289,7 @@ const eslint = async ({ cwd, options }) => {
950
1289
  const shared = options.rules ?? {};
951
1290
  const violations = [];
952
1291
  for (const sample of options.samples.map(sampleOf)) violations.push(...await sampleViolations(instance, sample, shared));
953
- if (options.lint === true) violations.push(...await lintViolations(cwd, instance, options.lintPatterns ?? DEFAULT_LINT_PATTERNS));
1292
+ if (options.lint === true) violations.push(...await lintViolations(cwd, instance, options.lintPatterns ?? DEFAULT_LINT_PATTERNS, context.note));
954
1293
  return violations;
955
1294
  };
956
1295
  //#endregion
@@ -960,10 +1299,10 @@ function escapeRegExp(text) {
960
1299
  return text.replace(REGEXP_SPECIAL, "\\$&");
961
1300
  }
962
1301
  /**
963
- * A regular expression, as source text, matching every file inside any of the packages. The trailing `/` keeps `packages/a` from matching `packages/ab`.
1302
+ * A regular expression, as source text, matching every file inside any of the packages: the path starts with one's {@link packagePathPrefix}.
964
1303
  */
965
1304
  function packagesPattern(packages) {
966
- return `^(${packages.map((member) => `${escapeRegExp(member.dir)}/`).join("|")})`;
1305
+ return `^(${packages.map((member) => escapeRegExp(packagePathPrefix(member.dir))).join("|")})`;
967
1306
  }
968
1307
  /**
969
1308
  * A regular expression, as source text, matching the name an import uses for any of the named packages: the name itself or a subpath of it. It matches nothing but those names, and is `undefined` when no package has a name.
@@ -1056,196 +1395,57 @@ function crossSliceRules(packages) {
1056
1395
  /**
1057
1396
  * Two rules per isolated pair, one for each direction.
1058
1397
  */
1059
- function isolatedGroupRules(packages, isolatedGroups) {
1060
- const byGroup = groupBy(packages, (member) => member.group);
1061
- return isolatedGroups.flatMap(([first, second]) => [{
1062
- from: first,
1063
- to: second
1064
- }, {
1065
- from: second,
1066
- to: first
1067
- }].flatMap(({ from, to }) => {
1068
- const own = byGroup.get(from);
1069
- const other = byGroup.get(to);
1070
- return own === void 0 || other === void 0 ? [] : forbid(`isolated-${from}-${to}`, `the '${from}' group may not import the '${to}' group`, own, other);
1071
- }));
1072
- }
1073
- /**
1074
- * The name of {@link cycleRule}, which a check reads its findings by.
1075
- */
1076
- const CYCLE_RULE_NAME = "import-cycle";
1077
- /**
1078
- * The name of {@link unresolvedNameImportRule}, which a check reads its findings by.
1079
- */
1080
- const UNRESOLVED_NAME_IMPORT_RULE_NAME = "unresolved-name-import";
1081
- /**
1082
- * The rule that forbids any import cycle among the packages' files.
1083
- */
1084
- function cycleRule() {
1085
- return {
1086
- name: CYCLE_RULE_NAME,
1087
- severity: "error",
1088
- comment: "files may not import each other in a cycle",
1089
- from: {},
1090
- to: { circular: true }
1091
- };
1092
- }
1093
- /**
1094
- * The rule that reports every import of a named package by a name that resolves to no file. It marks edges for the cycle check to follow, so a finding of it is an import and not a defect.
1095
- *
1096
- * It is `undefined` when no package has a name.
1097
- */
1098
- function unresolvedNameImportRule(packages) {
1099
- const names = packageNamesPattern(packages);
1100
- return names === void 0 ? void 0 : {
1101
- name: UNRESOLVED_NAME_IMPORT_RULE_NAME,
1102
- severity: "error",
1103
- comment: "marks an import of a workspace package by a name that resolves to no file",
1104
- from: { path: packagesPattern(packages) },
1105
- to: {
1106
- path: names,
1107
- couldNotResolve: true
1108
- }
1109
- };
1110
- }
1111
- //#endregion
1112
- //#region src/workspace/packages.ts
1113
- function segmentsOf(path) {
1114
- return path.split("/").filter((segment) => segment !== "" && segment !== ".");
1115
- }
1116
- function groupRoot(group) {
1117
- return segmentsOf(group.path ?? group.name);
1118
- }
1119
- function startsWithSegments(segments, prefix) {
1120
- return prefix.every((segment, index) => segments[index] === segment);
1121
- }
1122
- /**
1123
- * The group whose root is the longest prefix of `dir`; the first declared wins a tie. `undefined` when no group owns the directory.
1124
- */
1125
- function owningGroup(dir, groups) {
1126
- const segments = segmentsOf(dir);
1127
- let best;
1128
- let bestLength = -1;
1129
- for (const group of groups) {
1130
- const root = groupRoot(group);
1131
- if (root.length > bestLength && startsWithSegments(segments, root)) {
1132
- best = group;
1133
- bestLength = root.length;
1134
- }
1135
- }
1136
- return best;
1137
- }
1138
- function rankOf(name, group, layout) {
1139
- if (name !== void 0) {
1140
- const rule = layout.nameRanks?.find((candidate) => new RegExp(candidate.pattern, "u").test(name));
1141
- if (rule !== void 0) return rule.rank;
1142
- }
1143
- return group.rank ?? layout.defaultRank;
1144
- }
1145
- /**
1146
- * The name without its npm scope: `@scope/store-cli` gives `store-cli`.
1147
- */
1148
- function unscoped(name) {
1149
- return name.replace(/^@[^/]+\//u, "");
1150
- }
1151
- /**
1152
- * The longest slice value that is the whole unscoped name or its prefix up to a `-`.
1153
- */
1154
- function sliceByNamePrefix(name, known) {
1155
- const bare = unscoped(name);
1156
- return [...known].filter((candidate) => bare === candidate || bare.startsWith(`${candidate}-`)).sort((a, b) => b.length - a.length)[0];
1157
- }
1158
- /**
1159
- * Classify discovered packages by the layout: group, rank and slice. Pure.
1160
- *
1161
- * A package no group owns is a configuration error, because every check would otherwise skip it without saying so. Nested package directories are one too: the checks attribute a file to the package whose directory is its prefix, which is ambiguous for a package inside another. A `namePrefix` slice takes the longest slice value that a `segment` group produced and that prefixes the package's unscoped name; a package without a name has no such slice.
1162
- */
1163
- function classifyPackages(discovered, layout) {
1164
- const owned = discovered.map((found) => {
1165
- const group = owningGroup(found.dir, layout.groups);
1166
- if (group === void 0) throw new ConformanceError(`the package directory '${found.dir}' is not under any layout group's path; add a group whose path prefixes it, or narrow the workspace package globs`);
1167
- return {
1168
- found,
1169
- group
1170
- };
1171
- });
1172
- const knownSlices = /* @__PURE__ */ new Set();
1173
- for (const { found, group } of owned) if (group.slice !== void 0 && "segment" in group.slice) {
1174
- const value = segmentsOf(found.dir).slice(groupRoot(group).length)[group.slice.segment];
1175
- if (value !== void 0) knownSlices.add(value);
1176
- }
1177
- const packages = owned.map(({ found, group }) => {
1178
- let slice;
1179
- if (group.slice !== void 0 && "segment" in group.slice) slice = segmentsOf(found.dir).slice(groupRoot(group).length)[group.slice.segment];
1180
- else if (group.slice !== void 0 && found.name !== void 0) slice = sliceByNamePrefix(found.name, knownSlices);
1181
- return {
1182
- ...found,
1183
- group: group.name,
1184
- rank: rankOf(found.name, group, layout),
1185
- slice
1186
- };
1187
- });
1188
- for (const outer of packages) {
1189
- const nested = packages.find((inner) => inner.dir !== outer.dir && inner.dir.startsWith(`${outer.dir}/`));
1190
- if (nested !== void 0) throw new ConformanceError(`the package directory '${nested.dir}' is inside the package directory '${outer.dir}'; workspace packages must not nest`);
1191
- }
1192
- return packages;
1398
+ function isolatedGroupRules(packages, isolatedGroups) {
1399
+ const byGroup = groupBy(packages, (member) => member.group);
1400
+ return isolatedGroups.flatMap(([first, second]) => [{
1401
+ from: first,
1402
+ to: second
1403
+ }, {
1404
+ from: second,
1405
+ to: first
1406
+ }].flatMap(({ from, to }) => {
1407
+ const own = byGroup.get(from);
1408
+ const other = byGroup.get(to);
1409
+ return own === void 0 || other === void 0 ? [] : forbid(`isolated-${from}-${to}`, `the '${from}' group may not import the '${to}' group`, own, other);
1410
+ }));
1193
1411
  }
1194
1412
  /**
1195
- * The workspace root: `layout.root` resolved against `cwd`, or `cwd` itself.
1413
+ * The name of {@link cycleRule}, which a check reads its findings by.
1196
1414
  */
1197
- function workspaceRoot(cwd, layout) {
1198
- return layout.root === void 0 ? cwd : resolve(cwd, layout.root);
1199
- }
1415
+ const CYCLE_RULE_NAME = "import-cycle";
1200
1416
  /**
1201
- * The package globs: `layout.packages`, else the `packages` list of `pnpm-workspace.yaml` in `root`.
1417
+ * The name of {@link unresolvedNameImportRule}, which a check reads its findings by.
1202
1418
  */
1203
- async function workspacePatterns(root, layout) {
1204
- if (layout.packages !== void 0) return layout.packages;
1205
- const file = join(root, "pnpm-workspace.yaml");
1206
- let source;
1207
- try {
1208
- source = await readFile(file, "utf8");
1209
- } catch (error) {
1210
- throw new ConformanceError(`the layout has no 'packages' and ${file} cannot be read`, { cause: error });
1211
- }
1212
- const document = parse(source);
1213
- if (typeof document !== "object" || document === null || !("packages" in document) || !Array.isArray(document.packages)) throw new ConformanceError(`${file} has no 'packages' list`);
1214
- const patterns = document.packages;
1215
- if (!patterns.every((pattern) => typeof pattern === "string")) throw new ConformanceError(`${file}: every entry of 'packages' must be a string`);
1216
- return patterns;
1217
- }
1218
- async function readName(manifest) {
1219
- let content;
1220
- try {
1221
- content = JSON.parse(await readFile(manifest, "utf8"));
1222
- } catch (error) {
1223
- throw new ConformanceError(`${manifest} cannot be read as JSON`, { cause: error });
1224
- }
1225
- if (typeof content === "object" && content !== null && "name" in content && typeof content.name === "string") return content.name;
1226
- }
1419
+ const UNRESOLVED_NAME_IMPORT_RULE_NAME = "unresolved-name-import";
1227
1420
  /**
1228
- * The directories under `root` that the pnpm-style `patterns` select and that hold a `package.json`, sorted. A `!` pattern excludes. The root package itself (`.`) is not a member of any group and is left out.
1421
+ * The rule that forbids any import cycle among the packages' files.
1229
1422
  */
1230
- async function discoverPackages(root, patterns) {
1231
- const manifests = patterns.map((pattern) => pattern.startsWith("!") ? `!${pattern.slice(1)}/**` : `${pattern}/package.json`);
1232
- const dirs = (await glob(manifests, {
1233
- cwd: root,
1234
- dot: true,
1235
- ignore: [INSTALLED_DEPENDENCIES_GLOB],
1236
- onlyFiles: true
1237
- })).map((manifest) => manifest.replace(/\/?package\.json$/u, "")).filter((dir) => dir !== "");
1238
- return Promise.all([...new Set(dirs)].sort().map(async (dir) => ({
1239
- dir,
1240
- name: await readName(join(root, dir, "package.json"))
1241
- })));
1423
+ function cycleRule() {
1424
+ return {
1425
+ name: CYCLE_RULE_NAME,
1426
+ severity: "error",
1427
+ comment: "files may not import each other in a cycle",
1428
+ from: {},
1429
+ to: { circular: true }
1430
+ };
1242
1431
  }
1243
1432
  /**
1244
- * The layout's packages found under the workspace root.
1433
+ * The rule that reports every import of a named package by a name that resolves to no file. It marks edges for the cycle check to follow, so a finding of it is an import and not a defect.
1434
+ *
1435
+ * It is `undefined` when no package has a name.
1245
1436
  */
1246
- async function readWorkspacePackages(cwd, layout) {
1247
- const root = workspaceRoot(cwd, layout);
1248
- return classifyPackages(await discoverPackages(root, await workspacePatterns(root, layout)), layout);
1437
+ function unresolvedNameImportRule(packages) {
1438
+ const names = packageNamesPattern(packages);
1439
+ return names === void 0 ? void 0 : {
1440
+ name: UNRESOLVED_NAME_IMPORT_RULE_NAME,
1441
+ severity: "error",
1442
+ comment: "marks an import of a workspace package by a name that resolves to no file",
1443
+ from: { path: packagesPattern(packages) },
1444
+ to: {
1445
+ path: names,
1446
+ couldNotResolve: true
1447
+ }
1448
+ };
1249
1449
  }
1250
1450
  //#endregion
1251
1451
  //#region src/checks/import-graph.ts
@@ -1261,7 +1461,7 @@ const DEFAULT_DO_NOT_FOLLOW = ["(^|/)dist/"];
1261
1461
  * The package a path in the graph belongs to: the one whose directory holds the file, and only when no directory does, the one whose name the path is (an import that resolved to no file is known only by the name it was written with, or a subpath of it). The directory wins because an unscoped package name can equal the leading directory of another package's files. It throws `ConformanceError` for a path the graph should not contain.
1262
1462
  */
1263
1463
  function packageOfPath(packages, path) {
1264
- const found = packages.find((member) => path.startsWith(`${member.dir}/`)) ?? packages.find((member) => member.name !== void 0 && (path === member.name || path.startsWith(`${member.name}/`)));
1464
+ const found = packages.find((member) => isInPackage(member.dir, path)) ?? packages.find((member) => member.name !== void 0 && (path === member.name || path.startsWith(`${member.name}/`)));
1265
1465
  if (found === void 0) throw new ConformanceError(`${path} is in no workspace package, although the graph is limited to the packages' files and names`);
1266
1466
  return found;
1267
1467
  }
@@ -1417,7 +1617,7 @@ function describePackage(member) {
1417
1617
  */
1418
1618
  function describeTarget(edge) {
1419
1619
  const { to, toFile } = edge;
1420
- return !toFile.startsWith(`${to.dir}/`) && to.name !== void 0 && (toFile === to.name || toFile.startsWith(`${to.name}/`)) ? toFile : `${toFile} in ${describePackage(to)}`;
1620
+ return !isInPackage(to.dir, toFile) && to.name !== void 0 && (toFile === to.name || toFile.startsWith(`${to.name}/`)) ? toFile : `${toFile} in ${describePackage(to)}`;
1421
1621
  }
1422
1622
  //#endregion
1423
1623
  //#region src/checks/import-cross-slice.ts
@@ -1692,7 +1892,7 @@ async function leadsTo(cwd, file, entry, destination) {
1692
1892
  }
1693
1893
  }
1694
1894
  /**
1695
- * Each agent instruction file is tracked by git as a symbolic link (mode 120000) whose target is the README beside it, so the two cannot diverge. The link may be written in any form that resolves there (`./README.md`), and may lead through other tracked links, as in `CLAUDE.md` to `AGENTS.md` to `README.md`. It reads the index, not the working tree, so a checkout with `core.symlinks` false, where a link is written out as a plain file, is judged by what is committed.
1895
+ * Each agent instruction file is tracked by git as a symbolic link (mode 120000) whose target is the README beside it, so the two cannot diverge. A directory without a tracked README has nothing to link to, so a missing instruction file there is not reported; one that exists is still judged. The link may be written in any form that resolves there (`./README.md`), and may lead through other tracked links, as in `CLAUDE.md` to `AGENTS.md` to `README.md`. It reads the index, not the working tree, so a checkout with `core.symlinks` false, where a link is written out as a plain file, is judged by what is committed.
1696
1896
  */
1697
1897
  const instructionSymlinks = async ({ cwd, options }) => {
1698
1898
  const files = options.files ?? DEFAULT_INSTRUCTION_FILES;
@@ -1700,15 +1900,17 @@ const instructionSymlinks = async ({ cwd, options }) => {
1700
1900
  const violations = [];
1701
1901
  for (const directory of await directoriesOf(cwd, options.directories ?? ["."])) {
1702
1902
  const readme = posix.join(directory, target);
1903
+ const readmeTracked = await indexEntry(cwd, readme) !== void 0;
1703
1904
  for (const name of files) {
1704
1905
  const file = posix.join(directory, name);
1705
1906
  const entry = await indexEntry(cwd, file);
1706
- if (entry === void 0) violations.push({
1707
- code: "instruction-symlinks/missing",
1708
- message: `${file} is not tracked; commit it as a symbolic link to ${target}`,
1709
- file
1710
- });
1711
- else if (entry.mode !== "120000") violations.push({
1907
+ if (entry === void 0) {
1908
+ if (readmeTracked) violations.push({
1909
+ code: "instruction-symlinks/missing",
1910
+ message: `${file} is not tracked; commit it as a symbolic link to ${target}`,
1911
+ file
1912
+ });
1913
+ } else if (entry.mode !== "120000") violations.push({
1712
1914
  code: "instruction-symlinks/not-a-symlink",
1713
1915
  message: `${file} is committed as a regular file (mode ${entry.mode}); commit it as a symbolic link to ${target}`,
1714
1916
  file
@@ -1720,7 +1922,7 @@ const instructionSymlinks = async ({ cwd, options }) => {
1720
1922
  message: `${file} links to ${linked}; it should link to ${target}`,
1721
1923
  file
1722
1924
  });
1723
- } else if (await indexEntry(cwd, readme) === void 0) violations.push({
1925
+ } else if (!readmeTracked) violations.push({
1724
1926
  code: "instruction-symlinks/dangling",
1725
1927
  message: `${file} links to ${target}, which is not tracked`,
1726
1928
  file
@@ -1932,6 +2134,116 @@ const migrationsDirectory = async ({ cwd, options, configFiles }) => {
1932
2134
  return violations;
1933
2135
  };
1934
2136
  //#endregion
2137
+ //#region src/github.ts
2138
+ /**
2139
+ * GitHub's refusal to read a branch's rules because the repository's plan does not offer rulesets, as for a private repository on a plan without them: no ruleset applies to its branches, so a check that requires one cannot be met. The message is GitHub's own. A {@link GitHubClient} rejects `branchRules` with it, and with any other error for every other refusal.
2140
+ */
2141
+ var RulesetsUnavailableError = class extends ConformanceError {
2142
+ constructor(message, options) {
2143
+ super(message, options);
2144
+ this.name = "RulesetsUnavailableError";
2145
+ }
2146
+ };
2147
+ const repositorySchema = z.object({
2148
+ default_branch: z.string(),
2149
+ allow_rebase_merge: z.optional(z.boolean()),
2150
+ allow_squash_merge: z.optional(z.boolean()),
2151
+ allow_merge_commit: z.optional(z.boolean())
2152
+ });
2153
+ const rulesSchema = z.array(z.looseObject({
2154
+ type: z.string(),
2155
+ parameters: z.optional(z.looseObject({
2156
+ required_status_checks: z.optional(z.array(z.object({ context: z.string() }))),
2157
+ strict_required_status_checks_policy: z.optional(z.boolean()),
2158
+ required_review_thread_resolution: z.optional(z.boolean()),
2159
+ allowed_merge_methods: z.optional(z.array(z.string()))
2160
+ }))
2161
+ }));
2162
+ /**
2163
+ * The body of an error response of the REST API: `message` explains the refusal.
2164
+ */
2165
+ const errorBodySchema = z.looseObject({ message: z.string() });
2166
+ /**
2167
+ * The 403 status of a request that GitHub refuses, for a missing permission, a rate limit or a feature the plan lacks alike.
2168
+ */
2169
+ const FORBIDDEN = 403;
2170
+ /**
2171
+ * How GitHub's message starts when it refuses a request for a feature the repository's plan does not include ('Upgrade to GitHub Pro or make this repository public to enable this feature.'). The REST documentation of the branch rules endpoint lists no error status, and a 403 also means a missing permission ('Resource not accessible by personal access token') or a rate limit, so the message is the only thing that tells a plan limit apart.
2172
+ */
2173
+ const PLAN_LIMIT_PREFIX = "Upgrade to GitHub ";
2174
+ /**
2175
+ * The plan-limit refusal of a branch's rules as {@link RulesetsUnavailableError}.
2176
+ */
2177
+ const rulesRefusal = (status, githubMessage) => status === FORBIDDEN && githubMessage?.startsWith(PLAN_LIMIT_PREFIX) === true ? new RulesetsUnavailableError(githubMessage) : void 0;
2178
+ async function githubMessageOf(response) {
2179
+ const text = await response.text();
2180
+ let body;
2181
+ try {
2182
+ body = JSON.parse(text);
2183
+ } catch {
2184
+ return;
2185
+ }
2186
+ const parsed = errorBodySchema.safeParse(body);
2187
+ return parsed.success ? parsed.data.message : void 0;
2188
+ }
2189
+ const API_ROOT = "https://api.github.com";
2190
+ const API_VERSION = "2022-11-28";
2191
+ /**
2192
+ * How many rules the API returns in one page, its maximum.
2193
+ */
2194
+ const PAGE_SIZE = 100;
2195
+ /**
2196
+ * A {@link GitHubClient} over the REST API.
2197
+ */
2198
+ function createGitHubClient(options) {
2199
+ const request = options.fetch ?? fetch;
2200
+ const root = options.apiUrl ?? API_ROOT;
2201
+ async function get(path, refusal) {
2202
+ const response = await request(`${root}${path}`, { headers: {
2203
+ Accept: "application/vnd.github+json",
2204
+ Authorization: `Bearer ${options.token}`,
2205
+ "X-GitHub-Api-Version": API_VERSION
2206
+ } });
2207
+ if (!response.ok) {
2208
+ const githubMessage = await githubMessageOf(response);
2209
+ throw refusal?.(response.status, githubMessage) ?? new ConformanceError(`GET ${path} failed: ${String(response.status)} ${response.statusText}${githubMessage === void 0 ? "" : `: ${githubMessage}`}`);
2210
+ }
2211
+ return response.json();
2212
+ }
2213
+ return {
2214
+ repository: async (slug) => {
2215
+ const parsed = repositorySchema.parse(await get(`/repos/${slug.owner}/${slug.name}`));
2216
+ const { allow_rebase_merge: allowRebaseMerge, allow_squash_merge: allowSquashMerge, allow_merge_commit: allowMergeCommit } = parsed;
2217
+ if (allowRebaseMerge === void 0 || allowSquashMerge === void 0 || allowMergeCommit === void 0) throw new ConformanceError(`GET /repos/${slug.owner}/${slug.name} did not report the merge-method settings, which GitHub shows only to a token with write access to the repository`);
2218
+ return {
2219
+ defaultBranch: parsed.default_branch,
2220
+ allowRebaseMerge,
2221
+ allowSquashMerge,
2222
+ allowMergeCommit
2223
+ };
2224
+ },
2225
+ branchRules: async (slug, branch) => {
2226
+ const rules = [];
2227
+ for (let page = 1, more = true; more; page += 1) {
2228
+ const body = await get(`/repos/${slug.owner}/${slug.name}/rules/branches/${encodeURIComponent(branch)}?per_page=${String(PAGE_SIZE)}&page=${String(page)}`, rulesRefusal);
2229
+ const found = rulesSchema.parse(body);
2230
+ rules.push(...found);
2231
+ more = found.length === PAGE_SIZE;
2232
+ }
2233
+ return {
2234
+ requiredStatusChecks: rules.filter((rule) => rule.type === "required_status_checks").map((rule) => ({
2235
+ contexts: (rule.parameters?.required_status_checks ?? []).map((check) => check.context),
2236
+ strict: rule.parameters?.strict_required_status_checks_policy === true
2237
+ })),
2238
+ pullRequests: rules.filter((rule) => rule.type === "pull_request").map((rule) => ({
2239
+ requiredReviewThreadResolution: rule.parameters?.required_review_thread_resolution === true,
2240
+ allowedMergeMethods: rule.parameters?.allowed_merge_methods
2241
+ }))
2242
+ };
2243
+ }
2244
+ };
2245
+ }
2246
+ //#endregion
1935
2247
  //#region src/settings/repository.ts
1936
2248
  const SLUG = /^([^/\s]+)\/([^/\s]+)$/u;
1937
2249
  const REMOTE = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/u;
@@ -1968,6 +2280,24 @@ async function branchOf(github, slug, options) {
1968
2280
  function repositoryFile(slug) {
1969
2281
  return `${slug.owner}/${slug.name}`;
1970
2282
  }
2283
+ /**
2284
+ * The rules of the branch, or GitHub's message when the repository's plan has no rulesets, in which case no rule applies to the branch and none can be added. Any other refusal rejects.
2285
+ */
2286
+ async function branchRulesOf(github, slug, options) {
2287
+ const branch = await branchOf(github, slug, options);
2288
+ try {
2289
+ return { rules: await github.branchRules(slug, branch) };
2290
+ } catch (error) {
2291
+ if (error instanceof RulesetsUnavailableError) return { unavailable: error.message };
2292
+ throw error;
2293
+ }
2294
+ }
2295
+ /**
2296
+ * The message of a `rules-unavailable` violation: the branch rules of the repository cannot be read or enforced on its plan, so `what` cannot be required.
2297
+ */
2298
+ function rulesUnavailableMessage(file, what, githubMessage) {
2299
+ return `the branch rules of ${file} cannot be read or enforced on its plan, so ${what} cannot be required (GitHub: ${githubMessage})`;
2300
+ }
1971
2301
  //#endregion
1972
2302
  //#region src/checks/settings-merge-methods.ts
1973
2303
  const METHODS = [
@@ -1978,20 +2308,23 @@ const METHODS = [
1978
2308
  /**
1979
2309
  * Only one merge method is available for a pull request into the branch, `rebase` unless the options say otherwise. A method is available when the repository allows it and no `pull_request` rule that applies to the branch leaves it out of its allowed methods.
1980
2310
  *
2311
+ * When the repository's plan has no rulesets, no rule applies to the branch and the repository settings alone decide.
2312
+ *
1981
2313
  * Limits: it reads the repository settings and the rules of rulesets that apply to the branch; classic branch protection and a merge queue's own merge method are not read, so a repository whose queue owns the strategy is judged by what it still allows for a direct merge.
1982
2314
  */
1983
2315
  const settingsMergeMethods = async ({ cwd, options, github }) => {
1984
2316
  const slug = await repositoryOf(cwd, options);
1985
2317
  const file = repositoryFile(slug);
1986
2318
  const settings = await github.repository(slug);
1987
- const rules = await github.branchRules(slug, await branchOf(github, slug, options));
2319
+ const read = await branchRulesOf(github, slug, options);
2320
+ const pullRequests = "unavailable" in read ? [] : read.rules.pullRequests;
1988
2321
  const wanted = options.allowed ?? "rebase";
1989
2322
  const repositoryAllows = {
1990
2323
  rebase: settings.allowRebaseMerge,
1991
2324
  squash: settings.allowSquashMerge,
1992
2325
  merge: settings.allowMergeCommit
1993
2326
  };
1994
- const available = METHODS.filter((method) => repositoryAllows[method] && rules.pullRequests.every((rule) => rule.allowedMergeMethods === void 0 || rule.allowedMergeMethods.includes(method)));
2327
+ const available = METHODS.filter((method) => repositoryAllows[method] && pullRequests.every((rule) => rule.allowedMergeMethods === void 0 || rule.allowedMergeMethods.includes(method)));
1995
2328
  const violations = available.filter((method) => method !== wanted).map((method) => ({
1996
2329
  code: "settings-merge-methods/method-enabled",
1997
2330
  message: `${file} allows ${method} merges; only ${wanted} should be allowed`,
@@ -2390,14 +2723,20 @@ const REGISTRY_TOKEN_VARIABLES = ["NODE_AUTH_TOKEN", "NPM_TOKEN"];
2390
2723
  /**
2391
2724
  * The branch requires the check of every junction job of the workflows, and requires branches to be up to date before merging (strict mode). The check name of a job is its `name`, else its id.
2392
2725
  *
2393
- * The junction job is the one that reports for the whole workflow, so requiring it requires everything it needs, including jobs a path filter may skip. Codes: `no-required-checks` (no `required_status_checks` rule applies), `required-check-missing` (a junction job's check is not among the required ones), `not-strict` (no rule sets the strict policy) and `no-junction-job` (no workflow has a job with an id from `junctionJobs`).
2726
+ * The junction job is the one that reports for the whole workflow, so requiring it requires everything it needs, including jobs a path filter may skip. Codes: `no-required-checks` (no `required_status_checks` rule applies), `required-check-missing` (a junction job's check is not among the required ones), `not-strict` (no rule sets the strict policy), `no-junction-job` (no workflow has a job with an id from `junctionJobs`) and `rules-unavailable` (the repository's plan has no rulesets, so no check can be required; reported alone, with GitHub's message).
2394
2727
  *
2395
2728
  * Limits: it reads the rules of rulesets that apply to the branch; classic branch protection is not read, so a repository that uses it is reported as having no required checks. A junction job in a reusable workflow, or a name that is an expression, is not resolved.
2396
2729
  */
2397
2730
  const settingsRequiredChecks = async ({ cwd, options, github }) => {
2398
2731
  const slug = await repositoryOf(cwd, options);
2399
2732
  const file = repositoryFile(slug);
2400
- const rules = await github.branchRules(slug, await branchOf(github, slug, options));
2733
+ const read = await branchRulesOf(github, slug, options);
2734
+ if ("unavailable" in read) return [{
2735
+ code: "settings-required-checks/rules-unavailable",
2736
+ message: rulesUnavailableMessage(file, "a status check", read.unavailable),
2737
+ file
2738
+ }];
2739
+ const { rules } = read;
2401
2740
  const junctions = (await loadWorkflows(cwd, options)).flatMap((workflow) => jobsNamed(workflow, options.junctionJobs ?? DEFAULT_JUNCTION_JOBS).map((job) => ({
2402
2741
  workflow,
2403
2742
  name: job.name ?? job.id
@@ -2434,13 +2773,20 @@ const settingsRequiredChecks = async ({ cwd, options, github }) => {
2434
2773
  /**
2435
2774
  * A pull request cannot merge while a review conversation is unresolved: a `pull_request` rule that applies to the branch sets `required_review_thread_resolution`.
2436
2775
  *
2776
+ * When the repository's plan has no rulesets it reports `rules-unavailable` with GitHub's message, since nothing can require it.
2777
+ *
2437
2778
  * Limits: it reads the rules of rulesets; classic branch protection is not read.
2438
2779
  */
2439
2780
  const settingsReviewThreadResolution = async ({ cwd, options, github }) => {
2440
2781
  const slug = await repositoryOf(cwd, options);
2441
- const rules = await github.branchRules(slug, await branchOf(github, slug, options));
2782
+ const read = await branchRulesOf(github, slug, options);
2442
2783
  const file = repositoryFile(slug);
2443
- return rules.pullRequests.some((rule) => rule.requiredReviewThreadResolution) ? [] : [{
2784
+ if ("unavailable" in read) return [{
2785
+ code: "settings-review-thread-resolution/rules-unavailable",
2786
+ message: rulesUnavailableMessage(file, "resolving review conversations", read.unavailable),
2787
+ file
2788
+ }];
2789
+ return read.rules.pullRequests.some((rule) => rule.requiredReviewThreadResolution) ? [] : [{
2444
2790
  code: "settings-review-thread-resolution/not-required",
2445
2791
  message: `no rule requires review conversations to be resolved before merging on the branch of ${file}`,
2446
2792
  file
@@ -3330,6 +3676,7 @@ const checks = z.strictObject({
3330
3676
  commitlint: z.exactOptional(path),
3331
3677
  release: z.exactOptional(path)
3332
3678
  }))),
3679
+ "engines-floor": z.exactOptional(enabled(z.strictObject({ packages: z.exactOptional(paths) }))),
3333
3680
  "dockerfile-package-manager": z.exactOptional(enabled(z.strictObject({
3334
3681
  dockerfiles: z.exactOptional(paths),
3335
3682
  exclude: z.exactOptional(paths),
@@ -3419,76 +3766,6 @@ const conformanceSchema = z.strictObject({ checks });
3419
3766
  */
3420
3767
  const conformanceSection = defineSection("conformance", conformanceSchema);
3421
3768
  //#endregion
3422
- //#region src/github.ts
3423
- const repositorySchema = z.object({
3424
- default_branch: z.string(),
3425
- allow_rebase_merge: z.optional(z.boolean()),
3426
- allow_squash_merge: z.optional(z.boolean()),
3427
- allow_merge_commit: z.optional(z.boolean())
3428
- });
3429
- const rulesSchema = z.array(z.looseObject({
3430
- type: z.string(),
3431
- parameters: z.optional(z.looseObject({
3432
- required_status_checks: z.optional(z.array(z.object({ context: z.string() }))),
3433
- strict_required_status_checks_policy: z.optional(z.boolean()),
3434
- required_review_thread_resolution: z.optional(z.boolean()),
3435
- allowed_merge_methods: z.optional(z.array(z.string()))
3436
- }))
3437
- }));
3438
- const API_ROOT = "https://api.github.com";
3439
- const API_VERSION = "2022-11-28";
3440
- /**
3441
- * How many rules the API returns in one page, its maximum.
3442
- */
3443
- const PAGE_SIZE = 100;
3444
- /**
3445
- * A {@link GitHubClient} over the REST API.
3446
- */
3447
- function createGitHubClient(options) {
3448
- const request = options.fetch ?? fetch;
3449
- const root = options.apiUrl ?? API_ROOT;
3450
- async function get(path) {
3451
- const response = await request(`${root}${path}`, { headers: {
3452
- Accept: "application/vnd.github+json",
3453
- Authorization: `Bearer ${options.token}`,
3454
- "X-GitHub-Api-Version": API_VERSION
3455
- } });
3456
- if (!response.ok) throw new ConformanceError(`GET ${path} failed: ${String(response.status)} ${response.statusText}`);
3457
- return response.json();
3458
- }
3459
- return {
3460
- repository: async (slug) => {
3461
- const parsed = repositorySchema.parse(await get(`/repos/${slug.owner}/${slug.name}`));
3462
- const { allow_rebase_merge: allowRebaseMerge, allow_squash_merge: allowSquashMerge, allow_merge_commit: allowMergeCommit } = parsed;
3463
- if (allowRebaseMerge === void 0 || allowSquashMerge === void 0 || allowMergeCommit === void 0) throw new ConformanceError(`GET /repos/${slug.owner}/${slug.name} did not report the merge-method settings, which GitHub shows only to a token with write access to the repository`);
3464
- return {
3465
- defaultBranch: parsed.default_branch,
3466
- allowRebaseMerge,
3467
- allowSquashMerge,
3468
- allowMergeCommit
3469
- };
3470
- },
3471
- branchRules: async (slug, branch) => {
3472
- const rules = [];
3473
- for (let page = 1, more = true; more; page += 1) {
3474
- const found = rulesSchema.parse(await get(`/repos/${slug.owner}/${slug.name}/rules/branches/${encodeURIComponent(branch)}?per_page=${String(PAGE_SIZE)}&page=${String(page)}`));
3475
- rules.push(...found);
3476
- more = found.length === PAGE_SIZE;
3477
- }
3478
- return {
3479
- requiredStatusChecks: rules.filter((rule) => rule.type === "required_status_checks").map((rule) => ({
3480
- contexts: (rule.parameters?.required_status_checks ?? []).map((check) => check.context),
3481
- strict: rule.parameters?.strict_required_status_checks_policy === true
3482
- })),
3483
- pullRequests: rules.filter((rule) => rule.type === "pull_request").map((rule) => ({
3484
- requiredReviewThreadResolution: rule.parameters?.required_review_thread_resolution === true,
3485
- allowedMergeMethods: rule.parameters?.allowed_merge_methods
3486
- }))
3487
- };
3488
- }
3489
- };
3490
- }
3491
- //#endregion
3492
3769
  //#region src/registry.ts
3493
3770
  /**
3494
3771
  * The options of an enabled check, or `undefined` when the setting is absent or `false`.
@@ -3503,12 +3780,13 @@ function plain(spec) {
3503
3780
  requiresLayout: false,
3504
3781
  requiresGitHub: false,
3505
3782
  isEnabled: (checks) => spec.select(checks) !== void 0,
3506
- run: async ({ cwd, checks, configFiles }) => {
3783
+ run: async ({ cwd, checks, configFiles, note }) => {
3507
3784
  const options = spec.select(checks);
3508
3785
  if (options === void 0) throw new ConformanceError(`the check '${spec.name}' is not enabled`);
3509
3786
  return spec.check({
3510
3787
  cwd,
3511
3788
  options,
3789
+ note,
3512
3790
  ...configFiles === void 0 ? {} : { configFiles }
3513
3791
  });
3514
3792
  }
@@ -3521,7 +3799,7 @@ function online(spec) {
3521
3799
  requiresLayout: false,
3522
3800
  requiresGitHub: true,
3523
3801
  isEnabled: (checks) => spec.select(checks) !== void 0,
3524
- run: async ({ cwd, checks, configFiles, github }) => {
3802
+ run: async ({ cwd, checks, configFiles, github, note }) => {
3525
3803
  const options = spec.select(checks);
3526
3804
  if (options === void 0) throw new ConformanceError(`the check '${spec.name}' is not enabled`);
3527
3805
  if (github === void 0) throw new ConformanceError(`the check '${spec.name}' reads the repository's settings and needs a GitHub client`);
@@ -3529,6 +3807,7 @@ function online(spec) {
3529
3807
  cwd,
3530
3808
  options,
3531
3809
  github,
3810
+ note,
3532
3811
  ...configFiles === void 0 ? {} : { configFiles }
3533
3812
  });
3534
3813
  }
@@ -3623,6 +3902,12 @@ const registry = {
3623
3902
  select: (checks) => enabledOptions(checks["commit-types"]),
3624
3903
  check: commitTypes
3625
3904
  }),
3905
+ "engines-floor": plain({
3906
+ name: "engines-floor",
3907
+ description: "A package's engines.node range admits no Node version that one of its installed dependencies rejects",
3908
+ select: (checks) => enabledOptions(checks["engines-floor"]),
3909
+ check: enginesFloor
3910
+ }),
3626
3911
  "dockerfile-package-manager": plain({
3627
3912
  name: "dockerfile-package-manager",
3628
3913
  description: "A package manager version pinned in a Dockerfile is the version packageManager names",
@@ -3747,7 +4032,7 @@ async function conformanceOf(options) {
3747
4032
  cwd: options.cwd
3748
4033
  });
3749
4034
  if (loaded === void 0) throw new ConformanceError(`no 'conformance' section in ${options.cwd}; define it in exadev.config.ts or in exadev.conformance.config.ts`);
3750
- return loaded;
4035
+ return loaded.value;
3751
4036
  }
3752
4037
  async function layoutOf(options, needed) {
3753
4038
  if (options.layout !== void 0) return validateStandard(layoutSection.schema, options.layout, `'${layoutSection.name}' section passed to runChecks`);
@@ -3757,7 +4042,7 @@ async function layoutOf(options, needed) {
3757
4042
  cwd: options.cwd
3758
4043
  });
3759
4044
  if (loaded === void 0) throw new ConformanceError(`${needed.join(", ")} read the workspace layout, and there is no 'layout' section in ${options.cwd}; define it in exadev.config.ts or in exadev.layout.config.ts`);
3760
- return loaded;
4045
+ return loaded.value;
3761
4046
  }
3762
4047
  function selected(config, requested, online) {
3763
4048
  const enabled = checkNames.filter((name) => registry[name].isEnabled(config.checks));
@@ -3807,7 +4092,11 @@ function readImported(imported, name) {
3807
4092
  *
3808
4093
  * Violations do not throw. It throws `ConformanceError` when the checks cannot run (nothing enabled, a requested check disabled, a section missing) and `ConfigValidationError` when a section fails its schema, whether it was loaded from `cwd` or passed in.
3809
4094
  */
3810
- async function runChecks(options) {
4095
+ async function runChecks(given) {
4096
+ const options = {
4097
+ ...given,
4098
+ cwd: resolve(given.cwd)
4099
+ };
3811
4100
  const config = await conformanceOf(options);
3812
4101
  const names = selected(config, options.checks, options.github !== void 0);
3813
4102
  const layout = await layoutOf(options, names.filter((name) => registry[name].requiresLayout));
@@ -3815,16 +4104,22 @@ async function runChecks(options) {
3815
4104
  const results = [];
3816
4105
  for (const name of names) {
3817
4106
  const check = registry[name];
4107
+ const notes = [];
4108
+ const note = (text) => {
4109
+ notes.push(text);
4110
+ };
3818
4111
  const violations = "run" in check ? await check.run({
3819
4112
  cwd: options.cwd,
3820
4113
  checks: config.checks,
3821
4114
  layout,
3822
4115
  configFiles: options.configFiles,
3823
- github: options.github
4116
+ github: options.github,
4117
+ note
3824
4118
  }) : readImported(imported, name);
3825
4119
  results.push({
3826
4120
  check: name,
3827
- violations
4121
+ violations,
4122
+ notes
3828
4123
  });
3829
4124
  }
3830
4125
  const violations = results.flatMap((result) => result.violations);
@@ -3928,4 +4223,4 @@ function proveExhaustive(input) {
3928
4223
  }) };
3929
4224
  }
3930
4225
  //#endregion
3931
- export { ConformanceError, DEFAULT_DERIVED_TYPE_INFERENCES, DEFAULT_INFERENCES, DEFAULT_WORKFLOWS, EXIT_CODES, ExhaustivenessError, PRESET_COMMIT_TYPES, accessOf, aggregateMappers, checkNames, classifyPackages, codecPairs, commandTypes, commitTypes, conformanceSchema, conformanceSection, createGitHubClient, crossSliceRules, cycleRule, deployTools, derivedTypes, dockerfilePackageManager, effectiveEnv, effectivePermissions, eslint, generators, handlerCases, importCrossSlice, importCycles, importIsolatedGroups, importRankSkip, importUphill, instructionSymlinks, isCheckName, isolatedGroupRules, loadWorkflows, migrationsDirectory, packagesPattern, parseUses, parseWorkflow, proveExhaustive, rankSkipRules, registry, removeCase, runChecks, settingsMergeMethods, settingsRequiredChecks, settingsReviewThreadResolution, singleStorybook, transitiveNeeds, typeErrors, uphillRules, workflowActionPinning, workflowCredentials, workflowJobOrdering, workflowMergeGroup, workflowReleaseJob, workflowRepositoryDispatch, workflowRunnerResolution, workflowSkippableJobs, workflowUpdateBotCooldown, workflowVersionSingleSource };
4226
+ export { ConformanceError, DEFAULT_DERIVED_TYPE_INFERENCES, DEFAULT_INFERENCES, DEFAULT_WORKFLOWS, EXIT_CODES, ExhaustivenessError, PRESET_COMMIT_TYPES, RulesetsUnavailableError, accessOf, aggregateMappers, checkNames, classifyPackages, codecPairs, commandTypes, commitTypes, conformanceSchema, conformanceSection, createGitHubClient, crossSliceRules, cycleRule, deployTools, derivedTypes, dockerfilePackageManager, effectiveEnv, effectivePermissions, enginesFloor, eslint, generators, handlerCases, importCrossSlice, importCycles, importIsolatedGroups, importRankSkip, importUphill, instructionSymlinks, isCheckName, isolatedGroupRules, loadWorkflows, migrationsDirectory, packagesPattern, parseUses, parseWorkflow, proveExhaustive, rankSkipRules, registry, removeCase, runChecks, settingsMergeMethods, settingsRequiredChecks, settingsReviewThreadResolution, singleStorybook, transitiveNeeds, typeErrors, uphillRules, workflowActionPinning, workflowCredentials, workflowJobOrdering, workflowMergeGroup, workflowReleaseJob, workflowRepositoryDispatch, workflowRunnerResolution, workflowSkippableJobs, workflowUpdateBotCooldown, workflowVersionSingleSource };