@rtorcato/repo-tooling 3.7.4 → 3.8.1

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.
@@ -17,7 +17,7 @@ import { checkGitIdentity } from '../../base/git-identity.js';
17
17
  import { LOCKFILE_VERSION, readLockfile } from '../utils/lockfile.js';
18
18
  import { declinedInLock, getFixTargetForCheck } from './fix-targets.js';
19
19
  import { checkAiSetup, checkCodeowners, checkCodeQL, checkCommunityHealth, checkCoverageUpload, checkDependabot, checkEditorConfig, checkFile, checkGitHooks, checkGitHubActions, checkGitLabCI, checkNestedLanguages, checkPrePushHook, checkReadmeBadges, COMMITLINT_FILE_CHECK, } from '../../base/checks.js';
20
- import { allDeps, checkAreTheTypesWrong, checkConfigSchemaVersions, checkDocsSite, checkEnginesNode, checkGitDependencies, checkKnip, checkLintStaged, checkNodeVersionConsistency, checkNodeVersionPin, checkPackageJson, checkPublint, checkSemanticRelease, checkSizeLimit, checkTailwind, checkBuildApprovals, checkPnpmWorkspace, checkTreeshakeSetup, checkTurborepo, checkTypedoc, checkVerifyScript, checkVscodeExtensions, evaluateNodeVersion, FILE_CHECKS, findDocsAppDir, jsBadgeAudience, jsGitHooksProfile, readPackageJson, } from '../../languages/js/checks.js';
20
+ import { allDeps, checkAreTheTypesWrong, checkConfigSchemaVersions, checkDocsSite, checkEnginesNode, checkGitDependencies, checkKnip, checkLintStaged, checkNodeVersionConsistency, checkNodeVersionPin, checkPackageJson, checkPackageManager, checkPublint, checkSemanticRelease, checkSizeLimit, checkTailwind, checkBuildApprovals, checkPnpmWorkspace, checkTreeshakeSetup, checkTurborepo, checkTypedoc, checkVerifyScript, checkVscodeExtensions, evaluateNodeVersion, FILE_CHECKS, findDocsAppDir, jsBadgeAudience, jsGitHooksProfile, readPackageJson, } from '../../languages/js/checks.js';
21
21
  export { evaluateNodeVersion };
22
22
  const PACKAGE = '@rtorcato/repo-tooling';
23
23
  // Detects the broken-release-on-protected-main footgun: a workflow that runs
@@ -282,6 +282,7 @@ export async function runDoctor(dir) {
282
282
  results.push(evaluateNodeVersion(process.version));
283
283
  results.push(checkPackageJson(pkg));
284
284
  results.push(checkEnginesNode(pkg));
285
+ results.push(await checkPackageManager(targetDir, pkg));
285
286
  results.push(await checkConfigSchemaVersions(targetDir, pkg));
286
287
  results.push(checkGitDependencies(pkg));
287
288
  results.push(await checkVscodeExtensions(targetDir));
@@ -1,6 +1,7 @@
1
1
  export const FIX_TARGETS = {
2
2
  'package.json': 'package-json',
3
3
  'engines.node': 'engines',
4
+ packageManager: 'engines',
4
5
  EditorConfig: 'editorconfig',
5
6
  'VS Code extensions': 'vscode-extensions',
6
7
  'Node version pin': 'nvmrc',
@@ -156,6 +156,38 @@ export function checkPackageJson(pkg) {
156
156
  hint: `Run \`pnpm add -D ${PACKAGE}\``,
157
157
  };
158
158
  }
159
+ /**
160
+ * Whether the repo installs with pnpm. Three independent signals, any of which
161
+ * is enough: the workspace file, the lockfile, or a `packageManager` that
162
+ * already names pnpm. Shared so `packageManager` and `pnpm settings` agree on
163
+ * what "a pnpm repo" means.
164
+ */
165
+ export async function usesPnpm(dir, pkg) {
166
+ return ((await fs.pathExists(path.join(dir, WORKSPACE_FILE))) ||
167
+ (await fs.pathExists(path.join(dir, 'pnpm-lock.yaml'))) ||
168
+ (pkg?.packageManager ?? '').startsWith('pnpm'));
169
+ }
170
+ /**
171
+ * `packageManager` pins the pnpm that `pnpm/action-setup` resolves (#364). The
172
+ * generated workflow passes no `version:` input, so a pnpm repo without this
173
+ * field fails CI at setup — before a single check runs (#372).
174
+ */
175
+ export async function checkPackageManager(dir, pkg) {
176
+ const check = 'packageManager';
177
+ if (!(await usesPnpm(dir, pkg))) {
178
+ return { check, status: 'ok', detail: 'not a pnpm repo' };
179
+ }
180
+ const declared = pkg?.packageManager ?? '';
181
+ if (declared.trim() !== '') {
182
+ return { check, status: 'ok', detail: `packageManager = ${declared}` };
183
+ }
184
+ return {
185
+ check,
186
+ status: 'drift',
187
+ detail: 'packageManager not set in package.json',
188
+ hint: `Run \`npx ${PACKAGE} fix engines\` to pin the pnpm version CI resolves`,
189
+ };
190
+ }
159
191
  export function checkEnginesNode(pkg) {
160
192
  if (!pkg) {
161
193
  return {
@@ -844,10 +876,7 @@ export async function checkPnpmWorkspace(dir, pkg) {
844
876
  const hint = `Run \`npx ${PACKAGE} fix pnpm-workspace\` to merge them in`;
845
877
  const file = path.join(dir, WORKSPACE_FILE);
846
878
  const exists = await fs.pathExists(file);
847
- const usesPnpm = exists ||
848
- (await fs.pathExists(path.join(dir, 'pnpm-lock.yaml'))) ||
849
- (pkg?.packageManager ?? '').startsWith('pnpm');
850
- if (!usesPnpm) {
879
+ if (!(await usesPnpm(dir, pkg))) {
851
880
  return { check, status: 'ok', detail: 'not a pnpm repo' };
852
881
  }
853
882
  const yaml = exists ? await fs.readFile(file, 'utf-8') : '';
@@ -894,17 +923,74 @@ export function decidedBuilds(yaml) {
894
923
  return decided;
895
924
  }
896
925
  /**
897
- * Direct dependencies whose install would run a build script (#364).
926
+ * Package name encoded in a `node_modules/.pnpm` directory name (#373).
927
+ *
928
+ * Entries read `<name>@<version>` with `/` written as `+`, and the version may
929
+ * carry a peer suffix that contains further `@`s
930
+ * (`@babel+core@7.0.0_supports-color@8.0.0`), so the separator is the *first*
931
+ * `@` after index 0 — never the last.
932
+ */
933
+ export function pnpmStoreDirToName(entry) {
934
+ const at = entry.indexOf('@', 1);
935
+ if (at < 1)
936
+ return null;
937
+ return entry.slice(0, at).replace('+', '/');
938
+ }
939
+ /**
940
+ * Transitive packages that ship a build script and have no decision (#373).
941
+ *
942
+ * One `package.json` read per unique name — never a recursive walk — and the
943
+ * whole pass is skipped when `.pnpm` is absent (npm/yarn repos, or nothing
944
+ * installed). `skip` drops the names the direct pass already owns.
945
+ */
946
+ async function undecidedTransitiveBuilds(modulesDir, skip) {
947
+ const store = path.join(modulesDir, '.pnpm');
948
+ if (!(await fs.pathExists(store)))
949
+ return [];
950
+ const seen = new Set();
951
+ const undecided = new Set();
952
+ for (const entry of await fs.readdir(store)) {
953
+ const name = pnpmStoreDirToName(entry);
954
+ // A package present at two versions has two store dirs; report it once.
955
+ if (!name || seen.has(name) || skip(name))
956
+ continue;
957
+ seen.add(name);
958
+ // Store directory names come from registry metadata, and only the *first*
959
+ // `+` is decoded — the rest of the entry passes through literally, so a
960
+ // hostile name (`..+..@1.0.0` → `../..`) would climb out of the package
961
+ // directory and have `fs.readJson` read an unrelated file, whose `name`
962
+ // then lands in the report. Confirm the resolved path stays under this
963
+ // entry's `node_modules` before reading it.
964
+ const root = path.resolve(store, entry, 'node_modules');
965
+ const target = path.join(root, name, 'package.json');
966
+ if (!target.startsWith(root + path.sep))
967
+ continue;
968
+ let depPkg;
969
+ try {
970
+ depPkg = await fs.readJson(target);
971
+ }
972
+ catch {
973
+ continue;
974
+ }
975
+ const scripts = depPkg.scripts ?? {};
976
+ // `name` from the manifest is exact; the decoded dir name is the fallback.
977
+ if (BUILD_LIFECYCLE_SCRIPTS.some((s) => scripts[s]))
978
+ undecided.add(depPkg.name ?? name);
979
+ }
980
+ return [...undecided].filter((n) => !skip(n)).sort();
981
+ }
982
+ /**
983
+ * Dependencies whose install would run a build script (#364, #373).
898
984
  *
899
985
  * pnpm 11 turned undecided build scripts into a hard error, so
900
986
  * `pnpm install --frozen-lockfile` exits non-zero with ERR_PNPM_IGNORED_BUILDS
901
987
  * — a guaranteed CI failure. Locally the same message reads as advisory, which
902
988
  * is exactly why it gets missed until the pipeline goes red.
903
989
  *
904
- * Only direct dependencies are inspected: reaching transitive ones means
905
- * walking node_modules/.pnpm, and the packages that trip this in practice
906
- * (better-sqlite3, @prisma/client, esbuild) are ones the repo asked for by
907
- * name. A transitive offender is a false negative, never a false positive.
990
+ * Direct and transitive offenders are graded apart. A direct one is `drift`:
991
+ * the repo asked for the package by name and can answer for it. A transitive
992
+ * one is `optional-missing` — still worth recording, but common enough that
993
+ * grading it as drift would drown the report in noise.
908
994
  */
909
995
  export async function checkBuildApprovals(dir, pkg) {
910
996
  const check = 'pnpm build approvals';
@@ -935,13 +1021,19 @@ export async function checkBuildApprovals(dir, pkg) {
935
1021
  if (BUILD_LIFECYCLE_SCRIPTS.some((s) => scripts[s]))
936
1022
  undecided.push(name);
937
1023
  }
938
- if (undecided.length === 0) {
1024
+ const transitive = await undecidedTransitiveBuilds(modulesDir, (name) => decided.has(name) || name in deps);
1025
+ if (undecided.length === 0 && transitive.length === 0) {
939
1026
  return { check, status: 'ok', detail: 'every dependency with a build script has a decision' };
940
1027
  }
1028
+ const parts = [];
1029
+ if (undecided.length)
1030
+ parts.push(`${undecided.length} dependenc${undecided.length === 1 ? 'y' : 'ies'} with undecided build scripts: ${undecided.join(', ')}`);
1031
+ if (transitive.length)
1032
+ parts.push(`${transitive.length} transitive dependenc${transitive.length === 1 ? 'y' : 'ies'} with undecided build scripts: ${transitive.join(', ')}`);
941
1033
  return {
942
1034
  check,
943
- status: 'drift',
944
- detail: `${undecided.length} dependenc${undecided.length === 1 ? 'y' : 'ies'} with undecided build scripts: ${undecided.join(', ')}`,
1035
+ status: undecided.length ? 'drift' : 'optional-missing',
1036
+ detail: parts.join('; '),
945
1037
  hint: `Record a decision per package under \`allowBuilds:\` in ${WORKSPACE_FILE} (\`name: true\` to run it, \`false\` to skip). pnpm 11 fails \`pnpm install --frozen-lockfile\` outright while any is undecided, so CI cannot pass until each is answered.`,
946
1038
  };
947
1039
  }
@@ -10,6 +10,7 @@ import { GH_WORKFLOWS, generateGhWorkflow } from '../../cli/generators/github-wo
10
10
  import { BIOME_CONFIG, generateBiomeConfig, generateESLintConfig, generatePrettierConfig, } from '../../cli/generators/linting.js';
11
11
  import { alignNodeVersion, ensureEnginesNode, ensurePackageManager, generateKnipConfig, generateNvmrc, generateSizeLimitConfig, generateVscodeExtensions, } from '../../cli/generators/misc.js';
12
12
  import { scriptsOf } from './ci.js';
13
+ import { usesPnpm } from './checks.js';
13
14
  import { composeVerifyScriptFromPkg, ensureScripts } from '../../cli/generators/package-json.js';
14
15
  /** Kept in step with the biome branch of getScripts() in package-json.ts. */
15
16
  const BIOME_SCRIPTS = {
@@ -18,6 +19,15 @@ const BIOME_SCRIPTS = {
18
19
  check: 'biome check .',
19
20
  'check:fix': 'biome check --fix .',
20
21
  };
22
+ /** Kept in step with the eslint branch of getScripts() in package-json.ts. */
23
+ const ESLINT_SCRIPTS = {
24
+ lint: 'eslint .',
25
+ 'lint:fix': 'eslint . --fix',
26
+ };
27
+ /** Kept in step with the eslint branch of getScripts() in package-json.ts. */
28
+ const PRETTIER_SCRIPTS = {
29
+ format: 'prettier --write .',
30
+ };
21
31
  import { WORKSPACE_FILE, dependsOnEsbuild, ensurePnpmSettings, familyGlob, } from '../../cli/generators/pnpm-workspace.js';
22
32
  import { generatePostcss } from '../../cli/generators/postcss.js';
23
33
  import { generateCypressConfig, generateVitestConfig } from '../../cli/generators/testing.js';
@@ -151,24 +161,32 @@ export const FIXERS = [
151
161
  },
152
162
  {
153
163
  target: 'eslint',
154
- description: 'Scaffold eslint.config.mjs importing the @rtorcato/repo-tooling preset',
164
+ description: 'Scaffold eslint.config.mjs importing the @rtorcato/repo-tooling preset, plus the scripts that run it',
155
165
  appliesTo: ['ESLint'],
156
- outputs: ['eslint.config.mjs'],
166
+ outputs: ['eslint.config.mjs', 'package.json (scripts)'],
157
167
  canFixDrift: true,
158
168
  async run({ targetDir, pkg }) {
159
169
  await generateESLintConfig(inferProjectConfig(pkg), targetDir);
160
- return { filesWritten: ['eslint.config.mjs'] };
170
+ const filesWritten = ['eslint.config.mjs'];
171
+ // Without `lint` the generated CI drops its lint step and `fix verify`
172
+ // composes a chain with no linting in it at all (#371).
173
+ if (await ensureScripts(targetDir, ESLINT_SCRIPTS))
174
+ filesWritten.push('package.json');
175
+ return { filesWritten };
161
176
  },
162
177
  },
163
178
  {
164
179
  target: 'prettier',
165
- description: 'Scaffold prettier.config.mjs re-exporting the preset',
180
+ description: 'Scaffold prettier.config.mjs re-exporting the preset, plus the `format` script',
166
181
  appliesTo: ['Prettier'],
167
- outputs: ['prettier.config.mjs'],
182
+ outputs: ['prettier.config.mjs', 'package.json (scripts)'],
168
183
  canFixDrift: true,
169
184
  async run({ targetDir }) {
170
185
  await generatePrettierConfig(targetDir);
171
- return { filesWritten: ['prettier.config.mjs'] };
186
+ const filesWritten = ['prettier.config.mjs'];
187
+ if (await ensureScripts(targetDir, PRETTIER_SCRIPTS))
188
+ filesWritten.push('package.json');
189
+ return { filesWritten };
172
190
  },
173
191
  },
174
192
  {
@@ -459,14 +477,22 @@ export const FIXERS = [
459
477
  },
460
478
  {
461
479
  target: 'engines',
462
- description: 'Add engines.node to package.json',
463
- appliesTo: ['engines.node'],
464
- outputs: ['package.json (engines.node field)'],
480
+ description: 'Add engines.node and packageManager to package.json',
481
+ appliesTo: ['engines.node', 'packageManager'],
482
+ outputs: ['package.json (engines.node + packageManager fields)'],
465
483
  riskLevel: 'safe-merge',
466
484
  canFixDrift: true,
467
- async run({ targetDir }) {
468
- const result = await ensureEnginesNode(targetDir);
469
- return { filesWritten: result === 'added' ? ['package.json'] : [] };
485
+ async run({ targetDir, pkg }) {
486
+ // Same concern as engines.node — declaring the toolchain the repo
487
+ // expects. `fix github-actions` also pins it, but only reaches repos
488
+ // whose ci.yml is already drifted (#372). Guarded on pnpm because the
489
+ // value we write is a pnpm range; an npm or yarn repo must not get one.
490
+ const engines = await ensureEnginesNode(targetDir);
491
+ const manager = (await usesPnpm(targetDir, pkg))
492
+ ? await ensurePackageManager(targetDir)
493
+ : 'already-set';
494
+ const changed = engines === 'added' || manager === 'added';
495
+ return { filesWritten: changed ? ['package.json'] : [] };
470
496
  },
471
497
  },
472
498
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtorcato/repo-tooling",
3
- "version": "3.7.4",
3
+ "version": "3.8.1",
4
4
  "description": "One CLI to scaffold, audit and fix your repo's whole toolchain — linting, tests, commits, releases & CI.",
5
5
  "type": "module",
6
6
  "keywords": [