@alxwlw/stack 1.10.0 → 1.11.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.10.0",
14
- "@alxwlw/oxlint-config": "1.10.0",
15
- "@alxwlw/tsconfig": "1.10.0"
13
+ "@alxwlw/stack": "1.11.0",
14
+ "@alxwlw/oxlint-config": "1.11.0",
15
+ "@alxwlw/tsconfig": "1.11.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.10.0",
3
+ "version": "1.11.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": ["moon-tasks", "libs", "knip", "depcruise", "renovate"]
17
+ "enum": ["depcruise", "knip", "libs", "moon-tasks", "renovate"]
18
18
  }
19
19
  },
20
20
  "exceptions": {
@@ -37,7 +37,7 @@
37
37
  },
38
38
  {
39
39
  "required": ["catalog", "name"],
40
- "not": { "required": ["file"] }
40
+ "not": { "anyOf": [{ "required": ["file"] }] }
41
41
  }
42
42
  ]
43
43
  }
package/src/apply.ts CHANGED
@@ -2,14 +2,16 @@ import { mkdirSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
 
4
4
  import { applyEdits, modify } from 'jsonc-parser';
5
- import { parseDocument } from 'yaml';
5
+ import { isScalar, isSeq, parseDocument } from 'yaml';
6
6
 
7
7
  import type { Change } from './findings.ts';
8
8
 
9
9
  function renderFile(file: string, current: string | undefined, changes: Change[]): string {
10
10
  // Список по файлу не бывает пустым: правки группирует renderChanges.
11
11
  const first = changes[0] as Change;
12
- if (changes.some((c) => c.kind !== first.kind)) {
12
+ // Совместимость по формату файла: yaml-set и yaml-append — один формат.
13
+ const format = (c: Change) => (c.kind === 'yaml-append' ? 'yaml-set' : c.kind);
14
+ if (changes.some((c) => format(c) !== format(first))) {
13
15
  throw new Error(`conflicting changes for ${file}`);
14
16
  }
15
17
  if (first.kind === 'write') {
@@ -18,12 +20,21 @@ function renderFile(file: string, current: string | undefined, changes: Change[]
18
20
  for (const c of changes) if (c.kind === 'write') content = c.content;
19
21
  return content;
20
22
  }
21
- if (first.kind === 'yaml-set') {
23
+ if (format(first) === 'yaml-set') {
22
24
  const doc = parseDocument(current ?? '');
23
25
  for (const c of changes) {
24
26
  // setIn создаёт недостающие узлы и не трогает соседей и их комментарии.
25
- if (c.kind === 'yaml-set') {
26
- doc.setIn(c.path, Array.isArray(c.value) ? doc.createNode(c.value) : c.value);
27
+ if (c.kind === 'yaml-set') doc.setIn(c.path, c.value);
28
+ else if (c.kind === 'yaml-append') {
29
+ const node = doc.getIn(c.path, true);
30
+ if (isSeq(node)) node.add(doc.createNode(c.value));
31
+ else if (node === undefined || (isScalar(node) && node.value === null)) {
32
+ // yaml держит комментарии пустого ключа на null-скаляре: переносим на новую последовательность.
33
+ const seq = doc.createNode([c.value]);
34
+ if (node?.comment) seq.comment = node.comment;
35
+ if (node?.commentBefore) seq.commentBefore = node.commentBefore;
36
+ doc.setIn(c.path, seq);
37
+ } else throw new Error(`${file}: ${c.path.join('.')} is not a sequence`);
27
38
  }
28
39
  }
29
40
  // singleQuote: oxfmt (canon .oxfmtrc.jsonc) formats YAML with singleQuote:true, and
package/src/canon.ts CHANGED
@@ -2,9 +2,10 @@ import { readFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
 
5
- import { type Profile, type StackConfig, StackConfigError } from './config.ts';
5
+ import { type Profile, PROFILES, type StackConfig, StackConfigError } from './config.ts';
6
6
 
7
- export type SyncStrategy = 'verbatim' | 'create-if-absent';
7
+ export const SYNC_STRATEGIES = ['verbatim', 'create-if-absent'] as const;
8
+ export type SyncStrategy = (typeof SYNC_STRATEGIES)[number];
8
9
 
9
10
  export interface CanonFile {
10
11
  src: string;
@@ -17,6 +18,100 @@ export interface CanonFile {
17
18
  satisfiedBy?: string[];
18
19
  }
19
20
 
21
+ // Ключи записи manifest: Record<keyof CanonFile, true> не даёт полю без ключа и ключу без поля пройти tsc.
22
+ const ENTRY_KEYS: Record<keyof CanonFile, true> = {
23
+ src: true,
24
+ dest: true,
25
+ appliesTo: true,
26
+ strategy: true,
27
+ group: true,
28
+ satisfiedBy: true,
29
+ };
30
+
31
+ const isRecord = (v: unknown): v is Record<string, unknown> =>
32
+ typeof v === 'object' && v !== null && !Array.isArray(v);
33
+
34
+ const isNonEmptyString = (v: unknown): v is string => typeof v === 'string' && v !== '';
35
+
36
+ const isProfile = (v: unknown): v is Profile => PROFILES.some((known) => known === v);
37
+ const isStrategy = (v: unknown): v is SyncStrategy => SYNC_STRATEGIES.some((known) => known === v);
38
+
39
+ // Нарушение manifest — дефект пакета, а не потребителя: обычная Error, не StackConfigError.
40
+ function checkEntry(raw: unknown, index: number): CanonFile {
41
+ if (!isRecord(raw)) throw new Error(`canon manifest: entry ${index}: must be an object`);
42
+ const at = isNonEmptyString(raw.dest) ? `entry ${index} (${raw.dest})` : `entry ${index}`;
43
+ function bad(what: string): never {
44
+ throw new Error(`canon manifest: ${at}: ${what}`);
45
+ }
46
+ for (const key of Object.keys(raw)) {
47
+ if (!Object.hasOwn(ENTRY_KEYS, key)) bad(`unknown key ${JSON.stringify(key)}`);
48
+ }
49
+ const { src, dest, appliesTo, strategy, group, satisfiedBy } = raw;
50
+ if (!isNonEmptyString(dest)) return bad('"dest" must be a non-empty string');
51
+ if (!isNonEmptyString(src)) return bad('"src" must be a non-empty string');
52
+ if (!Array.isArray(appliesTo) || appliesTo.length === 0) {
53
+ return bad(
54
+ `"appliesTo" must be a non-empty array of profiles, got ${JSON.stringify(appliesTo)}`,
55
+ );
56
+ }
57
+ const profiles: Profile[] = [];
58
+ for (const p of appliesTo as unknown[]) {
59
+ if (!isProfile(p) || profiles.includes(p)) {
60
+ return bad(
61
+ `"appliesTo" has ${JSON.stringify(p)}: expected each of ${PROFILES.join(', ')} at most once`,
62
+ );
63
+ }
64
+ profiles.push(p);
65
+ }
66
+ const file: CanonFile = { src, dest, appliesTo: profiles };
67
+ if (strategy !== undefined) {
68
+ if (!isStrategy(strategy)) {
69
+ return bad(
70
+ `"strategy" is ${JSON.stringify(strategy)}, expected one of ${SYNC_STRATEGIES.join(', ')}`,
71
+ );
72
+ }
73
+ file.strategy = strategy;
74
+ }
75
+ if (group !== undefined) {
76
+ if (!isNonEmptyString(group)) return bad('"group" must be a non-empty string');
77
+ file.group = group;
78
+ }
79
+ if (satisfiedBy !== undefined) {
80
+ if (strategy !== 'create-if-absent')
81
+ return bad('"satisfiedBy" needs strategy "create-if-absent"');
82
+ if (
83
+ !Array.isArray(satisfiedBy) ||
84
+ satisfiedBy.length === 0 ||
85
+ !satisfiedBy.every(isNonEmptyString)
86
+ ) {
87
+ return bad('"satisfiedBy" must be a non-empty array of non-empty strings');
88
+ }
89
+ file.satisfiedBy = satisfiedBy;
90
+ }
91
+ return file;
92
+ }
93
+
94
+ // Manifest целиком, до чтения первого src. Среди записей одного Profile dest не повторяется
95
+ // (group не учитывается: группы выбирает потребитель, любые две рано или поздно включат вместе).
96
+ function checkManifest(raw: unknown): CanonFile[] {
97
+ const files = isRecord(raw) ? raw.files : undefined;
98
+ if (!Array.isArray(files)) throw new Error('canon manifest: "files" must be an array');
99
+ const entries = (files as unknown[]).map(checkEntry);
100
+ // Ruling 33: план напишет оба файла, применитель оставит последний, и следующий план вечно
101
+ // видит дрейф по проигравшей записи.
102
+ for (const profile of PROFILES) {
103
+ const seen = new Set<string>();
104
+ for (const e of entries) {
105
+ if (!e.appliesTo.includes(profile)) continue;
106
+ if (seen.has(e.dest)) {
107
+ throw new Error(`canon manifest: dest "${e.dest}" is listed twice for profile ${profile}`);
108
+ }
109
+ seen.add(e.dest);
110
+ }
111
+ }
112
+ return entries;
113
+ }
114
+
20
115
  export type CanonCatalogs = Record<string, Record<string, string>>;
21
116
 
22
117
  // Канон одного прогона как значение: уже отфильтрован под профиль и группы, содержимое файлов
@@ -58,11 +153,9 @@ export interface CanonSource {
58
153
  // Единственное место, где canon/ читается с диска: manifest.json и catalogs.json по разу, каждый src по разу.
59
154
  // Имена групп: файловые — поле group манифеста, каталожные — ключи catalogs.json кроме dev.
60
155
  export function readCanonSource(dir: string = canonDir()): CanonSource {
61
- const manifest = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')) as {
62
- files: CanonFile[];
63
- };
156
+ const manifest = checkManifest(JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')));
64
157
  const catalogs = JSON.parse(readFileSync(join(dir, 'catalogs.json'), 'utf8')) as CanonCatalogs;
65
- const entries = manifest.files.map((f) => ({
158
+ const entries = manifest.map((f) => ({
66
159
  ...f,
67
160
  content: readFileSync(join(dir, f.src), 'utf8'),
68
161
  }));
@@ -74,9 +167,13 @@ export function readCanonSource(dir: string = canonDir()): CanonSource {
74
167
  return { entries, catalogs, groups };
75
168
  }
76
169
 
170
+ // Все имена, допустимые в `with`: файловые, каталожные и устаревшие — без повторов, по алфавиту.
171
+ export function knownGroups(g: CanonGroups): string[] {
172
+ return [...new Set([...g.files, ...g.catalogs, ...g.deprecated])].sort();
173
+ }
174
+
77
175
  export function assertKnownGroups(groups: readonly string[], source: CanonSource): void {
78
- const g = source.groups;
79
- const known = [...g.files, ...g.catalogs, ...g.deprecated].sort();
176
+ const known = knownGroups(source.groups);
80
177
  for (const name of groups) {
81
178
  if (!known.includes(name)) {
82
179
  throw new StackConfigError(
package/src/check.ts CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  checkInlineVersions,
8
8
  checkRenovatePreset,
9
9
  } from './deps.ts';
10
- import { type Exception, type Held, isHeld, resolve } from './exceptions.ts';
10
+ import { allowedLine, type Exception, type Held, isHeld, resolve } from './exceptions.ts';
11
11
  import { planFiles } from './files.ts';
12
12
  import type { Drift, Finding } from './findings.ts';
13
13
  import { checkMoonToolchains } from './moon-toolchains.ts';
@@ -15,7 +15,8 @@ import { planPackageManager } from './package-manager.ts';
15
15
  import { planReleaseAgeExcludes } from './release-age.ts';
16
16
  import { loadRepo, type Repo } from './repo.ts';
17
17
 
18
- // План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, packageManager.
18
+ // План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, release-age,
19
+ // packageManager. Правки одного файла друг от друга не зависят: sync применяет любое их подмножество.
19
20
  export function plan(repo: Repo, canon: Canon): Drift[] {
20
21
  return [
21
22
  ...planFiles(repo, canon),
@@ -74,3 +75,14 @@ export function syncRepo(repoRoot: string, canon: Canon, exceptions: Exception[]
74
75
  );
75
76
  return result;
76
77
  }
78
+
79
+ // Строки вывода sync: удержанные — в stderr, правки и итог — в stdout. Общее для `stack sync` и `stack sync-pr`.
80
+ export function syncOutput(result: SyncResult): { stdout: string[]; stderr: string[] } {
81
+ return {
82
+ stderr: result.held.map((h) => allowedLine(h)),
83
+ stdout: [
84
+ ...result.applied.map((d) => d.fix),
85
+ `canon ${result.applied.length === 0 ? 'already up to date' : 'applied'}`,
86
+ ],
87
+ };
88
+ }
package/src/cli.ts CHANGED
@@ -1,13 +1,17 @@
1
1
  #!/usr/bin/env bun
2
+ import { spawnSync } from 'node:child_process';
2
3
  import { existsSync } from 'node:fs';
3
4
  import { parseArgs } from 'node:util';
4
5
 
5
6
  import { assertKnownGroups, loadCanon, readCanonSource } from './canon.ts';
6
- import { checkRepo, syncRepo } from './check.ts';
7
+ import { checkRepo, syncOutput, syncRepo } from './check.ts';
7
8
  import { type Profile, PROFILES, readStackConfig, StackConfigError } from './config.ts';
8
9
  import { allowedLine, isHeld } from './exceptions.ts';
9
10
  import { type Finding, isDrift } from './findings.ts';
11
+ import { ghGitHub } from './gh.ts';
10
12
  import { initConfig } from './init.ts';
13
+ import { npmRegistryReader } from './registry.ts';
14
+ import { ownVersion, type RunProcess, SYNC_PR_WAIT, syncPr, withoutGhToken } from './sync-pr.ts';
11
15
 
12
16
  function fail(message: string): never {
13
17
  console.error(message);
@@ -23,6 +27,8 @@ function parseCliArgs() {
23
27
  repo: { type: 'string' },
24
28
  profile: { type: 'string' },
25
29
  with: { type: 'string', multiple: true },
30
+ base: { type: 'string' },
31
+ 'no-install': { type: 'boolean' },
26
32
  },
27
33
  });
28
34
  } catch (error) {
@@ -42,6 +48,25 @@ function fixHint(blocking: Finding[]): string {
42
48
  return `${total} finding(s): ${bySync} fixable with: stack sync, ${total - bySync} to fix by hand (see above)`;
43
49
  }
44
50
 
51
+ // Боевой adapter порта процессов: stdio наследуется, вывод идёт в лог job.
52
+ const runProcess: RunProcess = (cmd, args, { cwd, env }) => {
53
+ // GH_TOKEN нужен только gh: установка и хук его не получают (скрипты зависимостей читают окружение).
54
+ const r = spawnSync(cmd, [...args], {
55
+ cwd,
56
+ stdio: 'inherit',
57
+ env: { ...withoutGhToken(process.env), ...env },
58
+ });
59
+ if (r.error) {
60
+ console.error(`sync-pr: ${cmd}: ${r.error.message}`);
61
+ return 127;
62
+ }
63
+ if (r.signal) {
64
+ console.error(`sync-pr: ${cmd} killed by ${r.signal}`);
65
+ return 1;
66
+ }
67
+ return r.status ?? 1;
68
+ };
69
+
45
70
  const { values, positionals } = parseCliArgs();
46
71
 
47
72
  const repoRoot = values.repo ?? process.cwd();
@@ -60,12 +85,9 @@ try {
60
85
  console.log(`created ${path}`);
61
86
  } else if (command === 'sync') {
62
87
  const cfg = readStackConfig(repoRoot);
63
- const { applied, held } = syncRepo(repoRoot, loadCanon(cfg), cfg.exceptions);
64
- for (const f of held) {
65
- console.warn(allowedLine(f));
66
- }
67
- for (const d of applied) console.log(d.fix);
68
- console.log(`canon ${applied.length === 0 ? 'already up to date' : 'applied'}`);
88
+ const { stdout, stderr } = syncOutput(syncRepo(repoRoot, loadCanon(cfg), cfg.exceptions));
89
+ for (const line of stderr) console.warn(line);
90
+ for (const line of stdout) console.log(line);
69
91
  } else if (command === 'check') {
70
92
  const cfg = readStackConfig(repoRoot);
71
93
  const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions);
@@ -77,8 +99,31 @@ try {
77
99
  process.exit(1);
78
100
  }
79
101
  console.log('canon: no drift');
102
+ } else if (command === 'sync-pr') {
103
+ const appSlug = process.env.STACK_APP_SLUG;
104
+ if (!process.env.GH_TOKEN || !appSlug) {
105
+ fail('sync-pr needs GH_TOKEN and STACK_APP_SLUG in the environment');
106
+ }
107
+ process.exit(
108
+ await syncPr(
109
+ {
110
+ repoRoot,
111
+ version: ownVersion(),
112
+ base: values.base,
113
+ appSlug,
114
+ install: !values['no-install'],
115
+ wait: SYNC_PR_WAIT,
116
+ },
117
+ {
118
+ run: runProcess,
119
+ github: ghGitHub(repoRoot),
120
+ registry: npmRegistryReader(),
121
+ print: (stream, line) => (stream === 'out' ? console.log(line) : console.error(line)),
122
+ },
123
+ ),
124
+ );
80
125
  } else {
81
- fail(`unknown command "${command ?? ''}". Available: init, sync, check`);
126
+ fail(`unknown command "${command ?? ''}". Available: init, sync, check, sync-pr`);
82
127
  }
83
128
  } catch (error) {
84
129
  if (error instanceof StackConfigError) fail(error.message);
package/src/config.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
 
4
- import { parse as parseJsonc, type ParseError } from 'jsonc-parser';
4
+ import { type Node, type ParseError, parseTree } from 'jsonc-parser';
5
5
 
6
- import { type Exception, exceptionProblem } from './exceptions.ts';
6
+ import { type Exception, exceptionProblem, exceptionSchema } from './exceptions.ts';
7
7
 
8
8
  export const STACK_CONFIG_FILE = '.stack.jsonc';
9
9
  export const PROFILES = ['node', 'contracts', 'infra'] as const;
10
+ // Допустимые ключи верхнего уровня .stack.jsonc; schema.json описывает тот же набор.
11
+ export const CONFIG_KEYS = ['$schema', 'profile', 'with', 'exceptions'] as const;
10
12
  export type Profile = (typeof PROFILES)[number];
11
13
 
12
14
  export interface StackConfig {
@@ -17,6 +19,21 @@ export interface StackConfig {
17
19
 
18
20
  export class StackConfigError extends Error {}
19
21
 
22
+ // Значение узла дерева разбора. parse из jsonc-parser пишет obj[key] = value: ключ __proto__ подменял бы
23
+ // прототип, а скаляр терялся; здесь объект собирается собственными свойствами, и __proto__ — обычный ключ.
24
+ function nodeValue(node: Node): unknown {
25
+ if (node.type === 'object') {
26
+ return Object.fromEntries(
27
+ (node.children ?? []).map((prop) => {
28
+ const [key, value] = prop.children ?? [];
29
+ return [key?.value, value ? nodeValue(value) : undefined];
30
+ }),
31
+ );
32
+ }
33
+ if (node.type === 'array') return (node.children ?? []).map(nodeValue);
34
+ return node.value;
35
+ }
36
+
20
37
  export function readStackConfig(repoRoot: string): StackConfig {
21
38
  const path = join(repoRoot, STACK_CONFIG_FILE);
22
39
  if (!existsSync(path)) {
@@ -25,28 +42,78 @@ export function readStackConfig(repoRoot: string): StackConfig {
25
42
  );
26
43
  }
27
44
  const errors: ParseError[] = [];
28
- const raw = parseJsonc(readFileSync(path, 'utf8'), errors, { allowTrailingComma: true }) as
29
- | Partial<StackConfig>
30
- | undefined;
31
- if (errors.length || raw == null || typeof raw !== 'object') {
32
- throw new StackConfigError(`${STACK_CONFIG_FILE}: does not parse as JSONC`);
45
+ const tree = parseTree(readFileSync(path, 'utf8'), errors, { allowTrailingComma: true });
46
+ if (errors.length) throw new StackConfigError(`${STACK_CONFIG_FILE}: does not parse as JSONC`);
47
+ const raw: unknown = tree === undefined ? undefined : nodeValue(tree);
48
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
49
+ throw new StackConfigError(`${STACK_CONFIG_FILE}: top level must be an object`);
50
+ }
51
+ const top = raw as Record<string, unknown>;
52
+ // Форму файла заявляют CONFIG_KEYS, PROFILES и EXCEPTION_SHAPES, schema.json строится из них: лишний
53
+ // ключ — опечатка, а не расширение.
54
+ const unknownKey = Object.keys(top).find((k) => !(CONFIG_KEYS as readonly string[]).includes(k));
55
+ if (unknownKey !== undefined) {
56
+ throw new StackConfigError(
57
+ `${STACK_CONFIG_FILE}: unknown key ${JSON.stringify(unknownKey)}, expected one of: ${CONFIG_KEYS.join(', ')}`,
58
+ );
59
+ }
60
+ if (top.$schema !== undefined && typeof top.$schema !== 'string') {
61
+ throw new StackConfigError(`${STACK_CONFIG_FILE}: "$schema" must be a string`);
33
62
  }
34
- const profile = raw.profile;
63
+ const profile = top.profile;
35
64
  if (!PROFILES.includes(profile as Profile)) {
36
65
  throw new StackConfigError(
37
66
  `${STACK_CONFIG_FILE}: profile="${String(profile)}", expected one of: ${PROFILES.join(', ')}`,
38
67
  );
39
68
  }
40
- const groups = raw.with ?? [];
69
+ // Умолчание — только для отсутствующего ключа: null схема запрещает так же, как не-массив.
70
+ const groups = top.with === undefined ? [] : top.with;
41
71
  if (!Array.isArray(groups) || groups.some((g) => typeof g !== 'string')) {
42
72
  throw new StackConfigError(`${STACK_CONFIG_FILE}: "with" must be an array of strings`);
43
73
  }
44
- const exceptions = raw.exceptions ?? [];
74
+ const exceptions = top.exceptions === undefined ? [] : top.exceptions;
45
75
  if (!Array.isArray(exceptions))
46
76
  throw new StackConfigError(`${STACK_CONFIG_FILE}: "exceptions" must be an array`);
47
77
  for (const e of exceptions) {
48
78
  const problem = exceptionProblem(e);
49
79
  if (problem) throw new StackConfigError(`${STACK_CONFIG_FILE}: ${problem}`);
50
80
  }
51
- return { profile: profile as Profile, with: groups, exceptions };
81
+ return {
82
+ profile: profile as Profile,
83
+ with: groups as string[],
84
+ exceptions: exceptions as Exception[],
85
+ };
86
+ }
87
+
88
+ // JSON Schema файла для редактора: строится из тех же констант, что читатель. packages/stack/schema.json
89
+ // равен её результату (config.test.ts). Свойство без ключа в CONFIG_KEYS и ключ без свойства не проходят tsc.
90
+ export function stackConfigSchema(groups: readonly string[]): Record<string, unknown> {
91
+ const properties: Record<(typeof CONFIG_KEYS)[number], unknown> = {
92
+ $schema: { type: 'string' },
93
+ profile: {
94
+ type: 'string',
95
+ enum: [...PROFILES],
96
+ description: 'Repo profile: picks which canon verbatim files get synced.',
97
+ },
98
+ with: {
99
+ type: 'array',
100
+ description:
101
+ 'Opt-in canon groups. "renovate" is deprecated and does nothing: Renovate is the canon\'s dependency bot for every profile.',
102
+ items: { type: 'string', enum: [...groups] },
103
+ },
104
+ exceptions: {
105
+ type: 'array',
106
+ description:
107
+ 'An exception holds its item back in both `stack check` (the finding is suppressed and reported as allowed) and `stack sync` (the item is left untouched). Each exception addresses exactly one canon file or exactly one catalog entry.',
108
+ items: exceptionSchema(),
109
+ },
110
+ };
111
+ return {
112
+ $schema: 'http://json-schema.org/draft-07/schema#',
113
+ title: 'stack config (.stack.jsonc)',
114
+ type: 'object',
115
+ properties,
116
+ required: ['profile'],
117
+ additionalProperties: false,
118
+ };
52
119
  }
package/src/exceptions.ts CHANGED
@@ -8,18 +8,55 @@ export interface Exception {
8
8
  reason: string;
9
9
  }
10
10
 
11
- // Допустимые адреса исключения. schema.json (oneOf исключения) сверяется с этим тестом.
11
+ // Допустимые адреса исключения. Схема строится из этих форм функцией exceptionSchema.
12
12
  export const EXCEPTION_SHAPES = [['file'], ['catalog', 'name']] as const;
13
13
 
14
- const ADDRESS_KEYS: string[] = EXCEPTION_SHAPES.flat();
14
+ const ADDRESS_KEYS: string[] = [...new Set(EXCEPTION_SHAPES.flat())];
15
15
 
16
- // Текст проблемы одной записи .stack.jsonc или undefined, если запись верна. Форма допустима, если
17
- // все ключи одной формы — непустые строки, а остальные адресные ключи отсутствуют.
16
+ // Допустимые ключи записи: адресные и reason; другой ключ — опечатка.
17
+ export const EXCEPTION_KEYS: readonly (keyof Exception)[] = [
18
+ ...new Set(EXCEPTION_SHAPES.flat()),
19
+ 'reason',
20
+ ];
21
+
22
+ // Фрагмент JSON Schema одной записи исключения: по ветке oneOf на форму, `not` запрещает адресные ключи
23
+ // чужих форм. Собирается из EXCEPTION_KEYS и EXCEPTION_SHAPES, чтобы схема не пересказывала их руками.
24
+ export function exceptionSchema(): Record<string, unknown> {
25
+ const oneOf = EXCEPTION_SHAPES.map((shape) => {
26
+ const own: readonly string[] = shape;
27
+ return {
28
+ required: [...shape],
29
+ not: { anyOf: ADDRESS_KEYS.filter((k) => !own.includes(k)).map((k) => ({ required: [k] })) },
30
+ };
31
+ });
32
+ return {
33
+ type: 'object',
34
+ additionalProperties: false,
35
+ properties: Object.fromEntries(
36
+ EXCEPTION_KEYS.map((k) => [k, { type: 'string', minLength: 1 }]),
37
+ ),
38
+ required: ['reason'],
39
+ oneOf,
40
+ };
41
+ }
42
+
43
+ // Текст проблемы одной записи .stack.jsonc или undefined, если запись верна. Порядок: запись — объект,
44
+ // ключи известны, причина есть и непустая строка, форма адреса. Форма допустима, если все ключи одной
45
+ // формы — непустые строки, а остальные адресные ключи отсутствуют.
18
46
  export function exceptionProblem(raw: unknown): string | undefined {
19
- // exceptions пришёл из JSON и типизирован через "as" — реальный элемент массива может быть
20
- // null/undefined, даже когда тип обещает Exception; проверяем честно, не полагаясь на "as".
21
- const e = raw as Record<string, unknown> | null | undefined;
22
- if (e == null || !e.reason) return `exception is missing "reason": ${JSON.stringify(e)}`;
47
+ // Запись пришла из JSON: строка, массив или null — не Exception, что бы ни обещал тип.
48
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
49
+ return `exception must be an object: ${JSON.stringify(raw)}`;
50
+ }
51
+ const e = raw as Record<string, unknown>;
52
+ const unknownKey = Object.keys(e).find((k) => !(EXCEPTION_KEYS as readonly string[]).includes(k));
53
+ if (unknownKey !== undefined) {
54
+ return `exception has unknown key ${JSON.stringify(unknownKey)}, expected one of: ${EXCEPTION_KEYS.join(', ')}: ${JSON.stringify(e)}`;
55
+ }
56
+ if (e.reason === undefined) return `exception is missing "reason": ${JSON.stringify(e)}`;
57
+ if (typeof e.reason !== 'string' || e.reason === '') {
58
+ return `exception "reason" must be a non-empty string: ${JSON.stringify(e)}`;
59
+ }
23
60
  const present = (v: unknown): boolean => v !== undefined;
24
61
  const nonEmpty = (v: unknown): boolean => typeof v === 'string' && v !== '';
25
62
  const fits = (keys: readonly string[]): boolean =>
package/src/findings.ts CHANGED
@@ -29,9 +29,12 @@ export type FindingCode = Finding['code'];
29
29
  export type FindingOf<C extends FindingCode> = Finding & { code: C };
30
30
 
31
31
  // Правка одного файла как данные: применитель собирает правки по файлу и пишет его один раз.
32
+ // yaml-append называет намерение («в последовательности по пути есть ещё один элемент»), позицию и
33
+ // создание последовательности решает применитель, поэтому правки одного файла не зависят друг от друга.
32
34
  export type Change =
33
35
  | { file: string; kind: 'write'; content: string }
34
- | { file: string; kind: 'yaml-set'; path: (string | number)[]; value: string | string[] }
36
+ | { file: string; kind: 'yaml-set'; path: (string | number)[]; value: string }
37
+ | { file: string; kind: 'yaml-append'; path: string[]; value: string }
35
38
  | { file: string; kind: 'json-set'; path: string[]; value: string };
36
39
 
37
40
  // Расхождение, которое sync умеет закрыть: находка плюс правка. check печатает message,
package/src/gh.ts ADDED
@@ -0,0 +1,78 @@
1
+ import { spawnSync } from 'node:child_process';
2
+
3
+ import type { GitHub } from './sync-pr.ts';
4
+
5
+ export type Exec = (
6
+ cmd: string,
7
+ args: readonly string[],
8
+ opts: { cwd: string; input?: string },
9
+ ) => { status: number | null; stdout: string; stderr: string; signal?: string | null };
10
+
11
+ // spawnSync с encoding utf8, cwd и input; бинаря нет (error) — status null, stderr = error.message.
12
+ // На ENOENT spawnSync оставляет stdout/stderr undefined — эта ветка возвращает строки.
13
+ export const spawnExec: Exec = (cmd, args, { cwd, input }) => {
14
+ const r = spawnSync(cmd, [...args], { cwd, encoding: 'utf8', input });
15
+ if (r.error) return { status: null, stdout: '', stderr: r.error.message };
16
+ return { status: r.status, signal: r.signal, stdout: r.stdout, stderr: r.stderr };
17
+ };
18
+
19
+ // Боевой adapter порта GitHub: gh берёт GH_TOKEN из окружения сам и запускается в cwd репозитория —
20
+ // git работает там же, и репозиторий для gh должен быть тем же.
21
+ export function ghGitHub(cwd: string, exec: Exec = spawnExec): GitHub {
22
+ function gh(args: readonly string[], input?: string): string {
23
+ const r = exec('gh', args, { cwd, input });
24
+ const name = `gh ${args[0]} ${args[1]}`;
25
+ if (r.signal) throw new Error(`${name} killed by ${r.signal}: ${r.stderr.trim()}`);
26
+ if (r.status !== 0) throw new Error(`${name} exited with ${r.status}: ${r.stderr.trim()}`);
27
+ return r.stdout;
28
+ }
29
+ // Синхронный spawn внутри Promise: throw становится отказом, а не исключением вызова.
30
+ const settle = <T>(f: () => T): Promise<T> => new Promise((resolve) => resolve(f()));
31
+ return {
32
+ botUserId: (slug) =>
33
+ settle(() => {
34
+ const stdout = gh(['api', `/users/${slug}[bot]`, '--jq', '.id']);
35
+ const id = Number(stdout.trim());
36
+ if (!Number.isInteger(id) || id <= 0) {
37
+ throw new Error(`gh api returned no user id for ${slug}[bot]: ${JSON.stringify(stdout)}`);
38
+ }
39
+ return id;
40
+ }),
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
+ createPr: (pr) =>
58
+ settle(() => {
59
+ const args = [
60
+ 'pr',
61
+ 'create',
62
+ '--title',
63
+ pr.title,
64
+ '--body-file',
65
+ '-',
66
+ '--head',
67
+ pr.head,
68
+ ...(pr.base ? ['--base', pr.base] : []),
69
+ ];
70
+ const lines = gh(args, pr.body)
71
+ .split('\n')
72
+ .filter((l) => l.trim() !== '');
73
+ const url = lines.at(-1);
74
+ if (!url) throw new Error('gh pr create printed no PR URL');
75
+ return url;
76
+ }),
77
+ };
78
+ }
@@ -0,0 +1,78 @@
1
+ // Чтение реестра npm и ожидание, пока в нём появятся версии. Импортирует только `node:*` (здесь —
2
+ // ничего): job rollout идёт без установки зависимостей (docs/release.md), а скрипт релиза
3
+ // и команда пакета ждут реестр одним и тем же кодом.
4
+
5
+ /** Читающий порт реестра: боевой — npm, в тестах — фейк. */
6
+ export interface Registry {
7
+ has(name: string, version: string): Promise<boolean>;
8
+ }
9
+
10
+ export interface Wanted {
11
+ readonly name: string;
12
+ readonly version: string;
13
+ }
14
+
15
+ export interface WaitOptions {
16
+ attempts: number;
17
+ intervalMs: number;
18
+ sleep?: (ms: number) => Promise<void>;
19
+ }
20
+
21
+ // Abbreviated-документ: те же заголовки, что у шага ожидания в sync.yml.
22
+ const ACCEPT = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*';
23
+
24
+ export function npmRegistryReader(timeoutMs = 30_000): Registry {
25
+ return {
26
+ async has(name, version) {
27
+ let res: Response;
28
+ try {
29
+ res = await fetch(`https://registry.npmjs.org/${name.replace('/', '%2f')}`, {
30
+ headers: { Accept: ACCEPT },
31
+ // Зависшее соединение иначе держит job релиза вечно.
32
+ signal: AbortSignal.timeout(timeoutMs),
33
+ });
34
+ } catch (e) {
35
+ throw new Error(
36
+ `${name}: реестр недоступен: ${e instanceof Error ? e.message : String(e)}`,
37
+ );
38
+ }
39
+ if (res.status === 404) return false;
40
+ if (!res.ok) throw new Error(`${name}: реестр ответил ${res.status}`);
41
+ let doc: { versions?: Record<string, unknown> };
42
+ try {
43
+ doc = (await res.json()) as { versions?: Record<string, unknown> };
44
+ } catch (e) {
45
+ // Не-JSON 200 или тело, оборванное abort'ом: без имени пакета лог не скажет, что чинить.
46
+ throw new Error(
47
+ `${name}: нечитаемый ответ реестра: ${e instanceof Error ? e.message : String(e)}`,
48
+ );
49
+ }
50
+ return doc.versions?.[version] !== undefined;
51
+ },
52
+ };
53
+ }
54
+
55
+ /** Ждёт, пока все записи появятся в реестре со своей версией; видимые повторно не опрашивает. */
56
+ export async function waitVisible(
57
+ wanted: readonly Wanted[],
58
+ registry: Registry,
59
+ opts: WaitOptions,
60
+ ): Promise<void> {
61
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
62
+ let pending = wanted;
63
+ for (let i = 1; i <= opts.attempts; i++) {
64
+ const left: Wanted[] = [];
65
+ for (const w of pending) {
66
+ // Сбой реестра (5xx, сеть) — «ещё не видно» на этой попытке, как в старом шаге sync.yml.
67
+ const visible = await registry.has(w.name, w.version).catch(() => false);
68
+ if (visible) console.log(`${w.name}@${w.version} есть в реестре`);
69
+ else left.push(w);
70
+ }
71
+ pending = left;
72
+ if (pending.length === 0) return;
73
+ if (i < opts.attempts) await sleep(opts.intervalMs);
74
+ }
75
+ throw new Error(
76
+ `за ${opts.attempts} попыток в реестре не появились версии: ${pending.map((w) => `${w.name}@${w.version}`).join(' ')}`,
77
+ );
78
+ }
@@ -21,43 +21,41 @@ function covers(entry: string, name: string, version: string): boolean {
21
21
  // Пока в pnpm-workspace.yaml включён minimumReleaseAge, свежий @alxwlw/* из канона pnpm install
22
22
  // отвергает в день публикации: sync держит версии канона в minimumReleaseAgeExclude. Чужие записи
23
23
  // и их порядок не трогаются, правка — только добавление версии к своей записи или новая запись.
24
+ // Правило называет намерение: позицию новой записи и создание списка (ключа нет, ключ без значения)
25
+ // решает применитель, поэтому находки не зависят друг от друга и любую из них можно удержать.
24
26
  export function planReleaseAgeExcludes(repo: Repo, canon: Canon): Drift[] {
25
27
  const doc = repo.workspace;
26
28
  if (doc === undefined) return [];
27
29
  const age = Number(doc.get('minimumReleaseAge'));
28
30
  if (!(age > 0)) return [];
29
31
  const existing = doc.get(KEY);
30
- // Ключ есть, а значения нет (`minimumReleaseAgeExclude:`): setIn по индексу в null бросает,
31
- // поэтому первая запись создаёт последовательность целиком.
32
- const empty = doc.has(KEY) && existing == null;
33
32
  // Не последовательность (скаляр, map): структуру руками не ломаем.
34
33
  if (existing != null && !isSeq(existing)) return [];
35
34
  const items: (string | undefined)[] = (existing?.items ?? []).map((n) =>
36
35
  isScalar(n) && typeof n.value === 'string' ? n.value : undefined,
37
36
  );
38
- let length = items.length;
39
37
  const plan: Drift[] = [];
40
38
  for (const [name, version] of Object.entries(canon.catalogs.dev ?? {})) {
41
39
  if (!name.startsWith(SCOPE)) continue;
42
40
  if (items.some((s) => s !== undefined && covers(s, name, version))) continue;
41
+ // Существующие элементы не сдвигаются, новые идут в конец: индекс своей записи верен при любом
42
+ // подмножестве применённых правок.
43
43
  const own = items.findIndex((s) => s !== undefined && s.trim().startsWith(`${name}@`));
44
- const extend = own >= 0;
45
- const seed = empty && !extend && length === 0;
46
- const path = seed ? [KEY] : [KEY, extend ? own : length];
47
- if (!extend) length++;
48
- const entry = extend ? `${items[own]} || ${version}` : `${name}@${version}`;
49
44
  plan.push({
50
45
  code: 'release-age-exclude',
51
46
  target: `${KEY}.${name}`,
52
47
  message: `${KEY} does not cover ${name}@${version}`,
53
48
  name,
54
49
  fix: `${KEY}: ${name}@${version}`,
55
- change: {
56
- kind: 'yaml-set',
57
- file: WORKSPACE_FILE,
58
- path,
59
- value: seed ? [entry] : entry,
60
- },
50
+ change:
51
+ own >= 0
52
+ ? {
53
+ kind: 'yaml-set',
54
+ file: WORKSPACE_FILE,
55
+ path: [KEY, own],
56
+ value: `${items[own]} || ${version}`,
57
+ }
58
+ : { kind: 'yaml-append', file: WORKSPACE_FILE, path: [KEY], value: `${name}@${version}` },
61
59
  });
62
60
  }
63
61
  return plan;
package/src/sync-pr.ts ADDED
@@ -0,0 +1,251 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+
5
+ import { loadCanon } from './canon.ts';
6
+ import { syncOutput, syncRepo } from './check.ts';
7
+ import { readStackConfig, StackConfigError } from './config.ts';
8
+ import { type Registry, type WaitOptions, waitVisible } from './registry.ts';
9
+
10
+ export interface NewPr {
11
+ head: string;
12
+ base?: string;
13
+ title: string;
14
+ body: string;
15
+ }
16
+
17
+ // Порт GitHub. Боевой adapter — gh; тесты — литерал.
18
+ export interface GitHub {
19
+ botUserId(slug: string): Promise<number>;
20
+ openPr(head: string): Promise<string | undefined>; // URL открытого PR с этой веткой
21
+ createPr(pr: NewPr): Promise<string>; // URL созданного PR
22
+ }
23
+
24
+ export type Print = (stream: 'out' | 'err', line: string) => void;
25
+
26
+ export interface PublishOptions {
27
+ repoRoot: string;
28
+ version: string;
29
+ base?: string;
30
+ appSlug: string;
31
+ }
32
+
33
+ export function prBody(version: string, files: readonly string[]): string {
34
+ return `Канон \`@alxwlw/stack@${version}\` применён к репозиторию.\n\nИзменённые файлы:\n${files.map((f) => `- ${f}\n`).join('')}\nРелиз: https://github.com/alxwlw/stack/releases/tag/v${version}\n`;
35
+ }
36
+
37
+ interface GitResult {
38
+ ok: boolean;
39
+ stdout: string;
40
+ stderr: string;
41
+ }
42
+
43
+ // Окружение дочернего процесса без GH_TOKEN: токен нужен только gh. git-хуки и скрипты зависимостей
44
+ // consumer'а исполняют чужой код и токена не получают (sync.yml даёт его одним шагам gh).
45
+ export function withoutGhToken(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
46
+ const rest = { ...env };
47
+ delete rest.GH_TOKEN;
48
+ return rest;
49
+ }
50
+
51
+ function runGit(cwd: string, args: readonly string[]): GitResult {
52
+ const r = spawnSync('git', args, {
53
+ cwd,
54
+ encoding: 'utf8',
55
+ maxBuffer: 1 << 30,
56
+ env: withoutGhToken(process.env),
57
+ });
58
+ const stderr = r.error ? r.error.message : r.stderr;
59
+ return { ok: r.status === 0 && !r.error, stdout: r.stdout, stderr: stderr.trimEnd() };
60
+ }
61
+
62
+ // Записи `XY путь` через NUL; при R/C следом идёт исходный путь. Игнорируемые файлы git не выводит.
63
+ function changedFiles(repoRoot: string): string[] {
64
+ const r = runGit(repoRoot, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
65
+ if (!r.ok) throw new Error(r.stderr);
66
+ const fields = r.stdout.split('\0');
67
+ const files: string[] = [];
68
+ for (let i = 0; i < fields.length; i++) {
69
+ const entry = fields[i] as string;
70
+ if (entry === '') continue;
71
+ files.push(entry.slice(3));
72
+ if (/[RC]/.test(entry.slice(0, 2))) {
73
+ const from = fields[++i];
74
+ if (from) files.push(from);
75
+ }
76
+ }
77
+ return [...new Set(files)];
78
+ }
79
+
80
+ const message = (error: unknown): string =>
81
+ error instanceof Error ? error.message : String(error);
82
+
83
+ // Шаги sync.yml:113-173 после установки и хука: список файлов, пользователь бота, ветка, commit, force-push, PR.
84
+ export async function publishChanges(
85
+ opts: PublishOptions,
86
+ github: GitHub,
87
+ print: Print,
88
+ ): Promise<0 | 1> {
89
+ const { repoRoot, version, appSlug } = opts;
90
+ const branch = `stack/v${version}`;
91
+ const title = `chore(stack): канон ${version}`;
92
+
93
+ let files: string[];
94
+ try {
95
+ files = changedFiles(repoRoot);
96
+ } catch (error) {
97
+ print('err', `sync-pr: git status failed: ${message(error)}`);
98
+ return 1;
99
+ }
100
+ if (files.length === 0) {
101
+ print('out', 'canon already applied, nothing to commit');
102
+ return 0;
103
+ }
104
+
105
+ let id: number;
106
+ try {
107
+ id = await github.botUserId(appSlug);
108
+ } catch (error) {
109
+ print('err', `sync-pr: bot user lookup failed: ${message(error)}`);
110
+ return 1;
111
+ }
112
+
113
+ const bot = `${appSlug}[bot]`;
114
+ const steps: [string, string[]][] = [
115
+ ['checkout', ['checkout', '-B', branch]],
116
+ ['add', ['add', '-A']],
117
+ [
118
+ 'commit',
119
+ [
120
+ '-c',
121
+ `user.name=${bot}`,
122
+ '-c',
123
+ `user.email=${id}+${bot}@users.noreply.github.com`,
124
+ 'commit',
125
+ '-m',
126
+ title,
127
+ ],
128
+ ],
129
+ ['push', ['push', '--force', 'origin', branch]],
130
+ ];
131
+ for (const [name, args] of steps) {
132
+ const r = runGit(repoRoot, args);
133
+ if (!r.ok) {
134
+ print('err', `sync-pr: git ${name} failed: ${r.stderr}`);
135
+ return 1;
136
+ }
137
+ }
138
+ print('out', `pushed ${branch}`);
139
+
140
+ let url: string | undefined;
141
+ try {
142
+ url = await github.openPr(branch);
143
+ } catch (error) {
144
+ print('err', `sync-pr: finding the open PR failed: ${message(error)}`);
145
+ return 1;
146
+ }
147
+ if (url) {
148
+ print('out', `updated PR ${url}`);
149
+ return 0;
150
+ }
151
+
152
+ try {
153
+ const pr: NewPr = { head: branch, title, body: prBody(version, files) };
154
+ if (opts.base) pr.base = opts.base;
155
+ url = await github.createPr(pr);
156
+ } catch (error) {
157
+ print('err', `sync-pr: creating the PR failed: ${message(error)}`);
158
+ return 1;
159
+ }
160
+ print('out', `opened PR ${url}`);
161
+ return 0;
162
+ }
163
+
164
+ // Порт процессов: код выхода; вывод процесса идёт в лог job (боевой adapter наследует stdio).
165
+ export type RunProcess = (
166
+ cmd: string,
167
+ args: readonly string[],
168
+ opts: { cwd: string; env?: Readonly<Record<string, string>> },
169
+ ) => number;
170
+
171
+ export interface SyncPrOptions extends PublishOptions {
172
+ install: boolean;
173
+ wait: WaitOptions;
174
+ }
175
+
176
+ export interface SyncPrPorts {
177
+ run: RunProcess;
178
+ github: GitHub;
179
+ registry: Registry;
180
+ print: Print;
181
+ }
182
+
183
+ // Как ATTEMPTS/INTERVAL шага ожидания в sync.yml.
184
+ export const SYNC_PR_WAIT: WaitOptions = { attempts: 12, intervalMs: 10_000 };
185
+
186
+ // Поле version из package.json пакета: он лежит рядом с src/, как canon/ (canonDir()).
187
+ export function ownVersion(): string {
188
+ const pkg = JSON.parse(readFileSync(join(import.meta.dir, '..', 'package.json'), 'utf8')) as {
189
+ version: string;
190
+ };
191
+ return pkg.version;
192
+ }
193
+
194
+ class StepFailed extends Error {}
195
+
196
+ // sync в процессе, ожидание реестра, установка, хук stack:post-sync, затем publishChanges.
197
+ export async function syncPr(opts: SyncPrOptions, ports: SyncPrPorts): Promise<0 | 1 | 2> {
198
+ const { repoRoot, version } = opts;
199
+ const { run, print } = ports;
200
+ try {
201
+ let canon: ReturnType<typeof loadCanon>;
202
+ try {
203
+ const cfg = readStackConfig(repoRoot);
204
+ canon = loadCanon(cfg);
205
+ const out = syncOutput(syncRepo(repoRoot, canon, cfg.exceptions));
206
+ for (const line of out.stderr) print('err', line);
207
+ for (const line of out.stdout) print('out', line);
208
+ } catch (error) {
209
+ if (error instanceof StackConfigError) {
210
+ print('err', error.message);
211
+ return 2;
212
+ }
213
+ throw error;
214
+ }
215
+
216
+ const pkgPath = join(repoRoot, 'package.json');
217
+ if (!existsSync(pkgPath)) return await publishChanges(opts, ports.github, print);
218
+
219
+ let hook = false;
220
+ try {
221
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as {
222
+ scripts?: Record<string, unknown>;
223
+ } | null;
224
+ const script = pkg?.scripts?.['stack:post-sync'];
225
+ hook = typeof script === 'string' && script !== '';
226
+ } catch (error) {
227
+ print('err', `sync-pr: package.json does not parse: ${message(error)}`);
228
+ return 1;
229
+ }
230
+
231
+ if (opts.install) {
232
+ const wanted = Object.entries(canon.catalogs.dev ?? {})
233
+ .filter(([name]) => name.startsWith('@alxwlw/'))
234
+ .map(([name, v]) => ({ name, version: v }));
235
+ await waitVisible(wanted, ports.registry, opts.wait);
236
+ }
237
+
238
+ const step = (cmd: string, args: string[], env?: Record<string, string>): void => {
239
+ const code = run(cmd, args, env ? { cwd: repoRoot, env } : { cwd: repoRoot });
240
+ if (code !== 0) throw new StepFailed(`\`${cmd} ${args.join(' ')}\` exited with ${code}`);
241
+ };
242
+ step('proto', ['install']);
243
+ if (opts.install) step('pnpm', ['install', '--no-frozen-lockfile']);
244
+ if (hook) step('pnpm', ['run', 'stack:post-sync'], { VERSION: version });
245
+
246
+ return await publishChanges(opts, ports.github, print);
247
+ } catch (error) {
248
+ print('err', `sync-pr: ${message(error)}`);
249
+ return 1;
250
+ }
251
+ }