import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; /** * Throws if a core package directory already exists. Used as the first action * in every per-package generator so re-running is safe. */ export function assertOptionalPackageNotPresent( name: string, cwd: string = process.cwd(), ): void { const pkgRoot = join(cwd, "packages", name); if (existsSync(pkgRoot)) { throw new Error( `packages/${name}/ already exists — refusing to scaffold (delete it first if intentional)`, ); } } /** * Inserts a package name into the transpilePackages array of a Next.js config * file, preserving alphabetical order. Idempotent. */ export function addToTranspilePackages( nextConfigPath: string, pkgName: string, ): void { const source = readFileSync(nextConfigPath, "utf8"); if (source.includes(`"${pkgName}"`)) return; const updated = source.replace( /(transpilePackages:\s*\[\s*)([\s\S]*?)(\s*\])/, (_match, open: string, body: string, close: string) => { const entries = body .split(",") .map((e) => e.trim()) .filter(Boolean); entries.push(`"${pkgName}"`); entries.sort(); const formatted = entries.map((e) => ` ${e}`).join(",\n"); return `${open}\n${formatted},${close}`; }, ); writeFileSync(nextConfigPath, updated); }