Open History to see the last commit
1/** Production drivers for release-history-oracle.js; no expected release plan. */
2import { execFileSync, spawnSync } from 'node:child_process'
3import {
4 existsSync,
5 mkdirSync,
6 mkdtempSync,
7 readFileSync,
8 readdirSync,
9 rmSync,
10 writeFileSync,
11} from 'node:fs'
12import { createRequire } from 'node:module'
13import { tmpdir } from 'node:os'
14import { join } from 'node:path'
15import { packageNames } from './release-history-oracle.js'
16
17const require = createRequire(import.meta.url)
18const cli = require.resolve('@changesets/cli/bin.js')
19export const fixtureRegistry = 'http://127.0.0.1:4873'
20
21export function writeJson(path, value) {
22 writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`)
23}
24
25export function readJson(path) {
26 return JSON.parse(readFileSync(path, 'utf8'))
27}
28
29export function manifestPath(root, key) {
30 return join(root, 'packages', key, 'package.json')
31}
32
33export function addFixtureChangeset(root, id, releases) {
34 const entries = Object.entries(releases)
35 .map(([key, type]) => `'${packageNames[key]}': ${type}`)
36 .join('\n')
37 writeFileSync(
38 join(root, '.changeset', `${id}.md`),
39 `---\n${entries}\n---\n\nrelease-token:${id}\n`,
40 )
41}
42
43export function createReleaseWorkspace(stableDependency = false) {
44 const root = mkdtempSync(join(tmpdir(), 'db-release-oracle-'))
45 mkdirSync(join(root, '.changeset'))
46 mkdirSync(join(root, 'examples'))
47 writeJson(join(root, 'package.json'), {
48 name: 'release-oracle-fixture',
49 private: true,
50 packageManager: 'pnpm@11.1.0',
51 })
52 writeFileSync(
53 join(root, 'pnpm-workspace.yaml'),
54 'packages:\n - packages/*\n',
55 )
56 writeJson(join(root, '.changeset', 'config.json'), {
57 changelog: ['./changelog.cjs', null],
58 commit: false,
59 access: 'public',
60 baseBranch: 'main',
61 updateInternalDependencies: 'patch',
62 fixed: [],
63 linked: [],
64 ignore: [],
65 privatePackages: { version: false, tag: false },
66 ___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH: {
67 onlyUpdatePeerDependentsWhenOutOfRange: true,
68 },
69 })
70 // Formatting is deliberately trivial. The callback supplies the raw ID;
71 // only the independent model decides when/where that ID must occur once.
72 writeFileSync(
73 join(root, '.changeset', 'changelog.cjs'),
74 `
75 exports.getReleaseLine = async (changeset) => {
76 if (process.env.RELEASE_ORACLE_CHANGELOG_FAIL === ${JSON.stringify(root)})
77 throw new Error('injected release changelog failure')
78 return '- ' + changeset.summary
79 }
80 exports.getDependencyReleaseLine = async () => ''
81 `,
82 )
83 const manifests = {
84 db: {
85 name: packageNames.db,
86 version: '0.15.2',
87 devDependencies: { 'release-private': 'workspace:*' },
88 },
89 react: {
90 name: packageNames.react,
91 version: '0.1.0',
92 dependencies: { [packageNames.db]: 'workspace:*' },
93 },
94 query: {
95 name: packageNames.query,
96 version: '1.4.8',
97 peerDependencies: { [packageNames.db]: '^1.0.0-rc.0' },
98 },
99 offline: {
100 name: packageNames.offline,
101 version: '1.1.4',
102 ...(stableDependency
103 ? { dependencies: { [packageNames.db]: 'workspace:*' } }
104 : { peerDependencies: { [packageNames.db]: '^1.0.0-rc.0' } }),
105 },
106 private: {
107 name: 'release-private',
108 version: '0.1.0',
109 private: true,
110 description: 'must retain exact original manifest bytes',
111 },
112 }
113 for (const [key, value] of Object.entries(manifests)) {
114 mkdirSync(join(root, 'packages', key), { recursive: true })
115 writeJson(manifestPath(root, key), value)
116 }
117 return { root, privateManifest: structuredClone(manifests.private) }
118}
119
120export function enterRealPreMode(root) {
121 execFileSync(process.execPath, [cli, 'pre', 'enter', 'rc'], {
122 cwd: root,
123 stdio: 'pipe',
124 timeout: 10_000,
125 env: { ...process.env, CI: 'true' },
126 })
127}
128
129export function exitRealPreMode(root) {
130 execFileSync(process.execPath, [cli, 'pre', 'exit'], {
131 cwd: root,
132 stdio: 'pipe',
133 timeout: 10_000,
134 env: { ...process.env, CI: 'true' },
135 })
136}
137
138export function repeatStableVersion(root) {
139 execFileSync(process.execPath, [cli, 'version'], {
140 cwd: root,
141 stdio: 'pipe',
142 timeout: 10_000,
143 env: { ...process.env, CI: 'true' },
144 })
145}
146
147export function observeRelease(fixture) {
148 const { root } = fixture
149 const manifests = Object.fromEntries(
150 Object.keys(packageNames).map((key) => [
151 key,
152 readJson(manifestPath(root, key)),
153 ]),
154 )
155 const prePath = join(root, '.changeset', 'pre.json')
156 return {
157 versions: Object.fromEntries(
158 Object.entries(manifests).map(([key, manifest]) => [
159 key,
160 manifest.version,
161 ]),
162 ),
163 tokens: Object.fromEntries(
164 Object.keys(packageNames).map((key) => {
165 const path = join(root, 'packages', key, 'CHANGELOG.md')
166 const text = existsSync(path) ? readFileSync(path, 'utf8') : ''
167 let version
168 const tokens = []
169 for (const line of text.split('\n')) {
170 if (line.startsWith('## ')) version = line.slice(3)
171 for (const match of line.matchAll(/release-token:([a-z0-9-]+)/g))
172 tokens.push({ id: match[1], version })
173 }
174 return [key, tokens]
175 }),
176 ),
177 pre: existsSync(prePath) ? readJson(prePath) : undefined,
178 changesets: readdirSync(join(root, '.changeset'))
179 .filter((file) => file.endsWith('.md'))
180 .map((file) => file.slice(0, -3)),
181 privateManifest: readJson(manifestPath(root, 'private')),
182 originalPrivateManifest: fixture.privateManifest,
183 ignoredDependency: manifests.db.devDependencies['release-private'],
184 dependencies: {
185 react: manifests.react.dependencies[packageNames.db],
186 query: manifests.query.peerDependencies[packageNames.db],
187 offline: (manifests.offline.dependencies ??
188 manifests.offline.peerDependencies)[packageNames.db],
189 },
190 }
191}
192
193export function workspaceBytes(root) {
194 const result = {}
195 const visit = (directory, prefix = '') => {
196 for (const entry of readdirSync(directory, { withFileTypes: true })) {
197 const name = `${prefix}${entry.name}`
198 if (entry.isDirectory()) visit(join(directory, entry.name), `${name}/`)
199 else
200 result[name] = readFileSync(join(directory, entry.name)).toString(
201 'base64',
202 )
203 }
204 }
205 visit(root)
206 return result
207}
208
209export async function withReleaseWorkspace(
210 body,
211 stableDependency = false,
212 cleanupWorkspace = rmSync,
213) {
214 const fixture = createReleaseWorkspace(stableDependency)
215 let failed = false
216 let primary
217 try {
218 return await body(fixture)
219 } catch (error) {
220 failed = true
221 primary = error
222 throw error
223 } finally {
224 try {
225 cleanupWorkspace(fixture.root, { recursive: true, force: true })
226 } catch (cleanup) {
227 throw failed
228 ? new AggregateError(
229 [primary, cleanup],
230 'Release mismatch and workspace cleanup failure',
231 { cause: primary },
232 )
233 : cleanup
234 }
235 }
236}
237
238/**
239 * Real Changesets runs behind strict local npm/pnpm process shims. Those shims
240 * only supply registry responses and capture requests; they choose no tag.
241 * No real npm command, network request, package install or HTTP server runs.
242 */
243export function preparePublishReceiver(root, history) {
244 const bin = join(root, 'bin')
245 mkdirSync(bin)
246 const registryPath = join(root, 'registry.json')
247 const logPath = join(root, 'registry-requests.json')
248 const emptyConfig = join(root, 'empty-config')
249 writeFileSync(emptyConfig, '')
250 const emptyHooks = join(root, 'empty-hooks')
251 mkdirSync(emptyHooks)
252 const commandEnvironment = () => ({
253 PATH: `${bin}:${process.env.PATH}`,
254 ...(process.env.HOME ? { HOME: process.env.HOME } : {}),
255 ...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}),
256 npm_config_registry: fixtureRegistry,
257 NPM_CONFIG_USERCONFIG: emptyConfig,
258 NPM_CONFIG_GLOBALCONFIG: emptyConfig,
259 GIT_CONFIG_GLOBAL: emptyConfig,
260 GIT_CONFIG_NOSYSTEM: '1',
261 GIT_TERMINAL_PROMPT: '0',
262 CI: 'true',
263 })
264 const manifests = Object.keys(packageNames).map((key) => {
265 const manifest = readJson(manifestPath(root, key))
266 manifest.version =
267 key === 'db' || key === 'react'
268 ? history.candidate
269 : key === 'query'
270 ? '1.5.0'
271 : '1.2.0'
272 writeJson(manifestPath(root, key), manifest)
273 return manifest
274 })
275 const registry = Object.fromEntries(
276 manifests.map((manifest) => [
277 manifest.name,
278 {
279 versions:
280 history.registry === 'never'
281 ? []
282 : history.registry === 'current'
283 ? [manifest.version]
284 : manifest.name === packageNames.db ||
285 manifest.name === packageNames.react
286 ? history.registry === 'only-rc'
287 ? ['1.0.0-rc.1']
288 : ['0.15.2']
289 : ['1.0.0'],
290 tags: {},
291 },
292 ]),
293 )
294 const failureName =
295 history.failure === 'stable'
296 ? packageNames.query
297 : history.failure === 'candidate'
298 ? packageNames.db
299 : undefined
300 writeJson(registryPath, { packages: registry, failureName, failed: false })
301 writeJson(logPath, [])
302 writeJson(join(root, '.changeset', 'pre.json'), {
303 mode: 'pre',
304 tag: 'rc',
305 initialVersions: Object.fromEntries(
306 manifests.map((manifest) => [manifest.name, manifest.version]),
307 ),
308 changesets: [],
309 })
310 const shim = `#!${process.execPath}
311const fs = require('node:fs')
312const path = require('node:path')
313const cp = require('node:child_process')
314const args = process.argv.slice(2)
315const tool = path.basename(process.argv[1])
316const statePath = ${JSON.stringify(registryPath)}
317const logPath = ${JSON.stringify(logPath)}
318const registry = process.env.npm_config_registry
319let lockHeld = false
320function stop(message) {
321 if (lockHeld) fs.rmdirSync(statePath + '.lock')
322 console.error(message); process.exit(91)
323}
324if (registry !== ${JSON.stringify(fixtureRegistry)}) stop('foreign or missing registry')
325if (tool === 'pnpm' && args.join(' ') === '--version') {
326 console.log('11.1.0'); process.exit(0)
327}
328if (tool === 'pnpm' && args.slice(0, 3).join(' ') === 'exec changeset publish' &&
329 (args.length === 3 || (args.length === 5 && args[3] === '--tag' && ['rc', 'latest'].includes(args[4])))) {
330 const result = cp.spawnSync(process.execPath, [${JSON.stringify(cli)}, 'publish', ...args.slice(3)], {
331 cwd: process.cwd(), env: process.env, stdio: 'inherit', timeout: 10000,
332 })
333 process.exit(result.status ?? 92)
334}
335// Changesets can publish independent packages concurrently. Serialize the
336// fixture's read-modify-write, preserving every raw attempt and result.
337const lock = statePath + '.lock'
338const deadline = Date.now() + 2000
339while (true) {
340 try { fs.mkdirSync(lock); lockHeld = true; break } catch (error) {
341 if (error.code !== 'EEXIST' || Date.now() > deadline) throw error
342 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 2)
343 }
344}
345const state = JSON.parse(fs.readFileSync(statePath))
346const log = JSON.parse(fs.readFileSync(logPath))
347if (tool === 'npm' && args[0] === 'info') {
348 const name = args[1]
349 if (!state.packages[name]) stop('unknown registry package ' + name)
350 if (JSON.stringify(args) !== JSON.stringify(['info', name, '--registry=' + registry, '--json']))
351 stop('unrecognized registry info arguments')
352 log.push({ type: 'info', name, registry, args })
353 fs.writeFileSync(logPath, JSON.stringify(log))
354 const versions = state.packages[name].versions
355 console.log(JSON.stringify(versions.length ? { versions }
356 : { error: { code: 'E404' } }))
357 fs.rmdirSync(lock)
358 process.exit(versions.length ? 0 : 1)
359}
360if (tool === 'pnpm' && args[0] === 'publish') {
361 const manifest = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json')))
362 const tag = args[args.indexOf('--tag') + 1]
363 const access = args[args.indexOf('--access') + 1]
364 if (JSON.stringify(args) !== JSON.stringify([
365 'publish', '--json', '--access', access, '--tag', tag, '--no-git-checks',
366 ]) || !state.packages[manifest.name] || tag.startsWith('-') || access.startsWith('-'))
367 stop('unrecognized publish command')
368 const success = state.failed || state.failureName !== manifest.name
369 log.push({ type: 'publish', name: manifest.name, version: manifest.version,
370 tag, access, registry, success, args })
371 if (success) {
372 state.packages[manifest.name].versions.push(manifest.version)
373 state.packages[manifest.name].tags[tag] = manifest.version
374 } else state.failed = true
375 fs.writeFileSync(statePath, JSON.stringify(state))
376 fs.writeFileSync(logPath, JSON.stringify(log))
377 console.log(JSON.stringify(success ? { id: manifest.name + '@' + manifest.version }
378 : { error: { code: 'EORACLE', summary: 'injected publish failure' } }))
379 fs.rmdirSync(lock)
380 process.exit(success ? 0 : 1)
381}
382stop('unrecognized command ' + tool + ' ' + args.join(' '))
383`
384 for (const name of ['npm', 'pnpm'])
385 writeFileSync(join(bin, name), shim, { mode: 0o755 })
386 for (const args of [
387 ['init', '--quiet', `--template=${emptyHooks}`],
388 ['config', 'core.hooksPath', emptyHooks],
389 ['config', 'commit.gpgSign', 'false'],
390 ['config', 'tag.gpgSign', 'false'],
391 ['config', 'user.email', 'oracle@example.invalid'],
392 ['config', 'user.name', 'Release oracle'],
393 ['add', '.'],
394 ['commit', '--quiet', '-m', 'release fixture'],
395 ])
396 execFileSync('git', args, {
397 cwd: root,
398 stdio: 'pipe',
399 timeout: 10_000,
400 env: commandEnvironment(),
401 })
402 return {
403 manifests,
404 initialRegistry: structuredClone(registry),
405 readRequests: () => readJson(logPath),
406 readRegistry: () => readJson(registryPath),
407 invokeCommand: (tool, args, key = 'db') =>
408 spawnSync(join(bin, tool), args, {
409 cwd: key === 'root' ? root : join(root, 'packages', key),
410 encoding: 'utf8',
411 timeout: 5_000,
412 env: commandEnvironment(),
413 }),
414 // Only manifest/pre-state bytes belong to the publish restoration promise;
415 // registry and Git logs deliberately change when a publish succeeds.
416 bytes: () =>
417 Object.fromEntries(
418 [
419 '.changeset/pre.json',
420 ...Object.keys(packageNames).map(
421 (key) => `packages/${key}/package.json`,
422 ),
423 ].map((file) => [file, readFileSync(join(root, file), 'base64')]),
424 ),
425 async run(publish) {
426 // Drop credential/scope overrides from child commands. HOME retains its
427 // normal value; npm and Git config files are explicitly isolated instead.
428 const before = { ...process.env }
429 const childEnvironment = commandEnvironment()
430 for (const name of Object.keys(process.env)) delete process.env[name]
431 Object.assign(process.env, childEnvironment)
432 try {
433 return await publish(root)
434 } finally {
435 for (const name of Object.keys(process.env)) delete process.env[name]
436 Object.assign(process.env, before)
437 }
438 },
439 }
440}