| 1 | import { execFileSync } from 'node:child_process'; |
| 2 | import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; |
| 3 | import { dirname, resolve } from 'node:path'; |
| 4 | import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 5 | |
| 6 | const numeric = /^(?:0|[1-9][0-9]*)$/; |
| 7 | const syntax = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; |
| 8 | |
| 9 | export function parseVersion(version) { |
| 10 | if (typeof version !== 'string' || version !== version.trim()) throw new Error('Expected a canonical SemVer without build metadata'); |
| 11 | const match = syntax.exec(version); |
| 12 | if (!match) throw new Error(`Invalid version: ${version}`); |
| 13 | const prerelease = match[4] ? match[4].split('.') : []; |
| 14 | if (prerelease.some(part => /^[0-9]+$/.test(part) && !numeric.test(part))) throw new Error(`Invalid numeric prerelease identifier: ${version}`); |
| 15 | return { major: BigInt(match[1]), minor: BigInt(match[2]), patch: BigInt(match[3]), prerelease }; |
| 16 | } |
| 17 | |
| 18 | function compare(a, b) { |
| 19 | return a === b ? 0 : a < b ? -1 : 1; |
| 20 | } |
| 21 | |
| 22 | export function compareVersions(a, b) { |
| 23 | const left = parseVersion(a); |
| 24 | const right = parseVersion(b); |
| 25 | for (const part of ['major', 'minor', 'patch']) { |
| 26 | const order = compare(left[part], right[part]); |
| 27 | if (order) return order; |
| 28 | } |
| 29 | if (!left.prerelease.length || !right.prerelease.length) { |
| 30 | return compare(Number(!left.prerelease.length), Number(!right.prerelease.length)); |
| 31 | } |
| 32 | for (let index = 0; index < Math.max(left.prerelease.length, right.prerelease.length); index++) { |
| 33 | const x = left.prerelease[index]; |
| 34 | const y = right.prerelease[index]; |
| 35 | if (x === undefined || y === undefined) return compare(left.prerelease.length, right.prerelease.length); |
| 36 | const xNumeric = numeric.test(x); |
| 37 | const yNumeric = numeric.test(y); |
| 38 | const order = xNumeric && yNumeric ? compare(BigInt(x), BigInt(y)) |
| 39 | : xNumeric !== yNumeric ? (xNumeric ? -1 : 1) : compare(x, y); |
| 40 | if (order) return order; |
| 41 | } |
| 42 | return 0; |
| 43 | } |
| 44 | |
| 45 | export function nextVersion(current, bump, existingTags = []) { |
| 46 | parseVersion(current); |
| 47 | if (!['prerelease', 'patch', 'minor', 'major'].includes(bump)) throw new Error(`Unsupported version bump: ${bump}`); |
| 48 | if (!Array.isArray(existingTags)) throw new TypeError('existingTags must be an array'); |
| 49 | let highest = current; |
| 50 | for (const tag of existingTags) { |
| 51 | if (typeof tag !== 'string' || !tag.startsWith('v')) continue; |
| 52 | const version = tag.slice(1); |
| 53 | try { parseVersion(version); } catch { continue; } |
| 54 | if (compareVersions(version, highest) > 0) highest = version; |
| 55 | } |
| 56 | let { major, minor, patch, prerelease } = parseVersion(highest); |
| 57 | if (bump === 'major') { |
| 58 | major++; |
| 59 | minor = patch = 0n; |
| 60 | prerelease = []; |
| 61 | } else if (bump === 'minor') { |
| 62 | minor++; |
| 63 | patch = 0n; |
| 64 | prerelease = []; |
| 65 | } else if (bump === 'patch') { |
| 66 | if (!prerelease.length) patch++; |
| 67 | prerelease = []; |
| 68 | } else if (!prerelease.length) { |
| 69 | patch++; |
| 70 | prerelease = ['alpha', '1']; |
| 71 | } else { |
| 72 | const last = prerelease.length - 1; |
| 73 | if (numeric.test(prerelease[last])) prerelease[last] = String(BigInt(prerelease[last]) + 1n); |
| 74 | else prerelease.push('1'); |
| 75 | } |
| 76 | return `${major}.${minor}.${patch}${prerelease.length ? `-${prerelease.join('.')}` : ''}`; |
| 77 | } |
| 78 | |
| 79 | |
| 80 | |
| 81 | function replaceVersions(text, paths, version) { |
| 82 | const tokens = [...text.matchAll(/"(?:\\.|[^"\\])*"|[{}\[\]:,]|-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|true|false|null/g)]; |
| 83 | const changes = []; |
| 84 | const counts = paths.map(() => 0); |
| 85 | let index = 0; |
| 86 | function value(path) { |
| 87 | const token = tokens[index++]; |
| 88 | const target = paths.findIndex(candidate => candidate.length === path.length && candidate.every((part, i) => part === path[i])); |
| 89 | if (target !== -1) { |
| 90 | if (!token[0].startsWith('"')) throw new Error('Package version fields must be strings'); |
| 91 | counts[target]++; |
| 92 | changes.push({ start: token.index, end: token.index + token[0].length }); |
| 93 | } |
| 94 | if (token[0] === '{') { |
| 95 | if (tokens[index][0] === '}') { index++; return; } |
| 96 | do { |
| 97 | const key = JSON.parse(tokens[index++][0]); |
| 98 | index++; |
| 99 | value([...path, key]); |
| 100 | } while (tokens[index++][0] !== '}'); |
| 101 | } else if (token[0] === '[') { |
| 102 | if (tokens[index][0] === ']') { index++; return; } |
| 103 | let item = 0; |
| 104 | do { value([...path, item++]); } while (tokens[index++][0] !== ']'); |
| 105 | } |
| 106 | } |
| 107 | value([]); |
| 108 | if (counts.some(count => count !== 1)) throw new Error('Expected exactly one value for each package version field'); |
| 109 | let result = text; |
| 110 | for (const { start, end } of changes.sort((a, b) => b.start - a.start)) { |
| 111 | result = result.slice(0, start) + JSON.stringify(version) + result.slice(end); |
| 112 | } |
| 113 | return result; |
| 114 | } |
| 115 | |
| 116 | export function versionFiles(root, version) { |
| 117 | parseVersion(version); |
| 118 | const versionPath = resolve(root, 'VERSION'); |
| 119 | const original = readFileSync(versionPath, 'utf8'); |
| 120 | const current = original.trim(); |
| 121 | parseVersion(current); |
| 122 | const result = new Map([[versionPath, original.replace(current, version)]]); |
| 123 | for (const directory of ['ui', 'www']) { |
| 124 | for (const filename of ['package.json', 'package-lock.json']) { |
| 125 | const path = resolve(root, directory, filename); |
| 126 | const text = readFileSync(path, 'utf8'); |
| 127 | const document = JSON.parse(text); |
| 128 | const lock = filename === 'package-lock.json'; |
| 129 | if (document?.version !== current || (lock && document?.packages?.['']?.version !== current)) { |
| 130 | throw new Error(`${directory}/${filename}: version fields must match VERSION (${current})`); |
| 131 | } |
| 132 | const paths = lock ? [['version'], ['packages', '', 'version']] : [['version']]; |
| 133 | result.set(path, replaceVersions(text, paths, version)); |
| 134 | } |
| 135 | } |
| 136 | return result; |
| 137 | } |
| 138 | |
| 139 | function main(args) { |
| 140 | const [command, platform, output] = args; |
| 141 | if (args.length !== 3 || command !== 'metadata' || !['macos', 'windows', 'linux'].includes(platform)) { |
| 142 | throw new Error('Usage: node scripts/release-version.mjs metadata <macos|windows|linux> <output>'); |
| 143 | } |
| 144 | const root = fileURLToPath(new URL('../', import.meta.url)); |
| 145 | const version = readFileSync(resolve(root, 'VERSION'), 'utf8').trim(); |
| 146 | parseVersion(version); |
| 147 | const commitSha = execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); |
| 148 | if (!/^[0-9a-f]{40}$/.test(commitSha)) throw new Error('Release metadata requires a 40-character Git commit SHA'); |
| 149 | const destination = resolve(output); |
| 150 | mkdirSync(dirname(destination), { recursive: true }); |
| 151 | writeFileSync(destination, `${JSON.stringify({ schema: 1, platform, version, commitSha }, null, 2)}\n`); |
| 152 | } |
| 153 | |
| 154 | if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { |
| 155 | try { main(process.argv.slice(2)); } catch (error) { console.error(error.message); process.exitCode = 1; } |
| 156 | } |