import { readdir, readFile, stat } from 'node:fs/promises' import path from 'node:path' /** * Resolve the npm dist-tag of a release from the versions being published. * * `lerna publish` takes a single `--dist-tag`, so the tag is only meaningful * when every published package belongs to the same release channel: a stable * release goes to `latest`, a prerelease goes to `next`, and a mixed set cannot * be published correctly under one tag. * * The versions are read from the workspace manifests after `lerna version` has * bumped them, so the tag follows the actual release, including the `graduate` * and `prerelease` modes. A `publish_only` run skips the bump and resolves the * tag from the current versions. */ const ROOT = path.resolve(import.meta.dirname, '../') const WORKSPACE_FILE = 'pnpm-workspace.yaml' const PACKAGE_MANIFEST = 'package.json' /** Directories that never contain a workspace package / 永远不包含工作区包的目录 */ const IGNORED_DIRECTORIES = new Set(['node_modules']) /** * An npm dist-tag a release can be published under, `latest` for a stable * release and `next` for a prerelease * * 一次发布可以使用的 npm dist-tag,稳定版为 `latest`,预发布版为 `next` */ export type DistTag = 'latest' | 'next' /** The release channel of a version / 版本号所属的发布序列 */ export type VersionChannel = 'prerelease' | 'stable' /** A publishable workspace package / 一个可发布的包 */ export interface PublishablePackage { /** Package name / 包名 */ name: string /** Version in the package `package.json` / 包 `package.json` 中的版本号 */ version: string } /** The dist-tag resolved from the published versions / 根据待发布版本解析出的 dist-tag */ export interface DistTagResult { /** Tag to publish under / 发布使用的 tag */ tag: DistTag /** Channel shared by every package / 所有包共用的发布序列 */ channel: VersionChannel /** Packages considered / 参与判断的包 */ packages: PublishablePackage[] } /** * A `major.minor.patch` version with an optional prerelease and build metadata, * e.g. `2.0.0`, `2.0.0-rc.142` or `2.0.0-beta.1+build.5` * * 带有可选预发布与构建信息的 `major.minor.patch` 版本号,例如 `2.0.0`、`2.0.0-rc.142` 或 * `2.0.0-beta.1+build.5` */ const SEMVER = /^(?\d+)\.(?\d+)\.(?\d+)(?:-(?[0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u /** * Raised when stable and prerelease versions are published together, because a * single `--dist-tag` cannot be correct for both * * 当稳定版和预发布版一起发布时抛出,因为同一个 `--dist-tag` 无法同时适用于两者 */ export class MixedVersionError extends Error { /** Packages on the stable channel / 稳定版序列的包 */ readonly stable: PublishablePackage[] /** Packages on the prerelease channel / 预发布版序列的包 */ readonly prerelease: PublishablePackage[] /** * @param stable - Packages on the stable channel / 稳定版序列的包 * @param prerelease - Packages on the prerelease channel / 预发布版序列的包 */ constructor(stable: PublishablePackage[], prerelease: PublishablePackage[]) { super( [ 'Cannot publish a mixed set of versions under a single dist-tag.', ` stable: ${stable .map(({ name, version }) => `${name}@${version}`) .join(', ')}`, ` prerelease: ${prerelease .map(({ name, version }) => `${name}@${version}`) .join(', ')}`, ].join('\n'), ) this.name = 'MixedVersionError' this.stable = stable this.prerelease = prerelease } } const isDirectory = async (target: string): Promise => { try { return (await stat(target)).isDirectory() } catch { return false } } const keepDirectories = async (candidates: string[]): Promise => { const checks = await Promise.all( candidates.map((candidate) => isDirectory(candidate)), ) return candidates.filter((_, index) => checks[index]) } const listDirectories = async (dir: string): Promise => { try { const entries = await readdir(dir, { withFileTypes: true }) return entries .filter( (entry) => entry.isDirectory() && !entry.name.startsWith('.') && !IGNORED_DIRECTORIES.has(entry.name), ) .map((entry) => path.join(dir, entry.name)) } catch { return [] } } const listDirectoriesDeep = async (dir: string): Promise => { const children = await listDirectories(dir) const nested = await Promise.all( children.map((child) => listDirectoriesDeep(child)), ) return [...children, ...nested.flat()] } const unquote = (value: string): string => { const [quote] = value return value.length > 1 && (quote === '"' || quote === "'") && value.endsWith(quote) ? value.slice(1, -1) : value } const globSegment = (segment: string): RegExp => new RegExp( `^${segment .split('*') .map((part) => part.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`)) .join('[^/]*')}$`, 'u', ) /** * Read the package patterns of `pnpm-workspace.yaml` * * Only the `packages` sequence is parsed, as the rest of the file configures * pnpm and does not define the workspace layout. Negated patterns are ignored, * since every package of the repository is includable by a positive pattern. * * 读取 `pnpm-workspace.yaml` 中的包匹配模式 * * 只解析 `packages` 序列,文件其余部分用于配置 pnpm 而不决定工作区布局。 否定模式会被忽略,因为仓库中的每个包都可以被正向模式匹配到。 * * @param root - Workspace root / 工作区根目录 * @returns The positive package patterns / 正向的包匹配模式 */ export const readWorkspacePatterns = async ( root: string = ROOT, ): Promise => { const content = await readFile(path.join(root, WORKSPACE_FILE), 'utf8') const patterns: string[] = [] let isPackagesKey = false for (const line of content.split(/\r?\n/u)) { // Comments are stripped, so a comment-only line becomes an empty line const text = line.replace(/(?:^|\s)#.*$/u, '').trimEnd() if (/^packages:\s*$/u.test(text)) { isPackagesKey = true continue } if (!isPackagesKey) continue const item = /^\s+-\s*(?.+?)\s*$/u.exec(text) if (item?.groups) { const pattern = unquote(item.groups.pattern) if (pattern && !pattern.startsWith('!')) patterns.push(pattern) continue } // A top-level key ends the sequence if (text.trim() !== '') break } return patterns } const expandSegment = async ( directories: string[], segment: string, ): Promise => { if (segment === '**') { return ( await Promise.all(directories.map((dir) => listDirectoriesDeep(dir))) ).flat() } if (segment.includes('*')) { const matcher = globSegment(segment) return ( await Promise.all( directories.map(async (dir) => (await listDirectories(dir)).filter((child) => matcher.test(path.basename(child)), ), ), ) ).flat() } return keepDirectories(directories.map((dir) => path.join(dir, segment))) } /** * Expand a workspace pattern to the directories it matches * * Supports the pnpm syntax this repository relies on: literal segments, `*` for * the immediate children and `**` for every nested directory. * * 将工作区模式展开为其匹配的目录 * * 支持本仓库使用的 pnpm 语法:字面量片段、匹配直接子目录的 `*`,以及匹配所有嵌套目录的 `**`。 * * @param root - Workspace root / 工作区根目录 * @param pattern - Workspace pattern / 工作区模式 * @returns The matched directories / 匹配到的目录 */ export const expandWorkspacePattern = async ( root: string, pattern: string, ): Promise => { const segments = pattern .split('/') .filter((segment) => segment !== '' && segment !== '.') let directories = [root] for (const segment of segments) { // Each segment filters the directories matched by the previous one, so the // expansion cannot be parallelized across the pattern. // oxlint-disable-next-line no-await-in-loop -- every segment depends on the previous result directories = await expandSegment(directories, segment) } return directories } interface PackageManifest { name?: unknown version?: unknown private?: unknown } const readManifest = async (dir: string): Promise => { try { const content = await readFile(path.join(dir, PACKAGE_MANIFEST), 'utf8') return JSON.parse(content) as PackageManifest } catch { return null } } /** * Collect the publishable packages of the workspace * * Packages are discovered from the patterns in `pnpm-workspace.yaml`, so the * list follows the workspace layout, and `private` packages such as the docs * site and the e2e tests are left out. * * 收集工作区中可发布的包 * * 包通过 `pnpm-workspace.yaml` 中的模式发现,因此该列表跟随工作区布局,同时会排除文档站点和端到端测试等 `private` 包。 * * @param root - Workspace root / 工作区根目录 * @returns The publishable packages sorted by name / 按包名排序的可发布包 */ export const collectPublishablePackages = async ( root: string = ROOT, ): Promise => { const patterns = await readWorkspacePatterns(root) if (patterns.length === 0) throw new Error(`No package pattern is declared in ${WORKSPACE_FILE}.`) const directories = [ ...new Set( ( await Promise.all( patterns.map((pattern) => expandWorkspacePattern(root, pattern)), ) ).flat(), ), ] const manifests = await Promise.all( directories.map(async (dir) => ({ dir, manifest: await readManifest(dir), })), ) const packages: PublishablePackage[] = [] for (const { dir, manifest } of manifests) { if (!manifest || manifest.private === true) continue if ( typeof manifest.name !== 'string' || typeof manifest.version !== 'string' ) { throw new TypeError( `Publishable package at ${path.relative(root, dir)} has no name or version in its ${PACKAGE_MANIFEST}.`, ) } packages.push({ name: manifest.name, version: manifest.version }) } return packages.sort((a, b) => a.name.localeCompare(b.name)) } /** * Classify a version as a stable or a prerelease one * * A version is a prerelease when it carries a prerelease identifier, e.g. * `2.0.0-beta.1` or `2.0.0-0`, and stable otherwise, i.e. `2.0.0`. * * 判断版本号属于稳定版还是预发布版 * * 带有预发布标识的版本号为预发布版,例如 `2.0.0-beta.1` 或 `2.0.0-0`,否则为稳定版,即 `2.0.0`。 * * @param version - Version to classify / 要判断的版本号 * @returns The release channel of the version / 版本号所属的发布序列 */ export const getVersionChannel = (version: string): VersionChannel => { const match = SEMVER.exec(version) if (!match?.groups) throw new Error(`"${version}" is not a supported semver version.`) return match.groups.prerelease === undefined ? 'stable' : 'prerelease' } /** * Resolve the dist-tag shared by every package * * `latest` is returned when every package is stable and `next` when every one * is a prerelease. A mixed set has no single correct tag, so it throws a * `MixedVersionError` naming the offending packages instead of guessing. * * 解析所有包共用的 dist-tag * * 所有包都是稳定版时返回 `latest`,都是预发布版时返回 `next`。 混合版本没有唯一正确的 tag,因此会抛出带有问题包名的 * `MixedVersionError`,而不是做出猜测。 * * @param packages - Packages being published / 待发布的包 * @returns The resolved tag and channel / 解析出的 tag 与发布序列 */ export const resolveDistTag = ( packages: PublishablePackage[], ): DistTagResult => { if (packages.length === 0) throw new Error('No publishable workspace package was found.') const stable: PublishablePackage[] = [] const prerelease: PublishablePackage[] = [] for (const pkg of packages) { ;(getVersionChannel(pkg.version) === 'stable' ? stable : prerelease).push( pkg, ) } if (stable.length > 0 && prerelease.length > 0) throw new MixedVersionError(stable, prerelease) return { channel: stable.length > 0 ? 'stable' : 'prerelease', packages, tag: stable.length > 0 ? 'latest' : 'next', } } const formatVersions = (packages: PublishablePackage[]): string => { const counts = new Map() for (const { version } of packages) counts.set(version, (counts.get(version) ?? 0) + 1) return [...counts.entries()] .sort(([versionA, countA], [versionB, countB]) => countA === countB ? versionA.localeCompare(versionB) : countB - countA, ) .map(([version, count]) => `${version} (${count})`) .join(', ') } /** * Resolve the dist-tag of the workspace and print it as the last line of stdout * * The reasoning is logged first, so a release log explains why a tag was * chosen, and the tag itself stays the last line for the workflow to capture. * Any problem, including a mixed set of versions, is reported on stderr and * makes the run fail so a broken release never reaches the publish step. * * 解析工作区的 dist-tag,并将其作为 stdout 的最后一行打印 * * 先输出判断过程,使发布日志能够解释 tag 的选择,tag 本身保持为最后一行以便工作流捕获。 任何问题(包括混合版本)都会输出到 stderr * 并让运行失败,从而避免有问题的发布进入发布步骤。 * * @param root - Workspace root / 工作区根目录 * @returns The exit code, `0` when a tag was resolved / 退出码,成功解析出 tag 时为 `0` */ export const runDistTag = async (root: string = ROOT): Promise => { let result: DistTagResult try { result = resolveDistTag(await collectPublishablePackages(root)) } catch (err) { console.error(`✖ ${err instanceof Error ? err.message : String(err)}`) return 1 } const { channel, packages, tag } = result console.log(`ℹ Found ${packages.length} publishable workspace package(s).`) console.log( `ℹ Versions: ${formatVersions(packages)} — all ${channel === 'stable' ? 'stable' : 'prerelease'}.`, ) console.log(`ℹ Publishing under the "${tag}" dist-tag.`) console.log(tag) return 0 }