import { readdir, readFile } from 'node:fs/promises' import path from 'node:path' const ROOT = path.resolve(import.meta.dirname, '../') const SYNC_API = 'https://registry-direct.npmmirror.com/-/package' const DEFAULT_TIMEOUT = 30_000 /** A request that triggers the npmmirror sync / 触发 npmmirror 同步的请求实现 */ export type SyncRequest = (url: string, init: RequestInit) => Promise /** Options of the npmmirror sync / npmmirror 同步的选项 */ export interface SyncOptions { /** * The request implementation, `fetch` by default / 请求实现,默认为 `fetch` * * @default fetch */ request?: SyncRequest /** * The timeout of one request in milliseconds / 单个请求的超时时间,单位为毫秒 * * @default 30000 */ timeout?: number } /** A package that failed to sync / 同步失败的包 */ export interface SyncFailure { /** The package name / 包名 */ name: string /** The failure / 错误 */ error: unknown } const listDirectories = async (dir: string): Promise => { const entries = await readdir(dir, { withFileTypes: true }) return entries .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')) .map((entry) => entry.name) } const readPackageName = async (dir: string): Promise => { const manifest = path.join(dir, 'package.json') let parsed: { name?: unknown } try { parsed = JSON.parse(await readFile(manifest, 'utf8')) as { name?: unknown } } catch (err) { throw new Error(`Cannot read a package name from ${manifest}.`, { cause: err, }) } if (typeof parsed.name !== 'string' || parsed.name === '') throw new Error(`${manifest} does not declare a package name.`) return parsed.name } const getErrorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error) /** * Discover the packages to sync from the workspace layout * * Plugins are nested in category directories (`plugins//`), * while themes and tools are flat (`themes/`, `tools/`), and * hidden directories are ignored. * * 从工作区布局中发现要同步的包 * * 插件位于分类目录中(`plugins//`),主题和工具为扁平结构(`themes/`、`tools/`),隐藏目录会被忽略。 * * @param root - The workspace root / 工作区根目录 * @returns The package names / 包名 */ export const discoverPackages = async ( root: string = ROOT, ): Promise => { const [categories, themes, tools] = await Promise.all([ listDirectories(path.join(root, 'plugins')), listDirectories(path.join(root, 'themes')), listDirectories(path.join(root, 'tools')), ]) const pluginDirs = ( await Promise.all( categories.map(async (category) => (await listDirectories(path.join(root, 'plugins', category))).map( (name) => path.join(root, 'plugins', category, name), ), ), ) ).flat() const dirs = [ ...pluginDirs, ...themes.map((name) => path.join(root, 'themes', name)), ...tools.map((name) => path.join(root, 'tools', name)), ] return Promise.all(dirs.map((dir) => readPackageName(dir))) } /** * Trigger the npmmirror sync of a package * * The sync is enqueued with an empty `PUT` request. A non-2xx response, a * network error and a timeout all reject with the package name, so the caller * can report the package that failed. * * 触发一个包的 npmmirror 同步 * * 同步通过空的 `PUT` 请求加入队列。非 2xx 响应、网络错误和超时都会抛出带有包名的错误,以便调用方报告失败的包。 * * @param name - The package name / 包名 * @param options - The request implementation and timeout / 请求实现与超时时间 * @returns A promise resolved when the sync is enqueued / 同步加入队列后完成的 Promise */ export const syncPackage = async ( name: string, { request = fetch, timeout = DEFAULT_TIMEOUT }: SyncOptions = {}, ): Promise => { let response: Response try { response = await request(`${SYNC_API}/${name}/syncs`, { method: 'PUT', headers: { 'Content-Length': '0', }, signal: AbortSignal.timeout(timeout), }) } catch (err) { const reason = err instanceof Error && err.name === 'TimeoutError' ? `timed out after ${timeout} ms` : getErrorMessage(err) throw new Error(`Failed to sync ${name} to npmmirror: ${reason}`, { cause: err, }) } // Release the connection before throwing, so a failed run does not leave // unread bodies behind. A cleanup failure must not mask the HTTP status. try { await response.body?.cancel() } catch { // The status of the response is what the caller has to report. } if (!response.ok) { const status = `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}` throw new Error(`Failed to sync ${name} to npmmirror: ${status}`) } } /** * Sync packages and collect the failures * * Every package is attempted even when another one fails, and the failures are * returned in the order of the package names. * * 同步多个包并收集失败项 * * 即使某个包失败,也会尝试同步其他包,失败项按包名顺序返回。 * * @param names - The package names / 包名 * @param options - The request implementation and timeout / 请求实现与超时时间 * @returns The packages that failed to sync / 同步失败的包 */ export const syncPackages = async ( names: string[], options: SyncOptions = {}, ): Promise => { const results = await Promise.allSettled( names.map((name) => syncPackage(name, options)), ) return results.flatMap((result, index) => result.status === 'rejected' ? [{ error: result.reason as unknown, name: names[index] }] : [], ) } /** * Sync every package of the workspace and report the failures * * Each failure is logged with the package name and the reason, and the run * fails when at least one package could not be synced. * * 同步工作区中的每个包并报告失败项 * * 每个失败项都会记录包名与原因,只要有一个包未能同步,本次运行就会失败。 * * @param root - The workspace root / 工作区根目录 * @param options - The request implementation and timeout / 请求实现与超时时间 * @returns The exit code, `0` when every package was synced / 退出码,所有包同步成功时为 `0` */ export const runSyncNpmmirror = async ( root: string = ROOT, options: SyncOptions = {}, ): Promise => { let names: string[] try { names = await discoverPackages(root) } catch (err) { console.error( `Failed to discover the packages to sync: ${getErrorMessage(err)}`, ) return 1 } const failures = await syncPackages(names, options) for (const { error } of failures) console.error(getErrorMessage(error)) if (failures.length > 0) { console.error( `Failed to sync ${failures.length} of ${names.length} package(s) to npmmirror: ${failures .map(({ name }) => name) .join(', ')}`, ) return 1 } console.log(`Synced ${names.length} package(s) to npmmirror.`) return 0 }