From 73e2b20f3569c71fae866e673f4e47bf151a76ee Mon Sep 17 00:00:00 2001 From: CJ Brewer Date: Wed, 18 Nov 2026 14:37:45 -0700 Subject: [PATCH] fix(release): version a minor of @cipherstash/auth as a minor, not 1.0.0 The Version Packages PR planned @cipherstash/auth and its six platform packages at 0.44.1 -> 1.0.0, with no changeset asking for a major. Two `minor` changesets for auth were pending. The wrapper pins its platform packages as exact-version optional `peerDependencies` (`workspace:*`), all seven in one changesets `fixed` group. They are peers and not `optionalDependencies` on purpose (c1fa5de): Deno's resolver, and Supabase Edge Runtime with it, treats a missing optional platform package as a fatal graph error. Changesets gives a dependent a major bump when a peer leaves its declared range on a minor or major, and it reads `workspace:*` as "exactly the current version", so any minor of a platform package is out of range. The fixed group gives the platform packages a minor whenever the wrapper has one; the peer rule then makes the wrapper a major; the fixed group makes all seven a major. A patch is exempt from the rule, which is how 0.44.1 went out without anyone meeting this. Inside a fixed group the rule is a false positive: the group is versioned as one and the `workspace:` range is rewritten from that same version at pack time, so the peer cannot be out of range in what is published. Changesets has no switch for it (`onlyUpdatePeerDependentsWhenOutOfRange` is already on). `scripts/with-lockstep-peers-hidden.mjs` runs a command with each fixed group's own `workspace:` peers taken out of the manifest, and restores them afterwards, including when the command fails or is interrupted. The root `version` script now runs `changeset version` through it. The committed, packed and published manifests are unchanged; only what Changesets sees while it plans differs. Run on this tree, the version step gives 0.45.0 for the seven auth packages, leaves the auth manifest differing by its version line alone, and leaves the other 22 planned versions as they were. The test drives the real changesets CLI over a throwaway workspace shaped like the auth group, bare (1.0.0, pinning the behaviour this exists for) and through the wrapper (0.45.0). `release-version-hook.test.mjs` now fails a root script that runs `changeset version` without it. `changeset status` is not wrapped and still reports the major. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/release.yml | 6 +- AGENTS.md | 20 ++ package.json | 2 +- .../__tests__/release-version-hook.test.mjs | 23 ++ .../with-lockstep-peers-hidden.test.mjs | 331 ++++++++++++++++++ scripts/with-lockstep-peers-hidden.mjs | 220 ++++++++++++ 6 files changed, 599 insertions(+), 3 deletions(-) create mode 100644 scripts/__tests__/with-lockstep-peers-hidden.test.mjs create mode 100644 scripts/with-lockstep-peers-hidden.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ff0453d5e9..265ce6d5f1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -545,8 +545,10 @@ jobs: # REQUIRED BY `version:` BELOW, and nothing in this file says so without # this comment — which is why there is also a test. `pnpm run version` is - # `changeset version && node scripts/sync-skill-pins.mjs && node - # scripts/sync-lockstep-versions.mjs`, and that last script ends in + # `node scripts/with-lockstep-peers-hidden.mjs changeset version && node + # scripts/sync-skill-pins.mjs && node scripts/sync-lockstep-versions.mjs` + # (the first script runs `changeset version` itself; without it a minor + # of @cipherstash/auth is versioned as a major), and that last script ends in # `execFileSync('mise', ['run', # 'release:prepare_bindings_assets', …])`, which reaches # `packages/eql/tasks/build.sh` and two `cargo run -p eql-codegen` calls. diff --git a/AGENTS.md b/AGENTS.md index 9e611f2505..6252615a79 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -646,6 +646,26 @@ monorepo, which is where the silent failures are. tracked files the wrapper publishes, so a reformat does not ride along with an auth release. + **A minor of `@cipherstash/auth` needs `scripts/with-lockstep-peers-hidden.mjs` + to come out as a minor.** The wrapper pins its six platform packages as + exact-version optional `peerDependencies` (`workspace:*`). They are peers + and not `optionalDependencies` on purpose: Deno's resolver, and Supabase + Edge Runtime with it, treats a missing optional platform package as a fatal + graph error. Changesets gives a dependent a MAJOR bump when a peer leaves + its range on a minor, and reads `workspace:*` as "exactly the current + version", so a `minor` changeset planned 0.44.1 -> 1.0.0 for all seven + packages with no changeset asking for a major. A patch is exempt from that + rule, which is how 0.44.1 went out unnoticed. Inside a fixed group the rule + is a false positive, because the range and the version move together, so + the root `version` script runs `changeset version` through that wrapper: it + takes a fixed group's own `workspace:` peers out of the manifest while + Changesets plans, and puts them back. The committed and published manifests + are unchanged. `scripts/__tests__/with-lockstep-peers-hidden.test.mjs` + drives the real CLI both ways. `changeset status`, and so anything that + reads its plan, is NOT wrapped and still reports the major; the Version + Packages PR is what shows the real number, so read the auth version there + before merging it. + **Check 3 is the one worth understanding before you touch a frozen package.** For a package this repo publishes, in-tree bytes differing from npm is an unreleased change — every pull request. For a frozen one it is a diff --git a/package.json b/package.json index 712d9e024d..2b8d5f9c7a 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "lint:typecheck-scope": "node scripts/lint-typecheck-scope.mjs", "lint:workflow-cache": "node scripts/lint-no-workflow-caching.mjs", "release:gate": "node scripts/release-gate.mjs", - "version": "changeset version && node scripts/sync-skill-pins.mjs && node scripts/sync-lockstep-versions.mjs", + "version": "node scripts/with-lockstep-peers-hidden.mjs changeset version && node scripts/sync-skill-pins.mjs && node scripts/sync-lockstep-versions.mjs", "release": "pnpm run build && changeset publish", "test": "turbo test --filter './languages/typescript/packages/**' --filter './packages/**'", "test:e2e": "turbo run test:e2e", diff --git a/scripts/__tests__/release-version-hook.test.mjs b/scripts/__tests__/release-version-hook.test.mjs index 9ec564197f..c643c9273a 100644 --- a/scripts/__tests__/release-version-hook.test.mjs +++ b/scripts/__tests__/release-version-hook.test.mjs @@ -36,6 +36,7 @@ import { readWorkflow } from './lib/workflows.mjs' const RELEASE_WORKFLOW = '.github/workflows/release.yml' const CHANGESETS_ACTION = 'changesets/action' const VERSION_SCRIPT = 'sync-lockstep-versions.mjs' +const PEERS_WRAPPER = 'with-lockstep-peers-hidden.mjs' /** Every step in a workflow, flattened across jobs, with its job name. */ function steps(workflow) { @@ -159,6 +160,28 @@ describe('no root script invokes a bare changesets command', () => { ).toEqual([]) }) + it('runs every `changeset version` with the lockstep peers hidden', () => { + // `@cipherstash/auth` pins its platform packages as exact-version peers in + // one fixed group. Run bare, `changeset version` reads that as a peer + // leaving its range and turns a minor changeset into 1.0.0 for all seven + // packages. The wrapper is what stops it; see + // `with-lockstep-peers-hidden.test.mjs`, which drives the real CLI both + // ways. + const offenders = invoking('version') + .filter( + ([, body]) => + !new RegExp(`${PEERS_WRAPPER}\\s+changeset\\s+version\\b`).test(body), + ) + .map(([name, body]) => `${name}: ${body}`) + expect( + offenders, + `A root script runs \`changeset version\` without scripts/${PEERS_WRAPPER}. A minor ` + + 'changeset on @cipherstash/auth would then be versioned as a major. Run it as ' + + `\`node scripts/${PEERS_WRAPPER} changeset version\`, or route the alias through ` + + '`pnpm run version`.', + ).toEqual([]) + }) + it('builds before every `changeset publish`', () => { const offenders = invoking('publish') .filter(([, body]) => !/\brun build\b/.test(body)) diff --git a/scripts/__tests__/with-lockstep-peers-hidden.test.mjs b/scripts/__tests__/with-lockstep-peers-hidden.test.mjs new file mode 100644 index 0000000000..5eee78e682 --- /dev/null +++ b/scripts/__tests__/with-lockstep-peers-hidden.test.mjs @@ -0,0 +1,331 @@ +import { spawnSync } from 'node:child_process' +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + lockstepPeers, + withoutPeers, + withPeersRestored, +} from '../with-lockstep-peers-hidden.mjs' +import { REPO_ROOT } from './lib/repo-root.mjs' + +/** + * `@cipherstash/auth` and its six platform packages version together as one + * changesets `fixed` group, and the wrapper pins the six as exact-version + * optional PEER dependencies (`workspace:*`). Changesets gives a dependent a + * MAJOR bump when a peer leaves its range on a minor, and reads `workspace:*` + * as "exactly the current version" — so a `minor` changeset on the wrapper + * planned 0.44.1 -> 1.0.0 for all seven, with no changeset asking for a major. + * It was caught in the Version Packages PR, by a person, days after the minor + * changeset merged. + * + * `scripts/with-lockstep-peers-hidden.mjs` runs `changeset version` with those + * peers hidden. Nothing type-checks a release plan, and the only other place + * the number shows up is a generated PR diff, so this file drives the REAL + * changesets CLI over a throwaway workspace shaped like the auth group: once + * bare, to pin the behaviour the wrapper exists for, and once through the + * wrapper. + */ + +const WRAPPER = join(REPO_ROOT, 'scripts/with-lockstep-peers-hidden.mjs') +const CHANGESETS_CLI = createRequire(join(REPO_ROOT, 'package.json')).resolve( + '@changesets/cli/bin.js', +) + +const WRAPPER_PEERS = { + 'wrapper-darwin': 'workspace:*', + 'wrapper-linux': 'workspace:*', + // A peer outside the fixed group. It must survive untouched. + 'some-framework': '>=1.132.0', +} + +const dirs = [] +afterEach(() => { + for (const dir of dirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } +}) + +/** + * A workspace with a `wrapper` package and two platform packages in one fixed + * group at 0.44.1, and one changeset bumping `wrapper` by `bump`. + */ +function workspace(bump = 'minor') { + const dir = mkdtempSync(join(tmpdir(), 'lockstep-peers-')) + dirs.push(dir) + const write = (file, value) => { + mkdirSync(join(dir, file, '..'), { recursive: true }) + writeFileSync( + join(dir, file), + typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`, + ) + } + write('package.json', { + name: 'fixture', + private: true, + workspaces: ['packages/*'], + }) + write('.changeset/config.json', { + changelog: false, + commit: false, + fixed: [['wrapper', 'wrapper-darwin', 'wrapper-linux']], + access: 'restricted', + baseBranch: 'main', + updateInternalDependencies: 'patch', + // As in this repo's own config. It is what makes `workspace:*` count as + // out of range rather than every peer bump being a major. + ___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH: { + onlyUpdatePeerDependentsWhenOutOfRange: true, + }, + }) + write('.changeset/bump.md', `---\n'wrapper': ${bump}\n---\n\nA change.\n`) + write('packages/wrapper/package.json', { + name: 'wrapper', + version: '0.44.1', + peerDependencies: WRAPPER_PEERS, + peerDependenciesMeta: { + 'wrapper-darwin': { optional: true }, + 'wrapper-linux': { optional: true }, + }, + dependencies: { 'left-pad': '^1.0.0' }, + }) + for (const name of ['wrapper-darwin', 'wrapper-linux']) { + write(`packages/${name}/package.json`, { name, version: '0.44.1' }) + } + return dir +} + +const manifest = (dir, name) => + JSON.parse(readFileSync(join(dir, 'packages', name, 'package.json'), 'utf8')) + +const versions = (dir) => + Object.fromEntries( + ['wrapper', 'wrapper-darwin', 'wrapper-linux'].map((name) => [ + name, + manifest(dir, name).version, + ]), + ) + +/** Run `node ` in `dir`, returning its status and combined output. */ +function run(dir, args) { + const result = spawnSync(process.execPath, args, { + cwd: dir, + encoding: 'utf8', + }) + return { + status: result.status, + output: `${result.stdout ?? ''}${result.stderr ?? ''}`, + } +} + +describe('changeset version over a fixed group with workspace:* peers', () => { + it('bare, turns a minor changeset into a major for the whole group', () => { + // The behaviour the wrapper exists for, pinned against the installed + // changesets. If this ever fails because the group comes out at 0.45.0, + // changesets has stopped applying its peer rule inside a fixed group, and + // `with-lockstep-peers-hidden.mjs` can be retired. + const dir = workspace('minor') + const { status, output } = run(dir, [CHANGESETS_CLI, 'version']) + expect(status, output).toBe(0) + expect(versions(dir)).toEqual({ + wrapper: '1.0.0', + 'wrapper-darwin': '1.0.0', + 'wrapper-linux': '1.0.0', + }) + }) + + it('through the wrapper, gives the minor that was asked for', () => { + const dir = workspace('minor') + const before = manifest(dir, 'wrapper') + const { status, output } = run(dir, [ + WRAPPER, + process.execPath, + CHANGESETS_CLI, + 'version', + ]) + expect(status, output).toBe(0) + expect(versions(dir)).toEqual({ + wrapper: '0.45.0', + 'wrapper-darwin': '0.45.0', + 'wrapper-linux': '0.45.0', + }) + + // The manifest that gets committed and packed is the one that was there, + // with a new version and nothing else: same peers, same order, same + // optional markers. A wrapper that left the peers out would publish a + // package that no longer names the binaries it needs. + const after = manifest(dir, 'wrapper') + expect(after).toEqual({ ...before, version: '0.45.0' }) + expect(Object.keys(after)).toEqual(Object.keys(before)) + expect(Object.keys(after.peerDependencies)).toEqual( + Object.keys(WRAPPER_PEERS), + ) + expect(output).toMatch( + /hiding 2 lockstep peer\(s\) of packages\/wrapper\/package\.json/, + ) + }) + + it('leaves a patch alone, which the peer rule never touched', () => { + const dir = workspace('patch') + const { status, output } = run(dir, [ + WRAPPER, + process.execPath, + CHANGESETS_CLI, + 'version', + ]) + expect(status, output).toBe(0) + expect(versions(dir).wrapper).toBe('0.44.2') + }) + + it('restores the peers and passes the exit status on when the command fails', () => { + const dir = workspace('minor') + const file = join(dir, 'packages/wrapper/package.json') + const before = readFileSync(file, 'utf8') + const { status } = run(dir, [ + WRAPPER, + process.execPath, + '-e', + // Fail while the peers are hidden, having proved that they are. + `const peers = require(${JSON.stringify(file)}).peerDependencies; + if ('wrapper-darwin' in peers || !('some-framework' in peers)) process.exit(9); + process.exit(3);`, + ]) + expect(status).toBe(3) + expect(readFileSync(file, 'utf8')).toBe(before) + }) + + it('refuses to run with no command', () => { + const dir = workspace('minor') + const { status, output } = run(dir, [WRAPPER]) + expect(status).toBe(2) + expect(output).toMatch(/usage:/) + }) +}) + +describe('lockstepPeers', () => { + const fixed = [['a', 'a-darwin', 'a-linux']] + + it('picks the workspace peers a package has on its own fixed group', () => { + expect( + lockstepPeers( + { + name: 'a', + peerDependencies: { + 'a-darwin': 'workspace:*', + 'a-linux': 'workspace:^', + react: '>=18', + }, + }, + fixed, + ), + ).toEqual(['a-darwin', 'a-linux']) + }) + + it('leaves a peer between packages that do not version together', () => { + // Here the changesets rule is right: `b` really can fall out of range. + expect( + lockstepPeers( + { name: 'b', peerDependencies: { a: 'workspace:*' } }, + fixed, + ), + ).toEqual([]) + expect( + lockstepPeers( + { name: 'a', peerDependencies: { b: 'workspace:*' } }, + fixed, + ), + ).toEqual([]) + }) + + it('leaves a group peer that is not a workspace range', () => { + // A literal range is published as written, so it can go out of range. + expect( + lockstepPeers( + { name: 'a', peerDependencies: { 'a-darwin': '0.44.1' } }, + fixed, + ), + ).toEqual([]) + }) + + it('copes with a package that has no peers at all', () => { + expect(lockstepPeers({ name: 'a-darwin' }, fixed)).toEqual([]) + }) +}) + +describe('withoutPeers / withPeersRestored', () => { + const original = `${JSON.stringify( + { + name: 'a', + version: '0.44.1', + peerDependencies: { 'a-darwin': 'workspace:*', react: '>=18' }, + dependencies: { x: '^1.0.0' }, + }, + null, + '\t', + )}\n` + + it('removes only the named peers, keeping the key and the formatting', () => { + const hidden = withoutPeers(original, ['a-darwin']) + expect(JSON.parse(hidden).peerDependencies).toEqual({ react: '>=18' }) + expect(hidden).toMatch(/^\t"name"/m) + expect(hidden.endsWith('}\n')).toBe(true) + // An emptied table stays as a key, so it keeps its place in the file. + const emptied = JSON.parse(withoutPeers(original, ['a-darwin', 'react'])) + expect(Object.keys(emptied)).toEqual(Object.keys(JSON.parse(original))) + expect(emptied.peerDependencies).toEqual({}) + }) + + it('restores the named peers and keeps what the command wrote', () => { + const afterCommand = JSON.stringify( + { + ...JSON.parse(withoutPeers(original, ['a-darwin'])), + version: '0.45.0', + // A range the command rewrote on a peer that was never hidden. + peerDependencies: { react: '>=19' }, + }, + null, + '\t', + ) + const restored = JSON.parse( + withPeersRestored(afterCommand, original, ['a-darwin']), + ) + expect(restored.version).toBe('0.45.0') + expect(restored.peerDependencies).toEqual({ + 'a-darwin': 'workspace:*', + react: '>=19', + }) + expect(Object.keys(restored.peerDependencies)).toEqual([ + 'a-darwin', + 'react', + ]) + }) +}) + +describe('this repository', () => { + const read = (file) => JSON.parse(readFileSync(join(REPO_ROOT, file), 'utf8')) + + it('is the case the wrapper exists for: auth pins its six platform packages as lockstep peers', () => { + // If this fails because the platform packages moved out of + // `peerDependencies`, the wrapper has nothing left to hide here. Before + // deleting it, read `scripts/with-lockstep-peers-hidden.mjs` for why they + // are peers at all (Deno's resolver). + const { fixed } = read('.changeset/config.json') + const auth = read('languages/typescript/packages/auth/package.json') + const hidden = lockstepPeers(auth, fixed) + expect(hidden).toHaveLength(6) + expect(hidden.every((name) => name.startsWith('@cipherstash/auth-'))).toBe( + true, + ) + // The peer on TanStack Start is not the group's own, and is not hidden. + expect(auth.peerDependencies['@tanstack/react-start']).toBeTruthy() + expect(hidden).not.toContain('@tanstack/react-start') + }) +}) diff --git a/scripts/with-lockstep-peers-hidden.mjs b/scripts/with-lockstep-peers-hidden.mjs new file mode 100644 index 0000000000..7edc8e1c13 --- /dev/null +++ b/scripts/with-lockstep-peers-hidden.mjs @@ -0,0 +1,220 @@ +// Run a command (in practice `changeset version`) with each changesets `fixed` +// group's own `workspace:` peer dependencies hidden, and put them back after. +// +// node scripts/with-lockstep-peers-hidden.mjs changeset version +// +// Why this exists. `@cipherstash/auth` declares its six platform packages as +// optional `peerDependencies` at `workspace:*`, deliberately: Deno's resolver +// (and Supabase Edge Runtime) treats a missing `optionalDependencies` platform +// package as a fatal graph error, so they are peers, and `pnpm pack` rewrites +// `workspace:*` to the exact version so the wrapper and its binaries stay +// paired. All seven version together as one changesets `fixed` group. +// +// Changesets has a rule for peers: when a peer dependency gets a minor or +// major bump that leaves the dependent's declared range, the DEPENDENT gets a +// MAJOR bump. It reads `workspace:*` as "exactly the current version", so any +// minor of a platform package is out of range — and the fixed group gives the +// platform packages a minor whenever the wrapper has one. A `minor` changeset +// on `@cipherstash/auth` therefore planned 0.44.1 -> 1.0.0 for all seven +// packages, with no changeset anywhere asking for a major. A patch is exempt +// from the rule, which is how 0.44.1 itself went out unnoticed. +// +// Inside a fixed group that rule is a false positive. The range and the +// version move together by construction: the group is versioned as one, and +// the `workspace:` range is rewritten from that same version at pack time. +// The peer can never be out of range in what is published. +// +// Changesets has no switch for this (`onlyUpdatePeerDependentsWhenOutOfRange` +// is already on, and is what makes `workspace:*` "out of range"). So the peers +// are taken out of the manifest for the duration of the command and restored +// afterwards, including when the command fails or is interrupted. Nothing +// about the manifest that is committed, packed or published changes; only what +// Changesets sees while it computes the plan. +// +// Only a fixed group's peers on its OWN members, at a `workspace:` range, are +// hidden. A peer on anything else (`@tanstack/react-start`, say) is left +// alone, and so is a peer between packages that do not version together — +// there the rule is doing its job. + +import { spawnSync } from 'node:child_process' +import { readFileSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { join, relative, sep } from 'node:path' +import { fileURLToPath } from 'node:url' + +const require = createRequire(import.meta.url) +// Changesets' own modules, so this sees the workspace and the `fixed` groups +// exactly as `changeset version` will. They are dependencies of the CLI, not +// of this repo, hence the second resolver. +const changesetsRequire = createRequire( + require.resolve('@changesets/cli/package.json'), +) + +/** + * The peers of `manifest` to hide: those naming another member of its fixed + * group at a `workspace:` range. + * + * @param {{ name?: string, peerDependencies?: Record }} manifest + * @param {ReadonlyArray>} fixedGroups + * @returns {string[]} + */ +export function lockstepPeers(manifest, fixedGroups) { + const group = fixedGroups.find((names) => names.includes(manifest.name)) + if (!group) return [] + return Object.entries(manifest.peerDependencies ?? {}) + .filter( + ([name, range]) => + name !== manifest.name && + group.includes(name) && + typeof range === 'string' && + range.startsWith('workspace:'), + ) + .map(([name]) => name) +} + +/** Serialise `manifest` the way `text` was written: same indent, same ending. */ +function serialise(manifest, text) { + const indent = /^([ \t]+)\S/m.exec(text)?.[1] ?? 2 + return ( + JSON.stringify(manifest, null, indent) + (text.endsWith('\n') ? '\n' : '') + ) +} + +/** + * `text` (a package.json) without the peers in `names`. The `peerDependencies` + * key itself stays, even when empty, so it keeps its place in the file. + * + * @param {string} text + * @param {ReadonlyArray} names + * @returns {string} + */ +export function withoutPeers(text, names) { + const manifest = JSON.parse(text) + for (const name of names) delete manifest.peerDependencies[name] + return serialise(manifest, text) +} + +/** + * `current` (the package.json as the command left it) with the peers in + * `names` put back from `original`, in their original order. Everything else + * `current` holds is kept: the version the command wrote, and any range it + * rewrote on a peer that was not hidden. + * + * @param {string} current + * @param {string} original + * @param {ReadonlyArray} names + * @returns {string} + */ +export function withPeersRestored(current, original, names) { + const manifest = JSON.parse(current) + const before = JSON.parse(original).peerDependencies ?? {} + const now = manifest.peerDependencies ?? {} + const restored = {} + for (const [name, range] of Object.entries(before)) { + restored[name] = names.includes(name) ? range : (now[name] ?? range) + } + for (const [name, range] of Object.entries(now)) { + if (!(name in restored)) restored[name] = range + } + manifest.peerDependencies = restored + return serialise(manifest, current) +} + +/** + * Hide the lockstep peers of every package under `root`. Returns what was + * hidden, for {@link restoreLockstepPeers}. + * + * @param {string} root The workspace root (where `.changeset/` lives). + * @returns {Promise>} + */ +export async function hideLockstepPeers(root) { + const { getPackagesSync } = changesetsRequire('@manypkg/get-packages') + const { read } = changesetsRequire('@changesets/config') + const packages = getPackagesSync(root) + const { fixed } = await read(root, packages) + + const hidden = [] + for (const { dir, packageJson } of packages.packages) { + const names = lockstepPeers(packageJson, fixed) + if (names.length === 0) continue + const manifestPath = join(dir, 'package.json') + const original = readFileSync(manifestPath, 'utf8') + writeFileSync(manifestPath, withoutPeers(original, names)) + hidden.push({ manifestPath, original, names }) + } + return hidden +} + +/** + * Put back what {@link hideLockstepPeers} hid, and check that it is back. + * + * @param {Array<{ manifestPath: string, original: string, names: string[] }>} hidden + */ +export function restoreLockstepPeers(hidden) { + for (const { manifestPath, original, names } of hidden) { + const current = readFileSync(manifestPath, 'utf8') + writeFileSync(manifestPath, withPeersRestored(current, original, names)) + + const peers = JSON.parse( + readFileSync(manifestPath, 'utf8'), + ).peerDependencies + const before = JSON.parse(original).peerDependencies + const missing = names.filter((name) => peers?.[name] !== before[name]) + if (missing.length > 0) { + throw new Error( + `${manifestPath}: could not restore the peer dependencies ${missing.join(', ')}. ` + + 'Do not commit this file as it is: the published package would lose the exact-version ' + + 'peers that pair it with its platform binaries.', + ) + } + } +} + +async function main() { + const argv = process.argv.slice(2) + if (argv[0] === '--') argv.shift() + const [command, ...args] = argv + if (!command) { + console.error( + 'usage: node scripts/with-lockstep-peers-hidden.mjs [args...]', + ) + process.exit(2) + } + + const root = process.cwd() + const hidden = await hideLockstepPeers(root) + for (const { manifestPath, names } of hidden) { + const file = relative(root, manifestPath).split(sep).join('/') + console.log( + `hiding ${names.length} lockstep peer(s) of ${file} while \`${command} ${args.join(' ')}\` runs`, + ) + } + + let restored = false + const restore = () => { + if (restored) return + restored = true + restoreLockstepPeers(hidden) + } + // With no handler, a signal ends this process without running `finally`, + // and leaves the manifests without their peers. With one, Node defers it + // until the synchronous child below has returned. + for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) { + process.on(signal, () => { + restore() + process.exit(1) + }) + } + + let result + try { + result = spawnSync(command, args, { cwd: root, stdio: 'inherit' }) + } finally { + restore() + } + if (hidden.length > 0) console.log('restored the lockstep peers') + if (result.error) throw result.error + process.exit(result.status ?? 1) +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) await main()