@alxwlw/stack 1.13.0 → 1.15.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.
@@ -10,9 +10,9 @@
10
10
  "dependency-cruiser": "18.8.0-beta-2",
11
11
  "vitest": "5.1.0",
12
12
  "@playwright/test": "1.64.1",
13
- "@alxwlw/stack": "1.13.0",
14
- "@alxwlw/oxlint-config": "1.13.0",
15
- "@alxwlw/tsconfig": "1.13.0"
13
+ "@alxwlw/stack": "1.15.0",
14
+ "@alxwlw/oxlint-config": "1.15.0",
15
+ "@alxwlw/tsconfig": "1.15.0"
16
16
  },
17
17
  "libs": {
18
18
  "@nestjs/core": "12.3.2",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alxwlw/stack",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
package/schema.json CHANGED
@@ -14,7 +14,7 @@
14
14
  "description": "Opt-in canon groups. \"renovate\" is deprecated and does nothing: Renovate is the canon's dependency bot for every profile.",
15
15
  "items": {
16
16
  "type": "string",
17
- "enum": ["depcruise", "knip", "libs", "moon-tasks", "renovate"]
17
+ "enum": ["depcruise", "knip", "libs", "moon-tasks", "peers", "renovate"]
18
18
  }
19
19
  },
20
20
  "exceptions": {
package/src/canon.ts CHANGED
@@ -120,6 +120,8 @@ export interface Canon {
120
120
  files: { dest: string; content: string; strategy?: SyncStrategy; satisfiedBy?: string[] }[];
121
121
  catalogs: CanonCatalogs;
122
122
  pins: Pins;
123
+ /** Включённые через with группы правил, в порядке RULE_GROUPS. */
124
+ rules: RuleGroup[];
123
125
  }
124
126
 
125
127
  // Пины инструментов из .prototools канона: node и pnpm обязательны, прочие строки верхнего уровня допустимы.
@@ -136,10 +138,15 @@ export function canonDir(): string {
136
138
  // Устаревшие группы принимаются ради старых .stack.jsonc и ничего не включают.
137
139
  const DEPRECATED_GROUPS: readonly string[] = ['renovate'];
138
140
 
141
+ // Группа правила включает правило `stack check`, файлов и каталогов не даёт.
142
+ export const RULE_GROUPS = ['peers'] as const;
143
+ export type RuleGroup = (typeof RULE_GROUPS)[number];
144
+
139
145
  export interface CanonGroups {
140
146
  files: string[];
141
147
  catalogs: string[];
142
148
  deprecated: readonly string[];
149
+ rules: readonly string[];
143
150
  }
144
151
 
145
152
  // canon/ как значение: все записи манифеста с содержимым, каталоги и имена групп. Читается один раз;
@@ -151,7 +158,8 @@ export interface CanonSource {
151
158
  }
152
159
 
153
160
  // Единственное место, где canon/ читается с диска: manifest.json и catalogs.json по разу, каждый src по разу.
154
- // Имена групп: файловые — поле group манифеста, каталожные — ключи catalogs.json кроме dev.
161
+ // Имена групп: файловые — поле group манифеста, каталожные — ключи catalogs.json кроме dev, устаревшие и
162
+ // группы правил — константы этого модуля.
155
163
  export function readCanonSource(dir: string = canonDir()): CanonSource {
156
164
  const manifest = checkManifest(JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')));
157
165
  const catalogs = JSON.parse(readFileSync(join(dir, 'catalogs.json'), 'utf8')) as CanonCatalogs;
@@ -163,13 +171,15 @@ export function readCanonSource(dir: string = canonDir()): CanonSource {
163
171
  files: [...new Set(entries.flatMap((f) => (f.group == null ? [] : [f.group])))],
164
172
  catalogs: Object.keys(catalogs).filter((g) => g !== 'dev'),
165
173
  deprecated: DEPRECATED_GROUPS,
174
+ rules: RULE_GROUPS,
166
175
  };
167
176
  return { entries, catalogs, groups };
168
177
  }
169
178
 
170
- // Все имена, допустимые в `with`: файловые, каталожные и устаревшие — без повторов, по алфавиту.
179
+ // Все имена, допустимые в `with`: файловые, каталожные, устаревшие и группы правил — без повторов,
180
+ // по алфавиту.
171
181
  export function knownGroups(g: CanonGroups): string[] {
172
- return [...new Set([...g.files, ...g.catalogs, ...g.deprecated])].sort();
182
+ return [...new Set([...g.files, ...g.catalogs, ...g.deprecated, ...g.rules])].sort();
173
183
  }
174
184
 
175
185
  export function assertKnownGroups(groups: readonly string[], source: CanonSource): void {
@@ -191,7 +201,8 @@ export function selectEntries(source: CanonSource, cfg: StackConfig): CanonSourc
191
201
  );
192
202
  }
193
203
 
194
- // Чистый шаг от источника к Canon: проверка групп, выбор записей, каталоги, пины. Диск не трогает.
204
+ // Чистый шаг от источника к Canon: проверка групп, выбор записей, каталоги, пины, группы правил.
205
+ // Диск не трогает.
195
206
  export function canonFor(source: CanonSource, cfg: StackConfig): Canon {
196
207
  assertKnownGroups(cfg.with, source);
197
208
  const files = selectEntries(source, cfg).map((f) => ({
@@ -215,7 +226,8 @@ export function canonFor(source: CanonSource, cfg: StackConfig): Canon {
215
226
  if (!node) throw new Error('canon .prototools has no node pin');
216
227
  // Пин pnpm нужен правилу package-manager: поле packageManager — второй источник версии pnpm.
217
228
  if (!pnpm) throw new Error('canon .prototools has no pnpm pin');
218
- return { files, catalogs, pins: { ...rest, node, pnpm } };
229
+ const rules = RULE_GROUPS.filter((g) => cfg.with.includes(g));
230
+ return { files, catalogs, pins: { ...rest, node, pnpm }, rules };
219
231
  }
220
232
 
221
233
  export function loadCanon(cfg: StackConfig, dir: string = canonDir()): Canon {
package/src/check.ts CHANGED
@@ -11,24 +11,34 @@ import { allowedLine, type Exception, type Held, isHeld, resolve } from './excep
11
11
  import { planFiles } from './files.ts';
12
12
  import type { Drift, Finding } from './findings.ts';
13
13
  import { checkMoonToolchains } from './moon-toolchains.ts';
14
+ import { checkMoonDefaultBranch, planMoonDefaultBranch } from './moon-workspace.ts';
14
15
  import { planPackageManager } from './package-manager.ts';
16
+ import { type PeersOutcome, peersOutcome, type PeersReader } from './peers.ts';
17
+ import { checkPeers } from './peers-rule.ts';
15
18
  import { planReleaseAgeExcludes } from './release-age.ts';
16
- import { loadRepo, type Repo } from './repo.ts';
19
+ import { loadRepo, LOCKFILE, type Repo } from './repo.ts';
17
20
 
18
21
  // План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, release-age,
19
- // packageManager. Правки одного файла друг от друга не зависят: sync применяет любое их подмножество.
22
+ // packageManager, ветка по умолчанию moon. Правки одного файла друг от друга не зависят: sync применяет любое их подмножество.
20
23
  export function plan(repo: Repo, canon: Canon): Drift[] {
21
24
  return [
22
25
  ...planFiles(repo, canon),
23
26
  ...planCatalogs(repo, canon),
24
27
  ...planReleaseAgeExcludes(repo, canon),
25
28
  ...planPackageManager(repo, canon),
29
+ ...planMoonDefaultBranch(repo),
26
30
  ];
27
31
  }
28
32
 
29
- // Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts; затем
30
- // протухшие исключения. Все они проходят через исключения.
31
- export function check(repo: Repo, canon: Canon, exceptions: Exception[]): Finding[] {
33
+ // Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts и moon,
34
+ // правило группы peers, если она включена; затем протухшие исключения. Все они проходят через
35
+ // исключения. peers — исход `pnpm peers check`, его получает checkRepo.
36
+ export function check(
37
+ repo: Repo,
38
+ canon: Canon,
39
+ exceptions: Exception[],
40
+ peers?: PeersOutcome,
41
+ ): Finding[] {
32
42
  const r = resolve(
33
43
  [
34
44
  ...plan(repo, canon),
@@ -38,6 +48,8 @@ export function check(repo: Repo, canon: Canon, exceptions: Exception[]): Findin
38
48
  ...checkRenovatePreset(repo),
39
49
  ...checkDependabot(repo),
40
50
  ...checkMoonToolchains(repo, canon),
51
+ ...checkMoonDefaultBranch(repo),
52
+ ...(canon.rules.includes('peers') ? checkPeers(repo, peers) : []),
41
53
  ],
42
54
  exceptions,
43
55
  );
@@ -48,8 +60,20 @@ export function planRepo(repoRoot: string, canon: Canon): Drift[] {
48
60
  return plan(loadRepo(repoRoot, canon), canon);
49
61
  }
50
62
 
51
- export function checkRepo(repoRoot: string, canon: Canon, exceptions: Exception[]): Finding[] {
52
- return check(loadRepo(repoRoot, canon), canon, exceptions);
63
+ // pnpm запускается, только если группа peers включена и лок есть: без лока правило отвечает само.
64
+ export function checkRepo(
65
+ repoRoot: string,
66
+ canon: Canon,
67
+ exceptions: Exception[],
68
+ readPeers?: PeersReader,
69
+ ): Finding[] {
70
+ const repo = loadRepo(repoRoot, canon);
71
+ let peers: PeersOutcome | undefined;
72
+ if (canon.rules.includes('peers') && repo.paths.has(LOCKFILE)) {
73
+ if (readPeers === undefined) throw new Error('checkRepo: peers group needs a PeersReader');
74
+ peers = peersOutcome(readPeers(repoRoot));
75
+ }
76
+ return check(repo, canon, exceptions, peers);
53
77
  }
54
78
 
55
79
  export interface SyncResult {
package/src/cli.ts CHANGED
@@ -10,6 +10,8 @@ import { allowedLine, isHeld } from './exceptions.ts';
10
10
  import { type Finding, isDrift } from './findings.ts';
11
11
  import { ghGitHub } from './gh.ts';
12
12
  import { initConfig } from './init.ts';
13
+ import type { PeersReader } from './peers.ts';
14
+ import { peersBaseline } from './peers-baseline.ts';
13
15
  import { npmRegistryReader } from './registry.ts';
14
16
  import { ownVersion, type RunProcess, SYNC_PR_WAIT, syncPr, withoutGhToken } from './sync-pr.ts';
15
17
 
@@ -29,6 +31,8 @@ function parseCliArgs() {
29
31
  with: { type: 'string', multiple: true },
30
32
  base: { type: 'string' },
31
33
  'no-install': { type: 'boolean' },
34
+ init: { type: 'boolean' },
35
+ 'allow-grow': { type: 'boolean' },
32
36
  },
33
37
  });
34
38
  } catch (error) {
@@ -67,6 +71,19 @@ const runProcess: RunProcess = (cmd, args, { cwd, env }) => {
67
71
  return r.status ?? 1;
68
72
  };
69
73
 
74
+ // Боевой adapter порта pnpm для группы peers: вывод захватывается, разбор — peersOutcome. Проверка
75
+ // идёт по локу, без установки; GH_TOKEN не нужен pnpm, как и установке в sync-pr.
76
+ const pnpmPeers: PeersReader = (cwd) => {
77
+ const r = spawnSync('pnpm', ['peers', 'check', '--lockfile-only', '--json'], {
78
+ cwd,
79
+ encoding: 'utf8',
80
+ maxBuffer: 1 << 30,
81
+ env: withoutGhToken(process.env),
82
+ });
83
+ if (r.error) return { error: r.error.message };
84
+ return { status: r.status, signal: r.signal, stdout: r.stdout, stderr: r.stderr };
85
+ };
86
+
70
87
  const { values, positionals } = parseCliArgs();
71
88
 
72
89
  const repoRoot = values.repo ?? process.cwd();
@@ -90,7 +107,7 @@ try {
90
107
  for (const line of stdout) console.log(line);
91
108
  } else if (command === 'check') {
92
109
  const cfg = readStackConfig(repoRoot);
93
- const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions);
110
+ const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions, pnpmPeers);
94
111
  const blocking = findings.filter((f) => !isHeld(f));
95
112
  for (const f of findings.filter(isHeld)) console.warn(allowedLine(f));
96
113
  for (const f of blocking) console.error(`${f.code}: ${f.target} — ${f.message}`);
@@ -119,11 +136,22 @@ try {
119
136
  github: ghGitHub(repoRoot),
120
137
  registry: npmRegistryReader(),
121
138
  print: (stream, line) => (stream === 'out' ? console.log(line) : console.error(line)),
139
+ peers: pnpmPeers,
122
140
  },
123
141
  ),
124
142
  );
143
+ } else if (command === 'peers-baseline') {
144
+ if (values.init && values['allow-grow']) fail('--init and --allow-grow do not go together');
145
+ const cfg = readStackConfig(repoRoot);
146
+ const mode = values.init ? 'init' : values['allow-grow'] ? 'grow' : 'lower';
147
+ const r = peersBaseline(repoRoot, loadCanon(cfg), mode, pnpmPeers);
148
+ for (const line of r.out) console.log(line);
149
+ for (const line of r.err) console.error(line);
150
+ process.exit(r.code);
125
151
  } else {
126
- fail(`unknown command "${command ?? ''}". Available: init, sync, check, sync-pr`);
152
+ fail(
153
+ `unknown command "${command ?? ''}". Available: init, sync, check, sync-pr, peers-baseline`,
154
+ );
127
155
  }
128
156
  } catch (error) {
129
157
  if (error instanceof StackConfigError) fail(error.message);
package/src/exceptions.ts CHANGED
@@ -92,8 +92,14 @@ const ADDRESS: { [C in FindingCode]: ((f: FindingOf<C>) => Address) | 'unsuppres
92
92
  'dependabot-config': 'unsuppressible',
93
93
  // Версия в moon toolchains — второй пин поверх .prototools; исключение держит её по файлу.
94
94
  'moon-toolchain-version': () => ({ file: '.moon/toolchains.yml' }),
95
+ // Ветка по умолчанию в moon workspace; исключение по найденному пути держит и drift, и отчёт.
96
+ 'moon-default-branch': (f) => ({ file: f.file }),
95
97
  'unreadable-file': 'unsuppressible',
96
98
  'stale-exception': 'unsuppressible',
99
+ // Исключение для находок peers — сам baseline; отказ от гейта — убрать группу из with.
100
+ 'peer-dependency': 'unsuppressible',
101
+ 'stale-peer-baseline': 'unsuppressible',
102
+ 'peers-unavailable': 'unsuppressible',
97
103
  };
98
104
 
99
105
  export function addressOf(f: Finding): Address | undefined {
package/src/findings.ts CHANGED
@@ -11,7 +11,7 @@ interface FindingBase {
11
11
  // находки без предмета не подавляются никогда.
12
12
  export type Finding = FindingBase &
13
13
  (
14
- | { code: 'file-drift' | 'file-missing'; file: string }
14
+ | { code: 'file-drift' | 'file-missing' | 'moon-default-branch'; file: string }
15
15
  | { code: 'catalog-drift' | 'catalog-missing'; catalog: string; name: string }
16
16
  | { code: 'inline-version' | 'release-age-exclude'; name: string }
17
17
  | {
@@ -22,7 +22,10 @@ export type Finding = FindingBase &
22
22
  | 'dependabot-config'
23
23
  | 'moon-toolchain-version'
24
24
  | 'unreadable-file'
25
- | 'stale-exception';
25
+ | 'stale-exception'
26
+ | 'peer-dependency'
27
+ | 'stale-peer-baseline'
28
+ | 'peers-unavailable';
26
29
  }
27
30
  );
28
31
  export type FindingCode = Finding['code'];
package/src/gh.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
 
3
- import type { GitHub } from './sync-pr.ts';
3
+ import type { GitHub, OpenPr } from './sync-pr.ts';
4
4
 
5
5
  export type Exec = (
6
6
  cmd: string,
@@ -16,6 +16,15 @@ export const spawnExec: Exec = (cmd, args, { cwd, input }) => {
16
16
  return { status: r.status, signal: r.signal, stdout: r.stdout, stderr: r.stderr };
17
17
  };
18
18
 
19
+ // Форма элемента `gh pr list --json number,url,headRefName,baseRefName,author`.
20
+ interface RawPr {
21
+ number: number;
22
+ url: string;
23
+ headRefName: string;
24
+ baseRefName: string;
25
+ author: { login: string } | null;
26
+ }
27
+
19
28
  // Боевой adapter порта GitHub: gh берёт GH_TOKEN из окружения сам и запускается в cwd репозитория —
20
29
  // git работает там же, и репозиторий для gh должен быть тем же.
21
30
  export function ghGitHub(cwd: string, exec: Exec = spawnExec): GitHub {
@@ -38,22 +47,6 @@ export function ghGitHub(cwd: string, exec: Exec = spawnExec): GitHub {
38
47
  }
39
48
  return id;
40
49
  }),
41
- openPr: (head) =>
42
- settle(() => {
43
- const url = gh([
44
- 'pr',
45
- 'list',
46
- '--head',
47
- head,
48
- '--state',
49
- 'open',
50
- '--json',
51
- 'url',
52
- '--jq',
53
- '.[0].url // ""',
54
- ]).trim();
55
- return url === '' ? undefined : url;
56
- }),
57
50
  createPr: (pr) =>
58
51
  settle(() => {
59
52
  const args = [
@@ -74,5 +67,50 @@ export function ghGitHub(cwd: string, exec: Exec = spawnExec): GitHub {
74
67
  if (!url) throw new Error('gh pr create printed no PR URL');
75
68
  return url;
76
69
  }),
70
+ defaultBranch: () =>
71
+ settle(() => {
72
+ const name = gh([
73
+ 'repo',
74
+ 'view',
75
+ '--json',
76
+ 'defaultBranchRef',
77
+ '--jq',
78
+ '.defaultBranchRef.name',
79
+ ]).trim();
80
+ if (name === '') throw new Error('gh repo view returned no default branch');
81
+ return name;
82
+ }),
83
+ // gh печатает логин GitHub App как `app/<slug>`; `[bot]` — форма из `user.name` бота в `publishChanges`.
84
+ openPrs: () =>
85
+ settle(() => {
86
+ const stdout = gh([
87
+ 'pr',
88
+ 'list',
89
+ '--state',
90
+ 'open',
91
+ '--limit',
92
+ '1000',
93
+ '--json',
94
+ 'number,url,headRefName,baseRefName,author',
95
+ ]);
96
+ const list: unknown = JSON.parse(stdout);
97
+ if (!Array.isArray(list)) {
98
+ throw new Error(`gh pr list returned no list: ${JSON.stringify(stdout)}`);
99
+ }
100
+ return (list as RawPr[]).map((p): OpenPr => {
101
+ const login = p.author?.login ?? '';
102
+ return {
103
+ number: p.number,
104
+ url: p.url,
105
+ head: p.headRefName,
106
+ base: p.baseRefName,
107
+ author: login.startsWith('app/') ? `${login.slice('app/'.length)}[bot]` : login,
108
+ };
109
+ });
110
+ }),
111
+ closePr: (number, comment) =>
112
+ settle(() => {
113
+ gh(['pr', 'close', String(number), '--comment', comment]);
114
+ }),
77
115
  };
78
116
  }
@@ -0,0 +1,51 @@
1
+ import type { Drift, Finding } from './findings.ts';
2
+ import type { Repo } from './repo.ts';
3
+
4
+ // Без vcs.defaultBranch moon сравнивает с master: на PR базу даёт событие и проверки зелёные, а на push
5
+ // в main CI падает. main — ветка, на push в которую канон запускает свой workflow stack.
6
+ const target = (file: string) => `${file}:vcs.defaultBranch`;
7
+
8
+ const isMap = (v: unknown): v is Record<string, unknown> =>
9
+ v !== null && typeof v === 'object' && !Array.isArray(v);
10
+
11
+ // Только существующий файл и только когда vcs — словарь или его нет: на узел-не-словарь setIn бросает.
12
+ export function planMoonDefaultBranch(repo: Repo): Drift[] {
13
+ const top = repo.moonWorkspace;
14
+ const file = repo.moonWorkspacePath;
15
+ if (top === undefined || file === undefined) return [];
16
+ const vcs = top.vcs;
17
+ if (vcs !== undefined && !isMap(vcs)) return [];
18
+ const current = isMap(vcs) ? vcs.defaultBranch : undefined;
19
+ if (typeof current === 'string' && current !== '') return [];
20
+ const from = current === undefined ? '—' : JSON.stringify(current);
21
+ return [
22
+ {
23
+ code: 'moon-default-branch',
24
+ target: target(file),
25
+ file,
26
+ message: `vcs.defaultBranch is not set — moon falls back to "master", and CI on a push to main dies with "ambiguous argument 'master'"`,
27
+ fix: `${file} vcs.defaultBranch: ${from} → main`,
28
+ change: {
29
+ file,
30
+ kind: 'yaml-set',
31
+ path: ['vcs', 'defaultBranch'],
32
+ value: 'main',
33
+ },
34
+ },
35
+ ];
36
+ }
37
+
38
+ // vcs не словарь (`vcs:` без значения, `vcs: git`): правки нет, только отчёт.
39
+ export function checkMoonDefaultBranch(repo: Repo): Finding[] {
40
+ const top = repo.moonWorkspace;
41
+ const file = repo.moonWorkspacePath;
42
+ if (top === undefined || file === undefined || !('vcs' in top) || isMap(top.vcs)) return [];
43
+ return [
44
+ {
45
+ code: 'moon-default-branch',
46
+ target: target(file),
47
+ file,
48
+ message: `vcs is not a map — set vcs.defaultBranch (main, the branch the canon's stack workflow runs on) by hand`,
49
+ },
50
+ ];
51
+ }
@@ -0,0 +1,88 @@
1
+ // `stack peers-baseline`: единственное место, где файл baseline группы peers пишется на диск.
2
+ // init — записать текущие проблемы в новый файл; lower — только убрать исправленные; grow — принять
3
+ // и новые; drop-fixed — убрать исправленные, если они есть, молча во всём остальном (sync-pr).
4
+
5
+ import { writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+
8
+ import type { Canon } from './canon.ts';
9
+ import {
10
+ comparePeers,
11
+ lowerPeersBaseline,
12
+ PEERS_BASELINE,
13
+ peersOutcome,
14
+ type PeersReader,
15
+ serializePeersBaseline,
16
+ } from './peers.ts';
17
+ import { loadRepo, LOCKFILE } from './repo.ts';
18
+
19
+ export type PeersBaselineMode = 'init' | 'lower' | 'grow' | 'drop-fixed';
20
+
21
+ export interface PeersBaselineResult {
22
+ code: 0 | 1 | 2;
23
+ out: string[];
24
+ err: string[];
25
+ }
26
+
27
+ const failed = (code: 1 | 2, line: string): PeersBaselineResult => ({ code, out: [], err: [line] });
28
+ const quiet = (): PeersBaselineResult => ({ code: 0, out: [], err: [] });
29
+
30
+ // Порядок проверок: группа, разбор файла, есть ли файл для режима, лок, pnpm, рост в lower. Первая
31
+ // сработавшая решает; файл пишется только в самом конце. drop-fixed там, где делать нечего, молчит.
32
+ export function peersBaseline(
33
+ repoRoot: string,
34
+ canon: Canon,
35
+ mode: PeersBaselineMode,
36
+ readPeers: PeersReader,
37
+ ): PeersBaselineResult {
38
+ const dropFixed = mode === 'drop-fixed';
39
+ if (!canon.rules.includes('peers')) {
40
+ return dropFixed
41
+ ? quiet()
42
+ : failed(2, 'peers-baseline needs "peers" in "with" of .stack.jsonc');
43
+ }
44
+ const repo = loadRepo(repoRoot, canon);
45
+ // Неразобранный файл не перезаписывается: в нём могли быть записи, которых больше нигде нет.
46
+ const broken = repo.unreadable.find((f) => f.target === PEERS_BASELINE);
47
+ if (broken !== undefined) return failed(2, broken.message);
48
+ const exists = repo.paths.has(PEERS_BASELINE);
49
+ if (mode === 'init' && exists) return failed(2, `${PEERS_BASELINE} already exists`);
50
+ if (mode !== 'init' && !exists) {
51
+ return dropFixed ? quiet() : failed(2, `no ${PEERS_BASELINE}: run stack peers-baseline --init`);
52
+ }
53
+ if (!repo.paths.has(LOCKFILE)) return failed(1, `no ${LOCKFILE}`);
54
+ const outcome = peersOutcome(readPeers(repoRoot));
55
+ if ('unavailable' in outcome) return failed(1, outcome.unavailable);
56
+
57
+ const current = outcome.issues;
58
+ const baseline = repo.peersBaseline ?? [];
59
+ const { added, stale } = comparePeers(current, baseline);
60
+ if (mode === 'lower' && added.length > 0) {
61
+ return {
62
+ code: 1,
63
+ out: [],
64
+ err: [
65
+ ...added.map((i) => `new: ${i.entry.peer} in ${i.entry.importer} — ${i.detail}`),
66
+ `${added.length} new entr(ies) — fix them or pass --allow-grow`,
67
+ ],
68
+ };
69
+ }
70
+ if (dropFixed && stale.length === 0) return quiet();
71
+
72
+ const next =
73
+ mode === 'init' || mode === 'grow'
74
+ ? current.map((i) => i.entry)
75
+ : lowerPeersBaseline(baseline, current);
76
+ writeFileSync(
77
+ join(repoRoot, PEERS_BASELINE),
78
+ serializePeersBaseline(next, repo.files.get(PEERS_BASELINE)),
79
+ );
80
+ const wrote = `wrote ${PEERS_BASELINE}: ${next.length} entr(ies)`;
81
+ const line =
82
+ mode === 'init'
83
+ ? wrote
84
+ : dropFixed
85
+ ? `dropped ${stale.length} fixed entr(ies) from ${PEERS_BASELINE}`
86
+ : `${wrote} (-${stale.length} fixed, +${added.length} new)`;
87
+ return { code: 0, out: [line], err: [] };
88
+ }
@@ -0,0 +1,48 @@
1
+ // Правило группы peers над Repo: исход `pnpm peers check` против baseline. Отдельный модуль, потому
2
+ // что repo.ts берёт разбор baseline из peers.ts, и правило в peers.ts замкнуло бы цикл импортов.
3
+
4
+ import type { Finding } from './findings.ts';
5
+ import { comparePeers, type PeerEntry, PEERS_BASELINE, type PeersOutcome } from './peers.ts';
6
+ import { LOCKFILE, type Repo } from './repo.ts';
7
+
8
+ const TARGET = 'pnpm peers check';
9
+
10
+ const where = (e: PeerEntry): string => `${e.peer} in ${e.importer}`;
11
+
12
+ // Запись baseline словами: вид, объявивший пакет и линия найденной версии, если они есть у вида.
13
+ function recorded(e: PeerEntry): string {
14
+ switch (e.kind) {
15
+ case 'unmet':
16
+ return `unmet by ${e.by} (found ${e.found})`;
17
+ case 'missing':
18
+ return `missing by ${e.by}`;
19
+ case 'conflict':
20
+ return 'conflict';
21
+ }
22
+ }
23
+
24
+ // Без лока pnpm ответил бы `{}` с кодом 0, то есть «чисто», поэтому исход тогда не читается вовсе.
25
+ // Неразобранный baseline даёт находку в загрузчике, и пустым baseline он не считается.
26
+ export function checkPeers(repo: Repo, outcome: PeersOutcome | undefined): Finding[] {
27
+ if (!repo.paths.has(LOCKFILE)) {
28
+ return [{ code: 'peers-unavailable', target: TARGET, message: `no ${LOCKFILE}` }];
29
+ }
30
+ if (outcome === undefined) throw new Error('checkPeers: no pnpm peers check outcome');
31
+ if ('unavailable' in outcome) {
32
+ return [{ code: 'peers-unavailable', target: TARGET, message: outcome.unavailable }];
33
+ }
34
+ if (repo.paths.has(PEERS_BASELINE) && repo.peersBaseline === undefined) return [];
35
+ const { added, stale } = comparePeers(outcome.issues, repo.peersBaseline ?? []);
36
+ return [
37
+ ...added.map((i): Finding => ({
38
+ code: 'peer-dependency',
39
+ target: where(i.entry),
40
+ message: `${i.detail}; not in ${PEERS_BASELINE}`,
41
+ })),
42
+ ...stale.map((e): Finding => ({
43
+ code: 'stale-peer-baseline',
44
+ target: where(e),
45
+ message: `recorded ${recorded(e)} is gone; drop it with: stack peers-baseline`,
46
+ })),
47
+ ];
48
+ }