@powerhousedao/ph-cli 6.3.0-dev.1 → 6.3.0-dev.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build-BdQFCpwz.mjs +4 -0
- package/dist/{build-CWm9MOFJ.mjs → build-CgLN1cEZ.mjs} +4 -4
- package/dist/{build-CWm9MOFJ.mjs.map → build-CgLN1cEZ.mjs.map} +1 -1
- package/dist/{check-BZOXiSys.mjs → check-C_x7U-2Y.mjs} +3 -3
- package/dist/{check-C9kQub0h.mjs → check-VPcldr0Q.mjs} +4 -4
- package/dist/{check-C9kQub0h.mjs.map → check-VPcldr0Q.mjs.map} +1 -1
- package/dist/cli.mjs +3 -3
- package/dist/{connect-build-is3cmf0E.mjs → connect-build-q1QDwrH9.mjs} +4 -4
- package/dist/{connect-build-is3cmf0E.mjs.map → connect-build-q1QDwrH9.mjs.map} +1 -1
- package/dist/{connect-studio-CBtduPet.mjs → connect-studio-Ds-mfXJI.mjs} +9 -6
- package/dist/connect-studio-Ds-mfXJI.mjs.map +1 -0
- package/dist/{connect-studio-BNSe_8PI.mjs → connect-studio-KdRWcq-A.mjs} +3 -3
- package/dist/definitions-worker.mjs +1 -1
- package/dist/{generate-desktop-shell-Dh9_bhLa.mjs → generate-desktop-shell-BovoRsR6.mjs} +5 -5
- package/dist/generate-desktop-shell-BovoRsR6.mjs.map +1 -0
- package/dist/{generate-document-model-OQPfeHs-.mjs → generate-document-model-BiD6ovXc.mjs} +4 -4
- package/dist/generate-document-model-BiD6ovXc.mjs.map +1 -0
- package/dist/{get-version-CrerlHgg.mjs → get-version-L0a1H7iV.mjs} +4 -4
- package/dist/{get-version-CrerlHgg.mjs.map → get-version-L0a1H7iV.mjs.map} +1 -1
- package/dist/{mcp-DJKiREkL.mjs → mcp-CfSjPzKW.mjs} +4 -4
- package/dist/{mcp-DJKiREkL.mjs.map → mcp-CfSjPzKW.mjs.map} +1 -1
- package/dist/{migrate-Bg-HBsYa.mjs → migrate-C5sxTyiG.mjs} +4 -4
- package/dist/{migrate-Bg-HBsYa.mjs.map → migrate-C5sxTyiG.mjs.map} +1 -1
- package/dist/migrate-document-models-B1TXNVes.mjs +489 -0
- package/dist/migrate-document-models-B1TXNVes.mjs.map +1 -0
- package/dist/migrate-subgraphs-Cn7bX56b.mjs +710 -0
- package/dist/migrate-subgraphs-Cn7bX56b.mjs.map +1 -0
- package/dist/migrate-subgraphs-SdawH0GP.mjs +4 -0
- package/dist/{ph-cli-commands-C6cJJQlA.mjs → ph-cli-commands-Ctnl0Ckw.mjs} +46 -22
- package/dist/ph-cli-commands-Ctnl0Ckw.mjs.map +1 -0
- package/dist/ph-cli-commands-DPhz3gjb.mjs +4 -0
- package/dist/runners/connect.mjs +2 -2
- package/dist/runners/switchboard.mjs +1 -1
- package/dist/{verify-CIWOkZZV.mjs → verify-DxhwtFdv.mjs} +4 -4
- package/dist/{verify-CIWOkZZV.mjs.map → verify-DxhwtFdv.mjs.map} +1 -1
- package/dist/{vetra-CmTg8Lja.mjs → vetra-BmluhGRB.mjs} +4 -4
- package/dist/{vetra-CmTg8Lja.mjs.map → vetra-BmluhGRB.mjs.map} +1 -1
- package/package.json +17 -17
- package/dist/build-1BN9BD49.mjs +0 -4
- package/dist/connect-studio-CBtduPet.mjs.map +0 -1
- package/dist/generate-desktop-shell-Dh9_bhLa.mjs.map +0 -1
- package/dist/generate-document-model-OQPfeHs-.mjs.map +0 -1
- package/dist/migrate-subgraphs-Bm3zpsO9.mjs +0 -214
- package/dist/migrate-subgraphs-Bm3zpsO9.mjs.map +0 -1
- package/dist/migrate-subgraphs-De_rX4Hv.mjs +0 -4
- package/dist/ph-cli-commands-C6cJJQlA.mjs.map +0 -1
- package/dist/ph-cli-commands-CCCVUIzM.mjs +0 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-CWm9MOFJ.mjs","sources":["../src/services/package-build/pipeline/steps.ts","../src/services/package-build/pipeline/run-steps.ts","../src/services/package-build/staging/files.ts","../src/services/package-build/staging/journal.ts","../src/services/package-build/staging/boot-id.ts","../src/services/package-build/staging/lock.ts","../src/services/definitions/paths.ts","../src/services/package-build/staging/recovery.ts","../src/services/compiler-output/emit.ts","../src/services/definitions/config-inputs.ts","../src/services/definitions/compiler-output.ts","../src/services/definitions/compiler.ts","../src/services/package-build/staging/inventory.ts","../src/services/package-build/staging/compiler.ts","../src/services/package-build/staging/session.ts","../src/services/package-build/staging/open.ts","../src/utils/offered-routes-manifest.ts","../src/services/package-build/steps/stage-logger.ts","../src/services/package-build/steps/bundles.ts","../src/services/package-build/steps/connect-routes.ts","../src/services/package-build/steps/definitions.ts","../src/services/package-build/steps/package-checks.ts","../src/services/package-build/steps/pieces.ts","../src/services/release/consumer.ts","../src/services/release/issuance.ts","../src/services/package-build/steps/release-approval.ts","../src/services/package-build/steps/stylesheet.ts","../src/services/package-build/steps/typecheck.ts","../src/services/package-build/steps/standard.ts","../src/services/package-build/steps/trace.ts","../src/services/package-build/run-build.ts","../src/services/subgraph-build-step.ts","../src/services/build.ts"],"sourcesContent":["/**\n * One step of `ph build`. A step without `after` follows the step listed\n * before it in its phase; a step with `after` runs as soon as every step it\n * names has run, so a list can insert a step after any other without\n * reordering the rest. A `committed` step runs once the output is replaced,\n * after every other step; a throw from it cannot bring the previous output\n * back.\n */\nexport type BuildStep<C> = {\n readonly id: string;\n readonly after?: readonly string[];\n readonly when?: \"committed\";\n readonly run: (ctx: C) => Promise<void>;\n};\n\n/** A step's decision not to finish the build. The runner rolls back first. */\nexport class BuildRefusal extends Error {\n readonly exitCode: number;\n\n constructor(message: string, exitCode = 1) {\n super(message);\n this.name = \"BuildRefusal\";\n this.exitCode = exitCode;\n }\n}\n\n/** The process was told to stop while the build ran; it was rolled back. */\nexport class BuildStopped extends Error {\n readonly signal: string;\n\n constructor(signal: string) {\n super(`The build was stopped by ${signal} before it finished.`);\n this.name = \"BuildStopped\";\n this.signal = signal;\n }\n}\n\nfunction dependencies<C>(\n steps: readonly BuildStep<C>[],\n): ReadonlyMap<string, readonly string[]> {\n const ids = new Set<string>();\n for (const { id } of steps) {\n if (ids.has(id)) throw new Error(`Build step \"${id}\" is listed twice.`);\n ids.add(id);\n }\n const committed = new Set(\n steps.filter(({ when }) => when === \"committed\").map(({ id }) => id),\n );\n const waits = new Map<string, readonly string[]>();\n steps.forEach((step, index) => {\n const previous = steps\n .slice(0, index)\n .findLast(({ when }) => when === step.when);\n const after = step.after ?? (previous === undefined ? [] : [previous.id]);\n for (const id of after) {\n if (!ids.has(id)) {\n throw new Error(\n `Build step \"${step.id}\" runs after \"${id}\", which no step provides.`,\n );\n }\n if (step.when !== \"committed\" && committed.has(id)) {\n throw new Error(\n `Build step \"${step.id}\" runs before the output is replaced, so it cannot run after \"${id}\", which runs once it is.`,\n );\n }\n }\n waits.set(step.id, after);\n });\n return waits;\n}\n\n/**\n * The order the steps run in: list order, with each step that names `after`\n * placed right after the last step it waits for, and every `committed` step\n * after every other. Throws on a duplicate id, an unknown `after` id, a step\n * that waits on a later phase, or steps that wait on each other.\n */\nexport function orderBuildSteps<C>(\n steps: readonly BuildStep<C>[],\n): BuildStep<C>[] {\n const waits = dependencies(steps);\n const placed = new Set<string>();\n const ordered: BuildStep<C>[] = [];\n while (ordered.length < steps.length) {\n const ready = steps.filter(\n ({ id }) =>\n !placed.has(id) && waits.get(id)!.every((wait) => placed.has(wait)),\n );\n if (ready.length === 0) {\n const waiting = steps\n .filter(({ id }) => !placed.has(id))\n .map(({ id }) => `\"${id}\"`);\n throw new Error(`Build steps ${waiting.join(\", \")} wait on each other.`);\n }\n const phase = ready.some(({ when }) => when !== \"committed\")\n ? ready.filter(({ when }) => when !== \"committed\")\n : ready;\n const next = phase.find((step) => step.after !== undefined) ?? phase[0];\n placed.add(next.id);\n ordered.push(next);\n }\n return ordered;\n}\n","import { type BuildStep, BuildStopped, orderBuildSteps } from \"./steps.js\";\n\n/** What the runner replaces the output with, or puts back. */\nexport type StepSession = {\n readonly commit: () => void;\n readonly rollback: () => void;\n /** The signal that cancelled the build, if one did. */\n readonly stopped: () => string | undefined;\n};\n\nfunction throwIfStopped(session: StepSession): void {\n const signal = session.stopped();\n if (signal === undefined) return;\n session.rollback();\n throw new BuildStopped(signal);\n}\n\n/**\n * Runs the steps in order, commits, then runs the `committed` steps. When a\n * step before the commit throws, `rollback` runs before the error goes on to\n * the caller, so nothing the build wrote outlives the failure. A committed\n * step's throw goes to the caller with the new output in place. A stop is\n * seen once the running step settles, and before each step and the commit:\n * no step starts after it, and the rollback waits for the step it stopped.\n */\nexport async function runBuildSteps<C>(\n steps: readonly BuildStep<C>[],\n ctx: C,\n session: StepSession,\n): Promise<void> {\n const ordered = orderBuildSteps(steps);\n for (const step of ordered.filter(({ when }) => when !== \"committed\")) {\n throwIfStopped(session);\n try {\n await step.run(ctx);\n } catch (error) {\n session.rollback();\n throwIfStopped(session);\n throw error;\n }\n }\n throwIfStopped(session);\n session.commit();\n for (const step of ordered.filter(({ when }) => when === \"committed\")) {\n throwIfStopped(session);\n await step.run(ctx);\n }\n}\n","import { createHash } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n constants,\n cpSync,\n linkSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n readlinkSync,\n renameSync,\n rmSync,\n type Stats,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport function exists(path: string): boolean {\n return lstatSync(path, { throwIfNoEntry: false }) !== undefined;\n}\n\n/**\n * Copies a file or a tree with its timestamps. A clone where the filesystem\n * has them, a byte copy elsewhere; never a hard link, because later steps\n * rewrite files in place.\n */\nexport function cloneTree(\n from: string,\n to: string,\n filter?: (source: string) => boolean,\n): void {\n cpSync(from, to, {\n recursive: true,\n mode: constants.COPYFILE_FICLONE,\n preserveTimestamps: true,\n verbatimSymlinks: true,\n ...(filter && { filter }),\n });\n}\n\n/**\n * Mirrors a tree whose files the next step unlinks before it writes (tsdown\n * cleans its output directory that way): each file is hard linked, so no\n * byte is copied and nothing written later reaches `from`. A file that\n * cannot be linked, and anything else, is copied.\n */\nexport function linkTree(\n from: string,\n to: string,\n filter: (source: string) => boolean,\n): void {\n mkdirSync(to);\n for (const entry of readdirSync(from, { withFileTypes: true })) {\n const source = join(from, entry.name);\n if (!filter(source)) continue;\n const target = join(to, entry.name);\n if (entry.isDirectory()) {\n linkTree(source, target, filter);\n continue;\n }\n if (entry.isFile()) {\n try {\n linkSync(source, target);\n continue;\n } catch {\n // Another filesystem, or one without hard links: copied below.\n }\n }\n cloneTree(source, target);\n }\n}\n\n/** A directory's permission bits, by POSIX path from a tree's root (\"\" for the root). */\nexport type DirectoryMode = readonly [path: string, mode: number];\n\nconst OWNER_RWX = 0o700;\n\n/**\n * Gives every directory of the tree at `path` that lacks it owner read,\n * write and search permission, which emptying it needs, and returns the\n * modes it changed, parents first.\n */\nexport function openDirectories(path: string): DirectoryMode[] {\n const changed: DirectoryMode[] = [];\n const visit = (dir: string, rel: string) => {\n const stat = lstatSync(dir, { throwIfNoEntry: false });\n if (!stat?.isDirectory()) return;\n const mode = stat.mode & 0o7777;\n if ((mode & OWNER_RWX) !== OWNER_RWX) {\n chmodSync(dir, mode | OWNER_RWX);\n changed.push([rel, mode]);\n }\n for (const entry of readdirSync(dir)) {\n visit(join(dir, entry), rel === \"\" ? entry : `${rel}/${entry}`);\n }\n };\n visit(path, \"\");\n return changed;\n}\n\n/** Sets back the modes `openDirectories` changed, children first. */\nexport function restoreDirectoryModes(\n path: string,\n modes: readonly DirectoryMode[],\n): void {\n for (const [rel, mode] of [...modes].reverse()) {\n chmodSync(rel === \"\" ? path : join(path, ...rel.split(\"/\")), mode);\n }\n}\n\n/**\n * Removes a tree. A directory without owner write permission keeps its\n * entries, so on failure each directory is opened and the removal tried\n * once more.\n */\nexport function removeTree(path: string): void {\n const remove = () =>\n rmSync(path, { recursive: true, force: true, maxRetries: 10 });\n try {\n remove();\n } catch (error) {\n try {\n openDirectories(path);\n } catch {\n throw error;\n }\n remove();\n }\n}\n\n/**\n * Makes `path` a copy of `from`. A directory that is there is emptied and\n * refilled rather than removed, so a mount point or a directory another\n * process holds stays where it is.\n */\nexport function replaceTree(from: string, path: string): void {\n const into =\n lstatSync(path, { throwIfNoEntry: false })?.isDirectory() &&\n lstatSync(from).isDirectory();\n if (!into) {\n removeTree(path);\n cloneTree(from, path);\n return;\n }\n openDirectories(path);\n for (const entry of readdirSync(path)) removeTree(join(path, entry));\n cloneTree(from, path);\n}\n\n/**\n * The tree by the bytes of its files and the targets of its links. Times\n * and inodes are left out: a touch changes them, and a rewrite can keep them.\n */\nexport function treeFingerprint(\n root: string,\n skipped: ReadonlySet<string>,\n unmarked: ReadonlySet<string> = new Set(),\n): string {\n const hash = createHash(\"sha256\");\n const visit = (path: string, rel: string) => {\n const stat = lstatSync(path);\n if (stat.isFile()) {\n const bytes = readFileSync(path);\n hash.update(`f\\0${rel}\\0${bytes.length}\\0`).update(bytes);\n return;\n }\n if (stat.isSymbolicLink()) {\n hash.update(`l\\0${rel}\\0${readlinkSync(path)}\\0`);\n return;\n }\n if (!stat.isDirectory()) {\n hash.update(`o\\0${rel}\\0`);\n return;\n }\n if (rel !== \"\" && !unmarked.has(rel)) hash.update(`d\\0${rel}\\0`);\n for (const entry of readdirSync(path).sort()) {\n const child = rel === \"\" ? entry : `${rel}/${entry}`;\n if (!skipped.has(child)) visit(join(path, entry), child);\n }\n };\n if (exists(root)) visit(root, \"\");\n return hash.digest(\"hex\");\n}\n\ntype Unstageable = { readonly path: string; readonly reason: string };\n\n/**\n * The first entry of the tree at `path`, itself included, that the stage\n * cannot copy as it is, and why: a FIFO, socket or device, which a copy\n * cannot represent, or a file or directory this process cannot read. Only\n * permissions are checked; no file is read. Entries `filter` rejects, and\n * what they hold, are not looked at.\n */\nexport function unstageableEntryIn(\n path: string,\n filter: (source: string) => boolean = () => true,\n): Unstageable | undefined {\n const visit = (path: string, stat: Stats): Unstageable | undefined => {\n if (stat.isSymbolicLink()) return;\n if (!stat.isFile() && !stat.isDirectory()) {\n return { path, reason: \"is not a file, directory or symbolic link\" };\n }\n const mode = stat.isDirectory()\n ? constants.R_OK | constants.X_OK\n : constants.R_OK;\n try {\n accessSync(path, mode);\n } catch {\n return { path, reason: \"cannot be read\" };\n }\n if (!stat.isDirectory()) return;\n for (const entry of readdirSync(path)) {\n const child = join(path, entry);\n if (!filter(child)) continue;\n const found = visit(child, lstatSync(child));\n if (found) return found;\n }\n return;\n };\n const stat = lstatSync(path, { throwIfNoEntry: false });\n return stat && visit(path, stat);\n}\n\nexport function entriesOf(dir: string): string[] {\n return exists(dir) ? readdirSync(dir) : [];\n}\n\nconst blocker = new Int32Array(new SharedArrayBuffer(4));\n\n/** Waits without returning to the event loop, so no signal handler runs meanwhile. */\nfunction sleepSync(ms: number): void {\n Atomics.wait(blocker, 0, 0, ms);\n}\n\n/** Windows refuses to rename a directory while another process holds a file in it. */\nexport function isHeldOpen(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n return code === \"EPERM\" || code === \"EBUSY\" || code === \"EACCES\";\n}\n\nexport const RENAME_PATIENCE_MS = 2000;\n\n/** `rename`, retried with backoff for about two seconds while the path is held open. */\nexport function renamePatiently(\n from: string,\n to: string,\n patienceMs = RENAME_PATIENCE_MS,\n): void {\n const deadline = Date.now() + patienceMs;\n for (let wait = 20; ; wait = Math.min(wait * 2, 400)) {\n try {\n renameSync(from, to);\n return;\n } catch (error) {\n if (!isHeldOpen(error) || Date.now() + wait > deadline) throw error;\n sleepSync(wait);\n }\n }\n}\n\n/** Moves each entry of `from` into `to`, replacing what `to` holds under that name. */\nexport function moveEntries(from: string, to: string): void {\n for (const entry of entriesOf(from)) {\n const target = join(to, entry);\n if (exists(target)) removeTree(target);\n renamePatiently(join(from, entry), target);\n }\n}\n\n/** Staging cannot run where the build would write; `message` says why. */\nexport class CannotStage extends Error {}\n\n// Errors that say a path cannot be created or written there, or that the\n// filesystem has no hard links for the lock.\nconst CANNOT_WRITE = new Set([\n \"ENOTDIR\",\n \"EACCES\",\n \"EPERM\",\n \"EROFS\",\n \"ENOTSUP\",\n \"EOPNOTSUPP\",\n]);\n\n/** Runs `create`, turning a refusal to write `where` into `CannotStage`. */\nexport async function creating<T>(\n where: string,\n create: () => T | Promise<T>,\n): Promise<T> {\n try {\n return await create();\n } catch (error) {\n const code = (error as { code?: unknown } | null)?.code;\n if (typeof code === \"string\" && CANNOT_WRITE.has(code)) {\n throw new CannotStage(`${where} cannot be written (${code})`);\n }\n throw error;\n }\n}\n","import { readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport nodePath, { join } from \"node:path\";\nimport { BUILD_DIRECTORY } from \"../../build-control.js\";\nimport type { DirectoryMode } from \"./files.js\";\nimport type { CompilerOutput } from \"./inventory.js\";\n\nexport const RUNS_DIRECTORY = join(BUILD_DIRECTORY, \"runs\");\nconst JOURNAL_FILE = \"journal.json\";\n\n/**\n * Where a run is, written before each move it makes:\n * - building: the stage is being written; the output is untouched.\n * - retiring: the output is moving aside to the retired path.\n * - installing: the stage is moving into the output's place.\n * - rolling-back: the run is being undone; `undo` names the step it is at.\n * - committed: the stage is the output; only cleanup is left.\n */\nexport type JournalState =\n | \"building\"\n | \"retiring\"\n | \"installing\"\n | \"rolling-back\"\n | \"committed\";\n\n/**\n * The steps of a rollback, in order, each safe to repeat:\n * - install: the output loses what the stage put in it.\n * - retire: the retired tree, or its entries, goes back into the output.\n * - stage: the stage goes and the compiler outputs come back.\n */\nexport const UNDO_STEPS = [\"install\", \"retire\", \"stage\"] as const;\nexport type UndoStep = (typeof UNDO_STEPS)[number];\n\n/**\n * A compiler output as it was before tsc ran. `copy` is null when it was\n * absent; `created` is then the outermost of its directories that was absent\n * too, removed again if tsc left nothing else in it. `modes` holds the\n * directories of the copy that lacked owner permissions, which the copy was\n * given so the run can be removed; a restore sets them back.\n */\nexport type CompilerSnapshot = {\n readonly path: string;\n readonly kind: CompilerOutput[\"kind\"];\n readonly copy: string | null;\n readonly created: string | null;\n readonly modes?: readonly DirectoryMode[];\n};\n\nexport type PendingBuildInfo = {\n readonly path: string;\n readonly target: string;\n};\n\n/** Paths as `toJournalPath` records them: package paths from the package root, copies from the run directory. */\nexport type RunJournal = {\n readonly format: 1;\n readonly runId: string;\n readonly pid: number;\n readonly state: JournalState;\n /** With `rolling-back`: the first rollback step not known to be done. */\n readonly undo: UndoStep | null;\n readonly output: string;\n readonly stage: string;\n readonly retired: string;\n readonly compiler: readonly CompilerSnapshot[] | null;\n readonly generatedConfig?: string;\n readonly pendingBuildInfo?: PendingBuildInfo;\n readonly outputDigest?: string;\n};\n\nconst STATES: readonly JournalState[] = [\n \"building\",\n \"retiring\",\n \"installing\",\n \"rolling-back\",\n \"committed\",\n];\n\n/**\n * A path inside `from` is recorded relative, in POSIX form. Any other path\n * is recorded absolute and comes back unchanged: a relative spelling of\n * another drive or a UNC share does not resolve back to it on Windows.\n */\nexport function toJournalPath(\n from: string,\n to: string,\n paths: typeof nodePath = nodePath,\n): string {\n const rel = paths.relative(from, to);\n if (\n paths.isAbsolute(rel) ||\n rel === \"..\" ||\n rel.startsWith(`..${paths.sep}`)\n ) {\n return paths.resolve(to);\n }\n return rel.split(paths.sep).join(\"/\");\n}\n\nexport function fromJournalPath(\n from: string,\n recorded: string,\n paths: typeof nodePath = nodePath,\n): string {\n return paths.isAbsolute(recorded) ? recorded : paths.resolve(from, recorded);\n}\n\nexport function journalPath(runDir: string): string {\n return join(runDir, JOURNAL_FILE);\n}\n\n/** Replaces the journal in one rename, so a reader sees the old state or the new. */\nexport function writeJournal(runDir: string, journal: RunJournal): void {\n const file = journalPath(runDir);\n const pending = `${file}.${process.pid}.tmp`;\n writeFileSync(pending, `${JSON.stringify(journal, null, 2)}\\n`);\n renameSync(pending, file);\n}\n\nconst isString = (value: unknown): value is string =>\n typeof value === \"string\" && value !== \"\";\n\nfunction parseSnapshot(value: unknown): CompilerSnapshot | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const { path, kind, copy, created } = value as Record<string, unknown>;\n if (\n !isString(path) ||\n (kind !== \"directory\" && kind !== \"build-info\" && kind !== \"file\")\n ) {\n return undefined;\n }\n if (copy !== null && !isString(copy)) return undefined;\n if (created !== null && !isString(created)) return undefined;\n const { modes } = value as Record<string, unknown>;\n if (modes === undefined) return { path, kind, copy, created };\n if (!Array.isArray(modes) || !modes.every(isDirectoryMode)) return undefined;\n return { path, kind, copy, created, modes };\n}\n\nfunction parsePendingBuildInfo(\n value: unknown,\n): PendingBuildInfo | undefined | null {\n if (value === undefined) return undefined;\n if (typeof value !== \"object\" || value === null) return null;\n const { path, target } = value as Record<string, unknown>;\n return isString(path) && isString(target) ? { path, target } : null;\n}\n\nconst isDirectoryMode = (value: unknown): value is DirectoryMode =>\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === \"string\" &&\n Number.isInteger(value[1]);\n\n/** The journal of a run directory, or undefined when it is missing or unreadable. */\nexport function readJournal(runDir: string): RunJournal | undefined {\n let value: unknown;\n try {\n value = JSON.parse(readFileSync(journalPath(runDir), \"utf8\"));\n } catch {\n return undefined;\n }\n if (typeof value !== \"object\" || value === null) return undefined;\n const record = value as Record<string, unknown>;\n if (\n record.format !== 1 ||\n !isString(record.runId) ||\n typeof record.pid !== \"number\" ||\n !STATES.includes(record.state as JournalState) ||\n !isString(record.output) ||\n !isString(record.stage) ||\n !isString(record.retired)\n ) {\n return undefined;\n }\n const optional = (key: string) =>\n record[key] === undefined || isString(record[key]);\n if (!optional(\"generatedConfig\") || !optional(\"outputDigest\"))\n return undefined;\n const pending = parsePendingBuildInfo(record.pendingBuildInfo);\n if (pending === null) return undefined;\n const undo = UNDO_STEPS.find((step) => step === record.undo) ?? null;\n if ((record.state === \"rolling-back\") !== (undo !== null)) return undefined;\n let compiler: CompilerSnapshot[] | null = null;\n if (Array.isArray(record.compiler)) {\n compiler = [];\n for (const entry of record.compiler) {\n const snapshot = parseSnapshot(entry);\n if (snapshot === undefined) return undefined;\n compiler.push(snapshot);\n }\n } else if (record.compiler !== null) {\n return undefined;\n }\n return {\n format: 1,\n runId: record.runId,\n pid: record.pid,\n state: record.state as JournalState,\n undo,\n output: record.output,\n stage: record.stage,\n retired: record.retired,\n compiler,\n ...(isString(record.generatedConfig) && {\n generatedConfig: record.generatedConfig,\n }),\n ...(pending !== undefined && { pendingBuildInfo: pending }),\n ...(isString(record.outputDigest) && { outputDigest: record.outputDigest }),\n };\n}\n","import { execFileSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\n\nfunction readBootId(): string | null {\n try {\n const id =\n process.platform === \"linux\"\n ? readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\")\n : process.platform === \"darwin\"\n ? execFileSync(\"sysctl\", [\"-n\", \"kern.bootsessionuuid\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n : \"\";\n return id.trim() || null;\n } catch {\n return null;\n }\n}\n\nlet memo: string | null | undefined;\n\n/**\n * This boot of the machine, as the OS names it, or null where it cannot be\n * read. Unlike a boot time derived from the clock, it changes only with a\n * reboot.\n */\nexport function currentBootId(): string | null {\n if (memo === undefined) memo = readBootId();\n return memo;\n}\n","import {\n linkSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { pendingPrefix, takeoverPrefix } from \"../../build-control.js\";\nimport { currentBootId } from \"./boot-id.js\";\nimport { removeTree } from \"./files.js\";\n\nconst POLL_MS = 100;\nconst TAKEOVER_RETRY_MS = 10;\n// A takeover takes milliseconds, so a contender waiting on one says so only\n// when it lasts: the holder may be paused, or gone under a reused pid.\nconst QUIET_TAKEOVER_WAIT_MS = 1000;\n\n/**\n * A lock's owner: the run, its process, and the machine and boot that\n * process lives in. Only an owner of this machine can be proven dead (see\n * `provenDead`).\n */\ntype LockOwner = {\n readonly pid: number;\n readonly runId: string;\n readonly host: string;\n /** The OS's id of the boot the process ran in, null where unknown. */\n readonly bootId: string | null;\n};\n\nfunction isOwner(value: unknown): value is LockOwner {\n const owner = value as Partial<LockOwner> | null;\n return (\n typeof owner?.pid === \"number\" &&\n typeof owner.runId === \"string\" &&\n typeof owner.host === \"string\" &&\n (typeof owner.bootId === \"string\" || owner.bootId === null)\n );\n}\n\n/**\n * The owner's process is gone: on this machine, it ran in another boot (so\n * the reboot ended it), or no process is left at its pid. Another host, or a\n * live pid in this boot or an unknown one, is not proof: such an owner may\n * still be building. A pid reused by another process of this boot reads as\n * live, so its lock waits until someone deletes it.\n */\nconst provenDead = (owner: LockOwner) => {\n if (owner.host !== hostname()) return false;\n const boot = currentBootId();\n if (owner.bootId !== null && boot !== null && owner.bootId !== boot) {\n return true;\n }\n return !isProcessAlive(owner.pid);\n};\n\nconst errorCode = (error: unknown) => (error as { code?: unknown }).code;\n\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM: alive, owned by another user.\n return errorCode(error) === \"EPERM\";\n }\n}\n\n/** What a waiting build says about who holds a lock or takeover file. */\nfunction described(value: unknown): string {\n const fields = value as Partial<Record<keyof LockOwner, unknown>> | null;\n const parts = (\n [\n [\"host\", fields?.host],\n [\"pid\", fields?.pid],\n [\"run\", fields?.runId],\n ] as const\n ).flatMap(([name, field]) =>\n typeof field === \"string\" || typeof field === \"number\"\n ? [`${name} ${field}`]\n : [],\n );\n return parts.length > 0 ? parts.join(\", \") : \"owner unknown\";\n}\n\n/**\n * Who holds a lock or takeover file. `id` names that one holding: the\n * owner's run id, or for a file that does not read as an owner, its inode\n * and time, so a replacement never passes for it. Such a file is never\n * proven dead.\n */\ntype Holder = {\n readonly id: string;\n readonly dead: boolean;\n readonly owner: string;\n};\n\nfunction holderOf(file: string): Holder | undefined {\n let value: unknown;\n try {\n value = JSON.parse(readFileSync(file, \"utf8\"));\n } catch (error) {\n if (errorCode(error) === \"ENOENT\") return undefined;\n }\n if (isOwner(value)) {\n return {\n id: value.runId,\n dead: provenDead(value),\n owner: described(value),\n };\n }\n const stat = lstatSync(file, { throwIfNoEntry: false });\n return (\n stat && {\n id: `file ${stat.ino} ${stat.mtimeMs}`,\n dead: false,\n owner: described(value),\n }\n );\n}\n\n/**\n * Creates `file` holding `owner`, or returns false when it exists. The file\n * appears with its content in one link, so no reader sees it empty.\n */\nfunction createOwned(file: string, owner: LockOwner): boolean {\n const pending = join(\n dirname(file),\n `${pendingPrefix(basename(file))}${owner.runId}.pending`,\n );\n writeFileSync(pending, JSON.stringify(owner));\n try {\n linkSync(pending, file);\n return true;\n } catch (error) {\n if (errorCode(error) === \"EEXIST\") return false;\n throw error;\n } finally {\n rmSync(pending, { force: true });\n }\n}\n\nconst takeoverFile = (lockFile: string, staleId: string) =>\n join(\n dirname(lockFile),\n `${takeoverPrefix(basename(lockFile))}${encodeURIComponent(staleId)}`,\n );\n\n/** A file a live or unknown holder keeps, which this build waits for. */\ntype Blocked = { readonly file: string; readonly holder: Holder };\n\n/**\n * Removes `file` while it still holds the dead holder `stale`. Only the\n * creator of the takeover file keyed to `stale` may remove it, and `stale`\n * cannot come back, so the owner read under that file is the one removed: a\n * contender that judged it stale before someone else took over removes\n * nothing. A takeover file is itself taken over only from a holder proven\n * dead, never for its age, so a paused holder keeps it. Returns what blocks\n * the takeover, or nothing when the caller should try again.\n */\nfunction takeOver(\n lockFile: string,\n file: string,\n stale: Holder,\n me: LockOwner,\n): Blocked | undefined {\n const guard = takeoverFile(lockFile, stale.id);\n if (!createOwned(guard, me)) {\n const holder = holderOf(guard);\n if (holder === undefined) return undefined;\n return holder.dead\n ? takeOver(lockFile, guard, holder, me)\n : { file: guard, holder };\n }\n try {\n if (holderOf(file)?.id === stale.id) removeTree(file);\n return undefined;\n } finally {\n if (holderOf(guard)?.id === me.runId) rmSync(guard, { force: true });\n }\n}\n\n/**\n * Takeover files left by contenders that died. Safe under the lock: one\n * matters only while the lock holds its stale owner, and the lock is ours.\n * A pending file goes only when its writer is proven dead: a live\n * contender links it next.\n */\nfunction removeTakeoverFiles(lockFile: string): void {\n const takeover = takeoverPrefix(basename(lockFile));\n const pending = pendingPrefix(basename(lockFile));\n for (const entry of readdirSync(dirname(lockFile))) {\n const file = join(dirname(lockFile), entry);\n if (\n entry.startsWith(takeover) ||\n (entry.startsWith(pending) &&\n entry.endsWith(\".pending\") &&\n holderOf(file)?.dead === true)\n ) {\n rmSync(file, { force: true });\n }\n }\n}\n\n/** The package's build lock, held until `release`. */\nexport type BuildLock = { readonly release: () => void };\n\n/** The file a build waits for and who holds it, as `host …, pid …, run …`. */\nexport type LockWait = { readonly file: string; readonly owner: string };\n\n/**\n * Takes `.ph/build/lock`, a file created exclusively that names this run.\n * A lock is taken over only from an owner proven dead (see `provenDead`);\n * otherwise this waits, and says once per holder which file it waits for.\n */\nexport async function acquireBuildLock(\n lockFile: string,\n runId: string,\n onWait: (wait: LockWait) => void,\n): Promise<BuildLock> {\n mkdirSync(dirname(lockFile), { recursive: true });\n const me: LockOwner = {\n pid: process.pid,\n runId,\n host: hostname(),\n bootId: currentBootId(),\n };\n const told = new Set<string>();\n const firstBlocked = new Map<string, number>();\n for (;;) {\n if (createOwned(lockFile, me)) {\n removeTakeoverFiles(lockFile);\n let held = true;\n return {\n release: () => {\n if (!held) return;\n held = false;\n if (holderOf(lockFile)?.id === runId) rmSync(lockFile);\n },\n };\n }\n const holder = holderOf(lockFile);\n if (holder === undefined) continue;\n const blocked = holder.dead\n ? takeOver(lockFile, lockFile, holder, me)\n : { file: lockFile, holder };\n if (blocked === undefined) {\n await sleep(TAKEOVER_RETRY_MS);\n continue;\n }\n const key = `${blocked.file}\\0${blocked.holder.id}`;\n const since = firstBlocked.get(key) ?? Date.now();\n firstBlocked.set(key, since);\n const quiet =\n blocked.file !== lockFile && Date.now() - since < QUIET_TAKEOVER_WAIT_MS;\n if (!quiet && !told.has(key)) {\n told.add(key);\n onWait({ file: blocked.file, owner: blocked.holder.owner });\n }\n await sleep(blocked.file === lockFile ? POLL_MS : TAKEOVER_RETRY_MS);\n }\n}\n","import { realPathThroughExistingParent } from \"@powerhousedao/shared/clis/real-paths\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\n\nexport function toPosixPath(path: string): string {\n return path.split(sep).join(\"/\");\n}\n\nexport function canonicalConfigFile(configFile: string): string {\n const absolute = resolve(configFile);\n return join(\n realPathThroughExistingParent(dirname(absolute)),\n basename(absolute),\n );\n}\n","import { mkdirSync, rmdirSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport { toPosixPath } from \"../../definitions/paths.js\";\nimport {\n entriesOf,\n exists,\n isHeldOpen,\n moveEntries,\n removeTree,\n renamePatiently,\n replaceTree,\n restoreDirectoryModes,\n treeFingerprint,\n} from \"./files.js\";\nimport {\n type CompilerSnapshot,\n fromJournalPath,\n type JournalState,\n type PendingBuildInfo,\n readJournal,\n RUNS_DIRECTORY,\n type RunJournal,\n toJournalPath,\n UNDO_STEPS,\n type UndoStep,\n writeJournal,\n} from \"./journal.js\";\n\n/** A run's paths, absolute. */\nexport type RunPaths = {\n readonly packageRoot: string;\n readonly runDir: string;\n readonly output: string;\n readonly stage: string;\n readonly retired: string;\n};\n\nexport function runPaths(\n packageRoot: string,\n runDir: string,\n journal: Pick<RunJournal, \"output\" | \"stage\" | \"retired\">,\n): RunPaths {\n return {\n packageRoot,\n runDir,\n output: fromJournalPath(packageRoot, journal.output),\n stage: fromJournalPath(packageRoot, journal.stage),\n retired: fromJournalPath(packageRoot, journal.retired),\n };\n}\n\nexport function outputDigest(\n packageRoot: string,\n output: string,\n compiler: readonly CompilerSnapshot[],\n): string | undefined {\n const real = realPathThroughExistingParent(output);\n const inOutput = (recorded: string) => {\n const rel = pathWithin(real, fromJournalPath(packageRoot, recorded));\n return rel === null ? null : toPosixPath(rel);\n };\n const skipped = new Set<string>();\n const unmarked = new Set<string>();\n for (const { path, created } of compiler) {\n if (pathWithin(fromJournalPath(packageRoot, path), real) !== null) {\n return undefined;\n }\n const rel = inOutput(path);\n if (rel === null) continue;\n skipped.add(rel);\n if (created !== null) {\n const parts = rel.split(\"/\");\n const createdRel = inOutput(created);\n const first = createdRel ? createdRel.split(\"/\").length : 1;\n for (let length = first; length < parts.length; length++) {\n unmarked.add(parts.slice(0, length).join(\"/\"));\n }\n }\n }\n return treeFingerprint(output, skipped, unmarked);\n}\n\nfunction removeScratch(\n packageRoot: string,\n journal: Pick<RunJournal, \"generatedConfig\" | \"pendingBuildInfo\">,\n): void {\n for (const recorded of [\n journal.generatedConfig,\n journal.pendingBuildInfo?.path,\n ]) {\n if (recorded !== undefined)\n removeTree(fromJournalPath(packageRoot, recorded));\n }\n}\n\nexport function installBuildInfo(\n packageRoot: string,\n pending: PendingBuildInfo | undefined,\n): void {\n if (pending === undefined) return;\n const path = fromJournalPath(packageRoot, pending.path);\n if (exists(path)) {\n renamePatiently(path, fromJournalPath(packageRoot, pending.target));\n }\n}\n\n/** Puts `from` at `to`: one rename, or entry by entry when `from` is held open. */\nexport function moveTree(from: string, to: string): \"renamed\" | \"entries\" {\n try {\n renamePatiently(from, to);\n return \"renamed\";\n } catch (error) {\n if (!isHeldOpen(error)) throw error;\n mkdirSync(to, { recursive: true });\n moveEntries(from, to);\n removeTree(from);\n return \"entries\";\n }\n}\n\n/** Build info first: if a later copy fails, tsc still sees its outputs as stale. */\nexport function restoreCompilerOutputs(\n paths: Pick<RunPaths, \"packageRoot\" | \"runDir\">,\n snapshots: readonly CompilerSnapshot[] | null,\n): void {\n const ordered = [...(snapshots ?? [])].sort(\n (a, b) => Number(b.kind === \"build-info\") - Number(a.kind === \"build-info\"),\n );\n for (const snapshot of ordered) {\n const path = fromJournalPath(paths.packageRoot, snapshot.path);\n if (snapshot.copy !== null) {\n replaceTree(fromJournalPath(paths.runDir, snapshot.copy), path);\n restoreDirectoryModes(path, snapshot.modes ?? []);\n continue;\n }\n removeTree(path);\n if (snapshot.created !== null) {\n removeEmptyDirectories(\n dirname(path),\n fromJournalPath(paths.packageRoot, snapshot.created),\n );\n }\n }\n}\n\n/** Removes `from` and its parents up to `upTo` while each is an empty directory. */\nfunction removeEmptyDirectories(from: string, upTo: string): void {\n for (let dir = from; ; dir = dirname(dir)) {\n if (!exists(dir) || entriesOf(dir).length > 0) return;\n rmdirSync(dir);\n if (dir === upTo || dirname(dir) === dir) return;\n }\n}\n\nconst FIRST_UNDO_STEP: Readonly<\n Record<Exclude<JournalState, \"rolling-back\" | \"committed\">, UndoStep>\n> = { building: \"stage\", retiring: \"retire\", installing: \"install\" };\n\nexport type Undone = \"restored\" | \"superseded\";\n\n/**\n * Undoes a run: the previous output goes back in place, the stage goes, and\n * the compiler outputs are restored, unless a later build replaced the output\n * since they were saved (`superseded`). The journal records each step before\n * it starts, so a rollback cut short is finished by the next build, never\n * rolled forward; the run directory, and the snapshot in it, stay until the\n * caller removes them.\n */\nexport function rollBack(paths: RunPaths, journal: RunJournal): Undone {\n if (journal.state === \"committed\") return \"restored\";\n const first =\n journal.state === \"rolling-back\"\n ? (journal.undo ?? \"stage\")\n : FIRST_UNDO_STEP[journal.state];\n const { output, retired } = paths;\n for (const step of UNDO_STEPS.slice(UNDO_STEPS.indexOf(first))) {\n writeJournal(paths.runDir, {\n ...journal,\n state: \"rolling-back\",\n undo: step,\n });\n if (step === \"install\") {\n // Every old entry is in the retired tree by now, so what the output\n // holds is new. Emptied rather than removed: a directory held open\n // cannot go.\n if (!exists(retired)) removeTree(output);\n else\n for (const entry of entriesOf(output)) removeTree(join(output, entry));\n } else if (step === \"retire\") {\n if (exists(retired)) {\n if (exists(output)) moveEntries(retired, output);\n else moveTree(retired, output);\n }\n } else {\n removeTree(paths.stage);\n removeTree(retired);\n removeScratch(paths.packageRoot, journal);\n const digest =\n journal.outputDigest === undefined\n ? undefined\n : outputDigest(paths.packageRoot, output, journal.compiler ?? []);\n if (digest !== undefined && digest !== journal.outputDigest) {\n return \"superseded\";\n }\n restoreCompilerOutputs(paths, journal.compiler);\n }\n }\n return \"restored\";\n}\n\n/** Finishes a run that was installing its stage: the stage becomes the output. */\nexport function rollForward(paths: RunPaths, journal: RunJournal): void {\n const { output, stage } = paths;\n if (exists(stage)) {\n if (exists(output)) moveEntries(stage, output);\n else moveTree(stage, output);\n }\n installBuildInfo(paths.packageRoot, journal.pendingBuildInfo);\n removeTree(stage);\n removeTree(paths.retired);\n removeScratch(paths.packageRoot, journal);\n}\n\nexport type Replayed = \"rolled-back\" | \"superseded\" | \"completed\" | \"discarded\";\n\n/**\n * Brings the package back to a consistent state after a run that died, then\n * removes its run directory. A run that had not started to install its stage,\n * or had started to roll back, is undone; one installing its stage is\n * finished.\n */\nexport function replayRun(packageRoot: string, runDir: string): Replayed {\n const journal = readJournal(runDir);\n let replayed: Replayed = \"discarded\";\n if (journal !== undefined) {\n const paths = runPaths(packageRoot, runDir, journal);\n if (journal.state !== \"installing\" && journal.state !== \"committed\") {\n replayed =\n rollBack(paths, journal) === \"superseded\"\n ? \"superseded\"\n : \"rolled-back\";\n } else {\n rollForward(paths, journal);\n replayed = \"completed\";\n }\n }\n removeTree(runDir);\n return replayed;\n}\n\n/** A run's stage and retired tree beside the output named `output`. */\nexport const isScratchOf = (output: string, entry: string) =>\n entry.startsWith(`.${output}.ph-stage-`) ||\n entry.startsWith(`.${output}.ph-old-`);\n\n/**\n * Undoes or finishes every run a dead build left behind, then removes any\n * stage or retired tree beside `output` that no run claims any more: a\n * bundler of a stopped build can go on writing after its rollback. Call\n * under the lock, where no other run of this package is live.\n */\nexport function recoverStaleRuns(packageRoot: string, output: string): void {\n const runsDir = join(packageRoot, RUNS_DIRECTORY);\n for (const runId of entriesOf(runsDir)) {\n const replayed = replayRun(packageRoot, join(runsDir, runId));\n if (replayed === \"rolled-back\") {\n console.warn(\n \"⚠ An earlier build of this package stopped before it finished; its partial output was removed and the previous output restored.\",\n );\n } else if (replayed === \"superseded\") {\n console.warn(\n `⚠ An earlier build of this package stopped before it finished, and a build that wrote ${toJournalPath(packageRoot, output) || \"the package root\"} in place ran after it; the earlier build's partial output was removed and the newer files were kept.`,\n );\n } else if (replayed === \"completed\") {\n console.warn(\n \"⚠ An earlier build of this package stopped while it replaced its output; the replacement was completed.\",\n );\n }\n }\n const beside = dirname(output);\n for (const entry of entriesOf(beside)) {\n if (isScratchOf(basename(output), entry)) removeTree(join(beside, entry));\n }\n}\n","import { basename, dirname, extname, relative, resolve } from \"node:path\";\n\n/** The compiler options that say where tsc writes, as `tsc --showConfig` prints them. */\nexport type EmitOptions = {\n readonly declaration?: boolean;\n readonly composite?: boolean;\n readonly declarationDir?: string;\n readonly outDir?: string;\n readonly outFile?: string;\n readonly rootDir?: string;\n readonly tsBuildInfoFile?: string;\n readonly noEmit?: boolean;\n readonly emitDeclarationOnly?: boolean;\n readonly sourceMap?: boolean;\n readonly declarationMap?: boolean;\n};\n\nconst withoutExtension = (path: string) => path.replace(/\\.[^./\\\\]+$/, \"\");\n\nconst declares = (options: EmitOptions) =>\n options.declaration === true || options.composite === true;\n\n/**\n * Where tsc keeps the build info of `configFile`, by TypeScript's rule:\n * `tsBuildInfoFile`; else beside `outFile`; else in `outDir`, at the\n * config's place relative to `rootDir` when that is set; else beside the\n * config.\n */\nexport function buildInfoFile(\n options: EmitOptions,\n configFile: string,\n): string {\n const configDir = dirname(configFile);\n const name = `${basename(configFile, extname(configFile))}.tsbuildinfo`;\n if (options.tsBuildInfoFile !== undefined) {\n return resolve(configDir, options.tsBuildInfoFile);\n }\n if (options.outFile !== undefined) {\n return resolve(\n configDir,\n `${withoutExtension(options.outFile)}.tsbuildinfo`,\n );\n }\n if (options.outDir === undefined) return resolve(configDir, name);\n const fromRoot =\n options.rootDir === undefined\n ? \"\"\n : relative(resolve(configDir, options.rootDir), configDir);\n return resolve(configDir, options.outDir, fromRoot, name);\n}\n\n/**\n * The files tsc writes for `outFile`: the bundle and its map unless it\n * emits declarations only, then the declaration and its map when it\n * declares. None without `outFile` or with `noEmit`.\n */\nexport function outFileOutputs(\n options: EmitOptions,\n configFile: string,\n): string[] {\n if (options.outFile === undefined || options.noEmit) return [];\n const output = resolve(dirname(configFile), options.outFile);\n const files: string[] = [];\n if (!options.emitDeclarationOnly) {\n files.push(output, ...(options.sourceMap ? [`${output}.map`] : []));\n }\n if (declares(options)) {\n const declaration = `${withoutExtension(output)}.d.ts`;\n files.push(\n declaration,\n ...(options.declarationMap ? [`${declaration}.map`] : []),\n );\n }\n return files;\n}\n\n/** The declaration and output directories the options name, resolved. */\nexport function outputDirectories(\n options: EmitOptions,\n configDir: string,\n): string[] {\n return [options.declarationDir, options.outDir]\n .filter((dir): dir is string => dir !== undefined)\n .map((dir) => resolve(configDir, dir));\n}\n\n/** Where tsc writes declarations, when it writes them to a directory of their own. */\nexport function declarationDirectory(\n options: EmitOptions,\n configDir: string,\n): string | undefined {\n const dir = options.declarationDir ?? options.outDir;\n if (!dir || !declares(options)) return undefined;\n return resolve(configDir, dir);\n}\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { satisfies } from \"semver\";\n\n// Resolve extends without loading the TypeScript compiler API at runtime.\nconst configSchema = z.object({\n extends: z.union([z.string(), z.array(z.string())]).optional(),\n compilerOptions: z.record(z.string(), z.json()).optional(),\n});\n\nexport function readConfig(path: string): unknown {\n const text = readFileSync(path, \"utf8\")\n .replace(/^\\uFEFF/, \"\")\n .replace(/\"(?:\\\\.|[^\"\\\\])*\"|\\/\\/[^\\r\\n]*|\\/\\*[\\s\\S]*?\\*\\//g, (token) =>\n token.startsWith('\"') ? token : \"\",\n )\n .replace(/\"(?:\\\\.|[^\"\\\\])*\"|,\\s*(?=[}\\]])/g, (token) =>\n token.startsWith('\"') ? token : \"\",\n );\n return JSON.parse(text);\n}\n\nconst manifestSchema = z.object({\n tsconfig: z.string().optional(),\n exports: z.json().optional(),\n typesVersions: z\n .record(z.string(), z.record(z.string(), z.array(z.string())))\n .optional(),\n});\ntype ExportTarget = z.infer<ReturnType<typeof z.json>>;\n\nexport function configDirOptions(\n configFile: string,\n compilerVersion: string,\n): Record<string, ExportTarget> {\n const visiting = new Set<string>();\n const options = (path: string): Record<string, ExportTarget> => {\n if (visiting.has(path)) return {};\n visiting.add(path);\n const config = configSchema.parse(readConfig(path));\n const bases =\n typeof config.extends === \"string\"\n ? [config.extends]\n : (config.extends ?? []);\n const inherited: Record<string, ExportTarget> = {};\n for (const base of bases)\n Object.assign(\n inherited,\n options(extendedConfig(path, base, compilerVersion)),\n );\n visiting.delete(path);\n return { ...inherited, ...config.compilerOptions };\n };\n const substitute = (value: ExportTarget): ExportTarget => {\n if (typeof value === \"string\")\n return value.replaceAll(\"${configDir}\", dirname(configFile));\n if (Array.isArray(value)) return value.map(substitute);\n if (value !== null && typeof value === \"object\")\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [key, substitute(entry)]),\n );\n return value;\n };\n return Object.fromEntries(\n Object.entries(options(configFile))\n .filter(([, value]) => JSON.stringify(value).includes(\"${configDir}\"))\n .map(([key, value]) => [key, substitute(value)]),\n );\n}\n\nfunction file(path: string): string | undefined {\n return statSync(path, { throwIfNoEntry: false })?.isFile() ? path : undefined;\n}\n\nfunction jsonFile(path: string): string | undefined {\n if (path.endsWith(\".json\")) return file(path);\n const rewritten = path.replace(/\\.(?:js|ts)$/, \"\");\n return file(`${rewritten}.json`) ?? file(`${path}.json`);\n}\n\nfunction matchedPath(\n paths: Readonly<Record<string, unknown>>,\n name: string,\n exports = false,\n): { key: string; match: string } | undefined {\n if (Object.hasOwn(paths, name)) return { key: name, match: \"\" };\n const keys = Object.keys(paths).filter(\n (key) =>\n (key.includes(\"*\") && key.indexOf(\"*\") === key.lastIndexOf(\"*\")) ||\n (exports && key.endsWith(\"/\")),\n );\n keys.sort((a, b) => {\n const prefix = (key: string) =>\n key.includes(\"*\") ? key.indexOf(\"*\") + 1 : key.length;\n return (\n prefix(b) - prefix(a) ||\n (exports\n ? Number(!a.includes(\"*\")) - Number(!b.includes(\"*\")) ||\n b.length - a.length\n : 0)\n );\n });\n for (const key of keys) {\n const star = key.indexOf(\"*\");\n if (\n star !== -1 &&\n name.startsWith(key.slice(0, star)) &&\n name.endsWith(key.slice(star + 1))\n )\n return {\n key,\n match: name.slice(star, name.length - (key.length - star - 1)),\n };\n if (star === -1 && name.startsWith(key))\n return { key, match: name.slice(key.length) };\n }\n return undefined;\n}\n\nfunction exportedConfig(\n target: ExportTarget,\n directory: string,\n compilerVersion: string,\n match: string,\n pattern: boolean,\n): { path?: string } | undefined {\n if (typeof target === \"string\") {\n if (\n !target.startsWith(\"./\") ||\n (!pattern && match !== \"\" && !target.endsWith(\"/\"))\n )\n return {};\n const path = pattern ? target.replaceAll(\"*\", match) : target + match;\n if (\n path\n .slice(2)\n .split(\"/\")\n .some(\n (part) => part === \".\" || part === \"..\" || part === \"node_modules\",\n )\n )\n return {};\n const resolved = jsonFile(resolve(directory, path));\n return resolved === undefined ? {} : { path: resolved };\n }\n if (target === null) return {};\n if (Array.isArray(target)) {\n if (target.length === 0) return {};\n for (const entry of target) {\n const result = exportedConfig(\n entry,\n directory,\n compilerVersion,\n match,\n pattern,\n );\n if (result !== undefined) return result;\n }\n } else if (typeof target === \"object\") {\n for (const [condition, entry] of Object.entries(target))\n if (\n [\"types\", \"require\", \"node\", \"default\"].includes(condition) ||\n (condition.startsWith(\"types@\") &&\n satisfies(compilerVersion, condition.slice(6)))\n ) {\n const result = exportedConfig(\n entry,\n directory,\n compilerVersion,\n match,\n pattern,\n );\n if (result !== undefined) return result;\n }\n } else return {};\n return undefined;\n}\n\nfunction extendedConfig(\n configFile: string,\n input: string,\n compilerVersion: string,\n): string {\n const specifier = input.replaceAll(\"\\\\\", \"/\");\n if (\n specifier.startsWith(\"./\") ||\n specifier.startsWith(\"../\") ||\n isAbsolute(specifier)\n ) {\n const path = resolve(dirname(configFile), specifier);\n const found =\n file(path) ??\n (!path.endsWith(\".json\") ? file(`${path}.json`) : undefined);\n if (found !== undefined) return found;\n } else {\n const parts = specifier.split(\"/\");\n const nameLength = specifier.startsWith(\"@\") ? 2 : 1;\n const packageName = parts.slice(0, nameLength).join(\"/\");\n const subpath = parts.slice(nameLength).join(\"/\");\n const manifestAt = (directory: string) => {\n const path = join(directory, \"package.json\");\n if (!existsSync(path)) return undefined;\n return manifestSchema.parse(readConfig(path));\n };\n const fromDirectory = (\n directory: string,\n pkg: ReturnType<typeof manifestAt>,\n ): string | undefined => {\n const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(\n ([range]) => satisfies(compilerVersion, range),\n )?.[1];\n const entry = pkg?.tsconfig\n ? resolve(directory, pkg.tsconfig)\n : join(directory, \"tsconfig\");\n if (versionPaths !== undefined) {\n const match = matchedPath(\n versionPaths,\n entry.slice(directory.length + 1),\n );\n if (match !== undefined)\n for (const path of versionPaths[match.key] ?? []) {\n const found = jsonFile(\n resolve(directory, path.replace(\"*\", match.match)),\n );\n if (found !== undefined) return found;\n }\n }\n return (\n (pkg?.tsconfig ? jsonFile(entry) : undefined) ??\n jsonFile(join(directory, \"tsconfig\"))\n );\n };\n for (const modules of createRequire(configFile).resolve.paths(specifier) ??\n []) {\n const directory = join(modules, packageName);\n const candidate = join(modules, specifier);\n const nested = manifestAt(candidate);\n const pkg = subpath === \"\" ? nested : manifestAt(directory);\n if (subpath !== \"\" && nested !== undefined && !pkg?.exports) {\n const found = jsonFile(candidate) ?? fromDirectory(candidate, nested);\n if (found !== undefined) return found;\n continue;\n }\n if (pkg?.exports) {\n const exports = pkg.exports;\n const key = subpath === \"\" ? \".\" : `./${subpath}`;\n let target: ExportTarget | undefined;\n let match = \"\";\n let pattern = false;\n if (\n typeof exports === \"object\" &&\n !Array.isArray(exports) &&\n Object.keys(exports).some((key) => key.startsWith(\".\"))\n ) {\n const matched = matchedPath(exports, key, true);\n if (matched !== undefined) {\n target = exports[matched.key];\n match = matched.match;\n pattern = matched.key.includes(\"*\");\n }\n } else if (key === \".\") target = exports;\n const found =\n target === undefined\n ? undefined\n : exportedConfig(target, directory, compilerVersion, match, pattern)\n ?.path;\n if (found !== undefined) return found;\n continue;\n }\n const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(\n ([range]) => satisfies(compilerVersion, range),\n )?.[1];\n if (subpath !== \"\" && versionPaths !== undefined) {\n const match = matchedPath(versionPaths, subpath);\n if (match !== undefined)\n for (const path of versionPaths[match.key] ?? []) {\n const found = jsonFile(\n resolve(directory, path.replace(\"*\", match.match)),\n );\n if (found !== undefined) return found;\n }\n }\n const found = jsonFile(candidate) ?? fromDirectory(candidate, pkg);\n if (found !== undefined) return found;\n }\n }\n throw new Error(\n `The extended TypeScript config ${JSON.stringify(specifier)} could not be resolved from ${JSON.stringify(configFile)}.`,\n );\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n// tsc ends its lines with \\r\\n on Windows.\nconst lines = (stdout: string) => stdout.split(/\\r?\\n/);\n\nexport function listedFiles(stdout = \"\", directory = \".\"): string[] {\n return lines(stdout)\n .map((line) => line.trim())\n .map((line) => resolve(directory, line))\n .filter((line) => existsSync(line) && statSync(line).isFile());\n}\n\nexport function explainedRoots(stdout: string, directory: string): string[] {\n const roots: string[] = [];\n let file: string | undefined;\n for (const line of lines(stdout)) {\n if (\n line !== \"\" &&\n line === line.trim() &&\n /\\.(?:[cm]?[jt]sx?|json)$/i.test(line)\n ) {\n const path = resolve(directory, line);\n file = statSync(path, { throwIfNoEntry: false })?.isFile()\n ? path\n : undefined;\n } else if (\n file !== undefined &&\n /Root file specified|Part of 'files' list|Matched by (default )?include pattern/.test(\n line,\n )\n ) {\n roots.push(file);\n }\n }\n return roots;\n}\n","import { SpawnError, spawnAsync } from \"@powerhousedao/shared/clis\";\nimport { mkdtempSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport type { Agent } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector\";\nimport { z } from \"zod\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport { canonicalConfigFile, toPosixPath } from \"./paths.js\";\nimport {\n buildInfoFile,\n outFileOutputs,\n outputDirectories,\n} from \"../compiler-output/emit.js\";\nimport { configDirOptions, readConfig } from \"./config-inputs.js\";\nimport { explainedRoots, listedFiles } from \"./compiler-output.js\";\n\ntype CommandResult = {\n readonly ok: boolean;\n readonly output: string;\n};\n\nasync function runLocal(\n packageRoot: string,\n agent: Agent,\n argv: readonly string[],\n): Promise<CommandResult> {\n const command = resolveCommand(agent, \"execute-local\", [...argv]);\n if (command === null)\n return {\n ok: false,\n output: `${argv[0]} is not installed in this package`,\n };\n try {\n // TypeScript uses PWD to spell paths even when cwd is canonical.\n const output = await spawnAsync(command.command, command.args, {\n cwd: packageRoot,\n env: { ...process.env, PWD: packageRoot },\n });\n return { ok: true, output };\n } catch (error) {\n return {\n ok: false,\n output:\n error instanceof SpawnError && error.stdout.length !== 0\n ? error.stdout\n : error instanceof Error\n ? error.message\n : `${argv[0]} failed`,\n };\n }\n}\n\nconst configSchema = z.object({\n compilerOptions: z.looseObject({\n declaration: z.boolean().optional(),\n composite: z.boolean().optional(),\n incremental: z.boolean().optional(),\n declarationDir: z.string().optional(),\n outDir: z.string().optional(),\n rootDir: z.string().optional(),\n noEmit: z.boolean().optional(),\n emitDeclarationOnly: z.boolean().optional(),\n sourceMap: z.boolean().optional(),\n declarationMap: z.boolean().optional(),\n jsx: z.string().optional(),\n outFile: z.string().optional(),\n tsBuildInfoFile: z.string().optional(),\n resolveJsonModule: z.boolean().optional(),\n }),\n references: z.array(z.object({ path: z.string() })).optional(),\n});\n\nexport type CompilerProject = {\n readonly diagnostic?: string;\n readonly configFile: string;\n readonly options: z.infer<typeof configSchema>[\"compilerOptions\"];\n readonly sources: readonly string[];\n readonly external: boolean;\n readonly emitRoot: string;\n readonly references: readonly string[];\n};\n\n/** What `tsc --build` on the package's root config reads and writes. */\nexport type CompilePlan = {\n /** A diagnostic tsc reports for a build it still runs, such as TS18003 for a project with no inputs. */\n readonly preflightTypeError?: string;\n /** The root project, then the projects it references. */\n readonly projects: readonly [CompilerProject, ...CompilerProject[]];\n /** What the build writes, relative to the package root. */\n readonly outputs: {\n readonly directories: readonly string[];\n readonly files: readonly string[];\n };\n};\nexport type CompilePreflight =\n | { readonly ok: true; readonly plan: CompilePlan }\n | { readonly ok: false; readonly summary: string };\n\nclass CompilerDiagnostic extends Error {\n constructor(\n summary: string,\n readonly configFile: string,\n readonly noWrites: boolean,\n ) {\n super(summary);\n }\n}\n\nfunction projectConfigFile(path: string): string {\n const entry = statSync(path, { throwIfNoEntry: false });\n return canonicalConfigFile(\n entry?.isDirectory() || (entry === undefined && !path.endsWith(\".json\"))\n ? join(path, \"tsconfig.json\")\n : path,\n );\n}\n\nexport function commonSourceDirectory(\n files: readonly string[],\n fallback: string,\n): string {\n let root = files.length === 0 ? fallback : dirname(files[0] ?? fallback);\n for (const file of files)\n while (pathWithin(root, file) === null) {\n const parent = dirname(root);\n if (parent === root)\n throw new Error(\n \"TypeScript sources on different drives have no common source directory.\",\n );\n root = parent;\n }\n return root;\n}\n\nfunction outputFiles(\n project: CompilerProject,\n emitsBuildInfoInBuildMode: boolean,\n): string[] {\n const { options, sources, configFile } = project;\n const directory = dirname(configFile);\n const root = project.emitRoot;\n const files =\n emitsBuildInfoInBuildMode ||\n options.composite ||\n options.incremental ||\n options.tsBuildInfoFile !== undefined\n ? [buildInfoFile(options, configFile)]\n : [];\n if (options.noEmit) return files;\n if (options.outFile !== undefined)\n return [...files, ...outFileOutputs(options, configFile)];\n const declares = options.declaration === true || options.composite === true;\n for (const source of sources) {\n if (/\\.json$/i.test(source)) {\n if (!options.emitDeclarationOnly) {\n const inside = pathWithin(root, source);\n files.push(\n options.outDir === undefined || inside === null\n ? source\n : resolve(directory, options.outDir, inside),\n );\n }\n continue;\n }\n const suffix = /\\.[cm]?[jt]sx?$/i;\n const jsExtension = /\\.[cm][jt]s$/i.test(source)\n ? source.slice(-4).replace(\"t\", \"j\")\n : options.jsx === \"preserve\" && /[jt]sx$/i.test(source)\n ? \".jsx\"\n : \".js\";\n const declarationExtension = /\\.[cm][jt]s$/i.test(source)\n ? source.slice(-4).replace(/j/, \"t\").replace(\".\", \".d.\")\n : \".d.ts\";\n const inRoot = pathWithin(root, source);\n const destination = (out: string | undefined, extension: string): string =>\n out === undefined || inRoot === null\n ? source.replace(suffix, extension)\n : resolve(directory, out, inRoot.replace(suffix, extension));\n if (!options.emitDeclarationOnly) {\n const js = destination(options.outDir, jsExtension);\n files.push(js, ...(options.sourceMap ? [js + \".map\"] : []));\n }\n if (declares) {\n const declaration = destination(\n options.declarationDir ?? options.outDir,\n declarationExtension,\n );\n files.push(\n declaration,\n ...(options.declarationMap ? [declaration + \".map\"] : []),\n );\n }\n }\n return files;\n}\n\n/**\n * Reads the package's project graph through its own `tsc` and predicts what\n * `tsc --build` writes, without writing. Refuses a build that would write\n * outside the package.\n */\nexport async function prepareCompile(\n packageRoot: string,\n agent: Agent,\n): Promise<CompilePreflight> {\n try {\n const version = await runLocal(packageRoot, agent, [\"tsc\", \"--version\"]);\n const match = /Version (\\d+)\\.(\\d+)/.exec(version.output);\n if (match === null)\n throw new Error(\n \"The installed TypeScript version could not be resolved.\",\n );\n const major = Number(match[1]);\n const minor = Number(match[2]);\n // From 5.6, `tsc --build` writes a .tsbuildinfo for every project it\n // builds; from 6.0, rootDir defaults to the config's directory.\n const emitsBuildInfoInBuildMode = major > 5 || (major === 5 && minor >= 6);\n const defaultsRootDirToConfig = major >= 6;\n const projects = await readProjectGraph(\n packageRoot,\n agent,\n join(packageRoot, \"tsconfig.json\"),\n defaultsRootDirToConfig,\n /Version (\\S+)/.exec(version.output)?.[1] ?? `${major}.${minor}.0`,\n );\n return {\n ok: true,\n plan: checkedCompilePlan(\n packageRoot,\n projects,\n emitsBuildInfoInBuildMode,\n ),\n };\n } catch (error) {\n if (\n error instanceof CompilerDiagnostic &&\n error.noWrites &&\n error.configFile === projectConfigFile(join(packageRoot, \"tsconfig.json\"))\n ) {\n const checked = checkedCompilePlan(\n packageRoot,\n [\n {\n configFile: error.configFile,\n options: { noEmit: true },\n sources: [],\n external: false,\n emitRoot: packageRoot,\n references: [],\n },\n ],\n false,\n );\n return {\n ok: true,\n plan: { ...checked, preflightTypeError: error.message },\n };\n }\n return {\n ok: false,\n summary:\n error instanceof Error\n ? error.message\n : \"The TypeScript output layout could not be resolved.\",\n };\n }\n}\n\nasync function readProjectGraph(\n packageRoot: string,\n agent: Agent,\n configPath: string,\n defaultsRootDirToConfig: boolean,\n compilerVersion: string,\n): Promise<CompilerProject[]> {\n const projects: CompilerProject[] = [];\n const visited = new Set<string>();\n const rootConfig = projectConfigFile(join(packageRoot, \"tsconfig.json\"));\n const visit = async (path: string): Promise<void> => {\n const configFile = projectConfigFile(path);\n if (visited.has(configFile)) return;\n visited.add(configFile);\n let shown = await runLocal(packageRoot, agent, [\n \"tsc\",\n \"-p\",\n configFile,\n \"--showConfig\",\n ]);\n let diagnostic: string | undefined;\n if (\n !shown.ok &&\n /TS18003/.test(shown.output) &&\n pathWithin(packageRoot, configFile) !== null\n ) {\n diagnostic = shown.output;\n shown = await showEmptyProjectConfig(\n packageRoot,\n agent,\n configFile,\n compilerVersion,\n );\n }\n if (!shown.ok) {\n throw new CompilerDiagnostic(\n shown.output,\n configFile,\n statSync(configFile, { throwIfNoEntry: false }) === undefined,\n );\n }\n const config = configSchema.parse(JSON.parse(shown.output));\n const project = await refreshProject(\n packageRoot,\n agent,\n {\n ...(diagnostic !== undefined && { diagnostic }),\n configFile,\n options: config.compilerOptions,\n sources: [],\n references: (config.references ?? []).map((reference) =>\n projectConfigFile(resolve(dirname(configFile), reference.path)),\n ),\n emitRoot: dirname(configFile),\n external:\n configFile !== rootConfig &&\n pathWithin(packageRoot, configFile) === null,\n },\n defaultsRootDirToConfig,\n );\n projects.push(project);\n for (const reference of project.references) await visit(reference);\n };\n await visit(configPath);\n return projects;\n}\n\nasync function showEmptyProjectConfig(\n packageRoot: string,\n agent: Agent,\n configFile: string,\n compilerVersion: string,\n): Promise<CommandResult> {\n const config = z\n .object({ references: configSchema.shape.references })\n .parse(readConfig(configFile));\n const directory = realPathThroughExistingParent(\n mkdtempSync(join(tmpdir(), \".ph-preflight-\")),\n );\n try {\n const probe = join(directory, \"tsconfig.json\");\n writeFileSync(\n probe,\n JSON.stringify({\n extends: configFile,\n compilerOptions: configDirOptions(configFile, compilerVersion),\n files: [configFile],\n include: [],\n references: config.references?.map(({ path }) => ({\n path: resolve(dirname(configFile), path),\n })),\n }),\n );\n const shown = await runLocal(packageRoot, agent, [\n \"tsc\",\n \"-p\",\n probe,\n \"--showConfig\",\n ]);\n if (!shown.ok) return shown;\n const resolved = configSchema.parse(JSON.parse(shown.output));\n const options = resolved.compilerOptions;\n const rebase = (path: string): string => {\n const absolute = resolve(directory, path);\n const inProbe = pathWithin(directory, absolute);\n return inProbe === null\n ? absolute\n : resolve(dirname(configFile), inProbe);\n };\n // showConfig rebases inherited paths to the probe directory.\n for (const key of [\n \"outDir\",\n \"declarationDir\",\n \"rootDir\",\n \"outFile\",\n \"tsBuildInfoFile\",\n ] as const) {\n const path = options[key];\n if (path !== undefined) options[key] = rebase(path);\n }\n return { ...shown, output: JSON.stringify(resolved) };\n } finally {\n rmSync(directory, { recursive: true, force: true });\n }\n}\n\nasync function listProjectFiles(\n packageRoot: string,\n agent: Agent,\n configFile: string,\n preserveSymlinks = false,\n) {\n const listed = await runLocal(packageRoot, agent, [\n \"tsc\",\n \"-p\",\n configFile,\n \"--listFilesOnly\",\n \"--explainFiles\",\n \"--pretty\",\n \"false\",\n ...(preserveSymlinks ? [\"--preserveSymlinks\", \"true\"] : []),\n ]);\n return {\n ...listed,\n files: listedFiles(listed.output, packageRoot),\n rootFiles: explainedRoots(listed.output, packageRoot),\n };\n}\n\nasync function refreshProject(\n packageRoot: string,\n agent: Agent,\n project: CompilerProject,\n defaultsRootDirToConfig: boolean,\n): Promise<CompilerProject> {\n const listed = await listProjectFiles(packageRoot, agent, project.configFile);\n const { files, rootFiles } = listed;\n if (!listed.ok && files.length === 0 && !/TS18003/.test(listed.output)) {\n throw new CompilerDiagnostic(listed.output, project.configFile, false);\n }\n const roots = new Set(\n rootFiles.map((file) => realPathThroughExistingParent(file)),\n );\n let sources = files.filter(\n (file) =>\n (/\\.[cm]?[jt]sx?$/i.test(file) ||\n (project.options.resolveJsonModule === true &&\n /\\.json$/i.test(file))) &&\n !/\\.d\\.[cm]?ts$/i.test(file) &&\n (roots.has(realPathThroughExistingParent(file)) ||\n !toPosixPath(file).includes(\"/node_modules/\")),\n );\n if (\n sources.some(\n (file) =>\n !roots.has(realPathThroughExistingParent(file)) &&\n pathWithin(packageRoot, realPathThroughExistingParent(file)) === null,\n )\n ) {\n const preserved = await listProjectFiles(\n packageRoot,\n agent,\n project.configFile,\n true,\n );\n const spellings = preserved.files;\n if (spellings.length === 0)\n throw new Error(\n \"tsc could not classify external library inputs without writing them.\",\n );\n const local = new Set(\n spellings\n .filter(\n (file) =>\n roots.has(realPathThroughExistingParent(file)) ||\n !toPosixPath(file).includes(\"/node_modules/\"),\n )\n .map((path) => realPathThroughExistingParent(path)),\n );\n const libraries = new Set(\n spellings\n .filter((file) => toPosixPath(file).includes(\"/node_modules/\"))\n .map((path) => realPathThroughExistingParent(path)),\n );\n sources = sources.filter(\n (file) =>\n !libraries.has(realPathThroughExistingParent(file)) ||\n local.has(realPathThroughExistingParent(file)),\n );\n }\n return {\n ...project,\n ...(/TS18003/.test(listed.output) && {\n diagnostic: listed.output,\n }),\n sources,\n emitRoot: resolve(\n dirname(project.configFile),\n project.options.rootDir ??\n (project.options.composite || defaultsRootDirToConfig\n ? \".\"\n : commonSourceDirectory(sources, dirname(project.configFile))),\n ),\n };\n}\n\nfunction checkedCompilePlan(\n packageRoot: string,\n projects: readonly CompilerProject[],\n emitsBuildInfoInBuildMode: boolean,\n): CompilePlan {\n const directories = new Set<string>();\n const files = new Set<string>();\n for (const project of projects) {\n if (project.external) continue;\n if (!project.options.noEmit) {\n for (const path of outputDirectories(\n project.options,\n dirname(project.configFile),\n )) {\n const target = realPathThroughExistingParent(path);\n if (pathWithin(packageRoot, target) === null)\n throw new Error(\n `tsc would write to ${JSON.stringify(path)} outside the package.`,\n );\n if (\n !project.sources.some(\n (file) =>\n pathWithin(target, realPathThroughExistingParent(file)) !== null,\n )\n ) {\n if (pathWithin(packageRoot, path) !== null)\n directories.add(toPosixPath(relative(packageRoot, path)));\n directories.add(toPosixPath(relative(packageRoot, target)));\n }\n }\n }\n for (const path of outputFiles(project, emitsBuildInfoInBuildMode)) {\n if (/\\.json$/i.test(path) && project.sources.includes(path)) continue;\n const target = realPathThroughExistingParent(path);\n if (pathWithin(packageRoot, target) === null)\n throw new Error(\n `tsc would write to ${JSON.stringify(path)} outside the package.`,\n );\n if (pathWithin(packageRoot, path) !== null)\n files.add(toPosixPath(relative(packageRoot, path)));\n files.add(toPosixPath(relative(packageRoot, target)));\n }\n }\n const root = projects.at(0);\n const references = projects.slice(1);\n if (root === undefined)\n throw new Error(\"The root TypeScript project could not be resolved.\");\n return {\n ...(root.diagnostic !== undefined && {\n preflightTypeError: root.diagnostic,\n }),\n projects: [root, ...references],\n outputs: {\n directories: [...directories].sort(),\n files: [...files].sort(),\n },\n };\n}\n","import { dirname } from \"node:path\";\nimport { pathWithin } from \"@powerhousedao/shared/clis/real-paths\";\nimport {\n buildInfoFile,\n type EmitOptions,\n outFileOutputs,\n outputDirectories,\n} from \"../../compiler-output/emit.js\";\n\n/** A path tsc writes that the build restores when it does not finish. */\nexport type CompilerOutput = {\n readonly path: string;\n readonly kind: \"directory\" | \"build-info\" | \"file\";\n};\n\nconst optionalString = (value: unknown) =>\n typeof value === \"string\" ? value : undefined;\nconst optionalBoolean = (value: unknown) =>\n typeof value === \"boolean\" ? value : undefined;\n\nexport type ShownConfig = {\n readonly options: EmitOptions & { readonly incremental?: boolean };\n /** As printed: with no `exclude` of its own, tsc's default, which names the output directories. */\n readonly exclude: readonly string[] | undefined;\n readonly references: readonly string[];\n};\n\nconst strings = (value: unknown) =>\n Array.isArray(value) && value.every((entry) => typeof entry === \"string\")\n ? (value as string[])\n : undefined;\n\n/** The config in `tsc --showConfig` output, or undefined when it is not JSON. */\nexport function parseShownConfig(text: string): ShownConfig | undefined {\n let shown: unknown;\n try {\n shown = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof shown !== \"object\" || shown === null) return undefined;\n const { compilerOptions, exclude, references } = shown as Record<\n string,\n unknown\n >;\n return {\n options: emitOptions(compilerOptions),\n exclude: strings(exclude),\n references: Array.isArray(references)\n ? references.flatMap((reference: unknown) => {\n const path = (reference as { path?: unknown } | null)?.path;\n return typeof path === \"string\" ? [path] : [];\n })\n : [],\n };\n}\n\nfunction emitOptions(options: unknown): ShownConfig[\"options\"] {\n if (typeof options !== \"object\" || options === null) return {};\n const record = options as Record<string, unknown>;\n return {\n declaration: optionalBoolean(record.declaration),\n composite: optionalBoolean(record.composite),\n incremental: optionalBoolean(record.incremental),\n declarationDir: optionalString(record.declarationDir),\n outDir: optionalString(record.outDir),\n outFile: optionalString(record.outFile),\n rootDir: optionalString(record.rootDir),\n tsBuildInfoFile: optionalString(record.tsBuildInfoFile),\n noEmit: optionalBoolean(record.noEmit),\n emitDeclarationOnly: optionalBoolean(record.emitDeclarationOnly),\n sourceMap: optionalBoolean(record.sourceMap),\n declarationMap: optionalBoolean(record.declarationMap),\n };\n}\n\n/**\n * What the root project's tsc writes inside the package, for the build to\n * snapshot and restore: its build info first, then the files `outFile`\n * writes, then its declaration and output directories, the build's own\n * output directory or one holding it included. A directory holding\n * `buildDirectory`, where the build keeps its runs and their snapshots, is\n * left out and unprotected, as without staging: a snapshot of it would copy\n * itself. This says what to protect, not what to carry into the stage.\n */\nexport function compilerOutputInventory(\n options: EmitOptions,\n at: {\n readonly configFile: string;\n readonly packageRoot: string;\n readonly buildDirectory: string;\n },\n): CompilerOutput[] {\n const inPackage = (path: string) => Boolean(pathWithin(at.packageRoot, path));\n const directories = outputDirectories(options, dirname(at.configFile))\n .filter(inPackage)\n .filter((dir) => pathWithin(dir, at.buildDirectory) === null);\n return [\n ...[buildInfoFile(options, at.configFile)]\n .filter(inPackage)\n .map((path) => ({ path, kind: \"build-info\" as const })),\n ...outFileOutputs(options, at.configFile)\n .filter(inPackage)\n .map((path) => ({ path, kind: \"file\" as const })),\n ...[...new Set(directories)].map((path) => ({\n path,\n kind: \"directory\" as const,\n })),\n ];\n}\n","import { lstatSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { Agent } from \"package-manager-detector\";\nimport {\n buildInfoFile,\n type EmitOptions,\n outFileOutputs,\n} from \"../../compiler-output/emit.js\";\nimport { prepareCompile } from \"../../definitions/compiler.js\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport {\n type CompilerOutput,\n compilerOutputInventory,\n type ShownConfig,\n} from \"./inventory.js\";\nfunction writesBesideSources(options: EmitOptions): boolean {\n if (options.noEmit || options.outFile !== undefined) return false;\n if (options.outDir !== undefined) return false;\n const declares = options.declaration === true || options.composite === true;\n return !options.emitDeclarationOnly || (declares && !options.declarationDir);\n}\n\ntype InventoryPlace = Parameters<typeof compilerOutputInventory>[1];\n\nconst redirectable = ({ references, options }: ShownConfig) =>\n references.length === 0 &&\n Boolean(options.incremental || options.composite || options.tsBuildInfoFile);\n\nexport async function compilerOutputs(\n config: ShownConfig,\n at: InventoryPlace & {\n readonly agent: Agent;\n readonly output: string;\n },\n): Promise<CompilerOutput[]> {\n const root = compilerOutputInventory(config.options, at);\n const real = (path: string) => realPathThroughExistingParent(path);\n const packageIdentity = real(at.packageRoot);\n const inPackage = (path: string) =>\n pathWithin(packageIdentity, real(path)) !== null;\n // A reference to another package is that package's build: its outputs are\n // not this package's to restore, and reading its project graph spawns tsc\n // once or twice per project it reaches.\n const referencesInPackage = config.references.some((reference) =>\n inPackage(resolve(dirname(at.configFile), reference)),\n );\n const holdsOutput = (dir: string) =>\n pathWithin(real(dir), at.output) !== null;\n const protectsOutput = root.some(\n ({ kind, path }) =>\n kind === \"directory\" &&\n holdsOutput(path) &&\n !(redirectable(config) && real(path) === at.output),\n );\n if (\n !referencesInPackage &&\n !writesBesideSources(config.options) &&\n !protectsOutput\n ) {\n return root;\n }\n const prepared = await prepareCompile(at.packageRoot, at.agent);\n if (!prepared.ok) return root;\n const { directories, files } = prepared.plan.outputs;\n const absolute = (path: string) => resolve(at.packageRoot, path);\n const owned = (path: string) =>\n inPackage(path) && pathWithin(path, at.buildDirectory) === null;\n const dirs = directories\n .map(absolute)\n .filter((dir) => owned(dir) && !holdsOutput(dir));\n return [\n ...files\n .map(absolute)\n .filter(\n (file) =>\n owned(file) && !dirs.some((dir) => pathWithin(dir, file) !== null),\n )\n .map((path) => ({\n path,\n kind: path.endsWith(\".tsbuildinfo\")\n ? (\"build-info\" as const)\n : (\"file\" as const),\n }))\n .sort(\n (a, b) =>\n Number(b.kind === \"build-info\") - Number(a.kind === \"build-info\"),\n ),\n ...dirs.map((path) => ({ path, kind: \"directory\" as const })),\n ];\n}\n\nexport type CompilerRedirect = {\n readonly compilerOptions: Readonly<Record<string, string>>;\n readonly exclude: readonly string[] | undefined;\n readonly pendingBuildInfo:\n | { readonly path: string; readonly target: string }\n | undefined;\n readonly staged: readonly string[];\n};\n\nexport function redirectRootProject(\n config: ShownConfig,\n at: {\n readonly configFile: string;\n readonly packageRoot: string;\n readonly output: string;\n readonly stage: string;\n readonly pending: (target: string) => string;\n },\n): CompilerRedirect | undefined {\n if (!redirectable(config)) return undefined;\n const { options } = config;\n const configDir = dirname(at.configFile);\n const real = (path: string) => realPathThroughExistingParent(path);\n const inOutput = (path: string) => pathWithin(at.output, real(path));\n const compilerOptions: Record<string, string> = {};\n const staged: string[] = [];\n for (const key of [\"declarationDir\", \"outDir\", \"outFile\"] as const) {\n const value = options[key];\n if (value === undefined || (key === \"outFile\" && options.noEmit)) continue;\n const rel = inOutput(resolve(configDir, value));\n if (rel === null) continue;\n compilerOptions[key] = join(at.stage, rel);\n staged.push(\n ...(key === \"outFile\"\n ? outFileOutputs(options, at.configFile)\n : [resolve(configDir, value)]\n ).map(real),\n );\n }\n const target = buildInfoFile(options, at.configFile);\n const rel = inOutput(target);\n let pendingBuildInfo: CompilerRedirect[\"pendingBuildInfo\"];\n if (rel !== null) {\n compilerOptions.tsBuildInfoFile = join(at.stage, rel);\n staged.push(real(target));\n } else if (\n pathWithin(at.packageRoot, target) !== null &&\n // A copy of the link would write through to the live file; tsc writes\n // it in place instead, and the run snapshots what the link points to.\n !lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()\n ) {\n pendingBuildInfo = { path: at.pending(target), target };\n compilerOptions.tsBuildInfoFile = pendingBuildInfo.path;\n staged.push(real(target));\n } else {\n compilerOptions.tsBuildInfoFile = target;\n }\n return { compilerOptions, exclude: config.exclude, pendingBuildInfo, staged };\n}\n","import {\n lstatSync,\n mkdirSync,\n statSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, dirname, extname, join } from \"node:path\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport {\n CannotStage,\n cloneTree,\n creating,\n exists,\n isHeldOpen,\n linkTree,\n moveEntries,\n openDirectories,\n removeTree,\n renamePatiently,\n unstageableEntryIn,\n} from \"./files.js\";\nimport { type CompilerRedirect, redirectRootProject } from \"./compiler.js\";\nimport type { CompilerOutput, ShownConfig } from \"./inventory.js\";\nimport { BUILD_DIRECTORY } from \"../../build-control.js\";\nimport {\n type CompilerSnapshot,\n fromJournalPath,\n type JournalState,\n type RunJournal,\n RUNS_DIRECTORY,\n toJournalPath,\n writeJournal,\n} from \"./journal.js\";\nimport type { BuildLock } from \"./lock.js\";\nimport {\n installBuildInfo,\n isScratchOf,\n outputDigest,\n rollBack,\n type RunPaths,\n runPaths,\n} from \"./recovery.js\";\n\nconst isUnreadable = (error: unknown) => {\n const code = (error as { code?: unknown } | null)?.code;\n return code === \"EACCES\" || code === \"EPERM\";\n};\n\n/** `path` is `dir` or holds it. */\nconst isOrHolds = (path: string, dir: string) => pathWithin(path, dir) !== null;\n\n/** The outermost directory of `path`, inside the package, that does not exist. */\nfunction outermostMissing(packageRoot: string, path: string): string {\n let missing = path;\n for (\n let parent = dirname(path);\n pathWithin(packageRoot, parent) && !exists(parent);\n parent = dirname(parent)\n ) {\n missing = parent;\n }\n return missing;\n}\n\n/** A path as messages name it: from the package root, which is named so. */\nexport const shownPath = (packageRoot: string, path: string) =>\n toJournalPath(packageRoot, path) || \"the package root\";\n\nexport const scratchBeside = (path: string, kind: string, runId: string) =>\n join(dirname(path), `.${basename(path)}.ph-${kind}-${runId}`);\n\nexport type CompilerRun = {\n readonly configFile: string;\n readonly config: ShownConfig;\n readonly outputs: readonly CompilerOutput[];\n};\n\n/** One `ph build` of one package, as the steps and the step runner see it. */\nexport type BuildSession = {\n /** The output directory's real path, for comparing it with other paths. */\n readonly output: string;\n /** The output is `<package>/dist`, where the stylesheet and manifest copy belong. */\n readonly writesPackageDist: boolean;\n /** The directory every output write targets. */\n stage(): string;\n /**\n * Call before tsc runs, with what it is about to write. Returns the\n * generated config tsc builds instead when it can write into the stage.\n */\n prepareCompiler(compiler: CompilerRun): Promise<string | undefined>;\n /** Call once tsc has written, whatever it reported, before any bundle step. */\n compilerOutputsWritten(): void;\n commit(): void;\n /** Releases the lock. Call once nothing of this build runs any more. */\n close(): void;\n /**\n * Releases the lock and keeps the run, for a process a signal is about to\n * end: the next build replays the run's journal.\n */\n releaseLock(): void;\n rollback(): void;\n /**\n * Notes that the process was told to stop. Synchronous, for a signal\n * handler; the step runner stops the build once the running step settles.\n */\n cancel(signal: NodeJS.Signals): void;\n stopped(): NodeJS.Signals | undefined;\n /**\n * Runs `stop` synchronously inside `cancel`, so work outside this process,\n * such as a child, ends before a signal handler lets the process exit.\n * Returns the unregister function.\n */\n onCancel(stop: () => void): () => void;\n};\n\ntype Status = \"open\" | \"committed\" | \"rolled-back\";\n\n/**\n * One `ph build` of one package: the output is written to a stage beside the\n * output directory and replaces it only on commit. Until then the previous\n * output and the compiler outputs tsc rewrote can be put back, by `rollback`\n * in this process or, after a crash, by the next build.\n */\nexport class StagedBuildSession implements BuildSession {\n readonly runId: string;\n readonly packageRoot: string;\n readonly output: string;\n readonly writesPackageDist: boolean;\n readonly runDir: string;\n private readonly paths: RunPaths;\n private readonly lock: BuildLock;\n private journal: RunJournal;\n private status: Status = \"open\";\n private stoppedBy: NodeJS.Signals | undefined;\n private seeded = false;\n private compilerWritten = false;\n private restored = false;\n private redirected: readonly string[] = [];\n private readonly cleanedEntries: readonly string[];\n private readonly linkCleanedEntries: boolean;\n\n private constructor(fields: {\n runId: string;\n packageRoot: string;\n output: string;\n writesPackageDist: boolean;\n cleanedEntries: readonly string[];\n linkCleanedEntries: boolean;\n runDir: string;\n lock: BuildLock;\n journal: RunJournal;\n }) {\n this.runId = fields.runId;\n this.packageRoot = fields.packageRoot;\n this.output = fields.output;\n this.writesPackageDist = fields.writesPackageDist;\n this.cleanedEntries = fields.cleanedEntries;\n this.linkCleanedEntries = fields.linkCleanedEntries;\n this.runDir = fields.runDir;\n this.lock = fields.lock;\n this.journal = fields.journal;\n this.paths = runPaths(fields.packageRoot, fields.runDir, fields.journal);\n }\n\n /**\n * Starts a run under `lock`, which the caller took and recovered stale\n * runs under; the caller still releases it when this throws. The stage\n * sits beside `logical`, the output as given, so the paths the bundlers\n * record from it are the ones an unstaged build records.\n */\n static async open(options: {\n readonly packageRoot: string;\n readonly logical: string;\n readonly output: string;\n readonly writesPackageDist: boolean;\n /** Top-level entries of the output a step empties before it writes them. */\n readonly cleanedEntries: readonly string[];\n /** Seed those entries by hard link: no step writes them before that. */\n readonly linkCleanedEntries: boolean;\n readonly runId: string;\n readonly lock: BuildLock;\n }): Promise<StagedBuildSession> {\n const { packageRoot, logical, runId } = options;\n const runDir = join(packageRoot, RUNS_DIRECTORY, runId);\n try {\n const beside = (kind: string) => scratchBeside(logical, kind, runId);\n const journal: RunJournal = {\n format: 1,\n runId,\n pid: process.pid,\n state: \"building\",\n undo: null,\n output: toJournalPath(packageRoot, logical),\n stage: toJournalPath(packageRoot, beside(\"stage\")),\n retired: toJournalPath(packageRoot, beside(\"old\")),\n compiler: null,\n };\n await creating(BUILD_DIRECTORY, () => {\n mkdirSync(runDir, { recursive: true });\n writeJournal(runDir, journal);\n });\n await creating(shownPath(packageRoot, dirname(logical)), () =>\n mkdirSync(beside(\"stage\"), { recursive: true }),\n );\n return new StagedBuildSession({ ...options, runDir, journal });\n } catch (error) {\n removeTree(runDir);\n throw error;\n }\n }\n\n private assertOpen(): void {\n if (this.status !== \"open\") {\n throw new Error(\"The build was stopped before it finished.\");\n }\n }\n\n private record(\n changes: Partial<\n Pick<\n RunJournal,\n | \"state\"\n | \"compiler\"\n | \"generatedConfig\"\n | \"pendingBuildInfo\"\n | \"outputDigest\"\n >\n >,\n ) {\n this.journal = { ...this.journal, ...changes };\n writeJournal(this.runDir, this.journal);\n }\n\n private setState(state: JournalState): void {\n this.record({ state });\n }\n\n /**\n * Compiler outputs strictly inside the output directory, relative to it:\n * tsc rewrote them in the real output, so the stage leaves them out when\n * it is seeded and takes them fresh at commit. A protected directory that\n * is the output or holds it is not one: it holds the bundles too.\n */\n private compilerOutputsInOutput(): string[] {\n // Compared by real path: tsc's outputs are recorded that way.\n return (this.journal.compiler ?? []).flatMap(({ path }) => {\n const rel = pathWithin(\n this.output,\n fromJournalPath(this.packageRoot, path),\n );\n return rel ? [rel] : [];\n });\n }\n\n /**\n * The stage directory every output write targets. The first call seeds it\n * with the current output, minus what tsc writes afresh. With\n * `linkCleanedEntries`, the entries a step cleans are seeded by hard link,\n * since it unlinks their files before it writes and says so in the same\n * words as on the output; the rest, and otherwise everything, by clone.\n */\n stage(): string {\n this.assertOpen();\n const { stage, output } = this.paths;\n if (this.seeded) return stage;\n removeTree(stage);\n if (exists(output)) {\n const skipped = new Set(\n this.compilerWritten\n ? []\n : this.compilerOutputsInOutput().map((rel) => join(output, rel)),\n );\n const keep = (source: string) => !skipped.has(source);\n // tsc rewrites files in place, so what it writes into is copied.\n const linked = (this.linkCleanedEntries ? this.cleanedEntries : [])\n .filter((entry) => {\n const real = join(this.output, entry);\n return !this.redirected.some(\n (path) => isOrHolds(real, path) || isOrHolds(path, real),\n );\n })\n .map((entry) => join(output, entry))\n .filter(\n (dir) =>\n keep(dir) &&\n lstatSync(dir, { throwIfNoEntry: false })?.isDirectory(),\n );\n cloneTree(\n output,\n stage,\n (source) => keep(source) && !linked.includes(source),\n );\n for (const dir of linked) {\n linkTree(dir, join(stage, basename(dir)), keep);\n }\n } else {\n mkdirSync(stage);\n }\n this.seeded = true;\n return stage;\n }\n\n async prepareCompiler(compiler: CompilerRun): Promise<string | undefined> {\n this.assertOpen();\n const redirect = redirectRootProject(compiler.config, {\n configFile: compiler.configFile,\n packageRoot: this.packageRoot,\n output: this.output,\n stage: this.paths.stage,\n pending: (target) => scratchBeside(target, \"stage\", this.runId),\n });\n let config: string | undefined;\n let staged: readonly string[] = [];\n if (redirect) {\n config = await this.writeCompilerConfig(compiler.configFile, redirect);\n if (config) staged = redirect.staged;\n }\n const real = (path: string) => realPathThroughExistingParent(path);\n this.protectCompilerOutputs(\n compiler.outputs.filter(\n ({ path }) => !staged.some((dir) => isOrHolds(dir, real(path))),\n ),\n );\n if (!config) return undefined;\n this.redirected = staged;\n this.stage();\n return config;\n }\n\n /**\n * Writes the config that sends the root project's outputs into the stage,\n * beside the package's so `${configDir}` and its relative paths mean the\n * same, with the package config's modification time so tsc finds the\n * project up to date when it would. The pending build info starts as a\n * copy of the real one. Undefined when the package does not let the run\n * write them: tsc then writes in place.\n */\n private async writeCompilerConfig(\n configFile: string,\n redirect: CompilerRedirect,\n ): Promise<string | undefined> {\n const generated = join(\n dirname(configFile),\n `.${basename(configFile, extname(configFile))}.ph-stage-${this.runId}.json`,\n );\n const pending = redirect.pendingBuildInfo;\n const recorded = (path: string) => toJournalPath(this.packageRoot, path);\n this.record({\n generatedConfig: recorded(generated),\n ...(pending && {\n pendingBuildInfo: {\n path: recorded(pending.path),\n target: recorded(pending.target),\n },\n }),\n });\n try {\n await creating(shownPath(this.packageRoot, dirname(configFile)), () => {\n writeFileSync(\n generated,\n `${JSON.stringify(\n {\n extends: `./${basename(configFile)}`,\n compilerOptions: redirect.compilerOptions,\n ...(redirect.exclude && { exclude: redirect.exclude }),\n },\n null,\n 2,\n )}\\n`,\n );\n const { atime, mtime } = statSync(configFile);\n utimesSync(generated, atime, mtime);\n if (pending && exists(pending.target)) {\n cloneTree(pending.target, pending.path);\n }\n });\n return generated;\n } catch (error) {\n if (!(error instanceof CannotStage)) throw error;\n removeTree(generated);\n if (pending) removeTree(pending.path);\n this.record({ generatedConfig: undefined, pendingBuildInfo: undefined });\n return undefined;\n }\n }\n\n /**\n * Copies what tsc is about to rewrite into the run, or notes it absent, so\n * a build that does not finish puts it back. Call before tsc runs. An\n * output that is or holds `.ph/build` or this run, by real path, is left\n * unprotected, as without staging: a copy of it would copy itself. So is\n * one holding something a copy cannot take: a FIFO, socket or device, or\n * an entry this process cannot read. The copy's directories are made\n * owner-writable, so the run can always be removed; the journal keeps\n * their modes for a restore.\n */\n private protectCompilerOutputs(outputs: readonly CompilerOutput[]): void {\n const real = (path: string) => realPathThroughExistingParent(path);\n const control = [\n real(join(this.packageRoot, BUILD_DIRECTORY)),\n real(this.runDir),\n ];\n const snapshots: CompilerSnapshot[] = [...(this.journal.compiler ?? [])];\n for (const { path, kind } of outputs) {\n const target = real(path);\n if (control.some((dir) => isOrHolds(target, dir))) continue;\n const recorded = toJournalPath(this.packageRoot, target);\n if (snapshots.some((snapshot) => snapshot.path === recorded)) continue;\n if (exists(target)) {\n const copy = `compiler/${snapshots.length}`;\n const output = basename(this.paths.output);\n const snapshot = join(this.runDir, copy);\n const keep = (source: string) => !isScratchOf(output, basename(source));\n // Left unprotected, as without staging.\n if (unstageableEntryIn(target, keep) !== undefined) continue;\n try {\n cloneTree(target, snapshot, keep);\n } catch (error) {\n if (!isUnreadable(error)) throw error;\n removeTree(snapshot);\n continue;\n }\n const modes = openDirectories(snapshot);\n snapshots.push({\n path: recorded,\n kind,\n copy,\n created: null,\n ...(modes.length > 0 && { modes }),\n });\n } else {\n const missing = outermostMissing(this.packageRoot, target);\n const created =\n missing === target ? null : toJournalPath(this.packageRoot, missing);\n snapshots.push({ path: recorded, kind, copy: null, created });\n }\n }\n const digest =\n snapshots.length > 0\n ? outputDigest(this.packageRoot, this.paths.output, snapshots)\n : undefined;\n this.record({\n compiler: snapshots,\n ...(digest !== undefined && { outputDigest: digest }),\n });\n }\n\n /**\n * tsc wrote into the real output directory; the stage takes its fresh\n * files now, before any bundle step, so a step that cleans or rewrites an\n * entry treats them as it would in the output.\n */\n compilerOutputsWritten(): void {\n this.assertOpen();\n this.compilerWritten = true;\n const generated = this.journal.generatedConfig;\n if (generated) removeTree(fromJournalPath(this.packageRoot, generated));\n if (this.seeded) this.carryOverCompilerOutputs(this.paths.stage);\n }\n\n private carryOverCompilerOutputs(stage: string): void {\n for (const rel of this.compilerOutputsInOutput()) {\n const target = join(stage, rel);\n removeTree(target);\n const source = join(this.paths.output, rel);\n if (exists(source)) {\n mkdirSync(dirname(target), { recursive: true });\n cloneTree(source, target);\n }\n }\n }\n\n private warnNotAtomic(): void {\n const shown = toJournalPath(this.packageRoot, this.paths.output);\n console.warn(\n `⚠ Another process holds files in ${shown}, so ${shown} was replaced entry by entry instead of in one rename; while that ran, it held parts of both builds.`,\n );\n }\n\n /**\n * Replaces the output with the stage: the output moves aside, the stage\n * takes its place, the old tree goes. The journal records each move first.\n * Synchronous, so no signal handler runs in between. The lock stays held\n * until `close`.\n */\n commit(): void {\n const stage = this.stage();\n const { output, retired } = this.paths;\n try {\n this.setState(\"retiring\");\n let entryByEntry = false;\n if (exists(output)) {\n try {\n renamePatiently(output, retired);\n } catch (error) {\n if (!isHeldOpen(error)) throw error;\n entryByEntry = true;\n mkdirSync(retired);\n moveEntries(output, retired);\n }\n }\n this.setState(\"installing\");\n if (exists(output)) {\n moveEntries(stage, output);\n removeTree(stage);\n } else {\n try {\n renamePatiently(stage, output);\n } catch (error) {\n if (!isHeldOpen(error)) throw error;\n entryByEntry = true;\n mkdirSync(output);\n moveEntries(stage, output);\n removeTree(stage);\n }\n }\n installBuildInfo(this.packageRoot, this.journal.pendingBuildInfo);\n this.status = \"committed\";\n if (entryByEntry) this.warnNotAtomic();\n } catch (error) {\n this.rollback();\n throw error;\n }\n try {\n this.setState(\"committed\");\n removeTree(retired);\n removeTree(this.runDir);\n } catch (error) {\n console.warn(\n `⚠ The build finished, but its scratch files were not all removed (${error instanceof Error ? error.message : String(error)}); the next build removes them.`,\n );\n }\n }\n\n /**\n * Releases the lock a commit keeps, so steps that read the committed\n * output finish before another build replaces it, and drops the run a\n * rollback restored from. Idempotent.\n */\n close(): void {\n try {\n if (this.status === \"rolled-back\" && this.restored) {\n removeTree(this.runDir);\n }\n } finally {\n this.lock.release();\n }\n }\n\n releaseLock(): void {\n this.lock.release();\n }\n\n /**\n * Puts the previous output and compiler outputs back. Synchronous, so a\n * signal handler can call it; a no-op after commit. The run and its\n * snapshot stay until `close`, so a call after a step still running at\n * the first one settles restores again, undoing what that step wrote\n * since. A restore that failed is left to the next build. The lock stays\n * held until `close`.\n */\n rollback(): void {\n if (this.status === \"committed\") return;\n if (this.status === \"rolled-back\" && !this.restored) return;\n this.status = \"rolled-back\";\n try {\n rollBack(this.paths, this.journal);\n this.journal = { ...this.journal, state: \"rolling-back\", undo: \"stage\" };\n this.restored = true;\n } catch (error) {\n this.restored = false;\n console.error(\n `✘ The previous output could not be restored (${error instanceof Error ? error.message : String(error)}); the next build restores it.`,\n );\n }\n }\n\n private readonly stops = new Set<() => void>();\n\n cancel(signal: NodeJS.Signals): void {\n this.stoppedBy ??= signal;\n for (const stop of [...this.stops]) stop();\n }\n\n onCancel(stop: () => void): () => void {\n this.stops.add(stop);\n return () => this.stops.delete(stop);\n }\n\n /** The signal `cancel` was called with, if it was. */\n stopped(): NodeJS.Signals | undefined {\n return this.stoppedBy;\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport { lstatSync, readdirSync, readlinkSync, statSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport { CannotStage, creating, unstageableEntryIn } from \"./files.js\";\nimport { BUILD_DIRECTORY, LOCK_FILE } from \"../../build-control.js\";\nimport { RUNS_DIRECTORY } from \"./journal.js\";\nimport { acquireBuildLock, type BuildLock } from \"./lock.js\";\nimport { recoverStaleRuns } from \"./recovery.js\";\nimport {\n type BuildSession,\n scratchBeside,\n shownPath,\n StagedBuildSession,\n} from \"./session.js\";\n\n/**\n * The first symlink among the output and its parents inside the package:\n * a stage beside its target would change the paths the bundlers record.\n */\nfunction symlinkOnPath(\n packageRoot: string,\n output: string,\n): string | undefined {\n const root = realPathThroughExistingParent(packageRoot);\n for (let dir = output; ; dir = dirname(dir)) {\n if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {\n return dir;\n }\n const parent = realPathThroughExistingParent(dirname(dir));\n if (parent === root || pathWithin(root, parent) === null) return;\n }\n}\n\n/**\n * The output is a mount point, or otherwise on another filesystem than the\n * directory beside it: the stage's rename cannot replace it.\n */\nfunction onAnotherFilesystem(output: string): boolean {\n const dev = statSync(output, { throwIfNoEntry: false })?.dev;\n return dev !== undefined && dev !== statSync(dirname(output)).dev;\n}\n\nfunction linkIntoOutput(\n logical: string,\n output: string,\n stage: string,\n): string | undefined {\n const visit = (dir: string): string | undefined => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n const found = visit(path);\n if (found) return found;\n continue;\n }\n if (!entry.isSymbolicLink()) continue;\n const target = readlinkSync(path);\n const copied = isAbsolute(target)\n ? target\n : resolve(stage, relative(logical, dirname(path)), target);\n if (pathWithin(logical, copied) !== null) return path;\n if (pathWithin(output, copied) !== null) return path;\n }\n return undefined;\n };\n return lstatSync(logical, { throwIfNoEntry: false })?.isDirectory()\n ? visit(logical)\n : undefined;\n}\n\n/**\n * Writes the output in place, as builds did before staging: no stage or\n * snapshot, and nothing to commit or roll back. It holds the package's lock\n * until `close` when `.ph/build` can hold one. A stop signal does not stop\n * it, as it did not stop an unstaged build.\n */\nclass InPlaceSession implements BuildSession {\n constructor(\n readonly output: string,\n private readonly logical: string,\n readonly writesPackageDist: boolean,\n private readonly lock: BuildLock | undefined,\n ) {}\n stage(): string {\n return this.logical;\n }\n prepareCompiler(): Promise<undefined> {\n return Promise.resolve(undefined);\n }\n compilerOutputsWritten(): void {}\n commit(): void {}\n close(): void {\n this.lock?.release();\n }\n releaseLock(): void {\n this.lock?.release();\n }\n rollback(): void {}\n private readonly stops = new Set<() => void>();\n cancel(): void {\n for (const stop of [...this.stops]) stop();\n }\n stopped(): undefined {\n return undefined;\n }\n onCancel(stop: () => void): () => void {\n this.stops.add(stop);\n return () => this.stops.delete(stop);\n }\n}\n\nfunction newRunId(): string {\n return `${Date.now().toString(36)}-${process.pid}-${randomBytes(3).toString(\"hex\")}`;\n}\n\n/**\n * Takes the package's lock and finishes what dead builds left, then opens a\n * staged session, or an in-place one when staging cannot run as an unstaged\n * build would: the output or a directory on its path in the package is a\n * symlink, the output is on another filesystem than its parent, it holds an\n * entry a copy cannot take (a FIFO, socket or device, or one this process\n * cannot read) or a symlink into itself, it holds `.ph/build`, whose lock and\n * journal a swap would move away, or the stage beside it cannot be written.\n * Only when `.ph/build` cannot hold the lock does the build run without one,\n * as builds did before staging. One warning says why a build writes in place.\n */\nexport async function openBuildSession(options: {\n readonly packageRoot: string;\n readonly outDir: string;\n /** Top-level entries of the output a step empties before it writes them. */\n readonly cleanedEntries: readonly string[];\n /** Seed those entries by hard link: no step writes them before that. */\n readonly linkCleanedEntries: boolean;\n}): Promise<BuildSession> {\n const { packageRoot, outDir, cleanedEntries, linkCleanedEntries } = options;\n const logical = resolve(packageRoot, outDir);\n const output = realPathThroughExistingParent(logical);\n const writesPackageDist =\n output === realPathThroughExistingParent(join(packageRoot, \"dist\"));\n const shown = (path: string) => shownPath(packageRoot, path);\n const inPlace = (reason: string, lock: BuildLock | undefined) => {\n console.warn(\n `⚠ ${reason}, so this build writes ${shown(logical)} in place: if it does not finish, ${shown(logical)} can be left part old, part new.`,\n );\n return new InPlaceSession(output, logical, writesPackageDist, lock);\n };\n const runId = newRunId();\n let lock: BuildLock;\n try {\n lock = await creating(BUILD_DIRECTORY, () =>\n acquireBuildLock(join(packageRoot, LOCK_FILE), runId, (wait) =>\n console.log(\n `Another build of this package holds ${shown(wait.file)} (${wait.owner}); waiting for it to finish... If that build is gone, delete ${shown(wait.file)}.`,\n ),\n ),\n );\n } catch (error) {\n if (!(error instanceof CannotStage)) throw error;\n return inPlace(error.message, undefined);\n }\n try {\n recoverStaleRuns(packageRoot, logical);\n const link = symlinkOnPath(packageRoot, logical);\n if (link !== undefined) {\n return inPlace(`${shown(link)} is a symbolic link`, lock);\n }\n if (onAnotherFilesystem(logical)) {\n return inPlace(\n `${shown(logical)} is on another filesystem than the directory that holds it`,\n lock,\n );\n }\n const unstageable = unstageableEntryIn(logical);\n if (unstageable !== undefined) {\n return inPlace(`${shown(unstageable.path)} ${unstageable.reason}`, lock);\n }\n const intoOutput = linkIntoOutput(\n logical,\n output,\n scratchBeside(logical, \"stage\", runId),\n );\n if (intoOutput !== undefined) {\n return inPlace(\n `${shown(intoOutput)} is a symbolic link into ${shown(logical)}`,\n lock,\n );\n }\n const control = [BUILD_DIRECTORY, join(RUNS_DIRECTORY, runId)].find(\n (dir) =>\n pathWithin(\n output,\n realPathThroughExistingParent(join(packageRoot, dir)),\n ) !== null,\n );\n if (control !== undefined) {\n return inPlace(`${shown(logical)} holds ${control}`, lock);\n }\n try {\n return await StagedBuildSession.open({\n packageRoot,\n logical,\n output,\n writesPackageDist,\n cleanedEntries,\n linkCleanedEntries,\n runId,\n lock,\n });\n } catch (error) {\n if (!(error instanceof CannotStage)) throw error;\n return inPlace(error.message, lock);\n }\n } catch (error) {\n lock.release();\n throw error;\n }\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// The manifest with `connectRoutes` set when the package offers routes; as it\n// is, byte for byte, when the flag is already right.\nfunction withOfferedRoutes(json: string, offers: boolean) {\n const manifest = JSON.parse(json) as { connectRoutes?: boolean };\n if (offers ? manifest.connectRoutes === true : !(\"connectRoutes\" in manifest))\n return json;\n if (offers) manifest.connectRoutes = true;\n else delete manifest.connectRoutes;\n return `${JSON.stringify(manifest, null, 2)}\\n`;\n}\n\nconst slashes = (path: string) => path.replaceAll(\"\\\\\", \"/\");\n\n/** Sets `connectRoutes` in the manifest the package's root module imports,\n * leaving the project's file as it is. */\nexport function offeredRoutesManifest(projectRoot: string, offers: boolean) {\n // Vite's ids use forward slashes on Windows too.\n const manifestPath = slashes(join(projectRoot, \"powerhouse.manifest.json\"));\n return {\n name: \"ph-offered-routes-manifest\",\n transform(code: string, id: string) {\n if (slashes(id) !== manifestPath) return null;\n return { code: withOfferedRoutes(code, offers), map: null };\n },\n };\n}\n\n/** Sets `connectRoutes` in the dist copy of the manifest. */\nexport function markOfferedRoutes(dir: string, offers: boolean) {\n const manifestPath = join(dir, \"powerhouse.manifest.json\");\n if (!existsSync(manifestPath)) return;\n const json = readFileSync(manifestPath, \"utf-8\");\n writeFileSync(manifestPath, withOfferedRoutes(json, offers));\n}\n","import { relative, resolve, sep } from \"node:path\";\nimport { globalLogger, type Logger } from \"tsdown\";\nimport type { BuildContext } from \"./context.js\";\n\n/**\n * tsdown labels each file it writes with its directory, relative to the\n * package. Bundles written to the stage keep the labels of the output\n * directory they stand in for, so the log reads as without staging.\n */\nexport function stageLogger({\n projectRoot,\n outDir,\n session,\n}: BuildContext): Logger {\n const shown = `${relative(projectRoot, resolve(projectRoot, outDir))}${sep}`;\n const written = `${relative(projectRoot, session.stage())}${sep}`;\n const label = (message: unknown) =>\n typeof message === \"string\" ? message.replaceAll(written, shown) : message;\n const relabel =\n (log: (...messages: unknown[]) => void) =>\n (...messages: unknown[]) =>\n log(...messages.map(label));\n return {\n get level() {\n return globalLogger.level;\n },\n set level(level) {\n globalLogger.level = level;\n },\n info: relabel((...m) => globalLogger.info(...m)),\n warn: relabel((...m) => globalLogger.warn(...m)),\n warnOnce: relabel((...m) => globalLogger.warnOnce(...m)),\n error: relabel((...m) => globalLogger.error(...m)),\n success: relabel((...m) => globalLogger.success(...m)),\n clearScreen: (type) => globalLogger.clearScreen(type),\n };\n}\n","import {\n browserEntry,\n buildBrowserBuildConfig,\n buildNodeBuildConfig,\n findBundledSharedDeps,\n} from \"@powerhousedao/shared/build-config\";\nimport type { ExternalDependency } from \"@powerhousedao/shared/build-pieces\";\nimport {\n expandEntryGlobs,\n externalDepsPlugin,\n projectPath,\n undeclaredExternalDependencies,\n} from \"@powerhousedao/shared/build-pieces\";\nimport {\n EXTERNALIZABLE_SHARED_SPECIFIERS,\n findSharedImports,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport { noConnectImports } from \"../../../utils/offered-routes-imports.js\";\nimport { offeredRoutesManifest } from \"../../../utils/offered-routes-manifest.js\";\nimport {\n HOST_ROUTES_DIR,\n OFFERED_ROUTES_MODULE,\n} from \"../../../utils/sync-connect-routes.js\";\nimport type { StandardBuildStep } from \"./context.js\";\nimport { stageLogger } from \"./stage-logger.js\";\n\n/**\n * Every shared specifier imported from the entry sources; the post-build\n * scan compares these against the built output.\n *\n * Scoped to the specifiers the build actually externalizes: a specifier the\n * vendor does not publish (the bare `@powerhousedao/shared` root, an\n * unvendored subpath) is deliberately bundled, so reporting it as \"bundled\n * instead of externalized\" would be a false alarm.\n */\nfunction findSharedImportsInSources(root: string, globs: string[]): string[] {\n const found = new Set<string>();\n for (const file of expandEntryGlobs(root, globs)) {\n const src = readFileSync(file, \"utf8\");\n for (const spec of findSharedImports(\n src,\n EXTERNALIZABLE_SHARED_SPECIFIERS,\n )) {\n found.add(spec);\n }\n }\n return [...found].sort();\n}\n\n/**\n * The built JS outputs of a browser build (entry files and chunks).\n */\nfunction readDistBrowserFiles(\n dir: string,\n): { path: string; content: string }[] {\n const out: { path: string; content: string }[] = [];\n if (!existsSync(dir)) return out;\n const walk = (d: string) => {\n for (const e of readdirSync(d, { withFileTypes: true })) {\n const p = join(d, e.name);\n if (e.isDirectory()) walk(p);\n else if (e.isFile() && e.name.endsWith(\".js\")) {\n out.push({ path: p, content: readFileSync(p, \"utf8\") });\n }\n }\n };\n walk(dir);\n return out;\n}\n\n// Everything in the browser build is code Connect can load: native fails it.\nexport const browserBundleStep: StandardBuildStep = {\n id: \"browser-bundle\",\n run: async (ctx) => {\n const { args, projectRoot, session, trace, detection, findings } = ctx;\n const stage = session.stage();\n const sharedDeps = !args.noSharedDeps;\n const routesEntry = join(projectRoot, OFFERED_ROUTES_MODULE);\n const config = buildBrowserBuildConfig({\n sharedDeps,\n plugins: [\n externalDepsPlugin(trace, new Map(), {\n root: projectRoot,\n browser: true,\n cache: detection,\n }),\n offeredRoutesManifest(projectRoot, findings.offersRoutes),\n noConnectImports(routesEntry, join(projectRoot, HOST_ROUTES_DIR)),\n ],\n });\n await tsdownBuild({\n ...config,\n // The manifest copy lands in the stage when it stands in for dist/.\n ...(session.writesPackageDist && {\n copy: [{ from: \"powerhouse.manifest.json\", to: stage }],\n }),\n // The offered routes in the package's build: a module both import is one\n // chunk, which other Connects evaluate once. Absolute: a relative entry\n // is a glob, and globs skip `.ph`.\n ...(findings.offersRoutes\n ? { entry: [...browserEntry, { \"connect-routes\": routesEntry }] }\n : {}),\n outDir: join(stage, \"browser\"),\n customLogger: stageLogger(ctx),\n });\n\n // Advisory: a shared dep the source imports but the output no longer\n // references as a bare import was inlined despite the external set.\n if (sharedDeps) {\n const imported = findSharedImportsInSources(projectRoot, browserEntry);\n const bundled = findBundledSharedDeps(\n imported,\n readDistBrowserFiles(join(stage, \"browser\")),\n );\n if (bundled.length > 0) {\n console.warn(\n `⚠ shared deps bundled instead of externalized: ${bundled.join(\", \")} — check your neverBundle config`,\n );\n }\n }\n },\n};\n\n// A package with a native addon or WebAssembly module stays external, so the\n// package's consumers must install it: devDependencies are skipped by every install.\nexport function assertExternalDependenciesDeclared(\n projectRoot: string,\n found: ExternalDependency[],\n pkg: Parameters<typeof undeclaredExternalDependencies>[1],\n) {\n for (const dep of found) {\n console.log(\n `${dep.name}@${dep.version} stays external, it needs ${projectPath(projectRoot, dep.file)}`,\n );\n }\n const undeclared = undeclaredExternalDependencies(found, pkg);\n if (undeclared.length === 0) return;\n const lines = undeclared.map(\n (dep) =>\n ` ${dep.name}${dep.importer ? ` (imported by ${projectPath(projectRoot, dep.importer)})` : \"\"}`,\n );\n throw new Error(\n `Packages with native addons or WebAssembly modules must be listed in package.json \"dependencies\", \"optionalDependencies\" or \"peerDependencies\":\\n` +\n `${lines.join(\"\\n\")}\\n\\n` +\n `They stay external to the build, and installs of this package skip devDependencies.`,\n );\n}\n\nexport const nodeBundleStep: StandardBuildStep = {\n id: \"node-bundle\",\n run: async (ctx) => {\n const { args, projectRoot, session, trace, detection, findings } = ctx;\n await tsdownBuild({\n ...buildNodeBuildConfig({\n sharedDeps: !args.noSharedDeps,\n plugins: [\n // Editors never run on a host; document models and scalars run in Connect too.\n externalDepsPlugin(trace, findings.external, {\n root: projectRoot,\n ignoreDirs: [\"editors\"],\n forbidDirs: [\"document-models\", \"scalars\"],\n cache: detection,\n }),\n ],\n }),\n outDir: join(session.stage(), \"node\"),\n customLogger: stageLogger(ctx),\n });\n findings.pkg = await readPackage({ cwd: projectRoot });\n assertExternalDependenciesDeclared(\n projectRoot,\n [...findings.external.values()],\n findings.pkg,\n );\n },\n};\n\n/** The output entry each bundle step writes, which tsdown empties first. */\nconst CLEANED_BY_STEP = new Map([\n [browserBundleStep.id, \"browser\"],\n [nodeBundleStep.id, \"node\"],\n]);\n\n/** The output entries `steps` empty before they write them, by step id. */\nexport const entriesCleanedBy = (\n steps: readonly { readonly id: string }[],\n): string[] => steps.flatMap(({ id }) => CLEANED_BY_STEP.get(id) ?? []);\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n OFFERED_ROUTES_MODULE,\n syncProjectConnectRoutes,\n} from \"../../../utils/sync-connect-routes.js\";\nimport type { StandardBuildStep } from \"./context.js\";\n\nexport const connectRoutesStep: StandardBuildStep = {\n id: \"connect-routes\",\n run: async ({ projectRoot, findings }) => {\n // Project routes type-check against the tree generated from them.\n await syncProjectConnectRoutes(projectRoot);\n // Connect reads the manifest's flag to load the package's routes.\n findings.offersRoutes = existsSync(\n join(projectRoot, OFFERED_ROUTES_MODULE),\n );\n },\n};\n","import type { DefinitionCheckReport } from \"@powerhousedao/shared/document-model\";\nimport { fork } from \"node:child_process\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport type {\n DefinitionsProfile,\n DefinitionsReply,\n} from \"../../model/definitions-worker.js\";\nimport type { BuildSession } from \"../staging/session.js\";\nimport { BuildRefusal } from \"../pipeline/steps.js\";\nimport type { StandardBuildStep } from \"./context.js\";\n\n/**\n * The built worker beside ph-cli's own code. Run from source (under vitest),\n * the TypeScript worker through tsx, so a test runs the current source.\n */\nfunction definitionsWorker(): { path: string; execArgv: string[] } {\n const root = dirname(\n createRequire(import.meta.url).resolve(\n \"@powerhousedao/ph-cli/package.json\",\n ),\n );\n if (!import.meta.url.endsWith(\".ts\")) {\n return { path: join(root, \"dist\", \"definitions-worker.mjs\"), execArgv: [] };\n }\n return {\n path: join(root, \"src\", \"services\", \"model\", \"definitions-worker.ts\"),\n execArgv: [\"--import\", import.meta.resolve(\"tsx\")],\n };\n}\n\n/**\n * Runs the definition check in a child process: the package's own modules\n * can exit, hang or start timers there without reaching the build. A child\n * that ends without a reply, outlives `timeoutMs` or outlives a stop of the\n * build is killed, and the reply says why the check could not run.\n */\nexport function checkInChild<P extends DefinitionsProfile>(\n projectRoot: string,\n profile: P,\n session: BuildSession,\n timeoutMs: number,\n): Promise<DefinitionsReply<P>> {\n const worker = definitionsWorker();\n return new Promise((resolve) => {\n let reply: DefinitionsReply<P> | undefined;\n let killedFor: string | undefined;\n // The package's modules print to the build's stderr, as under `ph model`.\n const child = fork(worker.path, [projectRoot, profile], {\n cwd: projectRoot,\n execArgv: worker.execArgv,\n stdio: [\"ignore\", 2, 2, \"ipc\"],\n });\n const kill = (why: string) => {\n killedFor ??= why;\n child.kill(\"SIGKILL\");\n };\n const timer = setTimeout(\n () => kill(`the check did not finish within ${timeoutMs / 1000} seconds`),\n timeoutMs,\n );\n // Synchronous, inside the signal handler: a worker stuck in a loop\n // cannot notice its parent is gone, so it must die before the parent.\n const unwatch = session.onCancel(() => kill(\"the build was stopped\"));\n if (session.stopped()) kill(\"the build was stopped\");\n const settle = (settled: DefinitionsReply<P>) => {\n clearTimeout(timer);\n unwatch();\n resolve(settled);\n };\n child.on(\"message\", (message) => {\n reply ??= message as DefinitionsReply<P>;\n });\n child.on(\"error\", (error) => {\n kill(error.message);\n settle({ ok: false, message: error.message });\n });\n child.on(\"exit\", (code, signal) => {\n settle(\n reply ?? {\n ok: false,\n message:\n killedFor ??\n `the check ${signal ? `was stopped by ${signal}` : `exited with code ${code}`} before it reported`,\n },\n );\n });\n });\n}\n\n/**\n * Checks the package's definitions after tsc and before any bundle, when\n * `ph build` asks or with `--release`. Without `--release` it checks the\n * package when discovery finds a code-first model directory or cannot read\n * the models directory, never stops the build, and skips without a word a\n * package with no code-first model. With `--release`\n * (experimental) it runs the release profile over every model, stored ones\n * included, and stops the build when the check is invalid or cannot run, a\n * configuration error included. The package's modules load only in the\n * definitions worker, which has `timeoutMs` to report.\n */\nexport function definitionsStepWithin(timeoutMs: number): StandardBuildStep {\n return {\n id: \"definitions\",\n after: [\"typecheck\"],\n run: async ({ args, checkDefinitions, projectRoot, session, findings }) => {\n if (!args.release && !checkDefinitions) return;\n if (!args.release) {\n const { resolveDefinitionSelection } =\n await import(\"document-model/tooling\");\n const selection = resolveDefinitionSelection({\n configFile: join(projectRoot, \"powerhouse.config.json\"),\n allowMissingConfig: true,\n });\n if (selection.status === \"skipped\") return;\n }\n const { renderCheckReport } = await import(\"../../model/render.js\");\n const printReport = (report: DefinitionCheckReport) => {\n const text = renderCheckReport(report);\n if (report.diagnostics.length > 0) {\n console.warn(\n `⚠ The definition check reported problems; the build goes on:\\n${text}`,\n );\n } else {\n console.log(`✔ ${text}`);\n }\n };\n console.log(\"\\n▶ Checking document model definitions...\");\n if (!args.release) {\n const edit = await checkInChild(\n projectRoot,\n \"edit\",\n session,\n timeoutMs,\n );\n if (edit.ok) printReport(edit.result);\n else\n console.warn(`⚠ The definition check could not run: ${edit.message}`);\n return;\n }\n const release = await checkInChild(\n projectRoot,\n \"release\",\n session,\n timeoutMs,\n );\n if (!release.ok) {\n throw new BuildRefusal(\n `✘ The definition check could not run: ${release.message}`,\n );\n }\n const { status } = release.result.report;\n if (status === \"invalid\" || status === \"failed\") {\n throw new BuildRefusal(\n `✘ The release definition check stopped the build:\\n${renderCheckReport(release.result.report)}`,\n );\n }\n findings.release = release.result;\n printReport(release.result.report);\n },\n };\n}\n\nexport const definitionsStep = definitionsStepWithin(5 * 60_000);\n","import { assertPiecesOutDir } from \"@powerhousedao/shared/build-pieces\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport type { StandardBuildStep } from \"./context.js\";\n\n/**\n * A Powerhouse package's `powerhouse.manifest.json` \"name\" must match its\n * `package.json` \"name\" — Connect and the registry resolve installed versions\n * by treating the manifest name as the npm package name, so a mismatch silently\n * breaks resolution. Fail the build early if they diverge. No-op when the\n * project has no manifest (nothing to compare).\n */\nexport async function assertManifestNameMatchesPackage(projectPath: string) {\n const manifestPath = join(projectPath, \"powerhouse.manifest.json\");\n if (!existsSync(manifestPath)) return;\n\n const { name: packageName } = await readPackage({ cwd: projectPath });\n\n let manifestName: unknown;\n try {\n manifestName = (\n JSON.parse(readFileSync(manifestPath, \"utf-8\")) as { name?: unknown }\n ).name;\n } catch {\n throw new Error(\n `Failed to parse \"powerhouse.manifest.json\" at ${manifestPath}. Make sure it is valid JSON.`,\n );\n }\n\n if (manifestName !== packageName) {\n throw new Error(\n `Package name mismatch — \"package.json\" and \"powerhouse.manifest.json\" must have the same \"name\":\\n` +\n ` package.json \"name\": ${JSON.stringify(packageName)}\\n` +\n ` powerhouse.manifest.json \"name\": ${JSON.stringify(manifestName)}\\n\\n` +\n `Update one so they match, then run the build again.`,\n );\n }\n}\n\n// Fail fast if the manifest name and package.json name have drifted apart.\nexport const manifestNameStep: StandardBuildStep = {\n id: \"manifest-name\",\n run: ({ projectRoot }) => assertManifestNameMatchesPackage(projectRoot),\n};\n\n// Before any bundler runs: an out-dir a host will never read from is worth\n// nothing built, and the failure names what the contract is.\nexport const piecesOutDirStep: StandardBuildStep = {\n id: \"pieces-out-dir\",\n run: ({ outDir, pieces }) => {\n assertPiecesOutDir({ outDir, pieces: [...pieces] });\n return Promise.resolve();\n },\n};\n","import {\n buildPieces,\n externalDependencyVersions,\n pieceListPath,\n syncDistManifest,\n} from \"@powerhousedao/shared/build-pieces\";\nimport { existsSync } from \"node:fs\";\nimport { readPackage } from \"read-pkg\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport { markOfferedRoutes } from \"../../../utils/offered-routes-manifest.js\";\nimport type { StandardBuildStep } from \"./context.js\";\nimport { stageLogger } from \"./stage-logger.js\";\n\n// After the node build: it cleans <outDir>/node, where the pieces land. The\n// built list is the gate, so a `bundle:` entry is validated with no piece dir.\nexport const piecesStep: StandardBuildStep = {\n id: \"pieces\",\n run: async (ctx) => {\n const { projectRoot, outDir, pieces, session, trace, detection, findings } =\n ctx;\n const stage = session.stage();\n if (!existsSync(pieceListPath({ projectRoot, outDir: stage }))) return;\n const pkg = findings.pkg ?? (await readPackage({ cwd: projectRoot }));\n const customLogger = stageLogger(ctx);\n findings.built = await buildPieces(\n { projectRoot, outDir, writeTo: stage, pieces: [...pieces] },\n {\n name: pkg.name,\n version: pkg.version,\n license: typeof pkg.license === \"string\" ? pkg.license : undefined,\n },\n {\n bundle: (config) => tsdownBuild({ ...config, customLogger }),\n trace,\n cache: detection,\n },\n );\n },\n};\n\nexport const distManifestStep: StandardBuildStep = {\n id: \"dist-manifest\",\n run: ({ projectRoot, pieces, session, findings }) => {\n syncDistManifest(\n { projectRoot, outDir: session.stage(), pieces: [...pieces] },\n findings.built,\n externalDependencyVersions(findings.external.values()),\n );\n return Promise.resolve();\n },\n};\n\nexport const offeredRoutesStep: StandardBuildStep = {\n id: \"offered-routes\",\n run: ({ session, findings }) => {\n markOfferedRoutes(session.stage(), findings.offersRoutes);\n return Promise.resolve();\n },\n};\n","import { spawn } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n realpathSync,\n symlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport type { PackedManifest, PackedRelease } from \"./pack.js\";\n\ntype Consumer = \"node\" | \"browser\";\n\nconst CONDITIONS: Readonly<Record<Consumer, ReadonlySet<string>>> = {\n node: new Set([\"node\", \"import\", \"module-sync\", \"default\"]),\n browser: new Set([\"browser\", \"import\", \"module\", \"default\"]),\n};\n\nconst IMPORTABLE = /\\.(m?js|cjs)$/;\n\nfunction resolveTarget(\n value: unknown,\n conditions: ReadonlySet<string>,\n): string | undefined {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) {\n for (const item of value) {\n const target = resolveTarget(item, conditions);\n if (target !== undefined) return target;\n }\n return undefined;\n }\n if (value === null || typeof value !== \"object\") return undefined;\n for (const [key, nested] of Object.entries(value)) {\n if (!conditions.has(key)) continue;\n const target = resolveTarget(nested, conditions);\n if (target !== undefined) return target;\n }\n return undefined;\n}\n\nfunction targetsOf(value: unknown): string[] {\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value.flatMap(targetsOf);\n if (value === null || typeof value !== \"object\") return [];\n return Object.values(value).flatMap(targetsOf);\n}\n\nfunction subpaths(manifest: PackedManifest): [string, unknown][] {\n const { exports } = manifest;\n if (exports === undefined) return [];\n if (\n exports !== null &&\n typeof exports === \"object\" &&\n !Array.isArray(exports) &&\n Object.keys(exports).some((key) => key.startsWith(\".\"))\n ) {\n return Object.entries(exports);\n }\n return [[\".\", exports]];\n}\n\nconst packedPath = (target: string) => target.replace(/^\\.\\//, \"\");\n\nexport function packedEntries(\n manifest: PackedManifest,\n files: ReadonlySet<string>,\n unbuilt: ReadonlySet<string>,\n): {\n readonly imports: Record<Consumer, string[]>;\n readonly missing: string[];\n} {\n const imports: Record<Consumer, string[]> = { node: [], browser: [] };\n const missing: string[] = [];\n const entries = subpaths(manifest);\n if (entries.length === 0) {\n imports.node.push(manifest.name);\n return { imports, missing };\n }\n for (const [subpath, value] of entries) {\n const targets = targetsOf(value).filter((target) => !target.includes(\"*\"));\n const absent = targets.filter((target) => !files.has(packedPath(target)));\n if (unbuilt.has(subpath) && absent.length === targets.length) continue;\n missing.push(\n ...absent.map((target) => `exports[\"${subpath}\"] names ${target}`),\n );\n if (subpath === \"./package.json\") continue;\n for (const consumer of [\"node\", \"browser\"] as const) {\n const target = resolveTarget(value, CONDITIONS[consumer]);\n if (target === undefined || !IMPORTABLE.test(target)) continue;\n const specifier = `${manifest.name}${subpath.slice(1)}`;\n if (!subpath.includes(\"*\")) {\n imports[consumer].push(specifier);\n continue;\n }\n const [before, after] = packedPath(target).split(\"*\");\n const [subBefore, subAfter] = specifier.split(\"*\");\n for (const file of [...files].sort()) {\n if (!file.startsWith(before) || !file.endsWith(after)) continue;\n const star = file.slice(before.length, file.length - after.length);\n if (star !== \"\")\n imports[consumer].push(`${subBefore}${star}${subAfter}`);\n }\n }\n }\n return { imports, missing };\n}\n\nfunction installed(projectRoot: string, name: string): string | undefined {\n for (let directory = projectRoot; ; directory = dirname(directory)) {\n const candidate = join(directory, \"node_modules\", ...name.split(\"/\"));\n if (existsSync(join(candidate, \"package.json\"))) {\n return realpathSync.native(candidate);\n }\n if (dirname(directory) === directory) return undefined;\n }\n}\n\n// Imports each specifier, writes the failures to the result file, then\n// exits, so a module that keeps a handle open cannot hold the check. The\n// modules own stdout. With conditions given, every import, the package's own\n// dependencies' too, resolves under those instead of Node's.\nconst IMPORT_EACH = `import { writeFileSync } from \"node:fs\";\nimport { registerHooks } from \"node:module\";\nconst { specifiers, conditions, resultFile } = JSON.parse(process.argv[1]);\nif (conditions) {\n registerHooks({\n resolve: (specifier, context, next) => next(specifier, {\n ...context,\n conditions: context.conditions.includes(\"require\")\n ? conditions.map((name) => (name === \"import\" ? \"require\" : name))\n : conditions,\n }),\n });\n}\nconst failed = [];\nfor (const specifier of specifiers) {\n try { await import(specifier); }\n catch (error) { failed.push(specifier + \": \" + (error instanceof Error ? error.message : String(error)).split(\"\\\\n\")[0]); }\n}\nwriteFileSync(resultFile, JSON.stringify(failed));\nprocess.exit(0);\n`;\n\nconst TIMEOUT_MS = 120_000;\nconst STDERR_LIMIT = 64 * 1024;\n\nasync function importAll(\n consumerRoot: string,\n consumer: Consumer,\n specifiers: readonly string[],\n signal: AbortSignal | undefined,\n): Promise<string[]> {\n if (specifiers.length === 0) return [];\n const env = { ...process.env };\n delete env.NODE_OPTIONS;\n delete env.NODE_PATH;\n const resultFile = join(dirname(consumerRoot), `${consumer}-result.json`);\n const input = {\n specifiers,\n conditions: consumer === \"browser\" ? [...CONDITIONS.browser] : null,\n resultFile,\n };\n const ended = await new Promise<string>((done) => {\n const child = spawn(\n process.execPath,\n [\"--input-type=module\", \"-e\", IMPORT_EACH, JSON.stringify(input)],\n { cwd: consumerRoot, env, signal, stdio: [\"ignore\", \"ignore\", \"pipe\"] },\n );\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill();\n }, TIMEOUT_MS);\n let stderr = \"\";\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk: string) => {\n if (stderr.length < STDERR_LIMIT) stderr += chunk;\n });\n child.on(\"error\", (error) => done(error.message));\n child.on(\"close\", (code, killedBy) => {\n clearTimeout(timer);\n if (timedOut) {\n done(`did not finish its imports within ${TIMEOUT_MS / 1000} seconds`);\n return;\n }\n const how = killedBy === null ? `exited with ${code}` : `got ${killedBy}`;\n const why = stderr.trim().split(\"\\n\")[0];\n done(why ? `${how}: ${why}` : how);\n });\n });\n if (!existsSync(resultFile)) {\n return [`${consumer} consumer did not finish: it ${ended}`];\n }\n return (JSON.parse(readFileSync(resultFile, \"utf8\")) as string[]).map(\n (failure) =>\n `${consumer} consumer cannot import ${failure.replace(/ imported from \\S*\\[eval\\d*\\]$/, \"\")}`,\n );\n}\n\nexport async function checkPackedConsumer(\n projectRoot: string,\n packed: PackedRelease,\n unbuilt: ReadonlySet<string>,\n signal?: AbortSignal,\n): Promise<string[]> {\n const { manifest, files } = packed;\n const consumerRoot = join(packed.directory, \"consumer\");\n const modules = join(consumerRoot, \"node_modules\");\n const installRoot = join(modules, ...manifest.name.split(\"/\"));\n for (const [path, bytes] of files) {\n const target = resolve(installRoot, path);\n if (!target.startsWith(`${installRoot}${sep}`)) {\n return [`the tarball has an entry outside the package: ${path}`];\n }\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, bytes);\n }\n writeFileSync(\n join(consumerRoot, \"package.json\"),\n `${JSON.stringify({ name: \"ph-packed-consumer\", private: true, type: \"module\" })}\\n`,\n );\n const runtime = new Set([\n ...Object.keys(manifest.dependencies ?? {}),\n ...Object.keys(manifest.optionalDependencies ?? {}),\n ...Object.keys(manifest.peerDependencies ?? {}),\n ]);\n for (const name of runtime) {\n if (name === manifest.name) continue;\n const from = installed(projectRoot, name);\n if (from === undefined) continue;\n const link = join(modules, ...name.split(\"/\"));\n mkdirSync(dirname(link), { recursive: true });\n symlinkSync(from, link, process.platform === \"win32\" ? \"junction\" : \"dir\");\n }\n const { imports, missing } = packedEntries(\n manifest,\n new Set(files.keys()),\n unbuilt,\n );\n const failures = await Promise.all(\n ([\"node\", \"browser\"] as const).map((consumer) =>\n importAll(consumerRoot, consumer, imports[consumer], signal),\n ),\n );\n return [\n ...missing.map((entry) => `${entry}, which the package does not contain`),\n ...failures.flat(),\n ].map((failure) => {\n const shown = failure\n .replaceAll(`${consumerRoot}${sep}`, \"\")\n .replaceAll(consumerRoot, \".\");\n // The same refusal on every platform: paths as package specifiers spell them.\n return sep === \"\\\\\" ? shown.replaceAll(\"\\\\\", \"/\") : shown;\n });\n}\n","import { listed } from \"./approval.js\";\nimport { changedPaths, type FileDigest } from \"./revision.js\";\n\nconst under = (path: string, directory: string) =>\n path === directory || path.startsWith(`${directory}/`);\n\n/** What a release build learned that decides whether it may write an approval. Paths are POSIX, from the package root. */\nexport type ApprovalBuild<Release> = {\n readonly typesOk: boolean;\n /** The release profile's result, when it ran. */\n readonly release: Release | undefined;\n /** The package's files when the build started. */\n readonly startFiles: readonly FileDigest[] | undefined;\n /** The output directory as given, then the directory the build replaced when that is elsewhere in the package. */\n readonly outputs: readonly [string, ...string[]];\n /** What tsc writes. */\n readonly compilerOutputs: readonly string[];\n};\n\nexport type ApprovalPlan<Release> =\n | { readonly refused: string }\n | {\n readonly release: Release;\n readonly startFiles: readonly FileDigest[];\n /** What the revision leaves out besides the output directory: neither is a source. */\n readonly excluded: readonly string[];\n };\n\n/**\n * Whether a release build may write an approval, and what its revision\n * leaves out: the replaced directory, and what tsc writes outside the\n * output.\n */\nexport function planApproval<Release>(\n build: ApprovalBuild<Release>,\n): ApprovalPlan<Release> {\n const { release, startFiles, outputs } = build;\n if (!build.typesOk) {\n return { refused: \"the build went on despite tsc's type errors\" };\n }\n if (release === undefined || startFiles === undefined) {\n return { refused: \"the release check did not run\" };\n }\n const excluded = [\n ...outputs.slice(1),\n ...build.compilerOutputs.filter(\n (path) => !outputs.some((directory) => under(path, directory)),\n ),\n ];\n return { release, startFiles, excluded };\n}\n\n/**\n * Why the approval may not be written because the package changed while it\n * was built, comparing its files at the start, minus what the revision\n * leaves out, with `endFiles`; undefined when nothing changed.\n */\nexport function changedWhileBuilt(\n plan: {\n readonly startFiles: readonly FileDigest[];\n readonly excluded: readonly string[];\n },\n endFiles: readonly FileDigest[],\n): string | undefined {\n const leftOut = (path: string) =>\n plan.excluded.some((exclusion) => under(path, exclusion));\n const changed = changedPaths(\n plan.startFiles.filter(({ path }) => !leftOut(path)),\n endFiles,\n );\n return changed.length === 0\n ? undefined\n : `the package's files changed while it was built (${listed(changed)})`;\n}\n","import { existsSync } from \"node:fs\";\nimport { isAbsolute, join } from \"node:path\";\nimport { getVersion } from \"../../../get-version.js\";\nimport {\n listed,\n PH_CLI_BINDING,\n RELEASE_APPROVAL_PATH,\n} from \"../../release/approval.js\";\nimport { checkPackedConsumer } from \"../../release/consumer.js\";\nimport {\n packagePath,\n revisionFiles,\n writeReleaseApproval,\n} from \"../../release/files.js\";\nimport { changedWhileBuilt, planApproval } from \"../../release/issuance.js\";\nimport {\n packedDigests,\n packRelease,\n type PackedRelease,\n} from \"../../release/pack.js\";\nimport { type FileDigest, packageRevision } from \"../../release/revision.js\";\nimport { BuildRefusal } from \"../pipeline/steps.js\";\nimport type { BuildSession } from \"../staging/session.js\";\nimport type { BuildFindings, StandardBuildStep } from \"./context.js\";\n\nconst under = (path: string, directory: string) =>\n path === directory || path.startsWith(`${directory}/`);\n\n/**\n * The output directory as given, then the directory the build replaces when\n * that is a symlink to another place in the package: neither is a source.\n */\nfunction outputDirectories(\n projectRoot: string,\n outDir: string,\n target: string,\n): [string, ...string[]] {\n const output = packagePath(projectRoot, outDir);\n const real = packagePath(projectRoot, target);\n const inPackage =\n real !== \"..\" && !real.startsWith(\"../\") && !isAbsolute(real);\n return inPackage && !under(real, output) ? [output, real] : [output];\n}\n\n/** With `--release`, records the package's files before anything is built. */\nexport const releaseStartStep: StandardBuildStep = {\n id: \"release-start\",\n run: ({ args, projectRoot, outDir, session, findings }) => {\n if (args.release) {\n findings.releaseStart = revisionFiles(\n projectRoot,\n outputDirectories(projectRoot, outDir, session.output),\n );\n }\n return Promise.resolve();\n },\n};\n\n/** Exports `ph init` declares whose entry the build skips when its source is absent. */\nconst OPTIONAL_EXPORTS: Readonly<Record<string, string>> = {\n \"./scalars\": \"scalars/index.ts\",\n \"./pieces\": \"pieces/index.ts\",\n};\n\nconst unbuiltExports = (projectRoot: string, findings: BuildFindings) =>\n new Set([\n ...Object.entries(OPTIONAL_EXPORTS)\n .filter(([, source]) => !existsSync(join(projectRoot, source)))\n .map(([subpath]) => subpath),\n ...(findings.offersRoutes ? [] : [\"./connect-routes\"]),\n ]);\n\nconst notWritten = (why: string) =>\n new BuildRefusal(\n `✘ No release approval was written: ${why}. The new output is in place; build again with --release to approve it.`,\n );\n\n/**\n * With `--release`, once the output is replaced: records what the release\n * check approved and what `npm pack` publishes from the new output, unless\n * tsc's errors were accepted, the package changed while it was built, or the\n * packed tarball fails to install and import in a scratch consumer.\n */\nexport const releaseApprovalStep: StandardBuildStep = {\n id: \"release-approval\",\n when: \"committed\",\n run: async ({ args, projectRoot, outDir, session, findings }) => {\n if (args.release) {\n await recordApproval(\n projectRoot,\n outputDirectories(projectRoot, outDir, session.output),\n findings,\n session,\n );\n }\n },\n};\n\nasync function recordApproval(\n projectRoot: string,\n outputs: readonly [string, ...string[]],\n findings: BuildFindings,\n session: BuildSession,\n): Promise<void> {\n const plan = planApproval({\n typesOk: findings.typesOk,\n release: findings.release,\n startFiles: findings.releaseStart,\n outputs,\n compilerOutputs: findings.compilerOutputs.map((path) =>\n packagePath(projectRoot, path),\n ),\n });\n if (\"refused\" in plan) throw notWritten(plan.refused);\n const { release, excluded } = plan;\n const [output] = outputs;\n const files = revisionFiles(projectRoot, [output, ...excluded]);\n const changed = changedWhileBuilt(plan, files);\n if (changed !== undefined) throw notWritten(changed);\n let packed: PackedRelease;\n try {\n packed = packRelease(projectRoot);\n } catch (error) {\n throw notWritten(error instanceof Error ? error.message : String(error));\n }\n let published: FileDigest[];\n const stop = new AbortController();\n const unwatch = session.onCancel(() => {\n stop.abort();\n packed.dispose();\n });\n try {\n const failures = await checkPackedConsumer(\n projectRoot,\n packed,\n unbuiltExports(projectRoot, findings),\n stop.signal,\n );\n if (failures.length > 0) {\n throw notWritten(\n `the packed package does not install and import in a scratch consumer: ${listed(failures)}`,\n );\n }\n published = packedDigests(packed);\n } finally {\n unwatch();\n packed.dispose();\n }\n const phCliVersion = getVersion();\n writeReleaseApproval(projectRoot, {\n kind: \"powerhouse.release-approval\",\n formatVersion: 1,\n phCliVersion,\n outDir: output,\n packageRevision: {\n digest: packageRevision(files, { [PH_CLI_BINDING]: phCliVersion }),\n excluded,\n },\n publishedFiles: published,\n report: {\n profile: \"release\",\n status: release.report.status,\n definitions: release.report.definitions,\n },\n scalars: release.scalars,\n hostValidation: release.host,\n });\n console.log(`✔ Release approval written to ${RELEASE_APPROVAL_PATH}`);\n}\n","import {\n localPackageNames,\n packageStyleEntry,\n packageStylesheet,\n} from \"@powerhousedao/shared/clis/package-style\";\nimport { execSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join, relative, resolve } from \"node:path\";\nimport { resolveCommand } from \"package-manager-detector\";\nimport { BuildRefusal } from \"../pipeline/steps.js\";\nimport type { StandardBuildStep } from \"./context.js\";\n\n// A path for `@source`, relative to the project, with forward slashes.\nfunction sourcePath(projectRoot: string, path: string) {\n return `./${relative(projectRoot, resolve(projectRoot, path)).replaceAll(\"\\\\\", \"/\")}`;\n}\n\n// The classes the browser build uses, and the package's tokens and rules, against\n// Connect's theme: the Connect that loads it has Tailwind's reset and Connect's classes.\nexport const stylesheetStep: StandardBuildStep = {\n id: \"stylesheet\",\n run: ({ agent, projectRoot, session }) => {\n const stage = session.stage();\n const command = resolveCommand(agent, \"execute-local\", [\n \"tailwindcss\",\n \"--input\",\n \"-\",\n \"--minify\",\n ]);\n if (command === null) {\n throw new BuildRefusal(\n \"You need to have tailwindcss installed to use the `build` command.\",\n );\n }\n const stylePath = join(projectRoot, \"style.css\");\n const style = existsSync(stylePath)\n ? readFileSync(stylePath, \"utf-8\")\n : undefined;\n const compiled = execSync(`${command.command} ${command.args.join(\" \")}`, {\n cwd: projectRoot,\n input: packageStyleEntry(style, {\n browserDir: sourcePath(projectRoot, join(stage, \"browser\")),\n localPackages: localPackageNames(projectRoot),\n }),\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n // A package that imports large vendor CSS outgrows the 1 MB default.\n maxBuffer: 64 * 1024 * 1024,\n });\n // `ph build` with another out-dir (the switchboard runner's) leaves no\n // staged dist/, so the stylesheet goes to dist/ directly, as it always has.\n const distDir = session.writesPackageDist\n ? stage\n : join(projectRoot, \"dist\");\n mkdirSync(distDir, { recursive: true });\n writeFileSync(join(distDir, \"style.css\"), packageStylesheet(compiled));\n return Promise.resolve();\n },\n};\n","import { execSync } from \"node:child_process\";\nimport { existsSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { type Agent, resolveCommand } from \"package-manager-detector\";\nimport { BuildRefusal } from \"../pipeline/steps.js\";\nimport { BUILD_DIRECTORY } from \"../../build-control.js\";\nimport {\n declarationDirectory,\n type EmitOptions,\n} from \"../../compiler-output/emit.js\";\nimport { compilerOutputs } from \"../staging/compiler.js\";\nimport { parseShownConfig, type ShownConfig } from \"../staging/inventory.js\";\nimport type { StandardBuildStep } from \"./context.js\";\n\nconst TYPE_ERROR_RISK =\n \"A package built with type errors can load and still fail at runtime.\";\n\nexport const UNSAFE_BUILD_WARNING =\n \"⚠ Built despite type errors. \" +\n TYPE_ERROR_RISK +\n \" Fix them before you publish or deploy it.\";\n\n/** The root project's config, as `tsc --showConfig` prints it. */\nfunction showCompilerConfig(\n agent: Agent,\n projectRoot: string,\n): ShownConfig | undefined {\n const showConfig = resolveCommand(agent, \"execute-local\", [\n \"tsc\",\n \"--showConfig\",\n ]);\n if (showConfig === null) return undefined;\n try {\n const output = execSync(\n `${showConfig.command} ${showConfig.args.join(\" \")}`,\n {\n cwd: projectRoot,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n },\n );\n return parseShownConfig(output);\n } catch {\n return undefined;\n }\n}\n\n// tsc's build info outlives a deleted dist; with the declarations gone, tsc\n// would call the project up to date and emit nothing.\nfunction declarationsMissing(\n options: EmitOptions,\n projectRoot: string,\n): boolean {\n const path = declarationDirectory(options, projectRoot);\n if (path === undefined) return false;\n return !existsSync(path) || readdirSync(path).length === 0;\n}\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function confirmBuildDespiteTypeErrors(): Promise<void> {\n const hint =\n \"Fix them and build again. --ignore-type-errors skips this check, at the risk of shipping that failure.\";\n if (!isInteractive()) {\n throw new BuildRefusal(\n `\\n✘ tsc reported the type errors above. ${TYPE_ERROR_RISK}\\n${hint}`,\n );\n }\n const enquirer = await import(\"enquirer\");\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `tsc reported the type errors above. ${TYPE_ERROR_RISK} Build anyway?`,\n initial: false,\n });\n confirmed = answer.confirmed;\n } catch {\n // Ctrl-C at the prompt is a decline.\n confirmed = false;\n }\n if (!confirmed) throw new BuildRefusal(`Build cancelled. ${hint}`);\n}\n\n/**\n * Runs tsc, which checks the project and writes its declarations either way,\n * as `tsc --build` in the package: the same command, build info and output\n * places as without staging. When the session can, tsc builds a generated\n * sibling config that writes into the stage; otherwise what it rewrites is\n * copied first, so a build that does not finish puts it back.\n */\nexport const typecheckStep: StandardBuildStep = {\n id: \"typecheck\",\n run: async ({ agent, args, outDir, projectRoot, session, findings }) => {\n const config = showCompilerConfig(agent, projectRoot);\n const force =\n config !== undefined && declarationsMissing(config.options, projectRoot);\n let generated: string | undefined;\n if (config !== undefined) {\n const configFile = join(projectRoot, \"tsconfig.json\");\n const outputs = await compilerOutputs(config, {\n configFile,\n packageRoot: projectRoot,\n buildDirectory: join(projectRoot, BUILD_DIRECTORY),\n agent,\n output: session.output,\n });\n generated = await session.prepareCompiler({\n configFile,\n config,\n outputs,\n });\n findings.compilerOutputs = outputs.map(({ path }) => path);\n }\n const tscCommand = resolveCommand(agent, \"execute-local\", [\n \"tsc\",\n \"--build\",\n ...(force ? [\"--force\"] : []),\n ...(generated ? [relative(projectRoot, generated)] : []),\n ]);\n if (tscCommand === null) {\n throw new BuildRefusal(\n \"You need to have typescript installed to use the `build` command.\",\n );\n }\n console.log(\"\\n▶ Type-checking and emitting types via tsc...\");\n try {\n execSync(`${tscCommand.command} ${tscCommand.args.join(\" \")}`, {\n stdio: \"inherit\",\n });\n console.log(\"✔ Types emitted to\", join(outDir, \"types\"));\n findings.typesOk = true;\n } catch {\n findings.typesOk = false;\n }\n session.compilerOutputsWritten();\n // Before any bundler runs, so declining leaves nothing half built.\n if (!findings.typesOk && !args.ignoreTypeErrors) {\n await confirmBuildDespiteTypeErrors();\n }\n },\n};\n","import { browserBundleStep, nodeBundleStep } from \"./bundles.js\";\nimport { connectRoutesStep } from \"./connect-routes.js\";\nimport type { StandardBuildStep } from \"./context.js\";\nimport { definitionsStep } from \"./definitions.js\";\nimport { manifestNameStep, piecesOutDirStep } from \"./package-checks.js\";\nimport { distManifestStep, offeredRoutesStep, piecesStep } from \"./pieces.js\";\nimport { releaseApprovalStep, releaseStartStep } from \"./release-approval.js\";\nimport { stylesheetStep } from \"./stylesheet.js\";\nimport { typecheckStep } from \"./typecheck.js\";\n\n/**\n * `ph build`'s steps in the order they run. Another phase inserts its own\n * with `[...standardBuildSteps, ...more]` and `after` on the step it follows.\n */\nexport const standardBuildSteps: readonly StandardBuildStep[] = [\n releaseStartStep,\n manifestNameStep,\n piecesOutDirStep,\n connectRoutesStep,\n typecheckStep,\n definitionsStep,\n browserBundleStep,\n nodeBundleStep,\n piecesStep,\n distManifestStep,\n offeredRoutesStep,\n stylesheetStep,\n releaseApprovalStep,\n];\n","import type { TraceFiles } from \"@powerhousedao/shared/build-pieces\";\nimport { resolve } from \"node:path\";\nimport { nodeFileTrace } from \"@vercel/nft\";\n\n// nft reports paths relative to its base; from \"/\" that is every path minus its root.\n// One cache per build: the traces of a project's packages share most files.\nexport function createTraceFiles(): TraceFiles {\n const cache = {};\n return (file) => traceFile(file, cache);\n}\n\nexport const traceFiles: TraceFiles = createTraceFiles();\n\nasync function traceFile(file: string, cache: object) {\n const { fileList, reasons } = await nodeFileTrace([file], {\n base: \"/\",\n cache,\n });\n const absolute = (p: string) => resolve(\"/\", p);\n return {\n fileList: new Set([...fileList].map(absolute)),\n reasons: new Map(\n [...reasons].map(([p, reason]) => [\n absolute(p),\n { parents: new Set([...reason.parents].map(absolute)) },\n ]),\n ),\n };\n}\n","import { planPieces } from \"@powerhousedao/shared/build-pieces\";\nimport { createDetectionCache } from \"@powerhousedao/shared/build-pieces\";\nimport { detect } from \"package-manager-detector\";\nimport type { BuildArgs } from \"../../types.js\";\nimport { runBuildSteps } from \"./pipeline/run-steps.js\";\nimport { openBuildSession } from \"./staging/open.js\";\nimport type { BuildSession } from \"./staging/session.js\";\nimport { entriesCleanedBy } from \"./steps/bundles.js\";\nimport type { BuildContext, StandardBuildStep } from \"./steps/context.js\";\nimport { standardBuildSteps } from \"./steps/standard.js\";\nimport { createTraceFiles } from \"./steps/trace.js\";\nimport { UNSAFE_BUILD_WARNING } from \"./steps/typecheck.js\";\n\nexport type BuildOptions = {\n readonly steps?: readonly StandardBuildStep[];\n /**\n * Check the package's definitions, importing its modules in a child\n * process. Only `ph build` asks; `--release` always checks.\n */\n readonly checkDefinitions?: boolean;\n /**\n * This process belongs to ph-cli and loads no package code, so a stop\n * signal ends it: the lock can go before the signal is re-raised, and a\n * next build on another host does not wait for it. An embedding process\n * (the switchboard runner) keeps the lock until the running step settles,\n * since one of its signal-exit callbacks may keep the process alive.\n */\n readonly ownsProcess?: boolean;\n};\n\nconst STOP_SIGNALS = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const;\n\n/**\n * The signal listeners signal-exit installs: each ends the process when\n * only signal-exit listeners are left, so they are not an embedding\n * process that keeps running. Read from the counts its copies share.\n */\nfunction exitOnlyListeners(): number {\n const count = (emitter: unknown) => {\n const value = (emitter as { count?: unknown } | undefined)?.count;\n return typeof value === \"number\" ? value : 0;\n };\n const shared = globalThis as Record<symbol, unknown>;\n const legacy = process as unknown as Record<string, unknown>;\n return (\n count(shared[Symbol.for(\"signal-exit emitter\")]) +\n count(legacy.__signal_exit_emitter__)\n );\n}\n\n/**\n * Stops the build when the process is told to stop, for as long as it runs.\n * The handler runs first and removes itself, so the listeners already there\n * act as if it had never been added. When one of them keeps the process\n * running (an embedding process), the handler only cancels: the step runner\n * rolls back once the running step settles, and the lock is released after\n * that. Otherwise the process should end with the signal: the handler\n * restores the previous output at once, releases the lock and, with no\n * listener left, re-raises the signal. The run and its snapshot stay for\n * the next build to replay. The lock does not: a dead owner's lock is taken\n * over only from the same host, which a new container or a renamed machine\n * is not. A signal-exit callback can still keep the process running; then\n * the runner restores again from that snapshot once the running step\n * settles.\n */\nfunction stopOnSignal(session: BuildSession, ownsProcess: boolean): () => void {\n const stop = (signal: NodeJS.Signals) => {\n session.cancel(signal);\n remove();\n if (process.listenerCount(signal) > exitOnlyListeners()) return;\n session.rollback();\n if (ownsProcess) session.releaseLock();\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n };\n const remove = () => {\n for (const signal of STOP_SIGNALS) process.removeListener(signal, stop);\n };\n for (const signal of STOP_SIGNALS) process.prependListener(signal, stop);\n return remove;\n}\n\n/**\n * Builds the package in the current directory: every step writes to a stage,\n * which replaces the output directory only when all of them succeed. A\n * failure, a refusal or a stop signal leaves the previous output and\n * compiler outputs as they were.\n */\nexport async function buildPackage(\n args: BuildArgs,\n options: BuildOptions = {},\n): Promise<void> {\n const { outDir } = args;\n const projectRoot = process.cwd();\n const steps = options.steps ?? standardBuildSteps;\n const session = await openBuildSession({\n packageRoot: projectRoot,\n outDir,\n cleanedEntries: entriesCleanedBy(steps),\n // Only in the standard list does no step write those entries before\n // the bundle steps empty them, which seeding them by hard link needs.\n linkCleanedEntries: options.steps === undefined,\n });\n const stopListening = stopOnSignal(session, options.ownsProcess ?? false);\n try {\n const detectResult = await detect();\n const ctx: BuildContext = {\n args,\n projectRoot,\n outDir,\n agent: detectResult?.agent ?? \"npm\",\n session,\n checkDefinitions: options.checkDefinitions ?? false,\n pieces: planPieces(projectRoot, outDir),\n detection: createDetectionCache(),\n trace: createTraceFiles(),\n findings: {\n offersRoutes: false,\n typesOk: true,\n compilerOutputs: [],\n releaseStart: undefined,\n release: undefined,\n external: new Map(),\n pkg: undefined,\n built: [],\n },\n };\n await runBuildSteps(steps, ctx, session);\n // Last, so it is the line a finished build leaves on screen.\n if (!ctx.findings.typesOk) console.warn(`\\n${UNSAFE_BUILD_WARNING}`);\n } finally {\n stopListening();\n session.rollback();\n session.close();\n }\n}\n","import { join } from \"node:path\";\nimport { checkInChild } from \"./package-build/steps/definitions.js\";\nimport type { StandardBuildStep } from \"./package-build/steps/context.js\";\n\n/** The definitions step checks the package, subgraphs included, unless\n * discovery skips it, as it does for a package with no document model. */\nasync function definitionsStepCoversSubgraphs(\n projectRoot: string,\n): Promise<boolean> {\n const { resolveDefinitionSelection } = await import(\"document-model/tooling\");\n const selection = resolveDefinitionSelection({\n configFile: join(projectRoot, \"powerhouse.config.json\"),\n allowMissingConfig: true,\n });\n return selection.status !== \"skipped\";\n}\n\n/**\n * Checks a package's code-first subgraphs in `ph build`'s edit profile when\n * the definitions step does not: a package where discovery skips it. Under `--release` the definitions\n * step runs the release profile, which carries the subgraph checks and\n * refuses on their errors.\n */\nexport function subgraphStepWithin(timeoutMs: number): StandardBuildStep {\n return {\n id: \"subgraphs\",\n after: [\"definitions\"],\n run: async ({ args, checkDefinitions, projectRoot, session }) => {\n if (args.release || !checkDefinitions) return;\n if (await definitionsStepCoversSubgraphs(projectRoot)) return;\n const { renderCheckReport } = await import(\"./model/render.js\");\n console.log(\"\\n▶ Checking subgraph definitions...\");\n const edit = await checkInChild(projectRoot, \"edit\", session, timeoutMs);\n if (!edit.ok) {\n console.warn(`⚠ The subgraph check could not run: ${edit.message}`);\n return;\n }\n const text = renderCheckReport(edit.result);\n if (edit.result.diagnostics.length > 0) {\n console.warn(\n `⚠ The subgraph check reported problems; the build goes on:\\n${text}`,\n );\n } else {\n console.log(`✔ ${text}`);\n }\n },\n };\n}\n\nexport const subgraphStep = subgraphStepWithin(5 * 60_000);\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { BuildArgs } from \"../types.js\";\nimport { BuildRefusal } from \"./package-build/pipeline/steps.js\";\nimport { type BuildOptions, buildPackage } from \"./package-build/run-build.js\";\nimport { standardBuildSteps } from \"./package-build/steps/standard.js\";\nimport { subgraphStep } from \"./subgraph-build-step.js\";\n\nexport { assertExternalDependenciesDeclared } from \"./package-build/steps/bundles.js\";\nexport { assertManifestNameMatchesPackage } from \"./package-build/steps/package-checks.js\";\nexport { createTraceFiles, traceFiles } from \"./package-build/steps/trace.js\";\n\n/**\n * The gate loads codegen, so a build without `checkDefinitions` or without a\n * `subgraphs/` directory never imports it.\n */\nasync function withSubgraphStep(options: BuildOptions): Promise<BuildOptions> {\n if (!options.checkDefinitions) return options;\n if (!existsSync(join(process.cwd(), \"subgraphs\"))) return options;\n const { hasCodeFirstSubgraph } = await import(\"./model/subgraph-gate.js\");\n if (!hasCodeFirstSubgraph(process.cwd())) return options;\n return {\n ...options,\n steps: [...(options.steps ?? standardBuildSteps), subgraphStep],\n };\n}\n\n/**\n * `ph build`, and the package build `ph connect build` and the switchboard\n * runner start from. A refusal (missing tsc or tailwindcss, type errors not\n * accepted, a release check that fails) prints its message and exits 1 once\n * the previous output is back, as these callers have always seen it.\n * Only `ph build` passes `checkDefinitions`, so the other callers import\n * none of the package's modules. A command that adds steps passes\n * `[...standardBuildSteps, ...its own]` as `steps`.\n */\nexport async function runBuild(\n args: BuildArgs,\n options: BuildOptions = {},\n): Promise<void> {\n try {\n return await buildPackage(args, await withSubgraphStep(options));\n } catch (error) {\n if (!(error instanceof BuildRefusal)) throw error;\n console.error(error.message);\n process.exit(error.exitCode);\n }\n}\n"],"names":["nodePath","sleep","outputDirectories","configSchema","z.object","z.union","z.string","z.array","z.record","z.json","z\n .record","z.object","z.looseObject","z.boolean","z.string","z.array","z\n .object","outputDirectories","outputDirectories","tsdownBuild","tsdownBuild","under"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,eAAb,cAAkC,MAAM;CACtC;CAEA,YAAY,SAAiB,WAAW,GAAG;EACzC,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;AAGA,IAAa,eAAb,cAAkC,MAAM;CACtC;CAEA,YAAY,QAAgB;EAC1B,MAAM,4BAA4B,OAAO,qBAAqB;EAC9D,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAEA,SAAS,aACP,OACwC;CACxC,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,EAAE,QAAQ,OAAO;EAC1B,IAAI,IAAI,IAAI,EAAE,GAAG,MAAM,IAAI,MAAM,eAAe,GAAG,mBAAmB;EACtE,IAAI,IAAI,EAAE;CACZ;CACA,MAAM,YAAY,IAAI,IACpB,MAAM,QAAQ,EAAE,WAAW,SAAS,WAAW,CAAC,CAAC,KAAK,EAAE,SAAS,EAAE,CACrE;CACA,MAAM,wBAAQ,IAAI,IAA+B;CACjD,MAAM,SAAS,MAAM,UAAU;EAC7B,MAAM,WAAW,MACd,MAAM,GAAG,KAAK,CAAC,CACf,UAAU,EAAE,WAAW,SAAS,K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.mjs","sources":["../src/services/package-build/pipeline/steps.ts","../src/services/package-build/pipeline/run-steps.ts","../src/services/package-build/staging/files.ts","../src/services/package-build/staging/journal.ts","../src/services/package-build/staging/boot-id.ts","../src/services/package-build/staging/lock.ts","../src/services/definitions/paths.ts","../src/services/package-build/staging/recovery.ts","../src/services/compiler-output/emit.ts","../src/services/definitions/config-inputs.ts","../src/services/definitions/compiler-output.ts","../src/services/definitions/compiler.ts","../src/services/package-build/staging/inventory.ts","../src/services/package-build/staging/compiler.ts","../src/services/package-build/staging/session.ts","../src/services/package-build/staging/open.ts","../src/utils/offered-routes-manifest.ts","../src/services/package-build/steps/stage-logger.ts","../src/services/package-build/steps/bundles.ts","../src/services/package-build/steps/connect-routes.ts","../src/services/package-build/steps/definitions.ts","../src/services/package-build/steps/package-checks.ts","../src/services/package-build/steps/pieces.ts","../src/services/release/consumer.ts","../src/services/release/issuance.ts","../src/services/package-build/steps/release-approval.ts","../src/services/package-build/steps/stylesheet.ts","../src/services/package-build/steps/typecheck.ts","../src/services/package-build/steps/standard.ts","../src/services/package-build/steps/trace.ts","../src/services/package-build/run-build.ts","../src/services/subgraph-build-step.ts","../src/services/build.ts"],"sourcesContent":["/**\n * One step of `ph build`. A step without `after` follows the step listed\n * before it in its phase; a step with `after` runs as soon as every step it\n * names has run, so a list can insert a step after any other without\n * reordering the rest. A `committed` step runs once the output is replaced,\n * after every other step; a throw from it cannot bring the previous output\n * back.\n */\nexport type BuildStep<C> = {\n readonly id: string;\n readonly after?: readonly string[];\n readonly when?: \"committed\";\n readonly run: (ctx: C) => Promise<void>;\n};\n\n/** A step's decision not to finish the build. The runner rolls back first. */\nexport class BuildRefusal extends Error {\n readonly exitCode: number;\n\n constructor(message: string, exitCode = 1) {\n super(message);\n this.name = \"BuildRefusal\";\n this.exitCode = exitCode;\n }\n}\n\n/** The process was told to stop while the build ran; it was rolled back. */\nexport class BuildStopped extends Error {\n readonly signal: string;\n\n constructor(signal: string) {\n super(`The build was stopped by ${signal} before it finished.`);\n this.name = \"BuildStopped\";\n this.signal = signal;\n }\n}\n\nfunction dependencies<C>(\n steps: readonly BuildStep<C>[],\n): ReadonlyMap<string, readonly string[]> {\n const ids = new Set<string>();\n for (const { id } of steps) {\n if (ids.has(id)) throw new Error(`Build step \"${id}\" is listed twice.`);\n ids.add(id);\n }\n const committed = new Set(\n steps.filter(({ when }) => when === \"committed\").map(({ id }) => id),\n );\n const waits = new Map<string, readonly string[]>();\n steps.forEach((step, index) => {\n const previous = steps\n .slice(0, index)\n .findLast(({ when }) => when === step.when);\n const after = step.after ?? (previous === undefined ? [] : [previous.id]);\n for (const id of after) {\n if (!ids.has(id)) {\n throw new Error(\n `Build step \"${step.id}\" runs after \"${id}\", which no step provides.`,\n );\n }\n if (step.when !== \"committed\" && committed.has(id)) {\n throw new Error(\n `Build step \"${step.id}\" runs before the output is replaced, so it cannot run after \"${id}\", which runs once it is.`,\n );\n }\n }\n waits.set(step.id, after);\n });\n return waits;\n}\n\n/**\n * The order the steps run in: list order, with each step that names `after`\n * placed right after the last step it waits for, and every `committed` step\n * after every other. Throws on a duplicate id, an unknown `after` id, a step\n * that waits on a later phase, or steps that wait on each other.\n */\nexport function orderBuildSteps<C>(\n steps: readonly BuildStep<C>[],\n): BuildStep<C>[] {\n const waits = dependencies(steps);\n const placed = new Set<string>();\n const ordered: BuildStep<C>[] = [];\n while (ordered.length < steps.length) {\n const ready = steps.filter(\n ({ id }) =>\n !placed.has(id) && waits.get(id)!.every((wait) => placed.has(wait)),\n );\n if (ready.length === 0) {\n const waiting = steps\n .filter(({ id }) => !placed.has(id))\n .map(({ id }) => `\"${id}\"`);\n throw new Error(`Build steps ${waiting.join(\", \")} wait on each other.`);\n }\n const phase = ready.some(({ when }) => when !== \"committed\")\n ? ready.filter(({ when }) => when !== \"committed\")\n : ready;\n const next = phase.find((step) => step.after !== undefined) ?? phase[0];\n placed.add(next.id);\n ordered.push(next);\n }\n return ordered;\n}\n","import { type BuildStep, BuildStopped, orderBuildSteps } from \"./steps.js\";\n\n/** What the runner replaces the output with, or puts back. */\nexport type StepSession = {\n readonly commit: () => void;\n readonly rollback: () => void;\n /** The signal that cancelled the build, if one did. */\n readonly stopped: () => string | undefined;\n};\n\nfunction throwIfStopped(session: StepSession): void {\n const signal = session.stopped();\n if (signal === undefined) return;\n session.rollback();\n throw new BuildStopped(signal);\n}\n\n/**\n * Runs the steps in order, commits, then runs the `committed` steps. When a\n * step before the commit throws, `rollback` runs before the error goes on to\n * the caller, so nothing the build wrote outlives the failure. A committed\n * step's throw goes to the caller with the new output in place. A stop is\n * seen once the running step settles, and before each step and the commit:\n * no step starts after it, and the rollback waits for the step it stopped.\n */\nexport async function runBuildSteps<C>(\n steps: readonly BuildStep<C>[],\n ctx: C,\n session: StepSession,\n): Promise<void> {\n const ordered = orderBuildSteps(steps);\n for (const step of ordered.filter(({ when }) => when !== \"committed\")) {\n throwIfStopped(session);\n try {\n await step.run(ctx);\n } catch (error) {\n session.rollback();\n throwIfStopped(session);\n throw error;\n }\n }\n throwIfStopped(session);\n session.commit();\n for (const step of ordered.filter(({ when }) => when === \"committed\")) {\n throwIfStopped(session);\n await step.run(ctx);\n }\n}\n","import { createHash } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n constants,\n cpSync,\n linkSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n readlinkSync,\n renameSync,\n rmSync,\n type Stats,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport function exists(path: string): boolean {\n return lstatSync(path, { throwIfNoEntry: false }) !== undefined;\n}\n\n/**\n * Copies a file or a tree with its timestamps. A clone where the filesystem\n * has them, a byte copy elsewhere; never a hard link, because later steps\n * rewrite files in place.\n */\nexport function cloneTree(\n from: string,\n to: string,\n filter?: (source: string) => boolean,\n): void {\n cpSync(from, to, {\n recursive: true,\n mode: constants.COPYFILE_FICLONE,\n preserveTimestamps: true,\n verbatimSymlinks: true,\n ...(filter && { filter }),\n });\n}\n\n/**\n * Mirrors a tree whose files the next step unlinks before it writes (tsdown\n * cleans its output directory that way): each file is hard linked, so no\n * byte is copied and nothing written later reaches `from`. A file that\n * cannot be linked, and anything else, is copied.\n */\nexport function linkTree(\n from: string,\n to: string,\n filter: (source: string) => boolean,\n): void {\n mkdirSync(to);\n for (const entry of readdirSync(from, { withFileTypes: true })) {\n const source = join(from, entry.name);\n if (!filter(source)) continue;\n const target = join(to, entry.name);\n if (entry.isDirectory()) {\n linkTree(source, target, filter);\n continue;\n }\n if (entry.isFile()) {\n try {\n linkSync(source, target);\n continue;\n } catch {\n // Another filesystem, or one without hard links: copied below.\n }\n }\n cloneTree(source, target);\n }\n}\n\n/** A directory's permission bits, by POSIX path from a tree's root (\"\" for the root). */\nexport type DirectoryMode = readonly [path: string, mode: number];\n\nconst OWNER_RWX = 0o700;\n\n/**\n * Gives every directory of the tree at `path` that lacks it owner read,\n * write and search permission, which emptying it needs, and returns the\n * modes it changed, parents first.\n */\nexport function openDirectories(path: string): DirectoryMode[] {\n const changed: DirectoryMode[] = [];\n const visit = (dir: string, rel: string) => {\n const stat = lstatSync(dir, { throwIfNoEntry: false });\n if (!stat?.isDirectory()) return;\n const mode = stat.mode & 0o7777;\n if ((mode & OWNER_RWX) !== OWNER_RWX) {\n chmodSync(dir, mode | OWNER_RWX);\n changed.push([rel, mode]);\n }\n for (const entry of readdirSync(dir)) {\n visit(join(dir, entry), rel === \"\" ? entry : `${rel}/${entry}`);\n }\n };\n visit(path, \"\");\n return changed;\n}\n\n/** Sets back the modes `openDirectories` changed, children first. */\nexport function restoreDirectoryModes(\n path: string,\n modes: readonly DirectoryMode[],\n): void {\n for (const [rel, mode] of [...modes].reverse()) {\n chmodSync(rel === \"\" ? path : join(path, ...rel.split(\"/\")), mode);\n }\n}\n\n/**\n * Removes a tree. A directory without owner write permission keeps its\n * entries, so on failure each directory is opened and the removal tried\n * once more.\n */\nexport function removeTree(path: string): void {\n const remove = () =>\n rmSync(path, { recursive: true, force: true, maxRetries: 10 });\n try {\n remove();\n } catch (error) {\n try {\n openDirectories(path);\n } catch {\n throw error;\n }\n remove();\n }\n}\n\n/**\n * Makes `path` a copy of `from`. A directory that is there is emptied and\n * refilled rather than removed, so a mount point or a directory another\n * process holds stays where it is.\n */\nexport function replaceTree(from: string, path: string): void {\n const into =\n lstatSync(path, { throwIfNoEntry: false })?.isDirectory() &&\n lstatSync(from).isDirectory();\n if (!into) {\n removeTree(path);\n cloneTree(from, path);\n return;\n }\n openDirectories(path);\n for (const entry of readdirSync(path)) removeTree(join(path, entry));\n cloneTree(from, path);\n}\n\n/**\n * The tree by the bytes of its files and the targets of its links. Times\n * and inodes are left out: a touch changes them, and a rewrite can keep them.\n */\nexport function treeFingerprint(\n root: string,\n skipped: ReadonlySet<string>,\n unmarked: ReadonlySet<string> = new Set(),\n): string {\n const hash = createHash(\"sha256\");\n const visit = (path: string, rel: string) => {\n const stat = lstatSync(path);\n if (stat.isFile()) {\n const bytes = readFileSync(path);\n hash.update(`f\\0${rel}\\0${bytes.length}\\0`).update(bytes);\n return;\n }\n if (stat.isSymbolicLink()) {\n hash.update(`l\\0${rel}\\0${readlinkSync(path)}\\0`);\n return;\n }\n if (!stat.isDirectory()) {\n hash.update(`o\\0${rel}\\0`);\n return;\n }\n if (rel !== \"\" && !unmarked.has(rel)) hash.update(`d\\0${rel}\\0`);\n for (const entry of readdirSync(path).sort()) {\n const child = rel === \"\" ? entry : `${rel}/${entry}`;\n if (!skipped.has(child)) visit(join(path, entry), child);\n }\n };\n if (exists(root)) visit(root, \"\");\n return hash.digest(\"hex\");\n}\n\ntype Unstageable = { readonly path: string; readonly reason: string };\n\n/**\n * The first entry of the tree at `path`, itself included, that the stage\n * cannot copy as it is, and why: a FIFO, socket or device, which a copy\n * cannot represent, or a file or directory this process cannot read. Only\n * permissions are checked; no file is read. Entries `filter` rejects, and\n * what they hold, are not looked at.\n */\nexport function unstageableEntryIn(\n path: string,\n filter: (source: string) => boolean = () => true,\n): Unstageable | undefined {\n const visit = (path: string, stat: Stats): Unstageable | undefined => {\n if (stat.isSymbolicLink()) return;\n if (!stat.isFile() && !stat.isDirectory()) {\n return { path, reason: \"is not a file, directory or symbolic link\" };\n }\n const mode = stat.isDirectory()\n ? constants.R_OK | constants.X_OK\n : constants.R_OK;\n try {\n accessSync(path, mode);\n } catch {\n return { path, reason: \"cannot be read\" };\n }\n if (!stat.isDirectory()) return;\n for (const entry of readdirSync(path)) {\n const child = join(path, entry);\n if (!filter(child)) continue;\n const found = visit(child, lstatSync(child));\n if (found) return found;\n }\n return;\n };\n const stat = lstatSync(path, { throwIfNoEntry: false });\n return stat && visit(path, stat);\n}\n\nexport function entriesOf(dir: string): string[] {\n return exists(dir) ? readdirSync(dir) : [];\n}\n\nconst blocker = new Int32Array(new SharedArrayBuffer(4));\n\n/** Waits without returning to the event loop, so no signal handler runs meanwhile. */\nfunction sleepSync(ms: number): void {\n Atomics.wait(blocker, 0, 0, ms);\n}\n\n/** Windows refuses to rename a directory while another process holds a file in it. */\nexport function isHeldOpen(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n return code === \"EPERM\" || code === \"EBUSY\" || code === \"EACCES\";\n}\n\nexport const RENAME_PATIENCE_MS = 2000;\n\n/** `rename`, retried with backoff for about two seconds while the path is held open. */\nexport function renamePatiently(\n from: string,\n to: string,\n patienceMs = RENAME_PATIENCE_MS,\n): void {\n const deadline = Date.now() + patienceMs;\n for (let wait = 20; ; wait = Math.min(wait * 2, 400)) {\n try {\n renameSync(from, to);\n return;\n } catch (error) {\n if (!isHeldOpen(error) || Date.now() + wait > deadline) throw error;\n sleepSync(wait);\n }\n }\n}\n\n/** Moves each entry of `from` into `to`, replacing what `to` holds under that name. */\nexport function moveEntries(from: string, to: string): void {\n for (const entry of entriesOf(from)) {\n const target = join(to, entry);\n if (exists(target)) removeTree(target);\n renamePatiently(join(from, entry), target);\n }\n}\n\n/** Staging cannot run where the build would write; `message` says why. */\nexport class CannotStage extends Error {}\n\n// Errors that say a path cannot be created or written there, or that the\n// filesystem has no hard links for the lock.\nconst CANNOT_WRITE = new Set([\n \"ENOTDIR\",\n \"EACCES\",\n \"EPERM\",\n \"EROFS\",\n \"ENOTSUP\",\n \"EOPNOTSUPP\",\n]);\n\n/** Runs `create`, turning a refusal to write `where` into `CannotStage`. */\nexport async function creating<T>(\n where: string,\n create: () => T | Promise<T>,\n): Promise<T> {\n try {\n return await create();\n } catch (error) {\n const code = (error as { code?: unknown } | null)?.code;\n if (typeof code === \"string\" && CANNOT_WRITE.has(code)) {\n throw new CannotStage(`${where} cannot be written (${code})`);\n }\n throw error;\n }\n}\n","import { readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport nodePath, { join } from \"node:path\";\nimport { BUILD_DIRECTORY } from \"../../build-control.js\";\nimport type { DirectoryMode } from \"./files.js\";\nimport type { CompilerOutput } from \"./inventory.js\";\n\nexport const RUNS_DIRECTORY = join(BUILD_DIRECTORY, \"runs\");\nconst JOURNAL_FILE = \"journal.json\";\n\n/**\n * Where a run is, written before each move it makes:\n * - building: the stage is being written; the output is untouched.\n * - retiring: the output is moving aside to the retired path.\n * - installing: the stage is moving into the output's place.\n * - rolling-back: the run is being undone; `undo` names the step it is at.\n * - committed: the stage is the output; only cleanup is left.\n */\nexport type JournalState =\n | \"building\"\n | \"retiring\"\n | \"installing\"\n | \"rolling-back\"\n | \"committed\";\n\n/**\n * The steps of a rollback, in order, each safe to repeat:\n * - install: the output loses what the stage put in it.\n * - retire: the retired tree, or its entries, goes back into the output.\n * - stage: the stage goes and the compiler outputs come back.\n */\nexport const UNDO_STEPS = [\"install\", \"retire\", \"stage\"] as const;\nexport type UndoStep = (typeof UNDO_STEPS)[number];\n\n/**\n * A compiler output as it was before tsc ran. `copy` is null when it was\n * absent; `created` is then the outermost of its directories that was absent\n * too, removed again if tsc left nothing else in it. `modes` holds the\n * directories of the copy that lacked owner permissions, which the copy was\n * given so the run can be removed; a restore sets them back.\n */\nexport type CompilerSnapshot = {\n readonly path: string;\n readonly kind: CompilerOutput[\"kind\"];\n readonly copy: string | null;\n readonly created: string | null;\n readonly modes?: readonly DirectoryMode[];\n};\n\nexport type PendingBuildInfo = {\n readonly path: string;\n readonly target: string;\n};\n\n/** Paths as `toJournalPath` records them: package paths from the package root, copies from the run directory. */\nexport type RunJournal = {\n readonly format: 1;\n readonly runId: string;\n readonly pid: number;\n readonly state: JournalState;\n /** With `rolling-back`: the first rollback step not known to be done. */\n readonly undo: UndoStep | null;\n readonly output: string;\n readonly stage: string;\n readonly retired: string;\n readonly compiler: readonly CompilerSnapshot[] | null;\n readonly generatedConfig?: string;\n readonly pendingBuildInfo?: PendingBuildInfo;\n readonly outputDigest?: string;\n};\n\nconst STATES: readonly JournalState[] = [\n \"building\",\n \"retiring\",\n \"installing\",\n \"rolling-back\",\n \"committed\",\n];\n\n/**\n * A path inside `from` is recorded relative, in POSIX form. Any other path\n * is recorded absolute and comes back unchanged: a relative spelling of\n * another drive or a UNC share does not resolve back to it on Windows.\n */\nexport function toJournalPath(\n from: string,\n to: string,\n paths: typeof nodePath = nodePath,\n): string {\n const rel = paths.relative(from, to);\n if (\n paths.isAbsolute(rel) ||\n rel === \"..\" ||\n rel.startsWith(`..${paths.sep}`)\n ) {\n return paths.resolve(to);\n }\n return rel.split(paths.sep).join(\"/\");\n}\n\nexport function fromJournalPath(\n from: string,\n recorded: string,\n paths: typeof nodePath = nodePath,\n): string {\n return paths.isAbsolute(recorded) ? recorded : paths.resolve(from, recorded);\n}\n\nexport function journalPath(runDir: string): string {\n return join(runDir, JOURNAL_FILE);\n}\n\n/** Replaces the journal in one rename, so a reader sees the old state or the new. */\nexport function writeJournal(runDir: string, journal: RunJournal): void {\n const file = journalPath(runDir);\n const pending = `${file}.${process.pid}.tmp`;\n writeFileSync(pending, `${JSON.stringify(journal, null, 2)}\\n`);\n renameSync(pending, file);\n}\n\nconst isString = (value: unknown): value is string =>\n typeof value === \"string\" && value !== \"\";\n\nfunction parseSnapshot(value: unknown): CompilerSnapshot | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const { path, kind, copy, created } = value as Record<string, unknown>;\n if (\n !isString(path) ||\n (kind !== \"directory\" && kind !== \"build-info\" && kind !== \"file\")\n ) {\n return undefined;\n }\n if (copy !== null && !isString(copy)) return undefined;\n if (created !== null && !isString(created)) return undefined;\n const { modes } = value as Record<string, unknown>;\n if (modes === undefined) return { path, kind, copy, created };\n if (!Array.isArray(modes) || !modes.every(isDirectoryMode)) return undefined;\n return { path, kind, copy, created, modes };\n}\n\nfunction parsePendingBuildInfo(\n value: unknown,\n): PendingBuildInfo | undefined | null {\n if (value === undefined) return undefined;\n if (typeof value !== \"object\" || value === null) return null;\n const { path, target } = value as Record<string, unknown>;\n return isString(path) && isString(target) ? { path, target } : null;\n}\n\nconst isDirectoryMode = (value: unknown): value is DirectoryMode =>\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === \"string\" &&\n Number.isInteger(value[1]);\n\n/** The journal of a run directory, or undefined when it is missing or unreadable. */\nexport function readJournal(runDir: string): RunJournal | undefined {\n let value: unknown;\n try {\n value = JSON.parse(readFileSync(journalPath(runDir), \"utf8\"));\n } catch {\n return undefined;\n }\n if (typeof value !== \"object\" || value === null) return undefined;\n const record = value as Record<string, unknown>;\n if (\n record.format !== 1 ||\n !isString(record.runId) ||\n typeof record.pid !== \"number\" ||\n !STATES.includes(record.state as JournalState) ||\n !isString(record.output) ||\n !isString(record.stage) ||\n !isString(record.retired)\n ) {\n return undefined;\n }\n const optional = (key: string) =>\n record[key] === undefined || isString(record[key]);\n if (!optional(\"generatedConfig\") || !optional(\"outputDigest\"))\n return undefined;\n const pending = parsePendingBuildInfo(record.pendingBuildInfo);\n if (pending === null) return undefined;\n const undo = UNDO_STEPS.find((step) => step === record.undo) ?? null;\n if ((record.state === \"rolling-back\") !== (undo !== null)) return undefined;\n let compiler: CompilerSnapshot[] | null = null;\n if (Array.isArray(record.compiler)) {\n compiler = [];\n for (const entry of record.compiler) {\n const snapshot = parseSnapshot(entry);\n if (snapshot === undefined) return undefined;\n compiler.push(snapshot);\n }\n } else if (record.compiler !== null) {\n return undefined;\n }\n return {\n format: 1,\n runId: record.runId,\n pid: record.pid,\n state: record.state as JournalState,\n undo,\n output: record.output,\n stage: record.stage,\n retired: record.retired,\n compiler,\n ...(isString(record.generatedConfig) && {\n generatedConfig: record.generatedConfig,\n }),\n ...(pending !== undefined && { pendingBuildInfo: pending }),\n ...(isString(record.outputDigest) && { outputDigest: record.outputDigest }),\n };\n}\n","import { execFileSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\n\nfunction readBootId(): string | null {\n try {\n const id =\n process.platform === \"linux\"\n ? readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\")\n : process.platform === \"darwin\"\n ? execFileSync(\"sysctl\", [\"-n\", \"kern.bootsessionuuid\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n : \"\";\n return id.trim() || null;\n } catch {\n return null;\n }\n}\n\nlet memo: string | null | undefined;\n\n/**\n * This boot of the machine, as the OS names it, or null where it cannot be\n * read. Unlike a boot time derived from the clock, it changes only with a\n * reboot.\n */\nexport function currentBootId(): string | null {\n if (memo === undefined) memo = readBootId();\n return memo;\n}\n","import {\n linkSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { pendingPrefix, takeoverPrefix } from \"../../build-control.js\";\nimport { currentBootId } from \"./boot-id.js\";\nimport { removeTree } from \"./files.js\";\n\nconst POLL_MS = 100;\nconst TAKEOVER_RETRY_MS = 10;\n// A takeover takes milliseconds, so a contender waiting on one says so only\n// when it lasts: the holder may be paused, or gone under a reused pid.\nconst QUIET_TAKEOVER_WAIT_MS = 1000;\n\n/**\n * A lock's owner: the run, its process, and the machine and boot that\n * process lives in. Only an owner of this machine can be proven dead (see\n * `provenDead`).\n */\ntype LockOwner = {\n readonly pid: number;\n readonly runId: string;\n readonly host: string;\n /** The OS's id of the boot the process ran in, null where unknown. */\n readonly bootId: string | null;\n};\n\nfunction isOwner(value: unknown): value is LockOwner {\n const owner = value as Partial<LockOwner> | null;\n return (\n typeof owner?.pid === \"number\" &&\n typeof owner.runId === \"string\" &&\n typeof owner.host === \"string\" &&\n (typeof owner.bootId === \"string\" || owner.bootId === null)\n );\n}\n\n/**\n * The owner's process is gone: on this machine, it ran in another boot (so\n * the reboot ended it), or no process is left at its pid. Another host, or a\n * live pid in this boot or an unknown one, is not proof: such an owner may\n * still be building. A pid reused by another process of this boot reads as\n * live, so its lock waits until someone deletes it.\n */\nconst provenDead = (owner: LockOwner) => {\n if (owner.host !== hostname()) return false;\n const boot = currentBootId();\n if (owner.bootId !== null && boot !== null && owner.bootId !== boot) {\n return true;\n }\n return !isProcessAlive(owner.pid);\n};\n\nconst errorCode = (error: unknown) => (error as { code?: unknown }).code;\n\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM: alive, owned by another user.\n return errorCode(error) === \"EPERM\";\n }\n}\n\n/** What a waiting build says about who holds a lock or takeover file. */\nfunction described(value: unknown): string {\n const fields = value as Partial<Record<keyof LockOwner, unknown>> | null;\n const parts = (\n [\n [\"host\", fields?.host],\n [\"pid\", fields?.pid],\n [\"run\", fields?.runId],\n ] as const\n ).flatMap(([name, field]) =>\n typeof field === \"string\" || typeof field === \"number\"\n ? [`${name} ${field}`]\n : [],\n );\n return parts.length > 0 ? parts.join(\", \") : \"owner unknown\";\n}\n\n/**\n * Who holds a lock or takeover file. `id` names that one holding: the\n * owner's run id, or for a file that does not read as an owner, its inode\n * and time, so a replacement never passes for it. Such a file is never\n * proven dead.\n */\ntype Holder = {\n readonly id: string;\n readonly dead: boolean;\n readonly owner: string;\n};\n\nfunction holderOf(file: string): Holder | undefined {\n let value: unknown;\n try {\n value = JSON.parse(readFileSync(file, \"utf8\"));\n } catch (error) {\n if (errorCode(error) === \"ENOENT\") return undefined;\n }\n if (isOwner(value)) {\n return {\n id: value.runId,\n dead: provenDead(value),\n owner: described(value),\n };\n }\n const stat = lstatSync(file, { throwIfNoEntry: false });\n return (\n stat && {\n id: `file ${stat.ino} ${stat.mtimeMs}`,\n dead: false,\n owner: described(value),\n }\n );\n}\n\n/**\n * Creates `file` holding `owner`, or returns false when it exists. The file\n * appears with its content in one link, so no reader sees it empty.\n */\nfunction createOwned(file: string, owner: LockOwner): boolean {\n const pending = join(\n dirname(file),\n `${pendingPrefix(basename(file))}${owner.runId}.pending`,\n );\n writeFileSync(pending, JSON.stringify(owner));\n try {\n linkSync(pending, file);\n return true;\n } catch (error) {\n if (errorCode(error) === \"EEXIST\") return false;\n throw error;\n } finally {\n rmSync(pending, { force: true });\n }\n}\n\nconst takeoverFile = (lockFile: string, staleId: string) =>\n join(\n dirname(lockFile),\n `${takeoverPrefix(basename(lockFile))}${encodeURIComponent(staleId)}`,\n );\n\n/** A file a live or unknown holder keeps, which this build waits for. */\ntype Blocked = { readonly file: string; readonly holder: Holder };\n\n/**\n * Removes `file` while it still holds the dead holder `stale`. Only the\n * creator of the takeover file keyed to `stale` may remove it, and `stale`\n * cannot come back, so the owner read under that file is the one removed: a\n * contender that judged it stale before someone else took over removes\n * nothing. A takeover file is itself taken over only from a holder proven\n * dead, never for its age, so a paused holder keeps it. Returns what blocks\n * the takeover, or nothing when the caller should try again.\n */\nfunction takeOver(\n lockFile: string,\n file: string,\n stale: Holder,\n me: LockOwner,\n): Blocked | undefined {\n const guard = takeoverFile(lockFile, stale.id);\n if (!createOwned(guard, me)) {\n const holder = holderOf(guard);\n if (holder === undefined) return undefined;\n return holder.dead\n ? takeOver(lockFile, guard, holder, me)\n : { file: guard, holder };\n }\n try {\n if (holderOf(file)?.id === stale.id) removeTree(file);\n return undefined;\n } finally {\n if (holderOf(guard)?.id === me.runId) rmSync(guard, { force: true });\n }\n}\n\n/**\n * Takeover files left by contenders that died. Safe under the lock: one\n * matters only while the lock holds its stale owner, and the lock is ours.\n * A pending file goes only when its writer is proven dead: a live\n * contender links it next.\n */\nfunction removeTakeoverFiles(lockFile: string): void {\n const takeover = takeoverPrefix(basename(lockFile));\n const pending = pendingPrefix(basename(lockFile));\n for (const entry of readdirSync(dirname(lockFile))) {\n const file = join(dirname(lockFile), entry);\n if (\n entry.startsWith(takeover) ||\n (entry.startsWith(pending) &&\n entry.endsWith(\".pending\") &&\n holderOf(file)?.dead === true)\n ) {\n rmSync(file, { force: true });\n }\n }\n}\n\n/** The package's build lock, held until `release`. */\nexport type BuildLock = { readonly release: () => void };\n\n/** The file a build waits for and who holds it, as `host …, pid …, run …`. */\nexport type LockWait = { readonly file: string; readonly owner: string };\n\n/**\n * Takes `.ph/build/lock`, a file created exclusively that names this run.\n * A lock is taken over only from an owner proven dead (see `provenDead`);\n * otherwise this waits, and says once per holder which file it waits for.\n */\nexport async function acquireBuildLock(\n lockFile: string,\n runId: string,\n onWait: (wait: LockWait) => void,\n): Promise<BuildLock> {\n mkdirSync(dirname(lockFile), { recursive: true });\n const me: LockOwner = {\n pid: process.pid,\n runId,\n host: hostname(),\n bootId: currentBootId(),\n };\n const told = new Set<string>();\n const firstBlocked = new Map<string, number>();\n for (;;) {\n if (createOwned(lockFile, me)) {\n removeTakeoverFiles(lockFile);\n let held = true;\n return {\n release: () => {\n if (!held) return;\n held = false;\n if (holderOf(lockFile)?.id === runId) rmSync(lockFile);\n },\n };\n }\n const holder = holderOf(lockFile);\n if (holder === undefined) continue;\n const blocked = holder.dead\n ? takeOver(lockFile, lockFile, holder, me)\n : { file: lockFile, holder };\n if (blocked === undefined) {\n await sleep(TAKEOVER_RETRY_MS);\n continue;\n }\n const key = `${blocked.file}\\0${blocked.holder.id}`;\n const since = firstBlocked.get(key) ?? Date.now();\n firstBlocked.set(key, since);\n const quiet =\n blocked.file !== lockFile && Date.now() - since < QUIET_TAKEOVER_WAIT_MS;\n if (!quiet && !told.has(key)) {\n told.add(key);\n onWait({ file: blocked.file, owner: blocked.holder.owner });\n }\n await sleep(blocked.file === lockFile ? POLL_MS : TAKEOVER_RETRY_MS);\n }\n}\n","import { realPathThroughExistingParent } from \"@powerhousedao/shared/clis/real-paths\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\n\nexport function toPosixPath(path: string): string {\n return path.split(sep).join(\"/\");\n}\n\nexport function canonicalConfigFile(configFile: string): string {\n const absolute = resolve(configFile);\n return join(\n realPathThroughExistingParent(dirname(absolute)),\n basename(absolute),\n );\n}\n","import { mkdirSync, rmdirSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport { toPosixPath } from \"../../definitions/paths.js\";\nimport {\n entriesOf,\n exists,\n isHeldOpen,\n moveEntries,\n removeTree,\n renamePatiently,\n replaceTree,\n restoreDirectoryModes,\n treeFingerprint,\n} from \"./files.js\";\nimport {\n type CompilerSnapshot,\n fromJournalPath,\n type JournalState,\n type PendingBuildInfo,\n readJournal,\n RUNS_DIRECTORY,\n type RunJournal,\n toJournalPath,\n UNDO_STEPS,\n type UndoStep,\n writeJournal,\n} from \"./journal.js\";\n\n/** A run's paths, absolute. */\nexport type RunPaths = {\n readonly packageRoot: string;\n readonly runDir: string;\n readonly output: string;\n readonly stage: string;\n readonly retired: string;\n};\n\nexport function runPaths(\n packageRoot: string,\n runDir: string,\n journal: Pick<RunJournal, \"output\" | \"stage\" | \"retired\">,\n): RunPaths {\n return {\n packageRoot,\n runDir,\n output: fromJournalPath(packageRoot, journal.output),\n stage: fromJournalPath(packageRoot, journal.stage),\n retired: fromJournalPath(packageRoot, journal.retired),\n };\n}\n\nexport function outputDigest(\n packageRoot: string,\n output: string,\n compiler: readonly CompilerSnapshot[],\n): string | undefined {\n const real = realPathThroughExistingParent(output);\n const inOutput = (recorded: string) => {\n const rel = pathWithin(real, fromJournalPath(packageRoot, recorded));\n return rel === null ? null : toPosixPath(rel);\n };\n const skipped = new Set<string>();\n const unmarked = new Set<string>();\n for (const { path, created } of compiler) {\n if (pathWithin(fromJournalPath(packageRoot, path), real) !== null) {\n return undefined;\n }\n const rel = inOutput(path);\n if (rel === null) continue;\n skipped.add(rel);\n if (created !== null) {\n const parts = rel.split(\"/\");\n const createdRel = inOutput(created);\n const first = createdRel ? createdRel.split(\"/\").length : 1;\n for (let length = first; length < parts.length; length++) {\n unmarked.add(parts.slice(0, length).join(\"/\"));\n }\n }\n }\n return treeFingerprint(output, skipped, unmarked);\n}\n\nfunction removeScratch(\n packageRoot: string,\n journal: Pick<RunJournal, \"generatedConfig\" | \"pendingBuildInfo\">,\n): void {\n for (const recorded of [\n journal.generatedConfig,\n journal.pendingBuildInfo?.path,\n ]) {\n if (recorded !== undefined)\n removeTree(fromJournalPath(packageRoot, recorded));\n }\n}\n\nexport function installBuildInfo(\n packageRoot: string,\n pending: PendingBuildInfo | undefined,\n): void {\n if (pending === undefined) return;\n const path = fromJournalPath(packageRoot, pending.path);\n if (exists(path)) {\n renamePatiently(path, fromJournalPath(packageRoot, pending.target));\n }\n}\n\n/** Puts `from` at `to`: one rename, or entry by entry when `from` is held open. */\nexport function moveTree(from: string, to: string): \"renamed\" | \"entries\" {\n try {\n renamePatiently(from, to);\n return \"renamed\";\n } catch (error) {\n if (!isHeldOpen(error)) throw error;\n mkdirSync(to, { recursive: true });\n moveEntries(from, to);\n removeTree(from);\n return \"entries\";\n }\n}\n\n/** Build info first: if a later copy fails, tsc still sees its outputs as stale. */\nexport function restoreCompilerOutputs(\n paths: Pick<RunPaths, \"packageRoot\" | \"runDir\">,\n snapshots: readonly CompilerSnapshot[] | null,\n): void {\n const ordered = [...(snapshots ?? [])].sort(\n (a, b) => Number(b.kind === \"build-info\") - Number(a.kind === \"build-info\"),\n );\n for (const snapshot of ordered) {\n const path = fromJournalPath(paths.packageRoot, snapshot.path);\n if (snapshot.copy !== null) {\n replaceTree(fromJournalPath(paths.runDir, snapshot.copy), path);\n restoreDirectoryModes(path, snapshot.modes ?? []);\n continue;\n }\n removeTree(path);\n if (snapshot.created !== null) {\n removeEmptyDirectories(\n dirname(path),\n fromJournalPath(paths.packageRoot, snapshot.created),\n );\n }\n }\n}\n\n/** Removes `from` and its parents up to `upTo` while each is an empty directory. */\nfunction removeEmptyDirectories(from: string, upTo: string): void {\n for (let dir = from; ; dir = dirname(dir)) {\n if (!exists(dir) || entriesOf(dir).length > 0) return;\n rmdirSync(dir);\n if (dir === upTo || dirname(dir) === dir) return;\n }\n}\n\nconst FIRST_UNDO_STEP: Readonly<\n Record<Exclude<JournalState, \"rolling-back\" | \"committed\">, UndoStep>\n> = { building: \"stage\", retiring: \"retire\", installing: \"install\" };\n\nexport type Undone = \"restored\" | \"superseded\";\n\n/**\n * Undoes a run: the previous output goes back in place, the stage goes, and\n * the compiler outputs are restored, unless a later build replaced the output\n * since they were saved (`superseded`). The journal records each step before\n * it starts, so a rollback cut short is finished by the next build, never\n * rolled forward; the run directory, and the snapshot in it, stay until the\n * caller removes them.\n */\nexport function rollBack(paths: RunPaths, journal: RunJournal): Undone {\n if (journal.state === \"committed\") return \"restored\";\n const first =\n journal.state === \"rolling-back\"\n ? (journal.undo ?? \"stage\")\n : FIRST_UNDO_STEP[journal.state];\n const { output, retired } = paths;\n for (const step of UNDO_STEPS.slice(UNDO_STEPS.indexOf(first))) {\n writeJournal(paths.runDir, {\n ...journal,\n state: \"rolling-back\",\n undo: step,\n });\n if (step === \"install\") {\n // Every old entry is in the retired tree by now, so what the output\n // holds is new. Emptied rather than removed: a directory held open\n // cannot go.\n if (!exists(retired)) removeTree(output);\n else\n for (const entry of entriesOf(output)) removeTree(join(output, entry));\n } else if (step === \"retire\") {\n if (exists(retired)) {\n if (exists(output)) moveEntries(retired, output);\n else moveTree(retired, output);\n }\n } else {\n removeTree(paths.stage);\n removeTree(retired);\n removeScratch(paths.packageRoot, journal);\n const digest =\n journal.outputDigest === undefined\n ? undefined\n : outputDigest(paths.packageRoot, output, journal.compiler ?? []);\n if (digest !== undefined && digest !== journal.outputDigest) {\n return \"superseded\";\n }\n restoreCompilerOutputs(paths, journal.compiler);\n }\n }\n return \"restored\";\n}\n\n/** Finishes a run that was installing its stage: the stage becomes the output. */\nexport function rollForward(paths: RunPaths, journal: RunJournal): void {\n const { output, stage } = paths;\n if (exists(stage)) {\n if (exists(output)) moveEntries(stage, output);\n else moveTree(stage, output);\n }\n installBuildInfo(paths.packageRoot, journal.pendingBuildInfo);\n removeTree(stage);\n removeTree(paths.retired);\n removeScratch(paths.packageRoot, journal);\n}\n\nexport type Replayed = \"rolled-back\" | \"superseded\" | \"completed\" | \"discarded\";\n\n/**\n * Brings the package back to a consistent state after a run that died, then\n * removes its run directory. A run that had not started to install its stage,\n * or had started to roll back, is undone; one installing its stage is\n * finished.\n */\nexport function replayRun(packageRoot: string, runDir: string): Replayed {\n const journal = readJournal(runDir);\n let replayed: Replayed = \"discarded\";\n if (journal !== undefined) {\n const paths = runPaths(packageRoot, runDir, journal);\n if (journal.state !== \"installing\" && journal.state !== \"committed\") {\n replayed =\n rollBack(paths, journal) === \"superseded\"\n ? \"superseded\"\n : \"rolled-back\";\n } else {\n rollForward(paths, journal);\n replayed = \"completed\";\n }\n }\n removeTree(runDir);\n return replayed;\n}\n\n/** A run's stage and retired tree beside the output named `output`. */\nexport const isScratchOf = (output: string, entry: string) =>\n entry.startsWith(`.${output}.ph-stage-`) ||\n entry.startsWith(`.${output}.ph-old-`);\n\n/**\n * Undoes or finishes every run a dead build left behind, then removes any\n * stage or retired tree beside `output` that no run claims any more: a\n * bundler of a stopped build can go on writing after its rollback. Call\n * under the lock, where no other run of this package is live.\n */\nexport function recoverStaleRuns(packageRoot: string, output: string): void {\n const runsDir = join(packageRoot, RUNS_DIRECTORY);\n for (const runId of entriesOf(runsDir)) {\n const replayed = replayRun(packageRoot, join(runsDir, runId));\n if (replayed === \"rolled-back\") {\n console.warn(\n \"⚠ An earlier build of this package stopped before it finished; its partial output was removed and the previous output restored.\",\n );\n } else if (replayed === \"superseded\") {\n console.warn(\n `⚠ An earlier build of this package stopped before it finished, and a build that wrote ${toJournalPath(packageRoot, output) || \"the package root\"} in place ran after it; the earlier build's partial output was removed and the newer files were kept.`,\n );\n } else if (replayed === \"completed\") {\n console.warn(\n \"⚠ An earlier build of this package stopped while it replaced its output; the replacement was completed.\",\n );\n }\n }\n const beside = dirname(output);\n for (const entry of entriesOf(beside)) {\n if (isScratchOf(basename(output), entry)) removeTree(join(beside, entry));\n }\n}\n","import { basename, dirname, extname, relative, resolve } from \"node:path\";\n\n/** The compiler options that say where tsc writes, as `tsc --showConfig` prints them. */\nexport type EmitOptions = {\n readonly declaration?: boolean;\n readonly composite?: boolean;\n readonly declarationDir?: string;\n readonly outDir?: string;\n readonly outFile?: string;\n readonly rootDir?: string;\n readonly tsBuildInfoFile?: string;\n readonly noEmit?: boolean;\n readonly emitDeclarationOnly?: boolean;\n readonly sourceMap?: boolean;\n readonly declarationMap?: boolean;\n};\n\nconst withoutExtension = (path: string) => path.replace(/\\.[^./\\\\]+$/, \"\");\n\nconst declares = (options: EmitOptions) =>\n options.declaration === true || options.composite === true;\n\n/**\n * Where tsc keeps the build info of `configFile`, by TypeScript's rule:\n * `tsBuildInfoFile`; else beside `outFile`; else in `outDir`, at the\n * config's place relative to `rootDir` when that is set; else beside the\n * config.\n */\nexport function buildInfoFile(\n options: EmitOptions,\n configFile: string,\n): string {\n const configDir = dirname(configFile);\n const name = `${basename(configFile, extname(configFile))}.tsbuildinfo`;\n if (options.tsBuildInfoFile !== undefined) {\n return resolve(configDir, options.tsBuildInfoFile);\n }\n if (options.outFile !== undefined) {\n return resolve(\n configDir,\n `${withoutExtension(options.outFile)}.tsbuildinfo`,\n );\n }\n if (options.outDir === undefined) return resolve(configDir, name);\n const fromRoot =\n options.rootDir === undefined\n ? \"\"\n : relative(resolve(configDir, options.rootDir), configDir);\n return resolve(configDir, options.outDir, fromRoot, name);\n}\n\n/**\n * The files tsc writes for `outFile`: the bundle and its map unless it\n * emits declarations only, then the declaration and its map when it\n * declares. None without `outFile` or with `noEmit`.\n */\nexport function outFileOutputs(\n options: EmitOptions,\n configFile: string,\n): string[] {\n if (options.outFile === undefined || options.noEmit) return [];\n const output = resolve(dirname(configFile), options.outFile);\n const files: string[] = [];\n if (!options.emitDeclarationOnly) {\n files.push(output, ...(options.sourceMap ? [`${output}.map`] : []));\n }\n if (declares(options)) {\n const declaration = `${withoutExtension(output)}.d.ts`;\n files.push(\n declaration,\n ...(options.declarationMap ? [`${declaration}.map`] : []),\n );\n }\n return files;\n}\n\n/** The declaration and output directories the options name, resolved. */\nexport function outputDirectories(\n options: EmitOptions,\n configDir: string,\n): string[] {\n return [options.declarationDir, options.outDir]\n .filter((dir): dir is string => dir !== undefined)\n .map((dir) => resolve(configDir, dir));\n}\n\n/** Where tsc writes declarations, when it writes them to a directory of their own. */\nexport function declarationDirectory(\n options: EmitOptions,\n configDir: string,\n): string | undefined {\n const dir = options.declarationDir ?? options.outDir;\n if (!dir || !declares(options)) return undefined;\n return resolve(configDir, dir);\n}\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { satisfies } from \"semver\";\n\n// Resolve extends without loading the TypeScript compiler API at runtime.\nconst configSchema = z.object({\n extends: z.union([z.string(), z.array(z.string())]).optional(),\n compilerOptions: z.record(z.string(), z.json()).optional(),\n});\n\nexport function readConfig(path: string): unknown {\n const text = readFileSync(path, \"utf8\")\n .replace(/^\\uFEFF/, \"\")\n .replace(/\"(?:\\\\.|[^\"\\\\])*\"|\\/\\/[^\\r\\n]*|\\/\\*[\\s\\S]*?\\*\\//g, (token) =>\n token.startsWith('\"') ? token : \"\",\n )\n .replace(/\"(?:\\\\.|[^\"\\\\])*\"|,\\s*(?=[}\\]])/g, (token) =>\n token.startsWith('\"') ? token : \"\",\n );\n return JSON.parse(text);\n}\n\nconst manifestSchema = z.object({\n tsconfig: z.string().optional(),\n exports: z.json().optional(),\n typesVersions: z\n .record(z.string(), z.record(z.string(), z.array(z.string())))\n .optional(),\n});\ntype ExportTarget = z.infer<ReturnType<typeof z.json>>;\n\nexport function configDirOptions(\n configFile: string,\n compilerVersion: string,\n): Record<string, ExportTarget> {\n const visiting = new Set<string>();\n const options = (path: string): Record<string, ExportTarget> => {\n if (visiting.has(path)) return {};\n visiting.add(path);\n const config = configSchema.parse(readConfig(path));\n const bases =\n typeof config.extends === \"string\"\n ? [config.extends]\n : (config.extends ?? []);\n const inherited: Record<string, ExportTarget> = {};\n for (const base of bases)\n Object.assign(\n inherited,\n options(extendedConfig(path, base, compilerVersion)),\n );\n visiting.delete(path);\n return { ...inherited, ...config.compilerOptions };\n };\n const substitute = (value: ExportTarget): ExportTarget => {\n if (typeof value === \"string\")\n return value.replaceAll(\"${configDir}\", dirname(configFile));\n if (Array.isArray(value)) return value.map(substitute);\n if (value !== null && typeof value === \"object\")\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [key, substitute(entry)]),\n );\n return value;\n };\n return Object.fromEntries(\n Object.entries(options(configFile))\n .filter(([, value]) => JSON.stringify(value).includes(\"${configDir}\"))\n .map(([key, value]) => [key, substitute(value)]),\n );\n}\n\nfunction file(path: string): string | undefined {\n return statSync(path, { throwIfNoEntry: false })?.isFile() ? path : undefined;\n}\n\nfunction jsonFile(path: string): string | undefined {\n if (path.endsWith(\".json\")) return file(path);\n const rewritten = path.replace(/\\.(?:js|ts)$/, \"\");\n return file(`${rewritten}.json`) ?? file(`${path}.json`);\n}\n\nfunction matchedPath(\n paths: Readonly<Record<string, unknown>>,\n name: string,\n exports = false,\n): { key: string; match: string } | undefined {\n if (Object.hasOwn(paths, name)) return { key: name, match: \"\" };\n const keys = Object.keys(paths).filter(\n (key) =>\n (key.includes(\"*\") && key.indexOf(\"*\") === key.lastIndexOf(\"*\")) ||\n (exports && key.endsWith(\"/\")),\n );\n keys.sort((a, b) => {\n const prefix = (key: string) =>\n key.includes(\"*\") ? key.indexOf(\"*\") + 1 : key.length;\n return (\n prefix(b) - prefix(a) ||\n (exports\n ? Number(!a.includes(\"*\")) - Number(!b.includes(\"*\")) ||\n b.length - a.length\n : 0)\n );\n });\n for (const key of keys) {\n const star = key.indexOf(\"*\");\n if (\n star !== -1 &&\n name.startsWith(key.slice(0, star)) &&\n name.endsWith(key.slice(star + 1))\n )\n return {\n key,\n match: name.slice(star, name.length - (key.length - star - 1)),\n };\n if (star === -1 && name.startsWith(key))\n return { key, match: name.slice(key.length) };\n }\n return undefined;\n}\n\nfunction exportedConfig(\n target: ExportTarget,\n directory: string,\n compilerVersion: string,\n match: string,\n pattern: boolean,\n): { path?: string } | undefined {\n if (typeof target === \"string\") {\n if (\n !target.startsWith(\"./\") ||\n (!pattern && match !== \"\" && !target.endsWith(\"/\"))\n )\n return {};\n const path = pattern ? target.replaceAll(\"*\", match) : target + match;\n if (\n path\n .slice(2)\n .split(\"/\")\n .some(\n (part) => part === \".\" || part === \"..\" || part === \"node_modules\",\n )\n )\n return {};\n const resolved = jsonFile(resolve(directory, path));\n return resolved === undefined ? {} : { path: resolved };\n }\n if (target === null) return {};\n if (Array.isArray(target)) {\n if (target.length === 0) return {};\n for (const entry of target) {\n const result = exportedConfig(\n entry,\n directory,\n compilerVersion,\n match,\n pattern,\n );\n if (result !== undefined) return result;\n }\n } else if (typeof target === \"object\") {\n for (const [condition, entry] of Object.entries(target))\n if (\n [\"types\", \"require\", \"node\", \"default\"].includes(condition) ||\n (condition.startsWith(\"types@\") &&\n satisfies(compilerVersion, condition.slice(6)))\n ) {\n const result = exportedConfig(\n entry,\n directory,\n compilerVersion,\n match,\n pattern,\n );\n if (result !== undefined) return result;\n }\n } else return {};\n return undefined;\n}\n\nfunction extendedConfig(\n configFile: string,\n input: string,\n compilerVersion: string,\n): string {\n const specifier = input.replaceAll(\"\\\\\", \"/\");\n if (\n specifier.startsWith(\"./\") ||\n specifier.startsWith(\"../\") ||\n isAbsolute(specifier)\n ) {\n const path = resolve(dirname(configFile), specifier);\n const found =\n file(path) ??\n (!path.endsWith(\".json\") ? file(`${path}.json`) : undefined);\n if (found !== undefined) return found;\n } else {\n const parts = specifier.split(\"/\");\n const nameLength = specifier.startsWith(\"@\") ? 2 : 1;\n const packageName = parts.slice(0, nameLength).join(\"/\");\n const subpath = parts.slice(nameLength).join(\"/\");\n const manifestAt = (directory: string) => {\n const path = join(directory, \"package.json\");\n if (!existsSync(path)) return undefined;\n return manifestSchema.parse(readConfig(path));\n };\n const fromDirectory = (\n directory: string,\n pkg: ReturnType<typeof manifestAt>,\n ): string | undefined => {\n const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(\n ([range]) => satisfies(compilerVersion, range),\n )?.[1];\n const entry = pkg?.tsconfig\n ? resolve(directory, pkg.tsconfig)\n : join(directory, \"tsconfig\");\n if (versionPaths !== undefined) {\n const match = matchedPath(\n versionPaths,\n entry.slice(directory.length + 1),\n );\n if (match !== undefined)\n for (const path of versionPaths[match.key] ?? []) {\n const found = jsonFile(\n resolve(directory, path.replace(\"*\", match.match)),\n );\n if (found !== undefined) return found;\n }\n }\n return (\n (pkg?.tsconfig ? jsonFile(entry) : undefined) ??\n jsonFile(join(directory, \"tsconfig\"))\n );\n };\n for (const modules of createRequire(configFile).resolve.paths(specifier) ??\n []) {\n const directory = join(modules, packageName);\n const candidate = join(modules, specifier);\n const nested = manifestAt(candidate);\n const pkg = subpath === \"\" ? nested : manifestAt(directory);\n if (subpath !== \"\" && nested !== undefined && !pkg?.exports) {\n const found = jsonFile(candidate) ?? fromDirectory(candidate, nested);\n if (found !== undefined) return found;\n continue;\n }\n if (pkg?.exports) {\n const exports = pkg.exports;\n const key = subpath === \"\" ? \".\" : `./${subpath}`;\n let target: ExportTarget | undefined;\n let match = \"\";\n let pattern = false;\n if (\n typeof exports === \"object\" &&\n !Array.isArray(exports) &&\n Object.keys(exports).some((key) => key.startsWith(\".\"))\n ) {\n const matched = matchedPath(exports, key, true);\n if (matched !== undefined) {\n target = exports[matched.key];\n match = matched.match;\n pattern = matched.key.includes(\"*\");\n }\n } else if (key === \".\") target = exports;\n const found =\n target === undefined\n ? undefined\n : exportedConfig(target, directory, compilerVersion, match, pattern)\n ?.path;\n if (found !== undefined) return found;\n continue;\n }\n const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(\n ([range]) => satisfies(compilerVersion, range),\n )?.[1];\n if (subpath !== \"\" && versionPaths !== undefined) {\n const match = matchedPath(versionPaths, subpath);\n if (match !== undefined)\n for (const path of versionPaths[match.key] ?? []) {\n const found = jsonFile(\n resolve(directory, path.replace(\"*\", match.match)),\n );\n if (found !== undefined) return found;\n }\n }\n const found = jsonFile(candidate) ?? fromDirectory(candidate, pkg);\n if (found !== undefined) return found;\n }\n }\n throw new Error(\n `The extended TypeScript config ${JSON.stringify(specifier)} could not be resolved from ${JSON.stringify(configFile)}.`,\n );\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n// tsc ends its lines with \\r\\n on Windows.\nconst lines = (stdout: string) => stdout.split(/\\r?\\n/);\n\nexport function listedFiles(stdout = \"\", directory = \".\"): string[] {\n return lines(stdout)\n .map((line) => line.trim())\n .map((line) => resolve(directory, line))\n .filter((line) => existsSync(line) && statSync(line).isFile());\n}\n\nexport function explainedRoots(stdout: string, directory: string): string[] {\n const roots: string[] = [];\n let file: string | undefined;\n for (const line of lines(stdout)) {\n if (\n line !== \"\" &&\n line === line.trim() &&\n /\\.(?:[cm]?[jt]sx?|json)$/i.test(line)\n ) {\n const path = resolve(directory, line);\n file = statSync(path, { throwIfNoEntry: false })?.isFile()\n ? path\n : undefined;\n } else if (\n file !== undefined &&\n /Root file specified|Part of 'files' list|Matched by (default )?include pattern/.test(\n line,\n )\n ) {\n roots.push(file);\n }\n }\n return roots;\n}\n","import { SpawnError, spawnAsync } from \"@powerhousedao/shared/clis\";\nimport { mkdtempSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport type { Agent } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector\";\nimport { z } from \"zod\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport { canonicalConfigFile, toPosixPath } from \"./paths.js\";\nimport {\n buildInfoFile,\n outFileOutputs,\n outputDirectories,\n} from \"../compiler-output/emit.js\";\nimport { configDirOptions, readConfig } from \"./config-inputs.js\";\nimport { explainedRoots, listedFiles } from \"./compiler-output.js\";\n\ntype CommandResult = {\n readonly ok: boolean;\n readonly output: string;\n};\n\nasync function runLocal(\n packageRoot: string,\n agent: Agent,\n argv: readonly string[],\n): Promise<CommandResult> {\n const command = resolveCommand(agent, \"execute-local\", [...argv]);\n if (command === null)\n return {\n ok: false,\n output: `${argv[0]} is not installed in this package`,\n };\n try {\n // TypeScript uses PWD to spell paths even when cwd is canonical.\n const output = await spawnAsync(command.command, command.args, {\n cwd: packageRoot,\n env: { ...process.env, PWD: packageRoot },\n });\n return { ok: true, output };\n } catch (error) {\n return {\n ok: false,\n output:\n error instanceof SpawnError && error.stdout.length !== 0\n ? error.stdout\n : error instanceof Error\n ? error.message\n : `${argv[0]} failed`,\n };\n }\n}\n\nconst configSchema = z.object({\n compilerOptions: z.looseObject({\n declaration: z.boolean().optional(),\n composite: z.boolean().optional(),\n incremental: z.boolean().optional(),\n declarationDir: z.string().optional(),\n outDir: z.string().optional(),\n rootDir: z.string().optional(),\n noEmit: z.boolean().optional(),\n emitDeclarationOnly: z.boolean().optional(),\n sourceMap: z.boolean().optional(),\n declarationMap: z.boolean().optional(),\n jsx: z.string().optional(),\n outFile: z.string().optional(),\n tsBuildInfoFile: z.string().optional(),\n resolveJsonModule: z.boolean().optional(),\n }),\n references: z.array(z.object({ path: z.string() })).optional(),\n});\n\nexport type CompilerProject = {\n readonly diagnostic?: string;\n readonly configFile: string;\n readonly options: z.infer<typeof configSchema>[\"compilerOptions\"];\n readonly sources: readonly string[];\n readonly external: boolean;\n readonly emitRoot: string;\n readonly references: readonly string[];\n};\n\n/** What `tsc --build` on the package's root config reads and writes. */\nexport type CompilePlan = {\n /** A diagnostic tsc reports for a build it still runs, such as TS18003 for a project with no inputs. */\n readonly preflightTypeError?: string;\n /** The root project, then the projects it references. */\n readonly projects: readonly [CompilerProject, ...CompilerProject[]];\n /** What the build writes, relative to the package root. */\n readonly outputs: {\n readonly directories: readonly string[];\n readonly files: readonly string[];\n };\n};\nexport type CompilePreflight =\n | { readonly ok: true; readonly plan: CompilePlan }\n | { readonly ok: false; readonly summary: string };\n\nclass CompilerDiagnostic extends Error {\n constructor(\n summary: string,\n readonly configFile: string,\n readonly noWrites: boolean,\n ) {\n super(summary);\n }\n}\n\nfunction projectConfigFile(path: string): string {\n const entry = statSync(path, { throwIfNoEntry: false });\n return canonicalConfigFile(\n entry?.isDirectory() || (entry === undefined && !path.endsWith(\".json\"))\n ? join(path, \"tsconfig.json\")\n : path,\n );\n}\n\nexport function commonSourceDirectory(\n files: readonly string[],\n fallback: string,\n): string {\n let root = files.length === 0 ? fallback : dirname(files[0] ?? fallback);\n for (const file of files)\n while (pathWithin(root, file) === null) {\n const parent = dirname(root);\n if (parent === root)\n throw new Error(\n \"TypeScript sources on different drives have no common source directory.\",\n );\n root = parent;\n }\n return root;\n}\n\nfunction outputFiles(\n project: CompilerProject,\n emitsBuildInfoInBuildMode: boolean,\n): string[] {\n const { options, sources, configFile } = project;\n const directory = dirname(configFile);\n const root = project.emitRoot;\n const files =\n emitsBuildInfoInBuildMode ||\n options.composite ||\n options.incremental ||\n options.tsBuildInfoFile !== undefined\n ? [buildInfoFile(options, configFile)]\n : [];\n if (options.noEmit) return files;\n if (options.outFile !== undefined)\n return [...files, ...outFileOutputs(options, configFile)];\n const declares = options.declaration === true || options.composite === true;\n for (const source of sources) {\n if (/\\.json$/i.test(source)) {\n if (!options.emitDeclarationOnly) {\n const inside = pathWithin(root, source);\n files.push(\n options.outDir === undefined || inside === null\n ? source\n : resolve(directory, options.outDir, inside),\n );\n }\n continue;\n }\n const suffix = /\\.[cm]?[jt]sx?$/i;\n const jsExtension = /\\.[cm][jt]s$/i.test(source)\n ? source.slice(-4).replace(\"t\", \"j\")\n : options.jsx === \"preserve\" && /[jt]sx$/i.test(source)\n ? \".jsx\"\n : \".js\";\n const declarationExtension = /\\.[cm][jt]s$/i.test(source)\n ? source.slice(-4).replace(/j/, \"t\").replace(\".\", \".d.\")\n : \".d.ts\";\n const inRoot = pathWithin(root, source);\n const destination = (out: string | undefined, extension: string): string =>\n out === undefined || inRoot === null\n ? source.replace(suffix, extension)\n : resolve(directory, out, inRoot.replace(suffix, extension));\n if (!options.emitDeclarationOnly) {\n const js = destination(options.outDir, jsExtension);\n files.push(js, ...(options.sourceMap ? [js + \".map\"] : []));\n }\n if (declares) {\n const declaration = destination(\n options.declarationDir ?? options.outDir,\n declarationExtension,\n );\n files.push(\n declaration,\n ...(options.declarationMap ? [declaration + \".map\"] : []),\n );\n }\n }\n return files;\n}\n\n/**\n * Reads the package's project graph through its own `tsc` and predicts what\n * `tsc --build` writes, without writing. Refuses a build that would write\n * outside the package.\n */\nexport async function prepareCompile(\n packageRoot: string,\n agent: Agent,\n): Promise<CompilePreflight> {\n try {\n const version = await runLocal(packageRoot, agent, [\"tsc\", \"--version\"]);\n const match = /Version (\\d+)\\.(\\d+)/.exec(version.output);\n if (match === null)\n throw new Error(\n \"The installed TypeScript version could not be resolved.\",\n );\n const major = Number(match[1]);\n const minor = Number(match[2]);\n // From 5.6, `tsc --build` writes a .tsbuildinfo for every project it\n // builds; from 6.0, rootDir defaults to the config's directory.\n const emitsBuildInfoInBuildMode = major > 5 || (major === 5 && minor >= 6);\n const defaultsRootDirToConfig = major >= 6;\n const projects = await readProjectGraph(\n packageRoot,\n agent,\n join(packageRoot, \"tsconfig.json\"),\n defaultsRootDirToConfig,\n /Version (\\S+)/.exec(version.output)?.[1] ?? `${major}.${minor}.0`,\n );\n return {\n ok: true,\n plan: checkedCompilePlan(\n packageRoot,\n projects,\n emitsBuildInfoInBuildMode,\n ),\n };\n } catch (error) {\n if (\n error instanceof CompilerDiagnostic &&\n error.noWrites &&\n error.configFile === projectConfigFile(join(packageRoot, \"tsconfig.json\"))\n ) {\n const checked = checkedCompilePlan(\n packageRoot,\n [\n {\n configFile: error.configFile,\n options: { noEmit: true },\n sources: [],\n external: false,\n emitRoot: packageRoot,\n references: [],\n },\n ],\n false,\n );\n return {\n ok: true,\n plan: { ...checked, preflightTypeError: error.message },\n };\n }\n return {\n ok: false,\n summary:\n error instanceof Error\n ? error.message\n : \"The TypeScript output layout could not be resolved.\",\n };\n }\n}\n\nasync function readProjectGraph(\n packageRoot: string,\n agent: Agent,\n configPath: string,\n defaultsRootDirToConfig: boolean,\n compilerVersion: string,\n): Promise<CompilerProject[]> {\n const projects: CompilerProject[] = [];\n const visited = new Set<string>();\n const rootConfig = projectConfigFile(join(packageRoot, \"tsconfig.json\"));\n const visit = async (path: string): Promise<void> => {\n const configFile = projectConfigFile(path);\n if (visited.has(configFile)) return;\n visited.add(configFile);\n let shown = await runLocal(packageRoot, agent, [\n \"tsc\",\n \"-p\",\n configFile,\n \"--showConfig\",\n ]);\n let diagnostic: string | undefined;\n if (\n !shown.ok &&\n /TS18003/.test(shown.output) &&\n pathWithin(packageRoot, configFile) !== null\n ) {\n diagnostic = shown.output;\n shown = await showEmptyProjectConfig(\n packageRoot,\n agent,\n configFile,\n compilerVersion,\n );\n }\n if (!shown.ok) {\n throw new CompilerDiagnostic(\n shown.output,\n configFile,\n statSync(configFile, { throwIfNoEntry: false }) === undefined,\n );\n }\n const config = configSchema.parse(JSON.parse(shown.output));\n const project = await refreshProject(\n packageRoot,\n agent,\n {\n ...(diagnostic !== undefined && { diagnostic }),\n configFile,\n options: config.compilerOptions,\n sources: [],\n references: (config.references ?? []).map((reference) =>\n projectConfigFile(resolve(dirname(configFile), reference.path)),\n ),\n emitRoot: dirname(configFile),\n external:\n configFile !== rootConfig &&\n pathWithin(packageRoot, configFile) === null,\n },\n defaultsRootDirToConfig,\n );\n projects.push(project);\n for (const reference of project.references) await visit(reference);\n };\n await visit(configPath);\n return projects;\n}\n\nasync function showEmptyProjectConfig(\n packageRoot: string,\n agent: Agent,\n configFile: string,\n compilerVersion: string,\n): Promise<CommandResult> {\n const config = z\n .object({ references: configSchema.shape.references })\n .parse(readConfig(configFile));\n const directory = realPathThroughExistingParent(\n mkdtempSync(join(tmpdir(), \".ph-preflight-\")),\n );\n try {\n const probe = join(directory, \"tsconfig.json\");\n writeFileSync(\n probe,\n JSON.stringify({\n extends: configFile,\n compilerOptions: configDirOptions(configFile, compilerVersion),\n files: [configFile],\n include: [],\n references: config.references?.map(({ path }) => ({\n path: resolve(dirname(configFile), path),\n })),\n }),\n );\n const shown = await runLocal(packageRoot, agent, [\n \"tsc\",\n \"-p\",\n probe,\n \"--showConfig\",\n ]);\n if (!shown.ok) return shown;\n const resolved = configSchema.parse(JSON.parse(shown.output));\n const options = resolved.compilerOptions;\n const rebase = (path: string): string => {\n const absolute = resolve(directory, path);\n const inProbe = pathWithin(directory, absolute);\n return inProbe === null\n ? absolute\n : resolve(dirname(configFile), inProbe);\n };\n // showConfig rebases inherited paths to the probe directory.\n for (const key of [\n \"outDir\",\n \"declarationDir\",\n \"rootDir\",\n \"outFile\",\n \"tsBuildInfoFile\",\n ] as const) {\n const path = options[key];\n if (path !== undefined) options[key] = rebase(path);\n }\n return { ...shown, output: JSON.stringify(resolved) };\n } finally {\n rmSync(directory, { recursive: true, force: true });\n }\n}\n\nasync function listProjectFiles(\n packageRoot: string,\n agent: Agent,\n configFile: string,\n preserveSymlinks = false,\n) {\n const listed = await runLocal(packageRoot, agent, [\n \"tsc\",\n \"-p\",\n configFile,\n \"--listFilesOnly\",\n \"--explainFiles\",\n \"--pretty\",\n \"false\",\n ...(preserveSymlinks ? [\"--preserveSymlinks\", \"true\"] : []),\n ]);\n return {\n ...listed,\n files: listedFiles(listed.output, packageRoot),\n rootFiles: explainedRoots(listed.output, packageRoot),\n };\n}\n\nasync function refreshProject(\n packageRoot: string,\n agent: Agent,\n project: CompilerProject,\n defaultsRootDirToConfig: boolean,\n): Promise<CompilerProject> {\n const listed = await listProjectFiles(packageRoot, agent, project.configFile);\n const { files, rootFiles } = listed;\n if (!listed.ok && files.length === 0 && !/TS18003/.test(listed.output)) {\n throw new CompilerDiagnostic(listed.output, project.configFile, false);\n }\n const roots = new Set(\n rootFiles.map((file) => realPathThroughExistingParent(file)),\n );\n let sources = files.filter(\n (file) =>\n (/\\.[cm]?[jt]sx?$/i.test(file) ||\n (project.options.resolveJsonModule === true &&\n /\\.json$/i.test(file))) &&\n !/\\.d\\.[cm]?ts$/i.test(file) &&\n (roots.has(realPathThroughExistingParent(file)) ||\n !toPosixPath(file).includes(\"/node_modules/\")),\n );\n if (\n sources.some(\n (file) =>\n !roots.has(realPathThroughExistingParent(file)) &&\n pathWithin(packageRoot, realPathThroughExistingParent(file)) === null,\n )\n ) {\n const preserved = await listProjectFiles(\n packageRoot,\n agent,\n project.configFile,\n true,\n );\n const spellings = preserved.files;\n if (spellings.length === 0)\n throw new Error(\n \"tsc could not classify external library inputs without writing them.\",\n );\n const local = new Set(\n spellings\n .filter(\n (file) =>\n roots.has(realPathThroughExistingParent(file)) ||\n !toPosixPath(file).includes(\"/node_modules/\"),\n )\n .map((path) => realPathThroughExistingParent(path)),\n );\n const libraries = new Set(\n spellings\n .filter((file) => toPosixPath(file).includes(\"/node_modules/\"))\n .map((path) => realPathThroughExistingParent(path)),\n );\n sources = sources.filter(\n (file) =>\n !libraries.has(realPathThroughExistingParent(file)) ||\n local.has(realPathThroughExistingParent(file)),\n );\n }\n return {\n ...project,\n ...(/TS18003/.test(listed.output) && {\n diagnostic: listed.output,\n }),\n sources,\n emitRoot: resolve(\n dirname(project.configFile),\n project.options.rootDir ??\n (project.options.composite || defaultsRootDirToConfig\n ? \".\"\n : commonSourceDirectory(sources, dirname(project.configFile))),\n ),\n };\n}\n\nfunction checkedCompilePlan(\n packageRoot: string,\n projects: readonly CompilerProject[],\n emitsBuildInfoInBuildMode: boolean,\n): CompilePlan {\n const directories = new Set<string>();\n const files = new Set<string>();\n for (const project of projects) {\n if (project.external) continue;\n if (!project.options.noEmit) {\n for (const path of outputDirectories(\n project.options,\n dirname(project.configFile),\n )) {\n const target = realPathThroughExistingParent(path);\n if (pathWithin(packageRoot, target) === null)\n throw new Error(\n `tsc would write to ${JSON.stringify(path)} outside the package.`,\n );\n if (\n !project.sources.some(\n (file) =>\n pathWithin(target, realPathThroughExistingParent(file)) !== null,\n )\n ) {\n if (pathWithin(packageRoot, path) !== null)\n directories.add(toPosixPath(relative(packageRoot, path)));\n directories.add(toPosixPath(relative(packageRoot, target)));\n }\n }\n }\n for (const path of outputFiles(project, emitsBuildInfoInBuildMode)) {\n if (/\\.json$/i.test(path) && project.sources.includes(path)) continue;\n const target = realPathThroughExistingParent(path);\n if (pathWithin(packageRoot, target) === null)\n throw new Error(\n `tsc would write to ${JSON.stringify(path)} outside the package.`,\n );\n if (pathWithin(packageRoot, path) !== null)\n files.add(toPosixPath(relative(packageRoot, path)));\n files.add(toPosixPath(relative(packageRoot, target)));\n }\n }\n const root = projects.at(0);\n const references = projects.slice(1);\n if (root === undefined)\n throw new Error(\"The root TypeScript project could not be resolved.\");\n return {\n ...(root.diagnostic !== undefined && {\n preflightTypeError: root.diagnostic,\n }),\n projects: [root, ...references],\n outputs: {\n directories: [...directories].sort(),\n files: [...files].sort(),\n },\n };\n}\n","import { dirname } from \"node:path\";\nimport { pathWithin } from \"@powerhousedao/shared/clis/real-paths\";\nimport {\n buildInfoFile,\n type EmitOptions,\n outFileOutputs,\n outputDirectories,\n} from \"../../compiler-output/emit.js\";\n\n/** A path tsc writes that the build restores when it does not finish. */\nexport type CompilerOutput = {\n readonly path: string;\n readonly kind: \"directory\" | \"build-info\" | \"file\";\n};\n\nconst optionalString = (value: unknown) =>\n typeof value === \"string\" ? value : undefined;\nconst optionalBoolean = (value: unknown) =>\n typeof value === \"boolean\" ? value : undefined;\n\nexport type ShownConfig = {\n readonly options: EmitOptions & { readonly incremental?: boolean };\n /** As printed: with no `exclude` of its own, tsc's default, which names the output directories. */\n readonly exclude: readonly string[] | undefined;\n readonly references: readonly string[];\n};\n\nconst strings = (value: unknown) =>\n Array.isArray(value) && value.every((entry) => typeof entry === \"string\")\n ? (value as string[])\n : undefined;\n\n/** The config in `tsc --showConfig` output, or undefined when it is not JSON. */\nexport function parseShownConfig(text: string): ShownConfig | undefined {\n let shown: unknown;\n try {\n shown = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof shown !== \"object\" || shown === null) return undefined;\n const { compilerOptions, exclude, references } = shown as Record<\n string,\n unknown\n >;\n return {\n options: emitOptions(compilerOptions),\n exclude: strings(exclude),\n references: Array.isArray(references)\n ? references.flatMap((reference: unknown) => {\n const path = (reference as { path?: unknown } | null)?.path;\n return typeof path === \"string\" ? [path] : [];\n })\n : [],\n };\n}\n\nfunction emitOptions(options: unknown): ShownConfig[\"options\"] {\n if (typeof options !== \"object\" || options === null) return {};\n const record = options as Record<string, unknown>;\n return {\n declaration: optionalBoolean(record.declaration),\n composite: optionalBoolean(record.composite),\n incremental: optionalBoolean(record.incremental),\n declarationDir: optionalString(record.declarationDir),\n outDir: optionalString(record.outDir),\n outFile: optionalString(record.outFile),\n rootDir: optionalString(record.rootDir),\n tsBuildInfoFile: optionalString(record.tsBuildInfoFile),\n noEmit: optionalBoolean(record.noEmit),\n emitDeclarationOnly: optionalBoolean(record.emitDeclarationOnly),\n sourceMap: optionalBoolean(record.sourceMap),\n declarationMap: optionalBoolean(record.declarationMap),\n };\n}\n\n/**\n * What the root project's tsc writes inside the package, for the build to\n * snapshot and restore: its build info first, then the files `outFile`\n * writes, then its declaration and output directories, the build's own\n * output directory or one holding it included. A directory holding\n * `buildDirectory`, where the build keeps its runs and their snapshots, is\n * left out and unprotected, as without staging: a snapshot of it would copy\n * itself. This says what to protect, not what to carry into the stage.\n */\nexport function compilerOutputInventory(\n options: EmitOptions,\n at: {\n readonly configFile: string;\n readonly packageRoot: string;\n readonly buildDirectory: string;\n },\n): CompilerOutput[] {\n const inPackage = (path: string) => Boolean(pathWithin(at.packageRoot, path));\n const directories = outputDirectories(options, dirname(at.configFile))\n .filter(inPackage)\n .filter((dir) => pathWithin(dir, at.buildDirectory) === null);\n return [\n ...[buildInfoFile(options, at.configFile)]\n .filter(inPackage)\n .map((path) => ({ path, kind: \"build-info\" as const })),\n ...outFileOutputs(options, at.configFile)\n .filter(inPackage)\n .map((path) => ({ path, kind: \"file\" as const })),\n ...[...new Set(directories)].map((path) => ({\n path,\n kind: \"directory\" as const,\n })),\n ];\n}\n","import { lstatSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { Agent } from \"package-manager-detector\";\nimport {\n buildInfoFile,\n type EmitOptions,\n outFileOutputs,\n} from \"../../compiler-output/emit.js\";\nimport { prepareCompile } from \"../../definitions/compiler.js\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport {\n type CompilerOutput,\n compilerOutputInventory,\n type ShownConfig,\n} from \"./inventory.js\";\nfunction writesBesideSources(options: EmitOptions): boolean {\n if (options.noEmit || options.outFile !== undefined) return false;\n if (options.outDir !== undefined) return false;\n const declares = options.declaration === true || options.composite === true;\n return !options.emitDeclarationOnly || (declares && !options.declarationDir);\n}\n\ntype InventoryPlace = Parameters<typeof compilerOutputInventory>[1];\n\nconst redirectable = ({ references, options }: ShownConfig) =>\n references.length === 0 &&\n Boolean(options.incremental || options.composite || options.tsBuildInfoFile);\n\nexport async function compilerOutputs(\n config: ShownConfig,\n at: InventoryPlace & {\n readonly agent: Agent;\n readonly output: string;\n },\n): Promise<CompilerOutput[]> {\n const root = compilerOutputInventory(config.options, at);\n const real = (path: string) => realPathThroughExistingParent(path);\n const packageIdentity = real(at.packageRoot);\n const inPackage = (path: string) =>\n pathWithin(packageIdentity, real(path)) !== null;\n // A reference to another package is that package's build: its outputs are\n // not this package's to restore, and reading its project graph spawns tsc\n // once or twice per project it reaches.\n const referencesInPackage = config.references.some((reference) =>\n inPackage(resolve(dirname(at.configFile), reference)),\n );\n const holdsOutput = (dir: string) =>\n pathWithin(real(dir), at.output) !== null;\n const protectsOutput = root.some(\n ({ kind, path }) =>\n kind === \"directory\" &&\n holdsOutput(path) &&\n !(redirectable(config) && real(path) === at.output),\n );\n if (\n !referencesInPackage &&\n !writesBesideSources(config.options) &&\n !protectsOutput\n ) {\n return root;\n }\n const prepared = await prepareCompile(at.packageRoot, at.agent);\n if (!prepared.ok) return root;\n const { directories, files } = prepared.plan.outputs;\n const absolute = (path: string) => resolve(at.packageRoot, path);\n const owned = (path: string) =>\n inPackage(path) && pathWithin(path, at.buildDirectory) === null;\n const dirs = directories\n .map(absolute)\n .filter((dir) => owned(dir) && !holdsOutput(dir));\n return [\n ...files\n .map(absolute)\n .filter(\n (file) =>\n owned(file) && !dirs.some((dir) => pathWithin(dir, file) !== null),\n )\n .map((path) => ({\n path,\n kind: path.endsWith(\".tsbuildinfo\")\n ? (\"build-info\" as const)\n : (\"file\" as const),\n }))\n .sort(\n (a, b) =>\n Number(b.kind === \"build-info\") - Number(a.kind === \"build-info\"),\n ),\n ...dirs.map((path) => ({ path, kind: \"directory\" as const })),\n ];\n}\n\nexport type CompilerRedirect = {\n readonly compilerOptions: Readonly<Record<string, string>>;\n readonly exclude: readonly string[] | undefined;\n readonly pendingBuildInfo:\n | { readonly path: string; readonly target: string }\n | undefined;\n readonly staged: readonly string[];\n};\n\nexport function redirectRootProject(\n config: ShownConfig,\n at: {\n readonly configFile: string;\n readonly packageRoot: string;\n readonly output: string;\n readonly stage: string;\n readonly pending: (target: string) => string;\n },\n): CompilerRedirect | undefined {\n if (!redirectable(config)) return undefined;\n const { options } = config;\n const configDir = dirname(at.configFile);\n const real = (path: string) => realPathThroughExistingParent(path);\n const inOutput = (path: string) => pathWithin(at.output, real(path));\n const compilerOptions: Record<string, string> = {};\n const staged: string[] = [];\n for (const key of [\"declarationDir\", \"outDir\", \"outFile\"] as const) {\n const value = options[key];\n if (value === undefined || (key === \"outFile\" && options.noEmit)) continue;\n const rel = inOutput(resolve(configDir, value));\n if (rel === null) continue;\n compilerOptions[key] = join(at.stage, rel);\n staged.push(\n ...(key === \"outFile\"\n ? outFileOutputs(options, at.configFile)\n : [resolve(configDir, value)]\n ).map(real),\n );\n }\n const target = buildInfoFile(options, at.configFile);\n const rel = inOutput(target);\n let pendingBuildInfo: CompilerRedirect[\"pendingBuildInfo\"];\n if (rel !== null) {\n compilerOptions.tsBuildInfoFile = join(at.stage, rel);\n staged.push(real(target));\n } else if (\n pathWithin(at.packageRoot, target) !== null &&\n // A copy of the link would write through to the live file; tsc writes\n // it in place instead, and the run snapshots what the link points to.\n !lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()\n ) {\n pendingBuildInfo = { path: at.pending(target), target };\n compilerOptions.tsBuildInfoFile = pendingBuildInfo.path;\n staged.push(real(target));\n } else {\n compilerOptions.tsBuildInfoFile = target;\n }\n return { compilerOptions, exclude: config.exclude, pendingBuildInfo, staged };\n}\n","import {\n lstatSync,\n mkdirSync,\n statSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, dirname, extname, join } from \"node:path\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport {\n CannotStage,\n cloneTree,\n creating,\n exists,\n isHeldOpen,\n linkTree,\n moveEntries,\n openDirectories,\n removeTree,\n renamePatiently,\n unstageableEntryIn,\n} from \"./files.js\";\nimport { type CompilerRedirect, redirectRootProject } from \"./compiler.js\";\nimport type { CompilerOutput, ShownConfig } from \"./inventory.js\";\nimport { BUILD_DIRECTORY } from \"../../build-control.js\";\nimport {\n type CompilerSnapshot,\n fromJournalPath,\n type JournalState,\n type RunJournal,\n RUNS_DIRECTORY,\n toJournalPath,\n writeJournal,\n} from \"./journal.js\";\nimport type { BuildLock } from \"./lock.js\";\nimport {\n installBuildInfo,\n isScratchOf,\n outputDigest,\n rollBack,\n type RunPaths,\n runPaths,\n} from \"./recovery.js\";\n\nconst isUnreadable = (error: unknown) => {\n const code = (error as { code?: unknown } | null)?.code;\n return code === \"EACCES\" || code === \"EPERM\";\n};\n\n/** `path` is `dir` or holds it. */\nconst isOrHolds = (path: string, dir: string) => pathWithin(path, dir) !== null;\n\n/** The outermost directory of `path`, inside the package, that does not exist. */\nfunction outermostMissing(packageRoot: string, path: string): string {\n let missing = path;\n for (\n let parent = dirname(path);\n pathWithin(packageRoot, parent) && !exists(parent);\n parent = dirname(parent)\n ) {\n missing = parent;\n }\n return missing;\n}\n\n/** A path as messages name it: from the package root, which is named so. */\nexport const shownPath = (packageRoot: string, path: string) =>\n toJournalPath(packageRoot, path) || \"the package root\";\n\nexport const scratchBeside = (path: string, kind: string, runId: string) =>\n join(dirname(path), `.${basename(path)}.ph-${kind}-${runId}`);\n\nexport type CompilerRun = {\n readonly configFile: string;\n readonly config: ShownConfig;\n readonly outputs: readonly CompilerOutput[];\n};\n\n/** One `ph build` of one package, as the steps and the step runner see it. */\nexport type BuildSession = {\n /** The output directory's real path, for comparing it with other paths. */\n readonly output: string;\n /** The output is `<package>/dist`, where the stylesheet and manifest copy belong. */\n readonly writesPackageDist: boolean;\n /** The directory every output write targets. */\n stage(): string;\n /**\n * Call before tsc runs, with what it is about to write. Returns the\n * generated config tsc builds instead when it can write into the stage.\n */\n prepareCompiler(compiler: CompilerRun): Promise<string | undefined>;\n /** Call once tsc has written, whatever it reported, before any bundle step. */\n compilerOutputsWritten(): void;\n commit(): void;\n /** Releases the lock. Call once nothing of this build runs any more. */\n close(): void;\n /**\n * Releases the lock and keeps the run, for a process a signal is about to\n * end: the next build replays the run's journal.\n */\n releaseLock(): void;\n rollback(): void;\n /**\n * Notes that the process was told to stop. Synchronous, for a signal\n * handler; the step runner stops the build once the running step settles.\n */\n cancel(signal: NodeJS.Signals): void;\n stopped(): NodeJS.Signals | undefined;\n /**\n * Runs `stop` synchronously inside `cancel`, so work outside this process,\n * such as a child, ends before a signal handler lets the process exit.\n * Returns the unregister function.\n */\n onCancel(stop: () => void): () => void;\n};\n\ntype Status = \"open\" | \"committed\" | \"rolled-back\";\n\n/**\n * One `ph build` of one package: the output is written to a stage beside the\n * output directory and replaces it only on commit. Until then the previous\n * output and the compiler outputs tsc rewrote can be put back, by `rollback`\n * in this process or, after a crash, by the next build.\n */\nexport class StagedBuildSession implements BuildSession {\n readonly runId: string;\n readonly packageRoot: string;\n readonly output: string;\n readonly writesPackageDist: boolean;\n readonly runDir: string;\n private readonly paths: RunPaths;\n private readonly lock: BuildLock;\n private journal: RunJournal;\n private status: Status = \"open\";\n private stoppedBy: NodeJS.Signals | undefined;\n private seeded = false;\n private compilerWritten = false;\n private restored = false;\n private redirected: readonly string[] = [];\n private readonly cleanedEntries: readonly string[];\n private readonly linkCleanedEntries: boolean;\n\n private constructor(fields: {\n runId: string;\n packageRoot: string;\n output: string;\n writesPackageDist: boolean;\n cleanedEntries: readonly string[];\n linkCleanedEntries: boolean;\n runDir: string;\n lock: BuildLock;\n journal: RunJournal;\n }) {\n this.runId = fields.runId;\n this.packageRoot = fields.packageRoot;\n this.output = fields.output;\n this.writesPackageDist = fields.writesPackageDist;\n this.cleanedEntries = fields.cleanedEntries;\n this.linkCleanedEntries = fields.linkCleanedEntries;\n this.runDir = fields.runDir;\n this.lock = fields.lock;\n this.journal = fields.journal;\n this.paths = runPaths(fields.packageRoot, fields.runDir, fields.journal);\n }\n\n /**\n * Starts a run under `lock`, which the caller took and recovered stale\n * runs under; the caller still releases it when this throws. The stage\n * sits beside `logical`, the output as given, so the paths the bundlers\n * record from it are the ones an unstaged build records.\n */\n static async open(options: {\n readonly packageRoot: string;\n readonly logical: string;\n readonly output: string;\n readonly writesPackageDist: boolean;\n /** Top-level entries of the output a step empties before it writes them. */\n readonly cleanedEntries: readonly string[];\n /** Seed those entries by hard link: no step writes them before that. */\n readonly linkCleanedEntries: boolean;\n readonly runId: string;\n readonly lock: BuildLock;\n }): Promise<StagedBuildSession> {\n const { packageRoot, logical, runId } = options;\n const runDir = join(packageRoot, RUNS_DIRECTORY, runId);\n try {\n const beside = (kind: string) => scratchBeside(logical, kind, runId);\n const journal: RunJournal = {\n format: 1,\n runId,\n pid: process.pid,\n state: \"building\",\n undo: null,\n output: toJournalPath(packageRoot, logical),\n stage: toJournalPath(packageRoot, beside(\"stage\")),\n retired: toJournalPath(packageRoot, beside(\"old\")),\n compiler: null,\n };\n await creating(BUILD_DIRECTORY, () => {\n mkdirSync(runDir, { recursive: true });\n writeJournal(runDir, journal);\n });\n await creating(shownPath(packageRoot, dirname(logical)), () =>\n mkdirSync(beside(\"stage\"), { recursive: true }),\n );\n return new StagedBuildSession({ ...options, runDir, journal });\n } catch (error) {\n removeTree(runDir);\n throw error;\n }\n }\n\n private assertOpen(): void {\n if (this.status !== \"open\") {\n throw new Error(\"The build was stopped before it finished.\");\n }\n }\n\n private record(\n changes: Partial<\n Pick<\n RunJournal,\n | \"state\"\n | \"compiler\"\n | \"generatedConfig\"\n | \"pendingBuildInfo\"\n | \"outputDigest\"\n >\n >,\n ) {\n this.journal = { ...this.journal, ...changes };\n writeJournal(this.runDir, this.journal);\n }\n\n private setState(state: JournalState): void {\n this.record({ state });\n }\n\n /**\n * Compiler outputs strictly inside the output directory, relative to it:\n * tsc rewrote them in the real output, so the stage leaves them out when\n * it is seeded and takes them fresh at commit. A protected directory that\n * is the output or holds it is not one: it holds the bundles too.\n */\n private compilerOutputsInOutput(): string[] {\n // Compared by real path: tsc's outputs are recorded that way.\n return (this.journal.compiler ?? []).flatMap(({ path }) => {\n const rel = pathWithin(\n this.output,\n fromJournalPath(this.packageRoot, path),\n );\n return rel ? [rel] : [];\n });\n }\n\n /**\n * The stage directory every output write targets. The first call seeds it\n * with the current output, minus what tsc writes afresh. With\n * `linkCleanedEntries`, the entries a step cleans are seeded by hard link,\n * since it unlinks their files before it writes and says so in the same\n * words as on the output; the rest, and otherwise everything, by clone.\n */\n stage(): string {\n this.assertOpen();\n const { stage, output } = this.paths;\n if (this.seeded) return stage;\n removeTree(stage);\n if (exists(output)) {\n const skipped = new Set(\n this.compilerWritten\n ? []\n : this.compilerOutputsInOutput().map((rel) => join(output, rel)),\n );\n const keep = (source: string) => !skipped.has(source);\n // tsc rewrites files in place, so what it writes into is copied.\n const linked = (this.linkCleanedEntries ? this.cleanedEntries : [])\n .filter((entry) => {\n const real = join(this.output, entry);\n return !this.redirected.some(\n (path) => isOrHolds(real, path) || isOrHolds(path, real),\n );\n })\n .map((entry) => join(output, entry))\n .filter(\n (dir) =>\n keep(dir) &&\n lstatSync(dir, { throwIfNoEntry: false })?.isDirectory(),\n );\n cloneTree(\n output,\n stage,\n (source) => keep(source) && !linked.includes(source),\n );\n for (const dir of linked) {\n linkTree(dir, join(stage, basename(dir)), keep);\n }\n } else {\n mkdirSync(stage);\n }\n this.seeded = true;\n return stage;\n }\n\n async prepareCompiler(compiler: CompilerRun): Promise<string | undefined> {\n this.assertOpen();\n const redirect = redirectRootProject(compiler.config, {\n configFile: compiler.configFile,\n packageRoot: this.packageRoot,\n output: this.output,\n stage: this.paths.stage,\n pending: (target) => scratchBeside(target, \"stage\", this.runId),\n });\n let config: string | undefined;\n let staged: readonly string[] = [];\n if (redirect) {\n config = await this.writeCompilerConfig(compiler.configFile, redirect);\n if (config) staged = redirect.staged;\n }\n const real = (path: string) => realPathThroughExistingParent(path);\n this.protectCompilerOutputs(\n compiler.outputs.filter(\n ({ path }) => !staged.some((dir) => isOrHolds(dir, real(path))),\n ),\n );\n if (!config) return undefined;\n this.redirected = staged;\n this.stage();\n return config;\n }\n\n /**\n * Writes the config that sends the root project's outputs into the stage,\n * beside the package's so `${configDir}` and its relative paths mean the\n * same, with the package config's modification time so tsc finds the\n * project up to date when it would. The pending build info starts as a\n * copy of the real one. Undefined when the package does not let the run\n * write them: tsc then writes in place.\n */\n private async writeCompilerConfig(\n configFile: string,\n redirect: CompilerRedirect,\n ): Promise<string | undefined> {\n const generated = join(\n dirname(configFile),\n `.${basename(configFile, extname(configFile))}.ph-stage-${this.runId}.json`,\n );\n const pending = redirect.pendingBuildInfo;\n const recorded = (path: string) => toJournalPath(this.packageRoot, path);\n this.record({\n generatedConfig: recorded(generated),\n ...(pending && {\n pendingBuildInfo: {\n path: recorded(pending.path),\n target: recorded(pending.target),\n },\n }),\n });\n try {\n await creating(shownPath(this.packageRoot, dirname(configFile)), () => {\n writeFileSync(\n generated,\n `${JSON.stringify(\n {\n extends: `./${basename(configFile)}`,\n compilerOptions: redirect.compilerOptions,\n ...(redirect.exclude && { exclude: redirect.exclude }),\n },\n null,\n 2,\n )}\\n`,\n );\n const { atime, mtime } = statSync(configFile);\n utimesSync(generated, atime, mtime);\n if (pending && exists(pending.target)) {\n cloneTree(pending.target, pending.path);\n }\n });\n return generated;\n } catch (error) {\n if (!(error instanceof CannotStage)) throw error;\n removeTree(generated);\n if (pending) removeTree(pending.path);\n this.record({ generatedConfig: undefined, pendingBuildInfo: undefined });\n return undefined;\n }\n }\n\n /**\n * Copies what tsc is about to rewrite into the run, or notes it absent, so\n * a build that does not finish puts it back. Call before tsc runs. An\n * output that is or holds `.ph/build` or this run, by real path, is left\n * unprotected, as without staging: a copy of it would copy itself. So is\n * one holding something a copy cannot take: a FIFO, socket or device, or\n * an entry this process cannot read. The copy's directories are made\n * owner-writable, so the run can always be removed; the journal keeps\n * their modes for a restore.\n */\n private protectCompilerOutputs(outputs: readonly CompilerOutput[]): void {\n const real = (path: string) => realPathThroughExistingParent(path);\n const control = [\n real(join(this.packageRoot, BUILD_DIRECTORY)),\n real(this.runDir),\n ];\n const snapshots: CompilerSnapshot[] = [...(this.journal.compiler ?? [])];\n for (const { path, kind } of outputs) {\n const target = real(path);\n if (control.some((dir) => isOrHolds(target, dir))) continue;\n const recorded = toJournalPath(this.packageRoot, target);\n if (snapshots.some((snapshot) => snapshot.path === recorded)) continue;\n if (exists(target)) {\n const copy = `compiler/${snapshots.length}`;\n const output = basename(this.paths.output);\n const snapshot = join(this.runDir, copy);\n const keep = (source: string) => !isScratchOf(output, basename(source));\n // Left unprotected, as without staging.\n if (unstageableEntryIn(target, keep) !== undefined) continue;\n try {\n cloneTree(target, snapshot, keep);\n } catch (error) {\n if (!isUnreadable(error)) throw error;\n removeTree(snapshot);\n continue;\n }\n const modes = openDirectories(snapshot);\n snapshots.push({\n path: recorded,\n kind,\n copy,\n created: null,\n ...(modes.length > 0 && { modes }),\n });\n } else {\n const missing = outermostMissing(this.packageRoot, target);\n const created =\n missing === target ? null : toJournalPath(this.packageRoot, missing);\n snapshots.push({ path: recorded, kind, copy: null, created });\n }\n }\n const digest =\n snapshots.length > 0\n ? outputDigest(this.packageRoot, this.paths.output, snapshots)\n : undefined;\n this.record({\n compiler: snapshots,\n ...(digest !== undefined && { outputDigest: digest }),\n });\n }\n\n /**\n * tsc wrote into the real output directory; the stage takes its fresh\n * files now, before any bundle step, so a step that cleans or rewrites an\n * entry treats them as it would in the output.\n */\n compilerOutputsWritten(): void {\n this.assertOpen();\n this.compilerWritten = true;\n const generated = this.journal.generatedConfig;\n if (generated) removeTree(fromJournalPath(this.packageRoot, generated));\n if (this.seeded) this.carryOverCompilerOutputs(this.paths.stage);\n }\n\n private carryOverCompilerOutputs(stage: string): void {\n for (const rel of this.compilerOutputsInOutput()) {\n const target = join(stage, rel);\n removeTree(target);\n const source = join(this.paths.output, rel);\n if (exists(source)) {\n mkdirSync(dirname(target), { recursive: true });\n cloneTree(source, target);\n }\n }\n }\n\n private warnNotAtomic(): void {\n const shown = toJournalPath(this.packageRoot, this.paths.output);\n console.warn(\n `⚠ Another process holds files in ${shown}, so ${shown} was replaced entry by entry instead of in one rename; while that ran, it held parts of both builds.`,\n );\n }\n\n /**\n * Replaces the output with the stage: the output moves aside, the stage\n * takes its place, the old tree goes. The journal records each move first.\n * Synchronous, so no signal handler runs in between. The lock stays held\n * until `close`.\n */\n commit(): void {\n const stage = this.stage();\n const { output, retired } = this.paths;\n try {\n this.setState(\"retiring\");\n let entryByEntry = false;\n if (exists(output)) {\n try {\n renamePatiently(output, retired);\n } catch (error) {\n if (!isHeldOpen(error)) throw error;\n entryByEntry = true;\n mkdirSync(retired);\n moveEntries(output, retired);\n }\n }\n this.setState(\"installing\");\n if (exists(output)) {\n moveEntries(stage, output);\n removeTree(stage);\n } else {\n try {\n renamePatiently(stage, output);\n } catch (error) {\n if (!isHeldOpen(error)) throw error;\n entryByEntry = true;\n mkdirSync(output);\n moveEntries(stage, output);\n removeTree(stage);\n }\n }\n installBuildInfo(this.packageRoot, this.journal.pendingBuildInfo);\n this.status = \"committed\";\n if (entryByEntry) this.warnNotAtomic();\n } catch (error) {\n this.rollback();\n throw error;\n }\n try {\n this.setState(\"committed\");\n removeTree(retired);\n removeTree(this.runDir);\n } catch (error) {\n console.warn(\n `⚠ The build finished, but its scratch files were not all removed (${error instanceof Error ? error.message : String(error)}); the next build removes them.`,\n );\n }\n }\n\n /**\n * Releases the lock a commit keeps, so steps that read the committed\n * output finish before another build replaces it, and drops the run a\n * rollback restored from. Idempotent.\n */\n close(): void {\n try {\n if (this.status === \"rolled-back\" && this.restored) {\n removeTree(this.runDir);\n }\n } finally {\n this.lock.release();\n }\n }\n\n releaseLock(): void {\n this.lock.release();\n }\n\n /**\n * Puts the previous output and compiler outputs back. Synchronous, so a\n * signal handler can call it; a no-op after commit. The run and its\n * snapshot stay until `close`, so a call after a step still running at\n * the first one settles restores again, undoing what that step wrote\n * since. A restore that failed is left to the next build. The lock stays\n * held until `close`.\n */\n rollback(): void {\n if (this.status === \"committed\") return;\n if (this.status === \"rolled-back\" && !this.restored) return;\n this.status = \"rolled-back\";\n try {\n rollBack(this.paths, this.journal);\n this.journal = { ...this.journal, state: \"rolling-back\", undo: \"stage\" };\n this.restored = true;\n } catch (error) {\n this.restored = false;\n console.error(\n `✘ The previous output could not be restored (${error instanceof Error ? error.message : String(error)}); the next build restores it.`,\n );\n }\n }\n\n private readonly stops = new Set<() => void>();\n\n cancel(signal: NodeJS.Signals): void {\n this.stoppedBy ??= signal;\n for (const stop of [...this.stops]) stop();\n }\n\n onCancel(stop: () => void): () => void {\n this.stops.add(stop);\n return () => this.stops.delete(stop);\n }\n\n /** The signal `cancel` was called with, if it was. */\n stopped(): NodeJS.Signals | undefined {\n return this.stoppedBy;\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport { lstatSync, readdirSync, readlinkSync, statSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport { CannotStage, creating, unstageableEntryIn } from \"./files.js\";\nimport { BUILD_DIRECTORY, LOCK_FILE } from \"../../build-control.js\";\nimport { RUNS_DIRECTORY } from \"./journal.js\";\nimport { acquireBuildLock, type BuildLock } from \"./lock.js\";\nimport { recoverStaleRuns } from \"./recovery.js\";\nimport {\n type BuildSession,\n scratchBeside,\n shownPath,\n StagedBuildSession,\n} from \"./session.js\";\n\n/**\n * The first symlink among the output and its parents inside the package:\n * a stage beside its target would change the paths the bundlers record.\n */\nfunction symlinkOnPath(\n packageRoot: string,\n output: string,\n): string | undefined {\n const root = realPathThroughExistingParent(packageRoot);\n for (let dir = output; ; dir = dirname(dir)) {\n if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {\n return dir;\n }\n const parent = realPathThroughExistingParent(dirname(dir));\n if (parent === root || pathWithin(root, parent) === null) return;\n }\n}\n\n/**\n * The output is a mount point, or otherwise on another filesystem than the\n * directory beside it: the stage's rename cannot replace it.\n */\nfunction onAnotherFilesystem(output: string): boolean {\n const dev = statSync(output, { throwIfNoEntry: false })?.dev;\n return dev !== undefined && dev !== statSync(dirname(output)).dev;\n}\n\nfunction linkIntoOutput(\n logical: string,\n output: string,\n stage: string,\n): string | undefined {\n const visit = (dir: string): string | undefined => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n const found = visit(path);\n if (found) return found;\n continue;\n }\n if (!entry.isSymbolicLink()) continue;\n const target = readlinkSync(path);\n const copied = isAbsolute(target)\n ? target\n : resolve(stage, relative(logical, dirname(path)), target);\n if (pathWithin(logical, copied) !== null) return path;\n if (pathWithin(output, copied) !== null) return path;\n }\n return undefined;\n };\n return lstatSync(logical, { throwIfNoEntry: false })?.isDirectory()\n ? visit(logical)\n : undefined;\n}\n\n/**\n * Writes the output in place, as builds did before staging: no stage or\n * snapshot, and nothing to commit or roll back. It holds the package's lock\n * until `close` when `.ph/build` can hold one. A stop signal does not stop\n * it, as it did not stop an unstaged build.\n */\nclass InPlaceSession implements BuildSession {\n constructor(\n readonly output: string,\n private readonly logical: string,\n readonly writesPackageDist: boolean,\n private readonly lock: BuildLock | undefined,\n ) {}\n stage(): string {\n return this.logical;\n }\n prepareCompiler(): Promise<undefined> {\n return Promise.resolve(undefined);\n }\n compilerOutputsWritten(): void {}\n commit(): void {}\n close(): void {\n this.lock?.release();\n }\n releaseLock(): void {\n this.lock?.release();\n }\n rollback(): void {}\n private readonly stops = new Set<() => void>();\n cancel(): void {\n for (const stop of [...this.stops]) stop();\n }\n stopped(): undefined {\n return undefined;\n }\n onCancel(stop: () => void): () => void {\n this.stops.add(stop);\n return () => this.stops.delete(stop);\n }\n}\n\nfunction newRunId(): string {\n return `${Date.now().toString(36)}-${process.pid}-${randomBytes(3).toString(\"hex\")}`;\n}\n\n/**\n * Takes the package's lock and finishes what dead builds left, then opens a\n * staged session, or an in-place one when staging cannot run as an unstaged\n * build would: the output or a directory on its path in the package is a\n * symlink, the output is on another filesystem than its parent, it holds an\n * entry a copy cannot take (a FIFO, socket or device, or one this process\n * cannot read) or a symlink into itself, it holds `.ph/build`, whose lock and\n * journal a swap would move away, or the stage beside it cannot be written.\n * Only when `.ph/build` cannot hold the lock does the build run without one,\n * as builds did before staging. One warning says why a build writes in place.\n */\nexport async function openBuildSession(options: {\n readonly packageRoot: string;\n readonly outDir: string;\n /** Top-level entries of the output a step empties before it writes them. */\n readonly cleanedEntries: readonly string[];\n /** Seed those entries by hard link: no step writes them before that. */\n readonly linkCleanedEntries: boolean;\n}): Promise<BuildSession> {\n const { packageRoot, outDir, cleanedEntries, linkCleanedEntries } = options;\n const logical = resolve(packageRoot, outDir);\n const output = realPathThroughExistingParent(logical);\n const writesPackageDist =\n output === realPathThroughExistingParent(join(packageRoot, \"dist\"));\n const shown = (path: string) => shownPath(packageRoot, path);\n const inPlace = (reason: string, lock: BuildLock | undefined) => {\n console.warn(\n `⚠ ${reason}, so this build writes ${shown(logical)} in place: if it does not finish, ${shown(logical)} can be left part old, part new.`,\n );\n return new InPlaceSession(output, logical, writesPackageDist, lock);\n };\n const runId = newRunId();\n let lock: BuildLock;\n try {\n lock = await creating(BUILD_DIRECTORY, () =>\n acquireBuildLock(join(packageRoot, LOCK_FILE), runId, (wait) =>\n console.log(\n `Another build of this package holds ${shown(wait.file)} (${wait.owner}); waiting for it to finish... If that build is gone, delete ${shown(wait.file)}.`,\n ),\n ),\n );\n } catch (error) {\n if (!(error instanceof CannotStage)) throw error;\n return inPlace(error.message, undefined);\n }\n try {\n recoverStaleRuns(packageRoot, logical);\n const link = symlinkOnPath(packageRoot, logical);\n if (link !== undefined) {\n return inPlace(`${shown(link)} is a symbolic link`, lock);\n }\n if (onAnotherFilesystem(logical)) {\n return inPlace(\n `${shown(logical)} is on another filesystem than the directory that holds it`,\n lock,\n );\n }\n const unstageable = unstageableEntryIn(logical);\n if (unstageable !== undefined) {\n return inPlace(`${shown(unstageable.path)} ${unstageable.reason}`, lock);\n }\n const intoOutput = linkIntoOutput(\n logical,\n output,\n scratchBeside(logical, \"stage\", runId),\n );\n if (intoOutput !== undefined) {\n return inPlace(\n `${shown(intoOutput)} is a symbolic link into ${shown(logical)}`,\n lock,\n );\n }\n const control = [BUILD_DIRECTORY, join(RUNS_DIRECTORY, runId)].find(\n (dir) =>\n pathWithin(\n output,\n realPathThroughExistingParent(join(packageRoot, dir)),\n ) !== null,\n );\n if (control !== undefined) {\n return inPlace(`${shown(logical)} holds ${control}`, lock);\n }\n try {\n return await StagedBuildSession.open({\n packageRoot,\n logical,\n output,\n writesPackageDist,\n cleanedEntries,\n linkCleanedEntries,\n runId,\n lock,\n });\n } catch (error) {\n if (!(error instanceof CannotStage)) throw error;\n return inPlace(error.message, lock);\n }\n } catch (error) {\n lock.release();\n throw error;\n }\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// The manifest with `connectRoutes` set when the package offers routes; as it\n// is, byte for byte, when the flag is already right.\nfunction withOfferedRoutes(json: string, offers: boolean) {\n const manifest = JSON.parse(json) as { connectRoutes?: boolean };\n if (offers ? manifest.connectRoutes === true : !(\"connectRoutes\" in manifest))\n return json;\n if (offers) manifest.connectRoutes = true;\n else delete manifest.connectRoutes;\n return `${JSON.stringify(manifest, null, 2)}\\n`;\n}\n\nconst slashes = (path: string) => path.replaceAll(\"\\\\\", \"/\");\n\n/** Sets `connectRoutes` in the manifest the package's root module imports,\n * leaving the project's file as it is. */\nexport function offeredRoutesManifest(projectRoot: string, offers: boolean) {\n // Vite's ids use forward slashes on Windows too.\n const manifestPath = slashes(join(projectRoot, \"powerhouse.manifest.json\"));\n return {\n name: \"ph-offered-routes-manifest\",\n transform(code: string, id: string) {\n if (slashes(id) !== manifestPath) return null;\n return { code: withOfferedRoutes(code, offers), map: null };\n },\n };\n}\n\n/** Sets `connectRoutes` in the dist copy of the manifest. */\nexport function markOfferedRoutes(dir: string, offers: boolean) {\n const manifestPath = join(dir, \"powerhouse.manifest.json\");\n if (!existsSync(manifestPath)) return;\n const json = readFileSync(manifestPath, \"utf-8\");\n writeFileSync(manifestPath, withOfferedRoutes(json, offers));\n}\n","import { relative, resolve, sep } from \"node:path\";\nimport { globalLogger, type Logger } from \"tsdown\";\nimport type { BuildContext } from \"./context.js\";\n\n/**\n * tsdown labels each file it writes with its directory, relative to the\n * package. Bundles written to the stage keep the labels of the output\n * directory they stand in for, so the log reads as without staging.\n */\nexport function stageLogger({\n projectRoot,\n outDir,\n session,\n}: BuildContext): Logger {\n const shown = `${relative(projectRoot, resolve(projectRoot, outDir))}${sep}`;\n const written = `${relative(projectRoot, session.stage())}${sep}`;\n const label = (message: unknown) =>\n typeof message === \"string\" ? message.replaceAll(written, shown) : message;\n const relabel =\n (log: (...messages: unknown[]) => void) =>\n (...messages: unknown[]) =>\n log(...messages.map(label));\n return {\n get level() {\n return globalLogger.level;\n },\n set level(level) {\n globalLogger.level = level;\n },\n info: relabel((...m) => globalLogger.info(...m)),\n warn: relabel((...m) => globalLogger.warn(...m)),\n warnOnce: relabel((...m) => globalLogger.warnOnce(...m)),\n error: relabel((...m) => globalLogger.error(...m)),\n success: relabel((...m) => globalLogger.success(...m)),\n clearScreen: (type) => globalLogger.clearScreen(type),\n };\n}\n","import {\n browserEntry,\n buildBrowserBuildConfig,\n buildNodeBuildConfig,\n findBundledSharedDeps,\n} from \"@powerhousedao/shared/build-config\";\nimport type { ExternalDependency } from \"@powerhousedao/shared/build-pieces\";\nimport {\n expandEntryGlobs,\n externalDepsPlugin,\n projectPath,\n undeclaredExternalDependencies,\n} from \"@powerhousedao/shared/build-pieces\";\nimport {\n EXTERNALIZABLE_SHARED_SPECIFIERS,\n findSharedImports,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport { noConnectImports } from \"../../../utils/offered-routes-imports.js\";\nimport { offeredRoutesManifest } from \"../../../utils/offered-routes-manifest.js\";\nimport {\n HOST_ROUTES_DIR,\n OFFERED_ROUTES_MODULE,\n} from \"../../../utils/sync-connect-routes.js\";\nimport type { StandardBuildStep } from \"./context.js\";\nimport { stageLogger } from \"./stage-logger.js\";\n\n/**\n * Every shared specifier imported from the entry sources; the post-build\n * scan compares these against the built output.\n *\n * Scoped to the specifiers the build actually externalizes: a specifier the\n * vendor does not publish (the bare `@powerhousedao/shared` root, an\n * unvendored subpath) is deliberately bundled, so reporting it as \"bundled\n * instead of externalized\" would be a false alarm.\n */\nfunction findSharedImportsInSources(root: string, globs: string[]): string[] {\n const found = new Set<string>();\n for (const file of expandEntryGlobs(root, globs)) {\n const src = readFileSync(file, \"utf8\");\n for (const spec of findSharedImports(\n src,\n EXTERNALIZABLE_SHARED_SPECIFIERS,\n )) {\n found.add(spec);\n }\n }\n return [...found].sort();\n}\n\n/**\n * The built JS outputs of a browser build (entry files and chunks).\n */\nfunction readDistBrowserFiles(\n dir: string,\n): { path: string; content: string }[] {\n const out: { path: string; content: string }[] = [];\n if (!existsSync(dir)) return out;\n const walk = (d: string) => {\n for (const e of readdirSync(d, { withFileTypes: true })) {\n const p = join(d, e.name);\n if (e.isDirectory()) walk(p);\n else if (e.isFile() && e.name.endsWith(\".js\")) {\n out.push({ path: p, content: readFileSync(p, \"utf8\") });\n }\n }\n };\n walk(dir);\n return out;\n}\n\n// Everything in the browser build is code Connect can load: native fails it.\nexport const browserBundleStep: StandardBuildStep = {\n id: \"browser-bundle\",\n run: async (ctx) => {\n const { args, projectRoot, session, trace, detection, findings } = ctx;\n const stage = session.stage();\n const sharedDeps = !args.noSharedDeps;\n const routesEntry = join(projectRoot, OFFERED_ROUTES_MODULE);\n const config = buildBrowserBuildConfig({\n sharedDeps,\n plugins: [\n externalDepsPlugin(trace, new Map(), {\n root: projectRoot,\n browser: true,\n cache: detection,\n }),\n offeredRoutesManifest(projectRoot, findings.offersRoutes),\n noConnectImports(routesEntry, join(projectRoot, HOST_ROUTES_DIR)),\n ],\n });\n await tsdownBuild({\n ...config,\n // The manifest copy lands in the stage when it stands in for dist/.\n ...(session.writesPackageDist && {\n copy: [{ from: \"powerhouse.manifest.json\", to: stage }],\n }),\n // The offered routes in the package's build: a module both import is one\n // chunk, which other Connects evaluate once. Absolute: a relative entry\n // is a glob, and globs skip `.ph`.\n ...(findings.offersRoutes\n ? { entry: [...browserEntry, { \"connect-routes\": routesEntry }] }\n : {}),\n outDir: join(stage, \"browser\"),\n customLogger: stageLogger(ctx),\n });\n\n // Advisory: a shared dep the source imports but the output no longer\n // references as a bare import was inlined despite the external set.\n if (sharedDeps) {\n const imported = findSharedImportsInSources(projectRoot, browserEntry);\n const bundled = findBundledSharedDeps(\n imported,\n readDistBrowserFiles(join(stage, \"browser\")),\n );\n if (bundled.length > 0) {\n console.warn(\n `⚠ shared deps bundled instead of externalized: ${bundled.join(\", \")} — check your neverBundle config`,\n );\n }\n }\n },\n};\n\n// A package with a native addon or WebAssembly module stays external, so the\n// package's consumers must install it: devDependencies are skipped by every install.\nexport function assertExternalDependenciesDeclared(\n projectRoot: string,\n found: ExternalDependency[],\n pkg: Parameters<typeof undeclaredExternalDependencies>[1],\n) {\n for (const dep of found) {\n console.log(\n `${dep.name}@${dep.version} stays external, it needs ${projectPath(projectRoot, dep.file)}`,\n );\n }\n const undeclared = undeclaredExternalDependencies(found, pkg);\n if (undeclared.length === 0) return;\n const lines = undeclared.map(\n (dep) =>\n ` ${dep.name}${dep.importer ? ` (imported by ${projectPath(projectRoot, dep.importer)})` : \"\"}`,\n );\n throw new Error(\n `Packages with native addons or WebAssembly modules must be listed in package.json \"dependencies\", \"optionalDependencies\" or \"peerDependencies\":\\n` +\n `${lines.join(\"\\n\")}\\n\\n` +\n `They stay external to the build, and installs of this package skip devDependencies.`,\n );\n}\n\nexport const nodeBundleStep: StandardBuildStep = {\n id: \"node-bundle\",\n run: async (ctx) => {\n const { args, projectRoot, session, trace, detection, findings } = ctx;\n await tsdownBuild({\n ...buildNodeBuildConfig({\n sharedDeps: !args.noSharedDeps,\n plugins: [\n // Editors never run on a host; document models and scalars run in Connect too.\n externalDepsPlugin(trace, findings.external, {\n root: projectRoot,\n ignoreDirs: [\"editors\"],\n forbidDirs: [\"document-models\", \"scalars\"],\n cache: detection,\n }),\n ],\n }),\n outDir: join(session.stage(), \"node\"),\n customLogger: stageLogger(ctx),\n });\n findings.pkg = await readPackage({ cwd: projectRoot });\n assertExternalDependenciesDeclared(\n projectRoot,\n [...findings.external.values()],\n findings.pkg,\n );\n },\n};\n\n/** The output entry each bundle step writes, which tsdown empties first. */\nconst CLEANED_BY_STEP = new Map([\n [browserBundleStep.id, \"browser\"],\n [nodeBundleStep.id, \"node\"],\n]);\n\n/** The output entries `steps` empty before they write them, by step id. */\nexport const entriesCleanedBy = (\n steps: readonly { readonly id: string }[],\n): string[] => steps.flatMap(({ id }) => CLEANED_BY_STEP.get(id) ?? []);\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n OFFERED_ROUTES_MODULE,\n syncProjectConnectRoutes,\n} from \"../../../utils/sync-connect-routes.js\";\nimport type { StandardBuildStep } from \"./context.js\";\n\nexport const connectRoutesStep: StandardBuildStep = {\n id: \"connect-routes\",\n run: async ({ projectRoot, findings }) => {\n // Project routes type-check against the tree generated from them.\n await syncProjectConnectRoutes(projectRoot);\n // Connect reads the manifest's flag to load the package's routes.\n findings.offersRoutes = existsSync(\n join(projectRoot, OFFERED_ROUTES_MODULE),\n );\n },\n};\n","import type { DefinitionCheckReport } from \"@powerhousedao/shared/document-model\";\nimport { fork } from \"node:child_process\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport type {\n DefinitionsProfile,\n DefinitionsReply,\n} from \"../../model/definitions-worker.js\";\nimport type { BuildSession } from \"../staging/session.js\";\nimport { BuildRefusal } from \"../pipeline/steps.js\";\nimport type { StandardBuildStep } from \"./context.js\";\n\n/**\n * The built worker beside ph-cli's own code. Run from source (under vitest),\n * the TypeScript worker through tsx, so a test runs the current source.\n */\nfunction definitionsWorker(): { path: string; execArgv: string[] } {\n const root = dirname(\n createRequire(import.meta.url).resolve(\n \"@powerhousedao/ph-cli/package.json\",\n ),\n );\n if (!import.meta.url.endsWith(\".ts\")) {\n return { path: join(root, \"dist\", \"definitions-worker.mjs\"), execArgv: [] };\n }\n return {\n path: join(root, \"src\", \"services\", \"model\", \"definitions-worker.ts\"),\n execArgv: [\"--import\", import.meta.resolve(\"tsx\")],\n };\n}\n\n/**\n * Runs the definition check in a child process: the package's own modules\n * can exit, hang or start timers there without reaching the build. A child\n * that ends without a reply, outlives `timeoutMs` or outlives a stop of the\n * build is killed, and the reply says why the check could not run.\n */\nexport function checkInChild<P extends DefinitionsProfile>(\n projectRoot: string,\n profile: P,\n session: BuildSession,\n timeoutMs: number,\n): Promise<DefinitionsReply<P>> {\n const worker = definitionsWorker();\n return new Promise((resolve) => {\n let reply: DefinitionsReply<P> | undefined;\n let killedFor: string | undefined;\n // The package's modules print to the build's stderr, as under `ph model`.\n const child = fork(worker.path, [projectRoot, profile], {\n cwd: projectRoot,\n execArgv: worker.execArgv,\n stdio: [\"ignore\", 2, 2, \"ipc\"],\n });\n const kill = (why: string) => {\n killedFor ??= why;\n child.kill(\"SIGKILL\");\n };\n const timer = setTimeout(\n () => kill(`the check did not finish within ${timeoutMs / 1000} seconds`),\n timeoutMs,\n );\n // Synchronous, inside the signal handler: a worker stuck in a loop\n // cannot notice its parent is gone, so it must die before the parent.\n const unwatch = session.onCancel(() => kill(\"the build was stopped\"));\n if (session.stopped()) kill(\"the build was stopped\");\n const settle = (settled: DefinitionsReply<P>) => {\n clearTimeout(timer);\n unwatch();\n resolve(settled);\n };\n child.on(\"message\", (message) => {\n reply ??= message as DefinitionsReply<P>;\n });\n child.on(\"error\", (error) => {\n kill(error.message);\n settle({ ok: false, message: error.message });\n });\n child.on(\"exit\", (code, signal) => {\n settle(\n reply ?? {\n ok: false,\n message:\n killedFor ??\n `the check ${signal ? `was stopped by ${signal}` : `exited with code ${code}`} before it reported`,\n },\n );\n });\n });\n}\n\n/**\n * Checks the package's definitions after tsc and before any bundle, when\n * `ph build` asks or with `--release`. Without `--release` it checks the\n * package when discovery finds a code-first model directory or cannot read\n * the models directory, never stops the build, and skips without a word a\n * package with no code-first model. With `--release`\n * (experimental) it runs the release profile over every model, stored ones\n * included, and stops the build when the check is invalid or cannot run, a\n * configuration error included. The package's modules load only in the\n * definitions worker, which has `timeoutMs` to report.\n */\nexport function definitionsStepWithin(timeoutMs: number): StandardBuildStep {\n return {\n id: \"definitions\",\n after: [\"typecheck\"],\n run: async ({ args, checkDefinitions, projectRoot, session, findings }) => {\n if (!args.release && !checkDefinitions) return;\n if (!args.release) {\n const { resolveDefinitionSelection } =\n await import(\"document-model/tooling\");\n const selection = resolveDefinitionSelection({\n configFile: join(projectRoot, \"powerhouse.config.json\"),\n allowMissingConfig: true,\n });\n if (selection.status === \"skipped\") return;\n }\n const { renderCheckReport } = await import(\"../../model/render.js\");\n const printReport = (report: DefinitionCheckReport) => {\n const text = renderCheckReport(report);\n if (report.diagnostics.length > 0) {\n console.warn(\n `⚠ The definition check reported problems; the build goes on:\\n${text}`,\n );\n } else {\n console.log(`✔ ${text}`);\n }\n };\n console.log(\"\\n▶ Checking document model definitions...\");\n if (!args.release) {\n const edit = await checkInChild(\n projectRoot,\n \"edit\",\n session,\n timeoutMs,\n );\n if (edit.ok) printReport(edit.result);\n else\n console.warn(`⚠ The definition check could not run: ${edit.message}`);\n return;\n }\n const release = await checkInChild(\n projectRoot,\n \"release\",\n session,\n timeoutMs,\n );\n if (!release.ok) {\n throw new BuildRefusal(\n `✘ The definition check could not run: ${release.message}`,\n );\n }\n const { status } = release.result.report;\n if (status === \"invalid\" || status === \"failed\") {\n throw new BuildRefusal(\n `✘ The release definition check stopped the build:\\n${renderCheckReport(release.result.report)}`,\n );\n }\n findings.release = release.result;\n printReport(release.result.report);\n },\n };\n}\n\nexport const definitionsStep = definitionsStepWithin(5 * 60_000);\n","import { assertPiecesOutDir } from \"@powerhousedao/shared/build-pieces\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport type { StandardBuildStep } from \"./context.js\";\n\n/**\n * A Powerhouse package's `powerhouse.manifest.json` \"name\" must match its\n * `package.json` \"name\" — Connect and the registry resolve installed versions\n * by treating the manifest name as the npm package name, so a mismatch silently\n * breaks resolution. Fail the build early if they diverge. No-op when the\n * project has no manifest (nothing to compare).\n */\nexport async function assertManifestNameMatchesPackage(projectPath: string) {\n const manifestPath = join(projectPath, \"powerhouse.manifest.json\");\n if (!existsSync(manifestPath)) return;\n\n const { name: packageName } = await readPackage({ cwd: projectPath });\n\n let manifestName: unknown;\n try {\n manifestName = (\n JSON.parse(readFileSync(manifestPath, \"utf-8\")) as { name?: unknown }\n ).name;\n } catch {\n throw new Error(\n `Failed to parse \"powerhouse.manifest.json\" at ${manifestPath}. Make sure it is valid JSON.`,\n );\n }\n\n if (manifestName !== packageName) {\n throw new Error(\n `Package name mismatch — \"package.json\" and \"powerhouse.manifest.json\" must have the same \"name\":\\n` +\n ` package.json \"name\": ${JSON.stringify(packageName)}\\n` +\n ` powerhouse.manifest.json \"name\": ${JSON.stringify(manifestName)}\\n\\n` +\n `Update one so they match, then run the build again.`,\n );\n }\n}\n\n// Fail fast if the manifest name and package.json name have drifted apart.\nexport const manifestNameStep: StandardBuildStep = {\n id: \"manifest-name\",\n run: ({ projectRoot }) => assertManifestNameMatchesPackage(projectRoot),\n};\n\n// Before any bundler runs: an out-dir a host will never read from is worth\n// nothing built, and the failure names what the contract is.\nexport const piecesOutDirStep: StandardBuildStep = {\n id: \"pieces-out-dir\",\n run: ({ outDir, pieces }) => {\n assertPiecesOutDir({ outDir, pieces: [...pieces] });\n return Promise.resolve();\n },\n};\n","import {\n buildPieces,\n externalDependencyVersions,\n pieceListPath,\n syncDistManifest,\n} from \"@powerhousedao/shared/build-pieces\";\nimport { existsSync } from \"node:fs\";\nimport { readPackage } from \"read-pkg\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport { markOfferedRoutes } from \"../../../utils/offered-routes-manifest.js\";\nimport type { StandardBuildStep } from \"./context.js\";\nimport { stageLogger } from \"./stage-logger.js\";\n\n// After the node build: it cleans <outDir>/node, where the pieces land. The\n// built list is the gate, so a `bundle:` entry is validated with no piece dir.\nexport const piecesStep: StandardBuildStep = {\n id: \"pieces\",\n run: async (ctx) => {\n const { projectRoot, outDir, pieces, session, trace, detection, findings } =\n ctx;\n const stage = session.stage();\n if (!existsSync(pieceListPath({ projectRoot, outDir: stage }))) return;\n const pkg = findings.pkg ?? (await readPackage({ cwd: projectRoot }));\n const customLogger = stageLogger(ctx);\n findings.built = await buildPieces(\n { projectRoot, outDir, writeTo: stage, pieces: [...pieces] },\n {\n name: pkg.name,\n version: pkg.version,\n license: typeof pkg.license === \"string\" ? pkg.license : undefined,\n },\n {\n bundle: (config) => tsdownBuild({ ...config, customLogger }),\n trace,\n cache: detection,\n },\n );\n },\n};\n\nexport const distManifestStep: StandardBuildStep = {\n id: \"dist-manifest\",\n run: ({ projectRoot, pieces, session, findings }) => {\n syncDistManifest(\n { projectRoot, outDir: session.stage(), pieces: [...pieces] },\n findings.built,\n externalDependencyVersions(findings.external.values()),\n );\n return Promise.resolve();\n },\n};\n\nexport const offeredRoutesStep: StandardBuildStep = {\n id: \"offered-routes\",\n run: ({ session, findings }) => {\n markOfferedRoutes(session.stage(), findings.offersRoutes);\n return Promise.resolve();\n },\n};\n","import { spawn } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n realpathSync,\n symlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport type { PackedManifest, PackedRelease } from \"./pack.js\";\n\ntype Consumer = \"node\" | \"browser\";\n\nconst CONDITIONS: Readonly<Record<Consumer, ReadonlySet<string>>> = {\n node: new Set([\"node\", \"import\", \"module-sync\", \"default\"]),\n browser: new Set([\"browser\", \"import\", \"module\", \"default\"]),\n};\n\nconst IMPORTABLE = /\\.(m?js|cjs)$/;\n\nfunction resolveTarget(\n value: unknown,\n conditions: ReadonlySet<string>,\n): string | undefined {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) {\n for (const item of value) {\n const target = resolveTarget(item, conditions);\n if (target !== undefined) return target;\n }\n return undefined;\n }\n if (value === null || typeof value !== \"object\") return undefined;\n for (const [key, nested] of Object.entries(value)) {\n if (!conditions.has(key)) continue;\n const target = resolveTarget(nested, conditions);\n if (target !== undefined) return target;\n }\n return undefined;\n}\n\nfunction targetsOf(value: unknown): string[] {\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value.flatMap(targetsOf);\n if (value === null || typeof value !== \"object\") return [];\n return Object.values(value).flatMap(targetsOf);\n}\n\nfunction subpaths(manifest: PackedManifest): [string, unknown][] {\n const { exports } = manifest;\n if (exports === undefined) return [];\n if (\n exports !== null &&\n typeof exports === \"object\" &&\n !Array.isArray(exports) &&\n Object.keys(exports).some((key) => key.startsWith(\".\"))\n ) {\n return Object.entries(exports);\n }\n return [[\".\", exports]];\n}\n\nconst packedPath = (target: string) => target.replace(/^\\.\\//, \"\");\n\nexport function packedEntries(\n manifest: PackedManifest,\n files: ReadonlySet<string>,\n unbuilt: ReadonlySet<string>,\n): {\n readonly imports: Record<Consumer, string[]>;\n readonly missing: string[];\n} {\n const imports: Record<Consumer, string[]> = { node: [], browser: [] };\n const missing: string[] = [];\n const entries = subpaths(manifest);\n if (entries.length === 0) {\n imports.node.push(manifest.name);\n return { imports, missing };\n }\n for (const [subpath, value] of entries) {\n const targets = targetsOf(value).filter((target) => !target.includes(\"*\"));\n const absent = targets.filter((target) => !files.has(packedPath(target)));\n if (unbuilt.has(subpath) && absent.length === targets.length) continue;\n missing.push(\n ...absent.map((target) => `exports[\"${subpath}\"] names ${target}`),\n );\n if (subpath === \"./package.json\") continue;\n for (const consumer of [\"node\", \"browser\"] as const) {\n const target = resolveTarget(value, CONDITIONS[consumer]);\n if (target === undefined || !IMPORTABLE.test(target)) continue;\n const specifier = `${manifest.name}${subpath.slice(1)}`;\n if (!subpath.includes(\"*\")) {\n imports[consumer].push(specifier);\n continue;\n }\n const [before, after] = packedPath(target).split(\"*\");\n const [subBefore, subAfter] = specifier.split(\"*\");\n for (const file of [...files].sort()) {\n if (!file.startsWith(before) || !file.endsWith(after)) continue;\n const star = file.slice(before.length, file.length - after.length);\n if (star !== \"\")\n imports[consumer].push(`${subBefore}${star}${subAfter}`);\n }\n }\n }\n return { imports, missing };\n}\n\nfunction installed(projectRoot: string, name: string): string | undefined {\n for (let directory = projectRoot; ; directory = dirname(directory)) {\n const candidate = join(directory, \"node_modules\", ...name.split(\"/\"));\n if (existsSync(join(candidate, \"package.json\"))) {\n return realpathSync.native(candidate);\n }\n if (dirname(directory) === directory) return undefined;\n }\n}\n\n// Imports each specifier, writes the failures to the result file, then\n// exits, so a module that keeps a handle open cannot hold the check. The\n// modules own stdout. With conditions given, every import, the package's own\n// dependencies' too, resolves under those instead of Node's.\nconst IMPORT_EACH = `import { writeFileSync } from \"node:fs\";\nimport { registerHooks } from \"node:module\";\nconst { specifiers, conditions, resultFile } = JSON.parse(process.argv[1]);\nif (conditions) {\n registerHooks({\n resolve: (specifier, context, next) => next(specifier, {\n ...context,\n conditions: context.conditions.includes(\"require\")\n ? conditions.map((name) => (name === \"import\" ? \"require\" : name))\n : conditions,\n }),\n });\n}\nconst failed = [];\nfor (const specifier of specifiers) {\n try { await import(specifier); }\n catch (error) { failed.push(specifier + \": \" + (error instanceof Error ? error.message : String(error)).split(\"\\\\n\")[0]); }\n}\nwriteFileSync(resultFile, JSON.stringify(failed));\nprocess.exit(0);\n`;\n\nconst TIMEOUT_MS = 120_000;\nconst STDERR_LIMIT = 64 * 1024;\n\nasync function importAll(\n consumerRoot: string,\n consumer: Consumer,\n specifiers: readonly string[],\n signal: AbortSignal | undefined,\n): Promise<string[]> {\n if (specifiers.length === 0) return [];\n const env = { ...process.env };\n delete env.NODE_OPTIONS;\n delete env.NODE_PATH;\n const resultFile = join(dirname(consumerRoot), `${consumer}-result.json`);\n const input = {\n specifiers,\n conditions: consumer === \"browser\" ? [...CONDITIONS.browser] : null,\n resultFile,\n };\n const ended = await new Promise<string>((done) => {\n const child = spawn(\n process.execPath,\n [\"--input-type=module\", \"-e\", IMPORT_EACH, JSON.stringify(input)],\n { cwd: consumerRoot, env, signal, stdio: [\"ignore\", \"ignore\", \"pipe\"] },\n );\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill();\n }, TIMEOUT_MS);\n let stderr = \"\";\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk: string) => {\n if (stderr.length < STDERR_LIMIT) stderr += chunk;\n });\n child.on(\"error\", (error) => done(error.message));\n child.on(\"close\", (code, killedBy) => {\n clearTimeout(timer);\n if (timedOut) {\n done(`did not finish its imports within ${TIMEOUT_MS / 1000} seconds`);\n return;\n }\n const how = killedBy === null ? `exited with ${code}` : `got ${killedBy}`;\n const why = stderr.trim().split(\"\\n\")[0];\n done(why ? `${how}: ${why}` : how);\n });\n });\n if (!existsSync(resultFile)) {\n return [`${consumer} consumer did not finish: it ${ended}`];\n }\n return (JSON.parse(readFileSync(resultFile, \"utf8\")) as string[]).map(\n (failure) =>\n `${consumer} consumer cannot import ${failure.replace(/ imported from \\S*\\[eval\\d*\\]$/, \"\")}`,\n );\n}\n\nexport async function checkPackedConsumer(\n projectRoot: string,\n packed: PackedRelease,\n unbuilt: ReadonlySet<string>,\n signal?: AbortSignal,\n): Promise<string[]> {\n const { manifest, files } = packed;\n const consumerRoot = join(packed.directory, \"consumer\");\n const modules = join(consumerRoot, \"node_modules\");\n const installRoot = join(modules, ...manifest.name.split(\"/\"));\n for (const [path, bytes] of files) {\n const target = resolve(installRoot, path);\n if (!target.startsWith(`${installRoot}${sep}`)) {\n return [`the tarball has an entry outside the package: ${path}`];\n }\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, bytes);\n }\n writeFileSync(\n join(consumerRoot, \"package.json\"),\n `${JSON.stringify({ name: \"ph-packed-consumer\", private: true, type: \"module\" })}\\n`,\n );\n const runtime = new Set([\n ...Object.keys(manifest.dependencies ?? {}),\n ...Object.keys(manifest.optionalDependencies ?? {}),\n ...Object.keys(manifest.peerDependencies ?? {}),\n ]);\n for (const name of runtime) {\n if (name === manifest.name) continue;\n const from = installed(projectRoot, name);\n if (from === undefined) continue;\n const link = join(modules, ...name.split(\"/\"));\n mkdirSync(dirname(link), { recursive: true });\n symlinkSync(from, link, process.platform === \"win32\" ? \"junction\" : \"dir\");\n }\n const { imports, missing } = packedEntries(\n manifest,\n new Set(files.keys()),\n unbuilt,\n );\n const failures = await Promise.all(\n ([\"node\", \"browser\"] as const).map((consumer) =>\n importAll(consumerRoot, consumer, imports[consumer], signal),\n ),\n );\n return [\n ...missing.map((entry) => `${entry}, which the package does not contain`),\n ...failures.flat(),\n ].map((failure) => {\n const shown = failure\n .replaceAll(`${consumerRoot}${sep}`, \"\")\n .replaceAll(consumerRoot, \".\");\n // The same refusal on every platform: paths as package specifiers spell them.\n return sep === \"\\\\\" ? shown.replaceAll(\"\\\\\", \"/\") : shown;\n });\n}\n","import { listed } from \"./approval.js\";\nimport { changedPaths, type FileDigest } from \"./revision.js\";\n\nconst under = (path: string, directory: string) =>\n path === directory || path.startsWith(`${directory}/`);\n\n/** What a release build learned that decides whether it may write an approval. Paths are POSIX, from the package root. */\nexport type ApprovalBuild<Release> = {\n readonly typesOk: boolean;\n /** The release profile's result, when it ran. */\n readonly release: Release | undefined;\n /** The package's files when the build started. */\n readonly startFiles: readonly FileDigest[] | undefined;\n /** The output directory as given, then the directory the build replaced when that is elsewhere in the package. */\n readonly outputs: readonly [string, ...string[]];\n /** What tsc writes. */\n readonly compilerOutputs: readonly string[];\n};\n\nexport type ApprovalPlan<Release> =\n | { readonly refused: string }\n | {\n readonly release: Release;\n readonly startFiles: readonly FileDigest[];\n /** What the revision leaves out besides the output directory: neither is a source. */\n readonly excluded: readonly string[];\n };\n\n/**\n * Whether a release build may write an approval, and what its revision\n * leaves out: the replaced directory, and what tsc writes outside the\n * output.\n */\nexport function planApproval<Release>(\n build: ApprovalBuild<Release>,\n): ApprovalPlan<Release> {\n const { release, startFiles, outputs } = build;\n if (!build.typesOk) {\n return { refused: \"the build went on despite tsc's type errors\" };\n }\n if (release === undefined || startFiles === undefined) {\n return { refused: \"the release check did not run\" };\n }\n const excluded = [\n ...outputs.slice(1),\n ...build.compilerOutputs.filter(\n (path) => !outputs.some((directory) => under(path, directory)),\n ),\n ];\n return { release, startFiles, excluded };\n}\n\n/**\n * Why the approval may not be written because the package changed while it\n * was built, comparing its files at the start, minus what the revision\n * leaves out, with `endFiles`; undefined when nothing changed.\n */\nexport function changedWhileBuilt(\n plan: {\n readonly startFiles: readonly FileDigest[];\n readonly excluded: readonly string[];\n },\n endFiles: readonly FileDigest[],\n): string | undefined {\n const leftOut = (path: string) =>\n plan.excluded.some((exclusion) => under(path, exclusion));\n const changed = changedPaths(\n plan.startFiles.filter(({ path }) => !leftOut(path)),\n endFiles,\n );\n return changed.length === 0\n ? undefined\n : `the package's files changed while it was built (${listed(changed)})`;\n}\n","import { existsSync } from \"node:fs\";\nimport { isAbsolute, join } from \"node:path\";\nimport { getVersion } from \"../../../get-version.js\";\nimport {\n listed,\n PH_CLI_BINDING,\n RELEASE_APPROVAL_PATH,\n} from \"../../release/approval.js\";\nimport { checkPackedConsumer } from \"../../release/consumer.js\";\nimport {\n packagePath,\n revisionFiles,\n writeReleaseApproval,\n} from \"../../release/files.js\";\nimport { changedWhileBuilt, planApproval } from \"../../release/issuance.js\";\nimport {\n packedDigests,\n packRelease,\n type PackedRelease,\n} from \"../../release/pack.js\";\nimport { type FileDigest, packageRevision } from \"../../release/revision.js\";\nimport { BuildRefusal } from \"../pipeline/steps.js\";\nimport type { BuildSession } from \"../staging/session.js\";\nimport type { BuildFindings, StandardBuildStep } from \"./context.js\";\n\nconst under = (path: string, directory: string) =>\n path === directory || path.startsWith(`${directory}/`);\n\n/**\n * The output directory as given, then the directory the build replaces when\n * that is a symlink to another place in the package: neither is a source.\n */\nfunction outputDirectories(\n projectRoot: string,\n outDir: string,\n target: string,\n): [string, ...string[]] {\n const output = packagePath(projectRoot, outDir);\n const real = packagePath(projectRoot, target);\n const inPackage =\n real !== \"..\" && !real.startsWith(\"../\") && !isAbsolute(real);\n return inPackage && !under(real, output) ? [output, real] : [output];\n}\n\n/** With `--release`, records the package's files before anything is built. */\nexport const releaseStartStep: StandardBuildStep = {\n id: \"release-start\",\n run: ({ args, projectRoot, outDir, session, findings }) => {\n if (args.release) {\n findings.releaseStart = revisionFiles(\n projectRoot,\n outputDirectories(projectRoot, outDir, session.output),\n );\n }\n return Promise.resolve();\n },\n};\n\n/** Exports `ph init` declares whose entry the build skips when its source is absent. */\nconst OPTIONAL_EXPORTS: Readonly<Record<string, string>> = {\n \"./scalars\": \"scalars/index.ts\",\n \"./pieces\": \"pieces/index.ts\",\n};\n\nconst unbuiltExports = (projectRoot: string, findings: BuildFindings) =>\n new Set([\n ...Object.entries(OPTIONAL_EXPORTS)\n .filter(([, source]) => !existsSync(join(projectRoot, source)))\n .map(([subpath]) => subpath),\n ...(findings.offersRoutes ? [] : [\"./connect-routes\"]),\n ]);\n\nconst notWritten = (why: string) =>\n new BuildRefusal(\n `✘ No release approval was written: ${why}. The new output is in place; build again with --release to approve it.`,\n );\n\n/**\n * With `--release`, once the output is replaced: records what the release\n * check approved and what `npm pack` publishes from the new output, unless\n * tsc's errors were accepted, the package changed while it was built, or the\n * packed tarball fails to install and import in a scratch consumer.\n */\nexport const releaseApprovalStep: StandardBuildStep = {\n id: \"release-approval\",\n when: \"committed\",\n run: async ({ args, projectRoot, outDir, session, findings }) => {\n if (args.release) {\n await recordApproval(\n projectRoot,\n outputDirectories(projectRoot, outDir, session.output),\n findings,\n session,\n );\n }\n },\n};\n\nasync function recordApproval(\n projectRoot: string,\n outputs: readonly [string, ...string[]],\n findings: BuildFindings,\n session: BuildSession,\n): Promise<void> {\n const plan = planApproval({\n typesOk: findings.typesOk,\n release: findings.release,\n startFiles: findings.releaseStart,\n outputs,\n compilerOutputs: findings.compilerOutputs.map((path) =>\n packagePath(projectRoot, path),\n ),\n });\n if (\"refused\" in plan) throw notWritten(plan.refused);\n const { release, excluded } = plan;\n const [output] = outputs;\n const files = revisionFiles(projectRoot, [output, ...excluded]);\n const changed = changedWhileBuilt(plan, files);\n if (changed !== undefined) throw notWritten(changed);\n let packed: PackedRelease;\n try {\n packed = packRelease(projectRoot);\n } catch (error) {\n throw notWritten(error instanceof Error ? error.message : String(error));\n }\n let published: FileDigest[];\n const stop = new AbortController();\n const unwatch = session.onCancel(() => {\n stop.abort();\n packed.dispose();\n });\n try {\n const failures = await checkPackedConsumer(\n projectRoot,\n packed,\n unbuiltExports(projectRoot, findings),\n stop.signal,\n );\n if (failures.length > 0) {\n throw notWritten(\n `the packed package does not install and import in a scratch consumer: ${listed(failures)}`,\n );\n }\n published = packedDigests(packed);\n } finally {\n unwatch();\n packed.dispose();\n }\n const phCliVersion = getVersion();\n writeReleaseApproval(projectRoot, {\n kind: \"powerhouse.release-approval\",\n formatVersion: 1,\n phCliVersion,\n outDir: output,\n packageRevision: {\n digest: packageRevision(files, { [PH_CLI_BINDING]: phCliVersion }),\n excluded,\n },\n publishedFiles: published,\n report: {\n profile: \"release\",\n status: release.report.status,\n definitions: release.report.definitions,\n },\n scalars: release.scalars,\n hostValidation: release.host,\n });\n console.log(`✔ Release approval written to ${RELEASE_APPROVAL_PATH}`);\n}\n","import {\n localPackageNames,\n packageStyleEntry,\n packageStylesheet,\n} from \"@powerhousedao/shared/clis/package-style\";\nimport { execSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join, relative, resolve } from \"node:path\";\nimport { resolveCommand } from \"package-manager-detector\";\nimport { BuildRefusal } from \"../pipeline/steps.js\";\nimport type { StandardBuildStep } from \"./context.js\";\n\n// A path for `@source`, relative to the project, with forward slashes.\nfunction sourcePath(projectRoot: string, path: string) {\n return `./${relative(projectRoot, resolve(projectRoot, path)).replaceAll(\"\\\\\", \"/\")}`;\n}\n\n// The classes the browser build uses, and the package's tokens and rules, against\n// Connect's theme: the Connect that loads it has Tailwind's reset and Connect's classes.\nexport const stylesheetStep: StandardBuildStep = {\n id: \"stylesheet\",\n run: ({ agent, projectRoot, session }) => {\n const stage = session.stage();\n const command = resolveCommand(agent, \"execute-local\", [\n \"tailwindcss\",\n \"--input\",\n \"-\",\n \"--minify\",\n ]);\n if (command === null) {\n throw new BuildRefusal(\n \"You need to have tailwindcss installed to use the `build` command.\",\n );\n }\n const stylePath = join(projectRoot, \"style.css\");\n const style = existsSync(stylePath)\n ? readFileSync(stylePath, \"utf-8\")\n : undefined;\n const compiled = execSync(`${command.command} ${command.args.join(\" \")}`, {\n cwd: projectRoot,\n input: packageStyleEntry(style, {\n browserDir: sourcePath(projectRoot, join(stage, \"browser\")),\n localPackages: localPackageNames(projectRoot),\n }),\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n // A package that imports large vendor CSS outgrows the 1 MB default.\n maxBuffer: 64 * 1024 * 1024,\n });\n // `ph build` with another out-dir (the switchboard runner's) leaves no\n // staged dist/, so the stylesheet goes to dist/ directly, as it always has.\n const distDir = session.writesPackageDist\n ? stage\n : join(projectRoot, \"dist\");\n mkdirSync(distDir, { recursive: true });\n writeFileSync(join(distDir, \"style.css\"), packageStylesheet(compiled));\n return Promise.resolve();\n },\n};\n","import { execSync } from \"node:child_process\";\nimport { existsSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { type Agent, resolveCommand } from \"package-manager-detector\";\nimport { BuildRefusal } from \"../pipeline/steps.js\";\nimport { BUILD_DIRECTORY } from \"../../build-control.js\";\nimport {\n declarationDirectory,\n type EmitOptions,\n} from \"../../compiler-output/emit.js\";\nimport { compilerOutputs } from \"../staging/compiler.js\";\nimport { parseShownConfig, type ShownConfig } from \"../staging/inventory.js\";\nimport type { StandardBuildStep } from \"./context.js\";\n\nconst TYPE_ERROR_RISK =\n \"A package built with type errors can load and still fail at runtime.\";\n\nexport const UNSAFE_BUILD_WARNING =\n \"⚠ Built despite type errors. \" +\n TYPE_ERROR_RISK +\n \" Fix them before you publish or deploy it.\";\n\n/** The root project's config, as `tsc --showConfig` prints it. */\nfunction showCompilerConfig(\n agent: Agent,\n projectRoot: string,\n): ShownConfig | undefined {\n const showConfig = resolveCommand(agent, \"execute-local\", [\n \"tsc\",\n \"--showConfig\",\n ]);\n if (showConfig === null) return undefined;\n try {\n const output = execSync(\n `${showConfig.command} ${showConfig.args.join(\" \")}`,\n {\n cwd: projectRoot,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n },\n );\n return parseShownConfig(output);\n } catch {\n return undefined;\n }\n}\n\n// tsc's build info outlives a deleted dist; with the declarations gone, tsc\n// would call the project up to date and emit nothing.\nfunction declarationsMissing(\n options: EmitOptions,\n projectRoot: string,\n): boolean {\n const path = declarationDirectory(options, projectRoot);\n if (path === undefined) return false;\n return !existsSync(path) || readdirSync(path).length === 0;\n}\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function confirmBuildDespiteTypeErrors(): Promise<void> {\n const hint =\n \"Fix them and build again. --ignore-type-errors skips this check, at the risk of shipping that failure.\";\n if (!isInteractive()) {\n throw new BuildRefusal(\n `\\n✘ tsc reported the type errors above. ${TYPE_ERROR_RISK}\\n${hint}`,\n );\n }\n const enquirer = await import(\"enquirer\");\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `tsc reported the type errors above. ${TYPE_ERROR_RISK} Build anyway?`,\n initial: false,\n });\n confirmed = answer.confirmed;\n } catch {\n // Ctrl-C at the prompt is a decline.\n confirmed = false;\n }\n if (!confirmed) throw new BuildRefusal(`Build cancelled. ${hint}`);\n}\n\n/**\n * Runs tsc, which checks the project and writes its declarations either way,\n * as `tsc --build` in the package: the same command, build info and output\n * places as without staging. When the session can, tsc builds a generated\n * sibling config that writes into the stage; otherwise what it rewrites is\n * copied first, so a build that does not finish puts it back.\n */\nexport const typecheckStep: StandardBuildStep = {\n id: \"typecheck\",\n run: async ({ agent, args, outDir, projectRoot, session, findings }) => {\n const config = showCompilerConfig(agent, projectRoot);\n const force =\n config !== undefined && declarationsMissing(config.options, projectRoot);\n let generated: string | undefined;\n if (config !== undefined) {\n const configFile = join(projectRoot, \"tsconfig.json\");\n const outputs = await compilerOutputs(config, {\n configFile,\n packageRoot: projectRoot,\n buildDirectory: join(projectRoot, BUILD_DIRECTORY),\n agent,\n output: session.output,\n });\n generated = await session.prepareCompiler({\n configFile,\n config,\n outputs,\n });\n findings.compilerOutputs = outputs.map(({ path }) => path);\n }\n const tscCommand = resolveCommand(agent, \"execute-local\", [\n \"tsc\",\n \"--build\",\n ...(force ? [\"--force\"] : []),\n ...(generated ? [relative(projectRoot, generated)] : []),\n ]);\n if (tscCommand === null) {\n throw new BuildRefusal(\n \"You need to have typescript installed to use the `build` command.\",\n );\n }\n console.log(\"\\n▶ Type-checking and emitting types via tsc...\");\n try {\n execSync(`${tscCommand.command} ${tscCommand.args.join(\" \")}`, {\n stdio: \"inherit\",\n });\n console.log(\"✔ Types emitted to\", join(outDir, \"types\"));\n findings.typesOk = true;\n } catch {\n findings.typesOk = false;\n }\n session.compilerOutputsWritten();\n // Before any bundler runs, so declining leaves nothing half built.\n if (!findings.typesOk && !args.ignoreTypeErrors) {\n await confirmBuildDespiteTypeErrors();\n }\n },\n};\n","import { browserBundleStep, nodeBundleStep } from \"./bundles.js\";\nimport { connectRoutesStep } from \"./connect-routes.js\";\nimport type { StandardBuildStep } from \"./context.js\";\nimport { definitionsStep } from \"./definitions.js\";\nimport { manifestNameStep, piecesOutDirStep } from \"./package-checks.js\";\nimport { distManifestStep, offeredRoutesStep, piecesStep } from \"./pieces.js\";\nimport { releaseApprovalStep, releaseStartStep } from \"./release-approval.js\";\nimport { stylesheetStep } from \"./stylesheet.js\";\nimport { typecheckStep } from \"./typecheck.js\";\n\n/**\n * `ph build`'s steps in the order they run. Another phase inserts its own\n * with `[...standardBuildSteps, ...more]` and `after` on the step it follows.\n */\nexport const standardBuildSteps: readonly StandardBuildStep[] = [\n releaseStartStep,\n manifestNameStep,\n piecesOutDirStep,\n connectRoutesStep,\n typecheckStep,\n definitionsStep,\n browserBundleStep,\n nodeBundleStep,\n piecesStep,\n distManifestStep,\n offeredRoutesStep,\n stylesheetStep,\n releaseApprovalStep,\n];\n","import type { TraceFiles } from \"@powerhousedao/shared/build-pieces\";\nimport { resolve } from \"node:path\";\nimport { nodeFileTrace } from \"@vercel/nft\";\n\n// nft reports paths relative to its base; from \"/\" that is every path minus its root.\n// One cache per build: the traces of a project's packages share most files.\nexport function createTraceFiles(): TraceFiles {\n const cache = {};\n return (file) => traceFile(file, cache);\n}\n\nexport const traceFiles: TraceFiles = createTraceFiles();\n\nasync function traceFile(file: string, cache: object) {\n const { fileList, reasons } = await nodeFileTrace([file], {\n base: \"/\",\n cache,\n });\n const absolute = (p: string) => resolve(\"/\", p);\n return {\n fileList: new Set([...fileList].map(absolute)),\n reasons: new Map(\n [...reasons].map(([p, reason]) => [\n absolute(p),\n { parents: new Set([...reason.parents].map(absolute)) },\n ]),\n ),\n };\n}\n","import { planPieces } from \"@powerhousedao/shared/build-pieces\";\nimport { createDetectionCache } from \"@powerhousedao/shared/build-pieces\";\nimport { detect } from \"package-manager-detector\";\nimport type { BuildArgs } from \"../../types.js\";\nimport { runBuildSteps } from \"./pipeline/run-steps.js\";\nimport { openBuildSession } from \"./staging/open.js\";\nimport type { BuildSession } from \"./staging/session.js\";\nimport { entriesCleanedBy } from \"./steps/bundles.js\";\nimport type { BuildContext, StandardBuildStep } from \"./steps/context.js\";\nimport { standardBuildSteps } from \"./steps/standard.js\";\nimport { createTraceFiles } from \"./steps/trace.js\";\nimport { UNSAFE_BUILD_WARNING } from \"./steps/typecheck.js\";\n\nexport type BuildOptions = {\n readonly steps?: readonly StandardBuildStep[];\n /**\n * Check the package's definitions, importing its modules in a child\n * process. Only `ph build` asks; `--release` always checks.\n */\n readonly checkDefinitions?: boolean;\n /**\n * This process belongs to ph-cli and loads no package code, so a stop\n * signal ends it: the lock can go before the signal is re-raised, and a\n * next build on another host does not wait for it. An embedding process\n * (the switchboard runner) keeps the lock until the running step settles,\n * since one of its signal-exit callbacks may keep the process alive.\n */\n readonly ownsProcess?: boolean;\n};\n\nconst STOP_SIGNALS = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const;\n\n/**\n * The signal listeners signal-exit installs: each ends the process when\n * only signal-exit listeners are left, so they are not an embedding\n * process that keeps running. Read from the counts its copies share.\n */\nfunction exitOnlyListeners(): number {\n const count = (emitter: unknown) => {\n const value = (emitter as { count?: unknown } | undefined)?.count;\n return typeof value === \"number\" ? value : 0;\n };\n const shared = globalThis as Record<symbol, unknown>;\n const legacy = process as unknown as Record<string, unknown>;\n return (\n count(shared[Symbol.for(\"signal-exit emitter\")]) +\n count(legacy.__signal_exit_emitter__)\n );\n}\n\n/**\n * Stops the build when the process is told to stop, for as long as it runs.\n * The handler runs first and removes itself, so the listeners already there\n * act as if it had never been added. When one of them keeps the process\n * running (an embedding process), the handler only cancels: the step runner\n * rolls back once the running step settles, and the lock is released after\n * that. Otherwise the process should end with the signal: the handler\n * restores the previous output at once, releases the lock and, with no\n * listener left, re-raises the signal. The run and its snapshot stay for\n * the next build to replay. The lock does not: a dead owner's lock is taken\n * over only from the same host, which a new container or a renamed machine\n * is not. A signal-exit callback can still keep the process running; then\n * the runner restores again from that snapshot once the running step\n * settles.\n */\nfunction stopOnSignal(session: BuildSession, ownsProcess: boolean): () => void {\n const stop = (signal: NodeJS.Signals) => {\n session.cancel(signal);\n remove();\n if (process.listenerCount(signal) > exitOnlyListeners()) return;\n session.rollback();\n if (ownsProcess) session.releaseLock();\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n };\n const remove = () => {\n for (const signal of STOP_SIGNALS) process.removeListener(signal, stop);\n };\n for (const signal of STOP_SIGNALS) process.prependListener(signal, stop);\n return remove;\n}\n\n/**\n * Builds the package in the current directory: every step writes to a stage,\n * which replaces the output directory only when all of them succeed. A\n * failure, a refusal or a stop signal leaves the previous output and\n * compiler outputs as they were.\n */\nexport async function buildPackage(\n args: BuildArgs,\n options: BuildOptions = {},\n): Promise<void> {\n const { outDir } = args;\n const projectRoot = process.cwd();\n const steps = options.steps ?? standardBuildSteps;\n const session = await openBuildSession({\n packageRoot: projectRoot,\n outDir,\n cleanedEntries: entriesCleanedBy(steps),\n // Only in the standard list does no step write those entries before\n // the bundle steps empty them, which seeding them by hard link needs.\n linkCleanedEntries: options.steps === undefined,\n });\n const stopListening = stopOnSignal(session, options.ownsProcess ?? false);\n try {\n const detectResult = await detect();\n const ctx: BuildContext = {\n args,\n projectRoot,\n outDir,\n agent: detectResult?.agent ?? \"npm\",\n session,\n checkDefinitions: options.checkDefinitions ?? false,\n pieces: planPieces(projectRoot, outDir),\n detection: createDetectionCache(),\n trace: createTraceFiles(),\n findings: {\n offersRoutes: false,\n typesOk: true,\n compilerOutputs: [],\n releaseStart: undefined,\n release: undefined,\n external: new Map(),\n pkg: undefined,\n built: [],\n },\n };\n await runBuildSteps(steps, ctx, session);\n // Last, so it is the line a finished build leaves on screen.\n if (!ctx.findings.typesOk) console.warn(`\\n${UNSAFE_BUILD_WARNING}`);\n } finally {\n stopListening();\n session.rollback();\n session.close();\n }\n}\n","import { join } from \"node:path\";\nimport { checkInChild } from \"./package-build/steps/definitions.js\";\nimport type { StandardBuildStep } from \"./package-build/steps/context.js\";\n\n/** The definitions step checks the package, subgraphs included, unless\n * discovery skips it, as it does for a package with no document model. */\nasync function definitionsStepCoversSubgraphs(\n projectRoot: string,\n): Promise<boolean> {\n const { resolveDefinitionSelection } = await import(\"document-model/tooling\");\n const selection = resolveDefinitionSelection({\n configFile: join(projectRoot, \"powerhouse.config.json\"),\n allowMissingConfig: true,\n });\n return selection.status !== \"skipped\";\n}\n\n/**\n * Checks a package's code-first subgraphs in `ph build`'s edit profile when\n * the definitions step does not: a package where discovery skips it. Under `--release` the definitions\n * step runs the release profile, which carries the subgraph checks and\n * refuses on their errors.\n */\nexport function subgraphStepWithin(timeoutMs: number): StandardBuildStep {\n return {\n id: \"subgraphs\",\n after: [\"definitions\"],\n run: async ({ args, checkDefinitions, projectRoot, session }) => {\n if (args.release || !checkDefinitions) return;\n if (await definitionsStepCoversSubgraphs(projectRoot)) return;\n const { renderCheckReport } = await import(\"./model/render.js\");\n console.log(\"\\n▶ Checking subgraph definitions...\");\n const edit = await checkInChild(projectRoot, \"edit\", session, timeoutMs);\n if (!edit.ok) {\n console.warn(`⚠ The subgraph check could not run: ${edit.message}`);\n return;\n }\n const text = renderCheckReport(edit.result);\n if (edit.result.diagnostics.length > 0) {\n console.warn(\n `⚠ The subgraph check reported problems; the build goes on:\\n${text}`,\n );\n } else {\n console.log(`✔ ${text}`);\n }\n },\n };\n}\n\nexport const subgraphStep = subgraphStepWithin(5 * 60_000);\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { BuildArgs } from \"../types.js\";\nimport { BuildRefusal } from \"./package-build/pipeline/steps.js\";\nimport { type BuildOptions, buildPackage } from \"./package-build/run-build.js\";\nimport { standardBuildSteps } from \"./package-build/steps/standard.js\";\nimport { subgraphStep } from \"./subgraph-build-step.js\";\n\nexport { assertExternalDependenciesDeclared } from \"./package-build/steps/bundles.js\";\nexport { assertManifestNameMatchesPackage } from \"./package-build/steps/package-checks.js\";\nexport { createTraceFiles, traceFiles } from \"./package-build/steps/trace.js\";\n\n/**\n * The gate loads codegen, so a build without `checkDefinitions` or without a\n * `subgraphs/` directory never imports it.\n */\nasync function withSubgraphStep(options: BuildOptions): Promise<BuildOptions> {\n if (!options.checkDefinitions) return options;\n if (!existsSync(join(process.cwd(), \"subgraphs\"))) return options;\n const { hasCodeFirstSubgraph } = await import(\"./model/subgraph-gate.js\");\n if (!hasCodeFirstSubgraph(process.cwd())) return options;\n return {\n ...options,\n steps: [...(options.steps ?? standardBuildSteps), subgraphStep],\n };\n}\n\n/**\n * `ph build`, and the package build `ph connect build` and the switchboard\n * runner start from. A refusal (missing tsc or tailwindcss, type errors not\n * accepted, a release check that fails) prints its message and exits 1 once\n * the previous output is back, as these callers have always seen it.\n * Only `ph build` passes `checkDefinitions`, so the other callers import\n * none of the package's modules. A command that adds steps passes\n * `[...standardBuildSteps, ...its own]` as `steps`.\n */\nexport async function runBuild(\n args: BuildArgs,\n options: BuildOptions = {},\n): Promise<void> {\n try {\n return await buildPackage(args, await withSubgraphStep(options));\n } catch (error) {\n if (!(error instanceof BuildRefusal)) throw error;\n console.error(error.message);\n process.exit(error.exitCode);\n }\n}\n"],"names":["nodePath","sleep","outputDirectories","configSchema","z.object","z.union","z.string","z.array","z.record","z.json","z\n .record","z.object","z.looseObject","z.boolean","z.string","z.array","z\n .object","outputDirectories","outputDirectories","tsdownBuild","tsdownBuild","under"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,eAAb,cAAkC,MAAM;CACtC;CAEA,YAAY,SAAiB,WAAW,GAAG;EACzC,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;AAGA,IAAa,eAAb,cAAkC,MAAM;CACtC;CAEA,YAAY,QAAgB;EAC1B,MAAM,4BAA4B,OAAO,qBAAqB;EAC9D,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAEA,SAAS,aACP,OACwC;CACxC,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,EAAE,QAAQ,OAAO;EAC1B,IAAI,IAAI,IAAI,EAAE,GAAG,MAAM,IAAI,MAAM,eAAe,GAAG,mBAAmB;EACtE,IAAI,IAAI,EAAE;CACZ;CACA,MAAM,YAAY,IAAI,IACpB,MAAM,QAAQ,EAAE,WAAW,SAAS,WAAW,CAAC,CAAC,KAAK,EAAE,SAAS,EAAE,CACrE;CACA,MAAM,wBAAQ,IAAI,IAA+B;CACjD,MAAM,SAAS,MAAM,UAAU;EAC7B,MAA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