bump.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /**
  2. * Bump one release family's version and commit it, so the published version is
  3. * readable from the repository rather than derived inside CI
  4. * ([rationale](../../.agents/notes/implemented/process/2026-08-10-npm-release-sequences.md)).
  5. *
  6. * The dsh family shares one version across its members and the workspace root:
  7. * `major`, `minor`, `patch`, or an explicit `x.y.z` (including a prerelease such
  8. * as `0.0.1-rc.1`). The vendored family has one version line per package, but
  9. * every release advances and publishes the complete family so the next release
  10. * never reuses an unchanged member's existing version from a different
  11. * repository state.
  12. *
  13. * The version lands in the manifests, the lockfile follows, and a human creates
  14. * the tag after the commit merges. CI never writes to the repository.
  15. */
  16. import { readFileSync, writeFileSync } from 'node:fs'
  17. import { join, matchesGlob } from 'node:path'
  18. import { parseArgs } from 'node:util'
  19. import { releaseFamily, type ReleaseFamily, type ReleaseMember } from './families.ts'
  20. import { capture, isEntry } from './process.ts'
  21. /** Files npm publishes whether or not `files` lists them. */
  22. const ALWAYS_PUBLISHED = ['package.json', 'README*', 'LICENSE*', 'LICENCE*'] as const
  23. /**
  24. * Inputs that decide what a built payload contains. A package whose `files`
  25. * selects `lib/` publishes build output that git does not track, so a change to
  26. * the sources or the build configuration changes the tarball while no published
  27. * path appears in the diff.
  28. */
  29. const BUILD_INPUTS = ['src/**', 'tsconfig*.json', 'tsdown.config.*', 'build.config.*'] as const
  30. /** Release types the dsh family accepts besides an explicit version. */
  31. const RELEASE_TYPES = ['major', 'minor', 'patch'] as const
  32. /** The workspace root manifest, which carries the dsh family's version. */
  33. const ROOT_MANIFEST = 'package.json'
  34. /** One manifest the bump rewrites, and the tag its new version will carry. */
  35. interface PlannedVersion {
  36. /** Repository-relative manifest path. */
  37. readonly manifestPath: string
  38. /** Label for the log line. */
  39. readonly label: string
  40. /** The version the manifest currently carries. */
  41. readonly from: string
  42. /** The version to write. */
  43. readonly to: string
  44. /** The tag this version publishes from, or undefined for the workspace root. */
  45. readonly tag: string | undefined
  46. }
  47. /**
  48. * Split a version into its release numbers, discarding any prerelease segment.
  49. * @param version - the current version.
  50. * @returns Major, minor, and patch.
  51. */
  52. function releaseNumbers(version: string): [number, number, number] {
  53. const match = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/.exec(version)
  54. if (match === null) throw new Error(`cannot read release numbers from version ${version}`)
  55. return [Number(match[1]), Number(match[2]), Number(match[3])]
  56. }
  57. /**
  58. * Order two versions by their release numbers alone.
  59. * @param left - one version.
  60. * @param right - the other version.
  61. * @returns Negative when `left` is lower, positive when higher, zero when equal.
  62. */
  63. function compareReleaseNumbers(left: string, right: string): number {
  64. const [leftMajor, leftMinor, leftPatch] = releaseNumbers(left)
  65. const [rightMajor, rightMinor, rightPatch] = releaseNumbers(right)
  66. return leftMajor - rightMajor || leftMinor - rightMinor || leftPatch - rightPatch
  67. }
  68. /**
  69. * The prerelease segment of a version, or undefined when it has none.
  70. * @param version - the version to read.
  71. * @returns The segment after the first `-`.
  72. */
  73. function prereleaseOf(version: string): string | undefined {
  74. const index = version.indexOf('-')
  75. return index === -1 ? undefined : version.slice(index + 1)
  76. }
  77. /**
  78. * Order two versions by semver precedence.
  79. *
  80. * Git's version sort cannot stand in for this: `--sort=v:refname` places
  81. * `4.0.1-rc.1` above `4.0.1`, while semver gives a prerelease lower precedence
  82. * than the release it precedes. Prerelease identifiers compare field by field,
  83. * numeric fields numerically, so `rc.10` outranks `rc.1`.
  84. * @param left - one version.
  85. * @param right - the other version.
  86. * @returns Negative when `left` is lower, positive when higher, zero when equal.
  87. */
  88. export function compareVersions(left: string, right: string): number {
  89. const numbers = compareReleaseNumbers(left, right)
  90. if (numbers !== 0) return numbers
  91. const leftPre = prereleaseOf(left)
  92. const rightPre = prereleaseOf(right)
  93. if (leftPre === undefined || rightPre === undefined) {
  94. if (leftPre === rightPre) return 0
  95. return leftPre === undefined ? 1 : -1
  96. }
  97. const leftFields = leftPre.split('.')
  98. const rightFields = rightPre.split('.')
  99. for (let index = 0; index < Math.max(leftFields.length, rightFields.length); index += 1) {
  100. const leftField = leftFields[index]
  101. const rightField = rightFields[index]
  102. // A shorter identifier list has lower precedence when all its fields match.
  103. if (leftField === undefined) return -1
  104. if (rightField === undefined) return 1
  105. if (leftField === rightField) continue
  106. const leftNumeric = /^\d+$/.test(leftField)
  107. const rightNumeric = /^\d+$/.test(rightField)
  108. if (leftNumeric && rightNumeric) return Number(leftField) - Number(rightField)
  109. // Numeric fields have lower precedence than alphanumeric ones.
  110. if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1
  111. return leftField < rightField ? -1 : 1
  112. }
  113. return 0
  114. }
  115. /**
  116. * The next dsh version.
  117. * @param current - the family's current shared version.
  118. * @param request - `major`, `minor`, `patch`, or an explicit version.
  119. * @returns The target version.
  120. */
  121. function nextSharedVersion(current: string, request: string): string {
  122. if (!RELEASE_TYPES.includes(request as typeof RELEASE_TYPES[number])) {
  123. if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(request)) {
  124. throw new Error(`usage: release:dsh <major|minor|patch|x.y.z>, got ${request}`)
  125. }
  126. return request
  127. }
  128. const [major, minor, patch] = releaseNumbers(current)
  129. if (request === 'major') return `${String(major + 1)}.0.0`
  130. if (request === 'minor') return `${String(major)}.${String(minor + 1)}.0`
  131. return `${String(major)}.${String(minor)}.${String(patch + 1)}`
  132. }
  133. /**
  134. * The version a vendored package publishes next.
  135. *
  136. * The baseline is the higher of the manifest version and the last tagged
  137. * version: a vendor re-sync restores upstream's version, which is lower than
  138. * the release version this repository already reserved, and incrementing that
  139. * would reuse an existing version.
  140. *
  141. * A prerelease does not consume its own release numbers. Publishing
  142. * `4.0.1-rc.1` leaves `4.0.1` free, so the next stable version is `4.0.1`
  143. * rather than `4.0.2`, and a second prerelease keeps those numbers too.
  144. * @param current - the package's manifest version.
  145. * @param tagged - the version its newest tag names, when it has one.
  146. * @param prerelease - prerelease identifier to append, for a rehearsal publication.
  147. * @returns The target version.
  148. */
  149. export function nextVendorVersion(
  150. current: string,
  151. tagged: string | undefined,
  152. prerelease?: string,
  153. ): string {
  154. const taggedOrder = tagged === undefined ? undefined : compareReleaseNumbers(tagged, current)
  155. const ahead = taggedOrder !== undefined && taggedOrder > 0
  156. const baseline = ahead && tagged !== undefined ? tagged : current
  157. const [major, minor, patch] = releaseNumbers(baseline)
  158. // Reuse the numbers when the tagged version that set them is a prerelease
  159. // of them; increment when a stable release already holds them.
  160. const taggedPrerelease = tagged !== undefined && prereleaseOf(tagged) !== undefined
  161. const sameReleasePrereleases = taggedOrder === 0 && prereleaseOf(current) !== undefined
  162. const reuse = taggedPrerelease && (ahead || sameReleasePrereleases)
  163. const numbers = reuse
  164. ? `${String(major)}.${String(minor)}.${String(patch)}`
  165. : `${String(major)}.${String(minor)}.${String(patch + 1)}`
  166. return prerelease === undefined ? numbers : `${numbers}-${prerelease}`
  167. }
  168. /**
  169. * Whether a repository-relative path reaches the member's published payload.
  170. * @param member - the member the path belongs to.
  171. * @param path - repository-relative path.
  172. * @returns True when `files`, npm's always-published set, or a build input selects it.
  173. */
  174. export function reachesPayload(member: ReleaseMember, path: string): boolean {
  175. const relative = path.slice(member.directory.length + 1)
  176. const files = member.manifest.files
  177. const selected = Array.isArray(files) ? files.filter((entry): entry is string => typeof entry === 'string') : []
  178. const built = selected.some(pattern => pattern.startsWith('lib'))
  179. const patterns = [...ALWAYS_PUBLISHED, ...selected, ...built ? BUILD_INPUTS : []]
  180. return patterns.some(pattern =>
  181. matchesGlob(relative, pattern) || matchesGlob(relative, `${pattern}/**`) || relative === pattern)
  182. }
  183. /**
  184. * The newest version a member tagged.
  185. * @param family - the member's family.
  186. * @param member - the member.
  187. * @returns The version, or undefined when the member has no release tag.
  188. */
  189. function lastTaggedVersion(family: ReleaseFamily, member: ReleaseMember): string | undefined {
  190. const prefix = family.tagPrefixFor(member)
  191. const versions = capture('git', ['tag', '--list', `${prefix}*`])
  192. .split('\n').filter(line => line !== '').map(tag => tag.slice(prefix.length))
  193. if (versions.length === 0) return undefined
  194. return versions.reduce((newest, candidate) => compareVersions(candidate, newest) > 0 ? candidate : newest)
  195. }
  196. /**
  197. * Write a version into a manifest, preserving formatting and key order.
  198. * @param root - repository root.
  199. * @param manifestPath - repository-relative manifest path.
  200. * @param from - the version the manifest currently carries.
  201. * @param to - the target version.
  202. */
  203. function writeVersion(root: string, manifestPath: string, from: string, to: string): void {
  204. const path = join(root, manifestPath)
  205. const text = readFileSync(path, 'utf8')
  206. const line = `"version": "${from}"`
  207. if (!text.includes(line)) throw new Error(`${manifestPath}: cannot locate ${line}`)
  208. writeFileSync(path, text.replace(line, `"version": "${to}"`))
  209. }
  210. /**
  211. * Read the workspace root version.
  212. * @param root - repository root.
  213. * @returns The root manifest version.
  214. */
  215. function rootVersion(root: string): string {
  216. const manifest: unknown = JSON.parse(readFileSync(join(root, ROOT_MANIFEST), 'utf8'))
  217. const version = (manifest as Record<string, unknown>).version
  218. if (typeof version !== 'string') throw new Error('package.json must declare a string version')
  219. return version
  220. }
  221. /**
  222. * Plan the dsh family's rewrite: one version for every member and the root.
  223. * @param family - the dsh family.
  224. * @param root - repository root.
  225. * @param members - the family's members.
  226. * @param request - `major`, `minor`, `patch`, or an explicit version.
  227. * @returns The manifests to rewrite and the shared target version.
  228. */
  229. function planShared(
  230. family: ReleaseFamily,
  231. root: string,
  232. members: readonly ReleaseMember[],
  233. request: string,
  234. ): { planned: PlannedVersion[]; version: string } {
  235. const [first] = members
  236. if (first === undefined) throw new Error(`release family ${family.id} has no members`)
  237. const version = nextSharedVersion(first.version, request)
  238. // The workspace root carries the family version too: the workspace constraint
  239. // requires every member's version to equal the root's.
  240. const planned: PlannedVersion[] = [
  241. { manifestPath: ROOT_MANIFEST, label: ROOT_MANIFEST, from: rootVersion(root), to: version, tag: undefined },
  242. ]
  243. for (const member of members) {
  244. planned.push({
  245. manifestPath: join(member.directory, 'package.json'),
  246. label: member.directory,
  247. from: member.version,
  248. to: version,
  249. tag: family.tagFor({ ...member, version }),
  250. })
  251. }
  252. return { planned, version }
  253. }
  254. /**
  255. * Plan the vendored family's rewrite: every package advances together while
  256. * retaining its own version line and tag.
  257. * @param family - the vendored family.
  258. * @param members - the family's members.
  259. * @param prerelease - prerelease identifier to append, for a rehearsal publication.
  260. * @returns The manifests to rewrite.
  261. */
  262. function planPerPackage(
  263. family: ReleaseFamily,
  264. members: readonly ReleaseMember[],
  265. prerelease: string | undefined,
  266. ): PlannedVersion[] {
  267. const planned: PlannedVersion[] = []
  268. for (const member of members) {
  269. const tagged = lastTaggedVersion(family, member)
  270. const to = nextVendorVersion(member.version, tagged, prerelease)
  271. planned.push({
  272. manifestPath: join(member.directory, 'package.json'),
  273. label: member.directory,
  274. from: member.version,
  275. to,
  276. tag: family.tagFor({ ...member, version: to }),
  277. })
  278. }
  279. return planned
  280. }
  281. /**
  282. * Bump the family named by `--family` and commit; `--dry-run` only reports the
  283. * plan. `--prerelease rc.1` makes the vendored family publish a rehearsal
  284. * version, which never takes the stable dist-tag.
  285. */
  286. function main(): void {
  287. const { values, positionals } = parseArgs({
  288. options: {
  289. family: { type: 'string' },
  290. prerelease: { type: 'string' },
  291. 'dry-run': { type: 'boolean', default: false },
  292. },
  293. allowPositionals: true,
  294. })
  295. if (values.family === undefined) throw new Error('usage: bump.ts --family <dsh|vendor> [version]')
  296. const family = releaseFamily(values.family)
  297. const root = process.cwd()
  298. const members = family.members(root)
  299. family.verifyVersions(members)
  300. let planned: PlannedVersion[]
  301. let sharedVersion: string | undefined
  302. if (family.id === 'dsh') {
  303. const request = positionals[0]
  304. if (request === undefined) throw new Error('usage: release:dsh <major|minor|patch|x.y.z>')
  305. if (values.prerelease !== undefined) {
  306. throw new Error('release:dsh takes the prerelease in its version argument, as in 0.0.1-rc.1')
  307. }
  308. const shared = planShared(family, root, members, request)
  309. planned = shared.planned
  310. sharedVersion = shared.version
  311. } else {
  312. if (positionals.length > 0) throw new Error('release:vendor takes no version: each package increments its own patch')
  313. if (values.prerelease !== undefined && !/^[0-9A-Za-z.-]+$/.test(values.prerelease)) {
  314. throw new Error(`--prerelease must be a semver prerelease identifier, got ${values.prerelease}`)
  315. }
  316. planned = planPerPackage(family, members, values.prerelease)
  317. }
  318. if (planned.length === 0) {
  319. console.log(`release bump: family ${family.id}, nothing changed since publication`)
  320. return
  321. }
  322. const dryRun = values['dry-run']
  323. if (!dryRun) {
  324. for (const entry of planned) writeVersion(root, entry.manifestPath, entry.from, entry.to)
  325. capture('pnpm', ['install', '--lockfile-only'])
  326. }
  327. const summary = sharedVersion
  328. ?? planned.map(entry => `${entry.label.replace('vendor/', '')} ${entry.to}`).join(', ')
  329. console.log(`release bump: family ${family.id} -> ${summary}`)
  330. for (const entry of planned) console.log(` ${entry.label}: ${entry.from} -> ${entry.to}`)
  331. if (dryRun) {
  332. console.log('release bump: dry run, nothing written')
  333. return
  334. }
  335. capture('git', ['add', 'pnpm-lock.yaml', ...planned.map(entry => entry.manifestPath)])
  336. capture('git', ['commit', '-m', `release(${family.id}): ${summary}`])
  337. console.log('release bump: committed. After this merges to master, tag it:')
  338. for (const tag of [...new Set(planned.map(entry => entry.tag).filter(tag => tag !== undefined))]) {
  339. console.log(` git tag ${tag} <merge commit> && git push origin ${tag}`)
  340. }
  341. }
  342. if (isEntry(import.meta.url)) main()