Open History to see the last commit
1/**
2 * Pack the public workspace packages for npm.
3 *
4 * This script only writes tarballs. Staging is `npm stage publish`
5 * from `.github/workflows/publish.yml` (OIDC, env `npm`, workflow
6 * filename `publish.yml`) so the trusted-publisher match holds.
7 * Future Actions stages get provenance; laptop `0.1.0` did not.
8 *
9 * pnpm run npm:pack # dist/npm, then stop
10 * pnpm run npm:pack -- --pack-dir /tmp/npm
11 *
12 * If `--tag` or `RELEASE_TAG` is set, it must be `vMAJOR.MINOR.PATCH`
13 * (optional prerelease) and match every public package's version.
14 *
15 * A package with a `build` script is built first. A package whose
16 * `publishConfig` names entry points (rate-card: `dist/` JS and .d.ts
17 * instead of `src/` TypeScript) is packed from a staged copy with those
18 * fields lifted onto the manifest. Staging leaves the workspace, so
19 * `workspace:*` is pinned to that package's version before `npm pack`.
20 * Every tarball must contain each file its manifest points at.
21 */
22import {
23 cpSync,
24 existsSync,
25 mkdirSync,
26 mkdtempSync,
27 readdirSync,
28 readFileSync,
29 rmSync,
30 writeFileSync,
31} from 'node:fs'
32import { tmpdir } from 'node:os'
33import { basename, join, resolve } from 'node:path'
34import { spawnSync } from 'node:child_process'
35
36export type PublicPackage = {
37 name: string
38 version: string
39 dir: string
40 dependencies: Record<string, string>
41}
42
43const WORKSPACE_OR_CATALOG = /^(workspace|catalog):/
44
45export function repoRoot(): string {
46 return join(import.meta.dirname, '..')
47}
48
49export function tarballFileName(name: string, version: string): string {
50 const unscoped = name.startsWith('@') ? name.slice(1).replace('/', '-') : name
51 return `${unscoped}-${version}.tgz`
52}
53
54/** `v0.1.0`, `refs/tags/v0.1.0`, or `v1.2.3-rc.1` → version. Else undefined. */
55export function versionFromTag(tag: string): string | undefined {
56 const trimmed = tag.replace(/^refs\/tags\//, '')
57 if (!/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(trimmed)) return undefined
58 return trimmed.slice(1)
59}
60
61export function listPublicPackages(
62 packagesDir: string = join(repoRoot(), 'packages'),
63): Array<PublicPackage> {
64 const pkgs: Array<PublicPackage> = []
65 for (const entry of readdirSync(packagesDir, { withFileTypes: true })) {
66 if (!entry.isDirectory()) continue
67 const pkgPath = join(packagesDir, entry.name, 'package.json')
68 let raw: string
69 try {
70 raw = readFileSync(pkgPath, 'utf8')
71 } catch {
72 continue
73 }
74 const parsed: unknown = JSON.parse(raw)
75 const pkg = asPackageJson(parsed, pkgPath)
76 if (pkg.private) continue
77 pkgs.push({
78 name: pkg.name,
79 version: pkg.version,
80 dir: join(packagesDir, entry.name),
81 dependencies: pkg.dependencies,
82 })
83 }
84 pkgs.sort((a, b) => a.name.localeCompare(b.name))
85 return pkgs
86}
87
88/** Dependents last (client/codegen, then vite, CLI) — npmjs.com approve order. */
89export function publishOrder(
90 packages: Array<PublicPackage>,
91): Array<PublicPackage> {
92 const byName = new Map(packages.map((pkg) => [pkg.name, pkg]))
93 const remaining = new Set(packages.map((pkg) => pkg.name))
94 const ordered: Array<PublicPackage> = []
95 while (remaining.size > 0) {
96 const ready = [...remaining]
97 .filter((name) => {
98 const pkg = byName.get(name)
99 if (!pkg) return false
100 return Object.keys(pkg.dependencies).every((dep) => !remaining.has(dep))
101 })
102 .sort()
103 if (ready.length === 0) {
104 throw new Error(
105 `workspace dependency cycle among ${[...remaining].join(', ')}`,
106 )
107 }
108 for (const name of ready) {
109 remaining.delete(name)
110 const pkg = byName.get(name)
111 if (!pkg) throw new Error(`missing package ${name}`)
112 ordered.push(pkg)
113 }
114 }
115 return ordered
116}
117
118export function assertVersionsMatchTag(
119 packages: Array<PublicPackage>,
120 tag: string,
121): void {
122 const expected = versionFromTag(tag)
123 if (expected === undefined) {
124 throw new Error(
125 `release tag ${JSON.stringify(tag)} is not vMAJOR.MINOR.PATCH`,
126 )
127 }
128 const mismatches = packages.filter((pkg) => pkg.version !== expected)
129 if (mismatches.length > 0) {
130 const detail = mismatches
131 .map((pkg) => `${pkg.name}@${pkg.version}`)
132 .join(', ')
133 throw new Error(
134 `tag v${expected} does not match package versions: ${detail}`,
135 )
136 }
137}
138
139export function assertPublishableManifest(
140 manifest: unknown,
141 source: string,
142): void {
143 const pkg = asPackageJson(manifest, source)
144 if (pkg.private) {
145 throw new Error(`${source}: packed manifest is private`)
146 }
147 for (const [name, spec] of Object.entries(pkg.dependencies)) {
148 if (WORKSPACE_OR_CATALOG.test(spec)) {
149 throw new Error(`${source}: ${name} still uses ${spec}`)
150 }
151 }
152}
153
154export function readPackedManifest(tarball: string): unknown {
155 return JSON.parse(
156 run('tar', ['-xOf', tarball, 'package/package.json'], process.cwd()),
157 ) as unknown
158}
159
160export function packedEntryNames(tarball: string): Array<string> {
161 return run('tar', ['-tzf', tarball], process.cwd())
162 .split('\n')
163 .filter((line) => line.length > 0)
164}
165
166/** Absolute dest so `npm pack` (cwd = package dir) writes where we look. */
167export function resolvePackDir(packDir: string): string {
168 return resolve(packDir)
169}
170
171/** `publishConfig` keys that configure npm, not the packed manifest. */
172const NPM_CONFIG_KEYS = new Set(['access', 'registry', 'tag', 'provenance'])
173
174/**
175 * The manifest npm should see: `publishConfig` manifest fields (`main`,
176 * `types`, `exports`) lifted to the top level, as pnpm does on publish.
177 * `undefined` when there is nothing to lift.
178 */
179export function publishManifest(
180 manifest: Record<string, unknown>,
181): Record<string, unknown> | undefined {
182 const config = manifest.publishConfig
183 if (!isRecord(config)) return undefined
184 const lifted = Object.entries(config).filter(
185 ([key]) => !NPM_CONFIG_KEYS.has(key),
186 )
187 if (lifted.length === 0) return undefined
188 return {
189 ...manifest,
190 ...Object.fromEntries(lifted),
191 publishConfig: Object.fromEntries(
192 Object.entries(config).filter(([key]) => NPM_CONFIG_KEYS.has(key)),
193 ),
194 }
195}
196
197const DEP_FIELDS = [
198 'dependencies',
199 'devDependencies',
200 'peerDependencies',
201 'optionalDependencies',
202] as const
203
204/** `workspace:*` → that package's version. npm does not rewrite the protocol. */
205export function pinWorkspaceSpecs(
206 manifest: Record<string, unknown>,
207 packagesDir: string,
208): void {
209 for (const field of DEP_FIELDS) {
210 const deps = manifest[field]
211 if (!isRecord(deps)) continue
212 for (const [name, spec] of Object.entries(deps)) {
213 if (typeof spec !== 'string' || !spec.startsWith('workspace:')) continue
214 if (spec !== 'workspace:*') {
215 throw new Error(`${name}: unsupported workspace spec ${spec}`)
216 }
217 deps[name] = workspaceVersion(packagesDir, name)
218 }
219 }
220}
221
222function workspaceVersion(packagesDir: string, name: string): string {
223 for (const entry of readdirSync(packagesDir, { withFileTypes: true })) {
224 if (!entry.isDirectory()) continue
225 const pkgPath = join(packagesDir, entry.name, 'package.json')
226 if (!existsSync(pkgPath)) continue
227 const parsed: unknown = JSON.parse(readFileSync(pkgPath, 'utf8'))
228 if (!isRecord(parsed) || parsed.name !== name) continue
229 if (typeof parsed.version !== 'string') {
230 throw new Error(`${pkgPath}: version is not a string`)
231 }
232 return parsed.version
233 }
234 throw new Error(`no workspace package named ${name}`)
235}
236
237/** Relative file paths a manifest's `main`, `types`, `bin` and `exports` name. */
238export function manifestEntryPoints(manifest: unknown): Array<string> {
239 if (!isRecord(manifest)) return []
240 const paths = new Set<string>()
241 const collect = (value: unknown) => {
242 if (typeof value === 'string') {
243 if (value.startsWith('./')) paths.add(value.slice(2))
244 } else if (isRecord(value)) {
245 Object.values(value).forEach(collect)
246 }
247 }
248 for (const key of ['main', 'types', 'module', 'bin', 'exports']) {
249 collect(manifest[key])
250 }
251 return [...paths].sort()
252}
253
254export function assertShipsEntryPoints(
255 manifest: unknown,
256 entries: Array<string>,
257 source: string,
258): void {
259 const missing = manifestEntryPoints(manifest).filter(
260 (path) => !entries.includes(`package/${path}`),
261 )
262 if (missing.length > 0) {
263 throw new Error(`${source}: does not ship ${missing.join(', ')}`)
264 }
265}
266
267export function run(command: string, args: Array<string>, cwd: string): string {
268 const result = spawnSync(command, args, { cwd, encoding: 'utf8' })
269 if (result.status !== 0) {
270 throw new Error(
271 `${command} ${args.join(' ')} in ${cwd} failed: ${result.stderr || result.stdout}`,
272 )
273 }
274 return result.stdout
275}
276
277export function packPackage(pkg: PublicPackage, packDir: string): string {
278 const dest = resolvePackDir(packDir)
279 mkdirSync(dest, { recursive: true })
280 const manifest: unknown = JSON.parse(
281 readFileSync(join(pkg.dir, 'package.json'), 'utf8'),
282 )
283 if (!isRecord(manifest)) {
284 throw new Error(`${pkg.dir}: package.json is not an object`)
285 }
286 if (
287 isRecord(manifest.scripts) &&
288 typeof manifest.scripts.build === 'string'
289 ) {
290 run('pnpm', ['run', 'build'], pkg.dir)
291 }
292 const published = publishManifest(manifest)
293 let cwd = pkg.dir
294 if (published) {
295 // Outside the workspace. Pin `workspace:*` before packing.
296 cwd = mkdtempSync(join(tmpdir(), 'npm-pack-'))
297 cpSync(pkg.dir, cwd, {
298 recursive: true,
299 filter: (path) => basename(path) !== 'node_modules',
300 })
301 pinWorkspaceSpecs(published, join(pkg.dir, '..'))
302 writeFileSync(
303 join(cwd, 'package.json'),
304 `${JSON.stringify(published, null, 2)}\n`,
305 )
306 }
307 let stdout: string
308 try {
309 stdout = run(
310 'npm',
311 ['pack', '--ignore-scripts', '--pack-destination', dest],
312 cwd,
313 )
314 } finally {
315 if (cwd !== pkg.dir) rmSync(cwd, { recursive: true, force: true })
316 }
317 const tarball = join(dest, tarballFileName(pkg.name, pkg.version))
318 if (!existsSync(tarball)) {
319 throw new Error(
320 `expected ${tarball} after npm pack; stdout=${stdout.trim()}`,
321 )
322 }
323 return tarball
324}
325
326export function packAll(
327 packages: Array<PublicPackage>,
328 packDir: string,
329): Array<{ pkg: PublicPackage; tarball: string }> {
330 const dest = resolvePackDir(packDir)
331 rmSync(dest, { recursive: true, force: true })
332 mkdirSync(dest, { recursive: true })
333 const packed: Array<{ pkg: PublicPackage; tarball: string }> = []
334 for (const pkg of packages) {
335 const tarball = packPackage(pkg, dest)
336 const manifest = readPackedManifest(tarball)
337 assertPublishableManifest(manifest, tarball)
338 const entries = packedEntryNames(tarball)
339 assertShipsEntryPoints(manifest, entries, tarball)
340 const tests = entries.filter((entry) => entry.endsWith('.test.ts'))
341 if (tests.length > 0) {
342 throw new Error(`${tarball} includes test files: ${tests.join(', ')}`)
343 }
344 packed.push({ pkg, tarball })
345 }
346 return packed
347}
348
349function asPackageJson(
350 value: unknown,
351 source: string,
352): {
353 name: string
354 version: string
355 private: boolean
356 dependencies: Record<string, string>
357} {
358 if (!isRecord(value)) {
359 throw new Error(`${source}: package.json is not an object`)
360 }
361 if (typeof value.name !== 'string' || typeof value.version !== 'string') {
362 throw new Error(`${source}: name and version must be strings`)
363 }
364 return {
365 name: value.name,
366 version: value.version,
367 private: value.private === true,
368 dependencies: {
369 ...stringRecord(value.dependencies, `${source} dependencies`),
370 ...stringRecord(
371 value.optionalDependencies,
372 `${source} optionalDependencies`,
373 ),
374 ...stringRecord(value.peerDependencies, `${source} peerDependencies`),
375 },
376 }
377}
378
379function isRecord(value: unknown): value is Record<string, unknown> {
380 return typeof value === 'object' && value !== null && !Array.isArray(value)
381}
382
383function stringRecord(value: unknown, source: string): Record<string, string> {
384 if (value === undefined) return {}
385 if (!isRecord(value)) throw new Error(`${source}: expected an object`)
386 const out: Record<string, string> = {}
387 for (const [key, spec] of Object.entries(value)) {
388 if (typeof spec !== 'string') {
389 throw new Error(`${source}: ${key} is not a string`)
390 }
391 out[key] = spec
392 }
393 return out
394}
395
396function parseCli(argv: Array<string>): {
397 packDir: string | undefined
398 tag: string | undefined
399} {
400 let packDir: string | undefined
401 let tag: string | undefined
402 for (let i = 0; i < argv.length; i += 1) {
403 const arg = argv[i]
404 if (arg === '--pack-dir') {
405 const value = argv[i + 1]
406 if (value === undefined) throw new Error('--pack-dir requires a path')
407 packDir = value
408 i += 1
409 continue
410 }
411 if (arg === '--tag') {
412 const value = argv[i + 1]
413 if (value === undefined) throw new Error('--tag requires a value')
414 tag = value
415 i += 1
416 continue
417 }
418 throw new Error(`unknown argument: ${arg}`)
419 }
420 return { packDir, tag }
421}
422
423export function main(argv: Array<string> = process.argv.slice(2)): void {
424 const flags = parseCli(argv)
425 const packages = publishOrder(listPublicPackages())
426 if (packages.length === 0) {
427 throw new Error('no public packages under packages/')
428 }
429 const tag = flags.tag ?? process.env.RELEASE_TAG
430 if (tag !== undefined && tag !== '') {
431 assertVersionsMatchTag(packages, tag)
432 }
433 const packDir = resolvePackDir(
434 flags.packDir ??
435 process.env.NPM_PACK_DIR ??
436 join(repoRoot(), 'dist', 'npm'),
437 )
438 const packed = packAll(packages, packDir)
439 console.log(`packed ${packed.length} packages → ${packDir}\n`)
440 for (const { pkg, tarball } of packed) {
441 console.log(` ${pkg.name}@${pkg.version}`)
442 console.log(` ${tarball}`)
443 }
444 console.log(
445 `\nNext: npm stage publish happens in .github/workflows/publish.yml (OIDC).`,
446 )
447}
448
449if (import.meta.main) {
450 try {
451 main()
452 } catch (error) {
453 const message = error instanceof Error ? error.message : String(error)
454 console.error(message)
455 process.exit(1)
456 }
457}