@powerhousedao/ph-cli 6.2.3-dev.96 → 6.2.3-dev.98

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.
Files changed (72) hide show
  1. package/dist/build--EI1OAjL.mjs +4 -0
  2. package/dist/{build-CVEsxazW.mjs → build-BlubqQME.mjs} +1182 -207
  3. package/dist/build-BlubqQME.mjs.map +1 -0
  4. package/dist/{check-d-VEsSZX.mjs → check-Cco7-UC2.mjs} +4 -4
  5. package/dist/{check-d-VEsSZX.mjs.map → check-Cco7-UC2.mjs.map} +1 -1
  6. package/dist/{check-DugP5VXV.mjs → check-CzNvklyE.mjs} +6 -6
  7. package/dist/{check-DugP5VXV.mjs.map → check-CzNvklyE.mjs.map} +1 -1
  8. package/dist/{check-_Vx8VsdJ.mjs → check-DQV3IopN.mjs} +3 -3
  9. package/dist/{cli-connect-override-BQr3yjC_.mjs → cli-connect-override-D3N3gbp_.mjs} +4 -4
  10. package/dist/{cli-connect-override-BQr3yjC_.mjs.map → cli-connect-override-D3N3gbp_.mjs.map} +1 -1
  11. package/dist/cli.mjs +4 -4
  12. package/dist/{compound-DO_mvh0O-D254asEo.mjs → compound-DO_mvh0O-Dp1YPhR0.mjs} +4 -4
  13. package/dist/{compound-DO_mvh0O-D254asEo.mjs.map → compound-DO_mvh0O-Dp1YPhR0.mjs.map} +1 -1
  14. package/dist/{connect-build-B3EnwJRo.mjs → connect-build-DEpfBUSe.mjs} +6 -6
  15. package/dist/{connect-build-B3EnwJRo.mjs.map → connect-build-DEpfBUSe.mjs.map} +1 -1
  16. package/dist/{connect-config-DWJf22Ro.mjs → connect-config-C6hKMsUG.mjs} +4 -4
  17. package/dist/{connect-config-DWJf22Ro.mjs.map → connect-config-C6hKMsUG.mjs.map} +1 -1
  18. package/dist/{connect-studio-DWty6fZd.mjs → connect-studio-C7Bbh50O.mjs} +4 -4
  19. package/dist/{connect-studio-DWty6fZd.mjs.map → connect-studio-C7Bbh50O.mjs.map} +1 -1
  20. package/dist/{connect-studio-DTZEwZ4C.mjs → connect-studio-xQNYl142.mjs} +3 -3
  21. package/dist/definitions-worker.d.mts +2 -0
  22. package/dist/definitions-worker.d.mts.map +1 -1
  23. package/dist/definitions-worker.mjs +1 -1
  24. package/dist/{dist-BOjmQhjX.mjs → dist-B-_lMGlB.mjs} +5 -5
  25. package/dist/{dist-BOjmQhjX.mjs.map → dist-B-_lMGlB.mjs.map} +1 -1
  26. package/dist/{evidence-BiMKzRLV.mjs → evidence-Dchpoogs.mjs} +4 -4
  27. package/dist/{evidence-BiMKzRLV.mjs.map → evidence-Dchpoogs.mjs.map} +1 -1
  28. package/dist/{explain-DKS-t7dS.mjs → explain-lynfOtDg.mjs} +5 -5
  29. package/dist/{explain-DKS-t7dS.mjs.map → explain-lynfOtDg.mjs.map} +1 -1
  30. package/dist/{export-DRw3XVfG.mjs → export-YkeGUZjR.mjs} +4 -4
  31. package/dist/{export-DRw3XVfG.mjs.map → export-YkeGUZjR.mjs.map} +1 -1
  32. package/dist/{files-D05VjxVj.mjs → files-D6_euBBn.mjs} +160 -53
  33. package/dist/files-D6_euBBn.mjs.map +1 -0
  34. package/dist/{generate-all-CMpNPpD8.mjs → generate-all-_7S0Iii2.mjs} +4 -4
  35. package/dist/{generate-all-CMpNPpD8.mjs.map → generate-all-_7S0Iii2.mjs.map} +1 -1
  36. package/dist/{generate-desktop-shell-B-Rf7ds8.mjs → generate-desktop-shell-CEcE_1gb.mjs} +5 -5
  37. package/dist/{generate-desktop-shell-B-Rf7ds8.mjs.map → generate-desktop-shell-CEcE_1gb.mjs.map} +1 -1
  38. package/dist/{get-version-CRMIOXgn.mjs → get-version-JUaeclcJ.mjs} +4 -4
  39. package/dist/{get-version-CRMIOXgn.mjs.map → get-version-JUaeclcJ.mjs.map} +1 -1
  40. package/dist/{init-Ch1rCksS.mjs → init-BjwbWklG.mjs} +12 -7
  41. package/dist/init-BjwbWklG.mjs.map +1 -0
  42. package/dist/{inspect-DlRPzee1.mjs → inspect-BpVHe9vz.mjs} +4 -4
  43. package/dist/{inspect-DlRPzee1.mjs.map → inspect-BpVHe9vz.mjs.map} +1 -1
  44. package/dist/{mcp-fJTu0s28.mjs → mcp-D9ZXXoSG.mjs} +4 -4
  45. package/dist/{mcp-fJTu0s28.mjs.map → mcp-D9ZXXoSG.mjs.map} +1 -1
  46. package/dist/{migrate-B9F_cSCA.mjs → migrate-B-MM9TlS.mjs} +4 -4
  47. package/dist/{migrate-B9F_cSCA.mjs.map → migrate-B-MM9TlS.mjs.map} +1 -1
  48. package/dist/ph-cli-commands-p8F2fENt.mjs +4 -0
  49. package/dist/{ph-cli-commands-CpLnxWAd.mjs → ph-cli-commands-racSfAU6.mjs} +96 -88
  50. package/dist/{ph-cli-commands-CpLnxWAd.mjs.map → ph-cli-commands-racSfAU6.mjs.map} +1 -1
  51. package/dist/{render-BinrNDU0.mjs → render-BO-Nwn2H.mjs} +6 -9
  52. package/dist/render-BO-Nwn2H.mjs.map +1 -0
  53. package/dist/render-DdieUjtg.mjs +4 -0
  54. package/dist/{run-sugar-yf2ggYJ9.mjs → run-sugar-D9lIzhAx.mjs} +4 -4
  55. package/dist/{run-sugar-yf2ggYJ9.mjs.map → run-sugar-D9lIzhAx.mjs.map} +1 -1
  56. package/dist/runners/connect.mjs +2 -2
  57. package/dist/runners/switchboard.mjs +1 -1
  58. package/dist/{schemas-ZQiV98u4.mjs → schemas-DzgKfQIx.mjs} +94 -4
  59. package/dist/{schemas-ZQiV98u4.mjs.map → schemas-DzgKfQIx.mjs.map} +1 -1
  60. package/dist/{verify-Dw_VUM2U.mjs → verify-DmO_x14L.mjs} +21 -14
  61. package/dist/verify-DmO_x14L.mjs.map +1 -0
  62. package/dist/{vetra-CdYsxlvS.mjs → vetra-DSFzAl_1.mjs} +6 -6
  63. package/dist/{vetra-CdYsxlvS.mjs.map → vetra-DSFzAl_1.mjs.map} +1 -1
  64. package/package.json +16 -16
  65. package/dist/build-CH3XMW4i.mjs +0 -4
  66. package/dist/build-CVEsxazW.mjs.map +0 -1
  67. package/dist/files-D05VjxVj.mjs.map +0 -1
  68. package/dist/init-Ch1rCksS.mjs.map +0 -1
  69. package/dist/ph-cli-commands-CHLBIDlQ.mjs +0 -4
  70. package/dist/render-BinrNDU0.mjs.map +0 -1
  71. package/dist/render-CTQG4359.mjs +0 -4
  72. package/dist/verify-Dw_VUM2U.mjs.map +0 -1
@@ -1,18 +1,22 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0939018c-cae4-50f2-804c-a7ec85183c00")}catch(e){}}();
3
- import { t as getVersion } from "./get-version-CRMIOXgn.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8efa3bd1-04ef-5d3a-8bcd-0da6b4001c3a")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-JUaeclcJ.mjs";
4
+ import { _ as pendingPrefix, a as writeReleaseApproval, c as PH_CLI_BINDING, d as listed, g as LOCK_FILE, h as BUILD_DIRECTORY, i as revisionFiles, l as RELEASE_APPROVAL_PATH, m as packageRevision, o as packRelease, p as changedPaths, s as packedDigests, t as packagePath, v as takeoverPrefix } from "./files-D6_euBBn.mjs";
5
+ import { d as object, f as record, g as union, i as boolean, l as looseObject, m as string, r as array, s as json } from "./schemas-DzgKfQIx.mjs";
4
6
  import { n as OFFERED_ROUTES_MODULE, r as syncProjectConnectRoutes, t as HOST_ROUTES_DIR } from "./sync-connect-routes-t0Slg-P6.mjs";
5
7
  import { r as noConnectImports } from "./offered-routes-imports-CalXK9dh.mjs";
6
- import { a as writeReleaseApproval, d as changedPaths, f as packageRevision, i as revisionFiles, l as listed, n as publishedFiles, o as PH_CLI_BINDING, s as RELEASE_APPROVAL_PATH, t as packagePath } from "./files-D05VjxVj.mjs";
7
8
  import { createRequire } from "node:module";
8
- import { accessSync, chmodSync, constants, cpSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
9
+ import { accessSync, chmodSync, constants, cpSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
9
10
  import path, { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
- import { execFileSync, execSync, fork } from "node:child_process";
11
+ import { execFileSync, execSync, fork, spawn } from "node:child_process";
12
+ import { SpawnError, spawnAsync } from "@powerhousedao/shared/clis";
11
13
  import { assertPiecesOutDir, buildPieces, createDetectionCache, expandEntryGlobs, externalDependencyVersions, externalDepsPlugin, pieceListPath, planPieces, projectPath, syncDistManifest, undeclaredExternalDependencies } from "@powerhousedao/shared/build-pieces";
12
14
  import { detect, resolveCommand } from "package-manager-detector";
13
- import { randomBytes } from "node:crypto";
14
- import { hostname } from "node:os";
15
+ import { createHash, randomBytes } from "node:crypto";
16
+ import { pathWithin, realPathThroughExistingParent } from "@powerhousedao/shared/clis/real-paths";
17
+ import { hostname, tmpdir } from "node:os";
15
18
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
+ import { satisfies } from "semver";
16
20
  import { browserEntry, buildBrowserBuildConfig, buildNodeBuildConfig, findBundledSharedDeps } from "@powerhousedao/shared/build-config";
17
21
  import { EXTERNALIZABLE_SHARED_SPECIFIERS, findSharedImports } from "@powerhousedao/shared/connect";
18
22
  import { readPackage } from "read-pkg";
@@ -116,29 +120,6 @@ async function runBuildSteps(steps, ctx, session) {
116
120
  }
117
121
  }
118
122
  //#endregion
119
- //#region src/services/definitions/paths.ts
120
- function canonicalPath(path, options = {}) {
121
- const absolute = resolve(path);
122
- let ancestor = absolute;
123
- while (lstatSync(ancestor, { throwIfNoEntry: false }) === void 0) {
124
- const parent = dirname(ancestor);
125
- if (parent === ancestor) break;
126
- ancestor = parent;
127
- }
128
- let canonical;
129
- try {
130
- canonical = realpathSync.native(ancestor);
131
- } catch (error) {
132
- if (options.resolveMissingLinks !== true || !(error instanceof Error && "code" in error && error.code === "ENOENT") || !lstatSync(ancestor, { throwIfNoEntry: false })?.isSymbolicLink()) throw error;
133
- canonical = canonicalPath(resolve(dirname(ancestor), readlinkSync(ancestor)), options);
134
- }
135
- return resolve(canonical, relative(ancestor, absolute));
136
- }
137
- function pathWithin(root, path) {
138
- const inside = relative(root, path);
139
- return inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside) ? null : inside;
140
- }
141
- //#endregion
142
123
  //#region src/services/package-build/staging/files.ts
143
124
  function exists(path) {
144
125
  return lstatSync(path, { throwIfNoEntry: false }) !== void 0;
@@ -228,6 +209,51 @@ function removeTree(path) {
228
209
  }
229
210
  }
230
211
  /**
212
+ * Makes `path` a copy of `from`. A directory that is there is emptied and
213
+ * refilled rather than removed, so a mount point or a directory another
214
+ * process holds stays where it is.
215
+ */
216
+ function replaceTree(from, path) {
217
+ if (!(lstatSync(path, { throwIfNoEntry: false })?.isDirectory() && lstatSync(from).isDirectory())) {
218
+ removeTree(path);
219
+ cloneTree(from, path);
220
+ return;
221
+ }
222
+ openDirectories(path);
223
+ for (const entry of readdirSync(path)) removeTree(join(path, entry));
224
+ cloneTree(from, path);
225
+ }
226
+ /**
227
+ * The tree by the bytes of its files and the targets of its links. Times
228
+ * and inodes are left out: a touch changes them, and a rewrite can keep them.
229
+ */
230
+ function treeFingerprint(root, skipped, unmarked = /* @__PURE__ */ new Set()) {
231
+ const hash = createHash("sha256");
232
+ const visit = (path, rel) => {
233
+ const stat = lstatSync(path);
234
+ if (stat.isFile()) {
235
+ const bytes = readFileSync(path);
236
+ hash.update(`f\0${rel}\0${bytes.length}\0`).update(bytes);
237
+ return;
238
+ }
239
+ if (stat.isSymbolicLink()) {
240
+ hash.update(`l\0${rel}\0${readlinkSync(path)}\0`);
241
+ return;
242
+ }
243
+ if (!stat.isDirectory()) {
244
+ hash.update(`o\0${rel}\0`);
245
+ return;
246
+ }
247
+ if (rel !== "" && !unmarked.has(rel)) hash.update(`d\0${rel}\0`);
248
+ for (const entry of readdirSync(path).sort()) {
249
+ const child = rel === "" ? entry : `${rel}/${entry}`;
250
+ if (!skipped.has(child)) visit(join(path, entry), child);
251
+ }
252
+ };
253
+ if (exists(root)) visit(root, "");
254
+ return hash.digest("hex");
255
+ }
256
+ /**
231
257
  * The first entry of the tree at `path`, itself included, that the stage
232
258
  * cannot copy as it is, and why: a FIFO, socket or device, which a copy
233
259
  * cannot represent, or a file or directory this process cannot read. Only
@@ -316,10 +342,7 @@ async function creating(where, create) {
316
342
  }
317
343
  //#endregion
318
344
  //#region src/services/package-build/staging/journal.ts
319
- /** Scratch space of `ph build`, per package. */
320
- const BUILD_DIRECTORY = join(".ph", "build");
321
345
  const RUNS_DIRECTORY = join(BUILD_DIRECTORY, "runs");
322
- const LOCK_FILE = join(BUILD_DIRECTORY, "lock");
323
346
  const JOURNAL_FILE = "journal.json";
324
347
  /**
325
348
  * The steps of a rollback, in order, each safe to repeat:
@@ -385,6 +408,15 @@ function parseSnapshot(value) {
385
408
  modes
386
409
  };
387
410
  }
411
+ function parsePendingBuildInfo(value) {
412
+ if (value === void 0) return void 0;
413
+ if (typeof value !== "object" || value === null) return null;
414
+ const { path, target } = value;
415
+ return isString(path) && isString(target) ? {
416
+ path,
417
+ target
418
+ } : null;
419
+ }
388
420
  const isDirectoryMode = (value) => Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && Number.isInteger(value[1]);
389
421
  /** The journal of a run directory, or undefined when it is missing or unreadable. */
390
422
  function readJournal(runDir) {
@@ -397,6 +429,10 @@ function readJournal(runDir) {
397
429
  if (typeof value !== "object" || value === null) return void 0;
398
430
  const record = value;
399
431
  if (record.format !== 1 || !isString(record.runId) || typeof record.pid !== "number" || !STATES.includes(record.state) || !isString(record.output) || !isString(record.stage) || !isString(record.retired)) return;
432
+ const optional = (key) => record[key] === void 0 || isString(record[key]);
433
+ if (!optional("generatedConfig") || !optional("outputDigest")) return void 0;
434
+ const pending = parsePendingBuildInfo(record.pendingBuildInfo);
435
+ if (pending === null) return void 0;
400
436
  const undo = UNDO_STEPS.find((step) => step === record.undo) ?? null;
401
437
  if (record.state === "rolling-back" !== (undo !== null)) return void 0;
402
438
  let compiler = null;
@@ -417,7 +453,10 @@ function readJournal(runDir) {
417
453
  output: record.output,
418
454
  stage: record.stage,
419
455
  retired: record.retired,
420
- compiler
456
+ compiler,
457
+ ...isString(record.generatedConfig) && { generatedConfig: record.generatedConfig },
458
+ ...pending !== void 0 && { pendingBuildInfo: pending },
459
+ ...isString(record.outputDigest) && { outputDigest: record.outputDigest }
421
460
  };
422
461
  }
423
462
  //#endregion
@@ -511,7 +550,7 @@ function holderOf(file) {
511
550
  * appears with its content in one link, so no reader sees it empty.
512
551
  */
513
552
  function createOwned(file, owner) {
514
- const pending = join(dirname(file), `.${basename(file)}.${owner.runId}.pending`);
553
+ const pending = join(dirname(file), `${pendingPrefix(basename(file))}${owner.runId}.pending`);
515
554
  writeFileSync(pending, JSON.stringify(owner));
516
555
  try {
517
556
  linkSync(pending, file);
@@ -523,7 +562,7 @@ function createOwned(file, owner) {
523
562
  rmSync(pending, { force: true });
524
563
  }
525
564
  }
526
- const takeoverFile = (lockFile, staleId) => `${lockFile}.takeover-${encodeURIComponent(staleId)}`;
565
+ const takeoverFile = (lockFile, staleId) => join(dirname(lockFile), `${takeoverPrefix(basename(lockFile))}${encodeURIComponent(staleId)}`);
527
566
  /**
528
567
  * Removes `file` while it still holds the dead holder `stale`. Only the
529
568
  * creator of the takeover file keyed to `stale` may remove it, and `stale`
@@ -557,8 +596,8 @@ function takeOver(lockFile, file, stale, me) {
557
596
  * contender links it next.
558
597
  */
559
598
  function removeTakeoverFiles(lockFile) {
560
- const takeover = `${basename(lockFile)}.takeover-`;
561
- const pending = `.${basename(lockFile)}.`;
599
+ const takeover = takeoverPrefix(basename(lockFile));
600
+ const pending = pendingPrefix(basename(lockFile));
562
601
  for (const entry of readdirSync(dirname(lockFile))) {
563
602
  const file = join(dirname(lockFile), entry);
564
603
  if (entry.startsWith(takeover) || entry.startsWith(pending) && entry.endsWith(".pending") && holderOf(file)?.dead === true) rmSync(file, { force: true });
@@ -613,6 +652,15 @@ async function acquireBuildLock(lockFile, runId, onWait) {
613
652
  }
614
653
  }
615
654
  //#endregion
655
+ //#region src/services/definitions/paths.ts
656
+ function toPosixPath(path) {
657
+ return path.split(sep).join("/");
658
+ }
659
+ function canonicalConfigFile(configFile) {
660
+ const absolute = resolve(configFile);
661
+ return join(realPathThroughExistingParent(dirname(absolute)), basename(absolute));
662
+ }
663
+ //#endregion
616
664
  //#region src/services/package-build/staging/recovery.ts
617
665
  function runPaths(packageRoot, runDir, journal) {
618
666
  return {
@@ -623,6 +671,36 @@ function runPaths(packageRoot, runDir, journal) {
623
671
  retired: fromJournalPath(packageRoot, journal.retired)
624
672
  };
625
673
  }
674
+ function outputDigest(packageRoot, output, compiler) {
675
+ const real = realPathThroughExistingParent(output);
676
+ const inOutput = (recorded) => {
677
+ const rel = pathWithin(real, fromJournalPath(packageRoot, recorded));
678
+ return rel === null ? null : toPosixPath(rel);
679
+ };
680
+ const skipped = /* @__PURE__ */ new Set();
681
+ const unmarked = /* @__PURE__ */ new Set();
682
+ for (const { path, created } of compiler) {
683
+ if (pathWithin(fromJournalPath(packageRoot, path), real) !== null) return;
684
+ const rel = inOutput(path);
685
+ if (rel === null) continue;
686
+ skipped.add(rel);
687
+ if (created !== null) {
688
+ const parts = rel.split("/");
689
+ const createdRel = inOutput(created);
690
+ const first = createdRel ? createdRel.split("/").length : 1;
691
+ for (let length = first; length < parts.length; length++) unmarked.add(parts.slice(0, length).join("/"));
692
+ }
693
+ }
694
+ return treeFingerprint(output, skipped, unmarked);
695
+ }
696
+ function removeScratch(packageRoot, journal) {
697
+ for (const recorded of [journal.generatedConfig, journal.pendingBuildInfo?.path]) if (recorded !== void 0) removeTree(fromJournalPath(packageRoot, recorded));
698
+ }
699
+ function installBuildInfo(packageRoot, pending) {
700
+ if (pending === void 0) return;
701
+ const path = fromJournalPath(packageRoot, pending.path);
702
+ if (exists(path)) renamePatiently(path, fromJournalPath(packageRoot, pending.target));
703
+ }
626
704
  /** Puts `from` at `to`: one rename, or entry by entry when `from` is held open. */
627
705
  function moveTree(from, to) {
628
706
  try {
@@ -641,11 +719,13 @@ function restoreCompilerOutputs(paths, snapshots) {
641
719
  const ordered = [...snapshots ?? []].sort((a, b) => Number(b.kind === "build-info") - Number(a.kind === "build-info"));
642
720
  for (const snapshot of ordered) {
643
721
  const path = fromJournalPath(paths.packageRoot, snapshot.path);
644
- removeTree(path);
645
722
  if (snapshot.copy !== null) {
646
- cloneTree(fromJournalPath(paths.runDir, snapshot.copy), path);
723
+ replaceTree(fromJournalPath(paths.runDir, snapshot.copy), path);
647
724
  restoreDirectoryModes(path, snapshot.modes ?? []);
648
- } else if (snapshot.created !== null) removeEmptyDirectories(dirname(path), fromJournalPath(paths.packageRoot, snapshot.created));
725
+ continue;
726
+ }
727
+ removeTree(path);
728
+ if (snapshot.created !== null) removeEmptyDirectories(dirname(path), fromJournalPath(paths.packageRoot, snapshot.created));
649
729
  }
650
730
  }
651
731
  /** Removes `from` and its parents up to `upTo` while each is an empty directory. */
@@ -663,13 +743,14 @@ const FIRST_UNDO_STEP = {
663
743
  };
664
744
  /**
665
745
  * Undoes a run: the previous output goes back in place, the stage goes, and
666
- * the compiler outputs are restored. The journal records each step before
746
+ * the compiler outputs are restored, unless a later build replaced the output
747
+ * since they were saved (`superseded`). The journal records each step before
667
748
  * it starts, so a rollback cut short is finished by the next build, never
668
- * rolled forward; the run directory, and the snapshot in it, stay until
669
- * the caller removes them.
749
+ * rolled forward; the run directory, and the snapshot in it, stay until the
750
+ * caller removes them.
670
751
  */
671
752
  function rollBack(paths, journal) {
672
- if (journal.state === "committed") return;
753
+ if (journal.state === "committed") return "restored";
673
754
  const first = journal.state === "rolling-back" ? journal.undo ?? "stage" : FIRST_UNDO_STEP[journal.state];
674
755
  const { output, retired } = paths;
675
756
  for (const step of UNDO_STEPS.slice(UNDO_STEPS.indexOf(first))) {
@@ -689,19 +770,25 @@ function rollBack(paths, journal) {
689
770
  } else {
690
771
  removeTree(paths.stage);
691
772
  removeTree(retired);
773
+ removeScratch(paths.packageRoot, journal);
774
+ const digest = journal.outputDigest === void 0 ? void 0 : outputDigest(paths.packageRoot, output, journal.compiler ?? []);
775
+ if (digest !== void 0 && digest !== journal.outputDigest) return "superseded";
692
776
  restoreCompilerOutputs(paths, journal.compiler);
693
777
  }
694
778
  }
779
+ return "restored";
695
780
  }
696
781
  /** Finishes a run that was installing its stage: the stage becomes the output. */
697
- function rollForward(paths) {
782
+ function rollForward(paths, journal) {
698
783
  const { output, stage } = paths;
699
784
  if (exists(stage)) {
700
785
  if (exists(output)) moveEntries(stage, output);
701
786
  else moveTree(stage, output);
702
787
  }
788
+ installBuildInfo(paths.packageRoot, journal.pendingBuildInfo);
703
789
  removeTree(stage);
704
790
  removeTree(paths.retired);
791
+ removeScratch(paths.packageRoot, journal);
705
792
  }
706
793
  /**
707
794
  * Brings the package back to a consistent state after a run that died, then
@@ -714,11 +801,9 @@ function replayRun(packageRoot, runDir) {
714
801
  let replayed = "discarded";
715
802
  if (journal !== void 0) {
716
803
  const paths = runPaths(packageRoot, runDir, journal);
717
- if (journal.state !== "installing" && journal.state !== "committed") {
718
- rollBack(paths, journal);
719
- replayed = "rolled-back";
720
- } else {
721
- rollForward(paths);
804
+ if (journal.state !== "installing" && journal.state !== "committed") replayed = rollBack(paths, journal) === "superseded" ? "superseded" : "rolled-back";
805
+ else {
806
+ rollForward(paths, journal);
722
807
  replayed = "completed";
723
808
  }
724
809
  }
@@ -738,31 +823,686 @@ function recoverStaleRuns(packageRoot, output) {
738
823
  for (const runId of entriesOf(runsDir)) {
739
824
  const replayed = replayRun(packageRoot, join(runsDir, runId));
740
825
  if (replayed === "rolled-back") console.warn("⚠ An earlier build of this package stopped before it finished; its partial output was removed and the previous output restored.");
826
+ else if (replayed === "superseded") console.warn(`⚠ 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.`);
741
827
  else if (replayed === "completed") console.warn("⚠ An earlier build of this package stopped while it replaced its output; the replacement was completed.");
742
828
  }
743
829
  const beside = dirname(output);
744
830
  for (const entry of entriesOf(beside)) if (isScratchOf(basename(output), entry)) removeTree(join(beside, entry));
745
831
  }
746
832
  //#endregion
747
- //#region src/services/package-build/staging/session.ts
748
- function within(root, path) {
749
- const rel = relative(root, path);
750
- return rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel) ? void 0 : rel;
833
+ //#region src/services/compiler-output/emit.ts
834
+ const withoutExtension = (path) => path.replace(/\.[^./\\]+$/, "");
835
+ const declares = (options) => options.declaration === true || options.composite === true;
836
+ /**
837
+ * Where tsc keeps the build info of `configFile`, by TypeScript's rule:
838
+ * `tsBuildInfoFile`; else beside `outFile`; else in `outDir`, at the
839
+ * config's place relative to `rootDir` when that is set; else beside the
840
+ * config.
841
+ */
842
+ function buildInfoFile(options, configFile) {
843
+ const configDir = dirname(configFile);
844
+ const name = `${basename(configFile, extname(configFile))}.tsbuildinfo`;
845
+ if (options.tsBuildInfoFile !== void 0) return resolve(configDir, options.tsBuildInfoFile);
846
+ if (options.outFile !== void 0) return resolve(configDir, `${withoutExtension(options.outFile)}.tsbuildinfo`);
847
+ if (options.outDir === void 0) return resolve(configDir, name);
848
+ const fromRoot = options.rootDir === void 0 ? "" : relative(resolve(configDir, options.rootDir), configDir);
849
+ return resolve(configDir, options.outDir, fromRoot, name);
850
+ }
851
+ /**
852
+ * The files tsc writes for `outFile`: the bundle and its map unless it
853
+ * emits declarations only, then the declaration and its map when it
854
+ * declares. None without `outFile` or with `noEmit`.
855
+ */
856
+ function outFileOutputs(options, configFile) {
857
+ if (options.outFile === void 0 || options.noEmit) return [];
858
+ const output = resolve(dirname(configFile), options.outFile);
859
+ const files = [];
860
+ if (!options.emitDeclarationOnly) files.push(output, ...options.sourceMap ? [`${output}.map`] : []);
861
+ if (declares(options)) {
862
+ const declaration = `${withoutExtension(output)}.d.ts`;
863
+ files.push(declaration, ...options.declarationMap ? [`${declaration}.map`] : []);
864
+ }
865
+ return files;
866
+ }
867
+ /** The declaration and output directories the options name, resolved. */
868
+ function outputDirectories$1(options, configDir) {
869
+ return [options.declarationDir, options.outDir].filter((dir) => dir !== void 0).map((dir) => resolve(configDir, dir));
870
+ }
871
+ /** Where tsc writes declarations, when it writes them to a directory of their own. */
872
+ function declarationDirectory(options, configDir) {
873
+ const dir = options.declarationDir ?? options.outDir;
874
+ if (!dir || !declares(options)) return void 0;
875
+ return resolve(configDir, dir);
876
+ }
877
+ //#endregion
878
+ //#region src/services/definitions/config-inputs.ts
879
+ const configSchema$1 = object({
880
+ extends: union([string(), array(string())]).optional(),
881
+ compilerOptions: record(string(), json()).optional()
882
+ });
883
+ function readConfig(path) {
884
+ const text = readFileSync(path, "utf8").replace(/^\uFEFF/, "").replace(/"(?:\\.|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, (token) => token.startsWith("\"") ? token : "").replace(/"(?:\\.|[^"\\])*"|,\s*(?=[}\]])/g, (token) => token.startsWith("\"") ? token : "");
885
+ return JSON.parse(text);
886
+ }
887
+ const manifestSchema = object({
888
+ tsconfig: string().optional(),
889
+ exports: json().optional(),
890
+ typesVersions: record(string(), record(string(), array(string()))).optional()
891
+ });
892
+ function configDirOptions(configFile, compilerVersion) {
893
+ const visiting = /* @__PURE__ */ new Set();
894
+ const options = (path) => {
895
+ if (visiting.has(path)) return {};
896
+ visiting.add(path);
897
+ const config = configSchema$1.parse(readConfig(path));
898
+ const bases = typeof config.extends === "string" ? [config.extends] : config.extends ?? [];
899
+ const inherited = {};
900
+ for (const base of bases) Object.assign(inherited, options(extendedConfig(path, base, compilerVersion)));
901
+ visiting.delete(path);
902
+ return {
903
+ ...inherited,
904
+ ...config.compilerOptions
905
+ };
906
+ };
907
+ const substitute = (value) => {
908
+ if (typeof value === "string") return value.replaceAll("${configDir}", dirname(configFile));
909
+ if (Array.isArray(value)) return value.map(substitute);
910
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, substitute(entry)]));
911
+ return value;
912
+ };
913
+ return Object.fromEntries(Object.entries(options(configFile)).filter(([, value]) => JSON.stringify(value).includes("${configDir}")).map(([key, value]) => [key, substitute(value)]));
914
+ }
915
+ function file(path) {
916
+ return statSync(path, { throwIfNoEntry: false })?.isFile() ? path : void 0;
917
+ }
918
+ function jsonFile(path) {
919
+ if (path.endsWith(".json")) return file(path);
920
+ return file(`${path.replace(/\.(?:js|ts)$/, "")}.json`) ?? file(`${path}.json`);
921
+ }
922
+ function matchedPath(paths, name, exports = false) {
923
+ if (Object.hasOwn(paths, name)) return {
924
+ key: name,
925
+ match: ""
926
+ };
927
+ const keys = Object.keys(paths).filter((key) => key.includes("*") && key.indexOf("*") === key.lastIndexOf("*") || exports && key.endsWith("/"));
928
+ keys.sort((a, b) => {
929
+ const prefix = (key) => key.includes("*") ? key.indexOf("*") + 1 : key.length;
930
+ return prefix(b) - prefix(a) || (exports ? Number(!a.includes("*")) - Number(!b.includes("*")) || b.length - a.length : 0);
931
+ });
932
+ for (const key of keys) {
933
+ const star = key.indexOf("*");
934
+ if (star !== -1 && name.startsWith(key.slice(0, star)) && name.endsWith(key.slice(star + 1))) return {
935
+ key,
936
+ match: name.slice(star, name.length - (key.length - star - 1))
937
+ };
938
+ if (star === -1 && name.startsWith(key)) return {
939
+ key,
940
+ match: name.slice(key.length)
941
+ };
942
+ }
943
+ }
944
+ function exportedConfig(target, directory, compilerVersion, match, pattern) {
945
+ if (typeof target === "string") {
946
+ if (!target.startsWith("./") || !pattern && match !== "" && !target.endsWith("/")) return {};
947
+ const path = pattern ? target.replaceAll("*", match) : target + match;
948
+ if (path.slice(2).split("/").some((part) => part === "." || part === ".." || part === "node_modules")) return {};
949
+ const resolved = jsonFile(resolve(directory, path));
950
+ return resolved === void 0 ? {} : { path: resolved };
951
+ }
952
+ if (target === null) return {};
953
+ if (Array.isArray(target)) {
954
+ if (target.length === 0) return {};
955
+ for (const entry of target) {
956
+ const result = exportedConfig(entry, directory, compilerVersion, match, pattern);
957
+ if (result !== void 0) return result;
958
+ }
959
+ } else if (typeof target === "object") {
960
+ for (const [condition, entry] of Object.entries(target)) if ([
961
+ "types",
962
+ "require",
963
+ "node",
964
+ "default"
965
+ ].includes(condition) || condition.startsWith("types@") && satisfies(compilerVersion, condition.slice(6))) {
966
+ const result = exportedConfig(entry, directory, compilerVersion, match, pattern);
967
+ if (result !== void 0) return result;
968
+ }
969
+ } else return {};
970
+ }
971
+ function extendedConfig(configFile, input, compilerVersion) {
972
+ const specifier = input.replaceAll("\\", "/");
973
+ if (specifier.startsWith("./") || specifier.startsWith("../") || isAbsolute(specifier)) {
974
+ const path = resolve(dirname(configFile), specifier);
975
+ const found = file(path) ?? (!path.endsWith(".json") ? file(`${path}.json`) : void 0);
976
+ if (found !== void 0) return found;
977
+ } else {
978
+ const parts = specifier.split("/");
979
+ const nameLength = specifier.startsWith("@") ? 2 : 1;
980
+ const packageName = parts.slice(0, nameLength).join("/");
981
+ const subpath = parts.slice(nameLength).join("/");
982
+ const manifestAt = (directory) => {
983
+ const path = join(directory, "package.json");
984
+ if (!existsSync(path)) return void 0;
985
+ return manifestSchema.parse(readConfig(path));
986
+ };
987
+ const fromDirectory = (directory, pkg) => {
988
+ const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(([range]) => satisfies(compilerVersion, range))?.[1];
989
+ const entry = pkg?.tsconfig ? resolve(directory, pkg.tsconfig) : join(directory, "tsconfig");
990
+ if (versionPaths !== void 0) {
991
+ const match = matchedPath(versionPaths, entry.slice(directory.length + 1));
992
+ if (match !== void 0) for (const path of versionPaths[match.key] ?? []) {
993
+ const found = jsonFile(resolve(directory, path.replace("*", match.match)));
994
+ if (found !== void 0) return found;
995
+ }
996
+ }
997
+ return (pkg?.tsconfig ? jsonFile(entry) : void 0) ?? jsonFile(join(directory, "tsconfig"));
998
+ };
999
+ for (const modules of createRequire(configFile).resolve.paths(specifier) ?? []) {
1000
+ const directory = join(modules, packageName);
1001
+ const candidate = join(modules, specifier);
1002
+ const nested = manifestAt(candidate);
1003
+ const pkg = subpath === "" ? nested : manifestAt(directory);
1004
+ if (subpath !== "" && nested !== void 0 && !pkg?.exports) {
1005
+ const found = jsonFile(candidate) ?? fromDirectory(candidate, nested);
1006
+ if (found !== void 0) return found;
1007
+ continue;
1008
+ }
1009
+ if (pkg?.exports) {
1010
+ const exports = pkg.exports;
1011
+ const key = subpath === "" ? "." : `./${subpath}`;
1012
+ let target;
1013
+ let match = "";
1014
+ let pattern = false;
1015
+ if (typeof exports === "object" && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith("."))) {
1016
+ const matched = matchedPath(exports, key, true);
1017
+ if (matched !== void 0) {
1018
+ target = exports[matched.key];
1019
+ match = matched.match;
1020
+ pattern = matched.key.includes("*");
1021
+ }
1022
+ } else if (key === ".") target = exports;
1023
+ const found = target === void 0 ? void 0 : exportedConfig(target, directory, compilerVersion, match, pattern)?.path;
1024
+ if (found !== void 0) return found;
1025
+ continue;
1026
+ }
1027
+ const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(([range]) => satisfies(compilerVersion, range))?.[1];
1028
+ if (subpath !== "" && versionPaths !== void 0) {
1029
+ const match = matchedPath(versionPaths, subpath);
1030
+ if (match !== void 0) for (const path of versionPaths[match.key] ?? []) {
1031
+ const found = jsonFile(resolve(directory, path.replace("*", match.match)));
1032
+ if (found !== void 0) return found;
1033
+ }
1034
+ }
1035
+ const found = jsonFile(candidate) ?? fromDirectory(candidate, pkg);
1036
+ if (found !== void 0) return found;
1037
+ }
1038
+ }
1039
+ throw new Error(`The extended TypeScript config ${JSON.stringify(specifier)} could not be resolved from ${JSON.stringify(configFile)}.`);
1040
+ }
1041
+ //#endregion
1042
+ //#region src/services/definitions/compiler-output.ts
1043
+ const lines = (stdout) => stdout.split(/\r?\n/);
1044
+ function listedFiles(stdout = "", directory = ".") {
1045
+ return lines(stdout).map((line) => line.trim()).map((line) => resolve(directory, line)).filter((line) => existsSync(line) && statSync(line).isFile());
1046
+ }
1047
+ function explainedRoots(stdout, directory) {
1048
+ const roots = [];
1049
+ let file;
1050
+ for (const line of lines(stdout)) if (line !== "" && line === line.trim() && /\.(?:[cm]?[jt]sx?|json)$/i.test(line)) {
1051
+ const path = resolve(directory, line);
1052
+ file = statSync(path, { throwIfNoEntry: false })?.isFile() ? path : void 0;
1053
+ } else if (file !== void 0 && /Root file specified|Part of 'files' list|Matched by (default )?include pattern/.test(line)) roots.push(file);
1054
+ return roots;
1055
+ }
1056
+ //#endregion
1057
+ //#region src/services/definitions/compiler.ts
1058
+ async function runLocal(packageRoot, agent, argv) {
1059
+ const command = resolveCommand(agent, "execute-local", [...argv]);
1060
+ if (command === null) return {
1061
+ ok: false,
1062
+ output: `${argv[0]} is not installed in this package`
1063
+ };
1064
+ try {
1065
+ return {
1066
+ ok: true,
1067
+ output: await spawnAsync(command.command, command.args, {
1068
+ cwd: packageRoot,
1069
+ env: {
1070
+ ...process.env,
1071
+ PWD: packageRoot
1072
+ }
1073
+ })
1074
+ };
1075
+ } catch (error) {
1076
+ return {
1077
+ ok: false,
1078
+ output: error instanceof SpawnError && error.stdout.length !== 0 ? error.stdout : error instanceof Error ? error.message : `${argv[0]} failed`
1079
+ };
1080
+ }
1081
+ }
1082
+ const configSchema = object({
1083
+ compilerOptions: looseObject({
1084
+ declaration: boolean().optional(),
1085
+ composite: boolean().optional(),
1086
+ incremental: boolean().optional(),
1087
+ declarationDir: string().optional(),
1088
+ outDir: string().optional(),
1089
+ rootDir: string().optional(),
1090
+ noEmit: boolean().optional(),
1091
+ emitDeclarationOnly: boolean().optional(),
1092
+ sourceMap: boolean().optional(),
1093
+ declarationMap: boolean().optional(),
1094
+ jsx: string().optional(),
1095
+ outFile: string().optional(),
1096
+ tsBuildInfoFile: string().optional(),
1097
+ resolveJsonModule: boolean().optional()
1098
+ }),
1099
+ references: array(object({ path: string() })).optional()
1100
+ });
1101
+ var CompilerDiagnostic = class extends Error {
1102
+ configFile;
1103
+ noWrites;
1104
+ constructor(summary, configFile, noWrites) {
1105
+ super(summary);
1106
+ this.configFile = configFile;
1107
+ this.noWrites = noWrites;
1108
+ }
1109
+ };
1110
+ function projectConfigFile(path) {
1111
+ const entry = statSync(path, { throwIfNoEntry: false });
1112
+ return canonicalConfigFile(entry?.isDirectory() || entry === void 0 && !path.endsWith(".json") ? join(path, "tsconfig.json") : path);
1113
+ }
1114
+ function commonSourceDirectory(files, fallback) {
1115
+ let root = files.length === 0 ? fallback : dirname(files[0] ?? fallback);
1116
+ for (const file of files) while (pathWithin(root, file) === null) {
1117
+ const parent = dirname(root);
1118
+ if (parent === root) throw new Error("TypeScript sources on different drives have no common source directory.");
1119
+ root = parent;
1120
+ }
1121
+ return root;
1122
+ }
1123
+ function outputFiles(project, emitsBuildInfoInBuildMode) {
1124
+ const { options, sources, configFile } = project;
1125
+ const directory = dirname(configFile);
1126
+ const root = project.emitRoot;
1127
+ const files = emitsBuildInfoInBuildMode || options.composite || options.incremental || options.tsBuildInfoFile !== void 0 ? [buildInfoFile(options, configFile)] : [];
1128
+ if (options.noEmit) return files;
1129
+ if (options.outFile !== void 0) return [...files, ...outFileOutputs(options, configFile)];
1130
+ const declares = options.declaration === true || options.composite === true;
1131
+ for (const source of sources) {
1132
+ if (/\.json$/i.test(source)) {
1133
+ if (!options.emitDeclarationOnly) {
1134
+ const inside = pathWithin(root, source);
1135
+ files.push(options.outDir === void 0 || inside === null ? source : resolve(directory, options.outDir, inside));
1136
+ }
1137
+ continue;
1138
+ }
1139
+ const suffix = /\.[cm]?[jt]sx?$/i;
1140
+ const jsExtension = /\.[cm][jt]s$/i.test(source) ? source.slice(-4).replace("t", "j") : options.jsx === "preserve" && /[jt]sx$/i.test(source) ? ".jsx" : ".js";
1141
+ const declarationExtension = /\.[cm][jt]s$/i.test(source) ? source.slice(-4).replace(/j/, "t").replace(".", ".d.") : ".d.ts";
1142
+ const inRoot = pathWithin(root, source);
1143
+ const destination = (out, extension) => out === void 0 || inRoot === null ? source.replace(suffix, extension) : resolve(directory, out, inRoot.replace(suffix, extension));
1144
+ if (!options.emitDeclarationOnly) {
1145
+ const js = destination(options.outDir, jsExtension);
1146
+ files.push(js, ...options.sourceMap ? [js + ".map"] : []);
1147
+ }
1148
+ if (declares) {
1149
+ const declaration = destination(options.declarationDir ?? options.outDir, declarationExtension);
1150
+ files.push(declaration, ...options.declarationMap ? [declaration + ".map"] : []);
1151
+ }
1152
+ }
1153
+ return files;
1154
+ }
1155
+ /**
1156
+ * Reads the package's project graph through its own `tsc` and predicts what
1157
+ * `tsc --build` writes, without writing. Refuses a build that would write
1158
+ * outside the package.
1159
+ */
1160
+ async function prepareCompile(packageRoot, agent) {
1161
+ try {
1162
+ const version = await runLocal(packageRoot, agent, ["tsc", "--version"]);
1163
+ const match = /Version (\d+)\.(\d+)/.exec(version.output);
1164
+ if (match === null) throw new Error("The installed TypeScript version could not be resolved.");
1165
+ const major = Number(match[1]);
1166
+ const minor = Number(match[2]);
1167
+ const emitsBuildInfoInBuildMode = major > 5 || major === 5 && minor >= 6;
1168
+ const defaultsRootDirToConfig = major >= 6;
1169
+ return {
1170
+ ok: true,
1171
+ plan: checkedCompilePlan(packageRoot, await readProjectGraph(packageRoot, agent, join(packageRoot, "tsconfig.json"), defaultsRootDirToConfig, /Version (\S+)/.exec(version.output)?.[1] ?? `${major}.${minor}.0`), emitsBuildInfoInBuildMode)
1172
+ };
1173
+ } catch (error) {
1174
+ if (error instanceof CompilerDiagnostic && error.noWrites && error.configFile === projectConfigFile(join(packageRoot, "tsconfig.json"))) return {
1175
+ ok: true,
1176
+ plan: {
1177
+ ...checkedCompilePlan(packageRoot, [{
1178
+ configFile: error.configFile,
1179
+ options: { noEmit: true },
1180
+ sources: [],
1181
+ external: false,
1182
+ emitRoot: packageRoot,
1183
+ references: []
1184
+ }], false),
1185
+ preflightTypeError: error.message
1186
+ }
1187
+ };
1188
+ return {
1189
+ ok: false,
1190
+ summary: error instanceof Error ? error.message : "The TypeScript output layout could not be resolved."
1191
+ };
1192
+ }
1193
+ }
1194
+ async function readProjectGraph(packageRoot, agent, configPath, defaultsRootDirToConfig, compilerVersion) {
1195
+ const projects = [];
1196
+ const visited = /* @__PURE__ */ new Set();
1197
+ const rootConfig = projectConfigFile(join(packageRoot, "tsconfig.json"));
1198
+ const visit = async (path) => {
1199
+ const configFile = projectConfigFile(path);
1200
+ if (visited.has(configFile)) return;
1201
+ visited.add(configFile);
1202
+ let shown = await runLocal(packageRoot, agent, [
1203
+ "tsc",
1204
+ "-p",
1205
+ configFile,
1206
+ "--showConfig"
1207
+ ]);
1208
+ let diagnostic;
1209
+ if (!shown.ok && /TS18003/.test(shown.output) && pathWithin(packageRoot, configFile) !== null) {
1210
+ diagnostic = shown.output;
1211
+ shown = await showEmptyProjectConfig(packageRoot, agent, configFile, compilerVersion);
1212
+ }
1213
+ if (!shown.ok) throw new CompilerDiagnostic(shown.output, configFile, statSync(configFile, { throwIfNoEntry: false }) === void 0);
1214
+ const config = configSchema.parse(JSON.parse(shown.output));
1215
+ const project = await refreshProject(packageRoot, agent, {
1216
+ ...diagnostic !== void 0 && { diagnostic },
1217
+ configFile,
1218
+ options: config.compilerOptions,
1219
+ sources: [],
1220
+ references: (config.references ?? []).map((reference) => projectConfigFile(resolve(dirname(configFile), reference.path))),
1221
+ emitRoot: dirname(configFile),
1222
+ external: configFile !== rootConfig && pathWithin(packageRoot, configFile) === null
1223
+ }, defaultsRootDirToConfig);
1224
+ projects.push(project);
1225
+ for (const reference of project.references) await visit(reference);
1226
+ };
1227
+ await visit(configPath);
1228
+ return projects;
1229
+ }
1230
+ async function showEmptyProjectConfig(packageRoot, agent, configFile, compilerVersion) {
1231
+ const config = object({ references: configSchema.shape.references }).parse(readConfig(configFile));
1232
+ const directory = realPathThroughExistingParent(mkdtempSync(join(tmpdir(), ".ph-preflight-")));
1233
+ try {
1234
+ const probe = join(directory, "tsconfig.json");
1235
+ writeFileSync(probe, JSON.stringify({
1236
+ extends: configFile,
1237
+ compilerOptions: configDirOptions(configFile, compilerVersion),
1238
+ files: [configFile],
1239
+ include: [],
1240
+ references: config.references?.map(({ path }) => ({ path: resolve(dirname(configFile), path) }))
1241
+ }));
1242
+ const shown = await runLocal(packageRoot, agent, [
1243
+ "tsc",
1244
+ "-p",
1245
+ probe,
1246
+ "--showConfig"
1247
+ ]);
1248
+ if (!shown.ok) return shown;
1249
+ const resolved = configSchema.parse(JSON.parse(shown.output));
1250
+ const options = resolved.compilerOptions;
1251
+ const rebase = (path) => {
1252
+ const absolute = resolve(directory, path);
1253
+ const inProbe = pathWithin(directory, absolute);
1254
+ return inProbe === null ? absolute : resolve(dirname(configFile), inProbe);
1255
+ };
1256
+ for (const key of [
1257
+ "outDir",
1258
+ "declarationDir",
1259
+ "rootDir",
1260
+ "outFile",
1261
+ "tsBuildInfoFile"
1262
+ ]) {
1263
+ const path = options[key];
1264
+ if (path !== void 0) options[key] = rebase(path);
1265
+ }
1266
+ return {
1267
+ ...shown,
1268
+ output: JSON.stringify(resolved)
1269
+ };
1270
+ } finally {
1271
+ rmSync(directory, {
1272
+ recursive: true,
1273
+ force: true
1274
+ });
1275
+ }
1276
+ }
1277
+ async function listProjectFiles(packageRoot, agent, configFile, preserveSymlinks = false) {
1278
+ const listed = await runLocal(packageRoot, agent, [
1279
+ "tsc",
1280
+ "-p",
1281
+ configFile,
1282
+ "--listFilesOnly",
1283
+ "--explainFiles",
1284
+ "--pretty",
1285
+ "false",
1286
+ ...preserveSymlinks ? ["--preserveSymlinks", "true"] : []
1287
+ ]);
1288
+ return {
1289
+ ...listed,
1290
+ files: listedFiles(listed.output, packageRoot),
1291
+ rootFiles: explainedRoots(listed.output, packageRoot)
1292
+ };
1293
+ }
1294
+ async function refreshProject(packageRoot, agent, project, defaultsRootDirToConfig) {
1295
+ const listed = await listProjectFiles(packageRoot, agent, project.configFile);
1296
+ const { files, rootFiles } = listed;
1297
+ if (!listed.ok && files.length === 0 && !/TS18003/.test(listed.output)) throw new CompilerDiagnostic(listed.output, project.configFile, false);
1298
+ const roots = new Set(rootFiles.map((file) => realPathThroughExistingParent(file)));
1299
+ let sources = files.filter((file) => (/\.[cm]?[jt]sx?$/i.test(file) || project.options.resolveJsonModule === true && /\.json$/i.test(file)) && !/\.d\.[cm]?ts$/i.test(file) && (roots.has(realPathThroughExistingParent(file)) || !toPosixPath(file).includes("/node_modules/")));
1300
+ if (sources.some((file) => !roots.has(realPathThroughExistingParent(file)) && pathWithin(packageRoot, realPathThroughExistingParent(file)) === null)) {
1301
+ const spellings = (await listProjectFiles(packageRoot, agent, project.configFile, true)).files;
1302
+ if (spellings.length === 0) throw new Error("tsc could not classify external library inputs without writing them.");
1303
+ const local = new Set(spellings.filter((file) => roots.has(realPathThroughExistingParent(file)) || !toPosixPath(file).includes("/node_modules/")).map((path) => realPathThroughExistingParent(path)));
1304
+ const libraries = new Set(spellings.filter((file) => toPosixPath(file).includes("/node_modules/")).map((path) => realPathThroughExistingParent(path)));
1305
+ sources = sources.filter((file) => !libraries.has(realPathThroughExistingParent(file)) || local.has(realPathThroughExistingParent(file)));
1306
+ }
1307
+ return {
1308
+ ...project,
1309
+ .../TS18003/.test(listed.output) && { diagnostic: listed.output },
1310
+ sources,
1311
+ emitRoot: resolve(dirname(project.configFile), project.options.rootDir ?? (project.options.composite || defaultsRootDirToConfig ? "." : commonSourceDirectory(sources, dirname(project.configFile))))
1312
+ };
1313
+ }
1314
+ function checkedCompilePlan(packageRoot, projects, emitsBuildInfoInBuildMode) {
1315
+ const directories = /* @__PURE__ */ new Set();
1316
+ const files = /* @__PURE__ */ new Set();
1317
+ for (const project of projects) {
1318
+ if (project.external) continue;
1319
+ if (!project.options.noEmit) for (const path of outputDirectories$1(project.options, dirname(project.configFile))) {
1320
+ const target = realPathThroughExistingParent(path);
1321
+ if (pathWithin(packageRoot, target) === null) throw new Error(`tsc would write to ${JSON.stringify(path)} outside the package.`);
1322
+ if (!project.sources.some((file) => pathWithin(target, realPathThroughExistingParent(file)) !== null)) {
1323
+ if (pathWithin(packageRoot, path) !== null) directories.add(toPosixPath(relative(packageRoot, path)));
1324
+ directories.add(toPosixPath(relative(packageRoot, target)));
1325
+ }
1326
+ }
1327
+ for (const path of outputFiles(project, emitsBuildInfoInBuildMode)) {
1328
+ if (/\.json$/i.test(path) && project.sources.includes(path)) continue;
1329
+ const target = realPathThroughExistingParent(path);
1330
+ if (pathWithin(packageRoot, target) === null) throw new Error(`tsc would write to ${JSON.stringify(path)} outside the package.`);
1331
+ if (pathWithin(packageRoot, path) !== null) files.add(toPosixPath(relative(packageRoot, path)));
1332
+ files.add(toPosixPath(relative(packageRoot, target)));
1333
+ }
1334
+ }
1335
+ const root = projects.at(0);
1336
+ const references = projects.slice(1);
1337
+ if (root === void 0) throw new Error("The root TypeScript project could not be resolved.");
1338
+ return {
1339
+ ...root.diagnostic !== void 0 && { preflightTypeError: root.diagnostic },
1340
+ projects: [root, ...references],
1341
+ outputs: {
1342
+ directories: [...directories].sort(),
1343
+ files: [...files].sort()
1344
+ }
1345
+ };
1346
+ }
1347
+ //#endregion
1348
+ //#region src/services/package-build/staging/inventory.ts
1349
+ const optionalString = (value) => typeof value === "string" ? value : void 0;
1350
+ const optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
1351
+ const strings = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : void 0;
1352
+ /** The config in `tsc --showConfig` output, or undefined when it is not JSON. */
1353
+ function parseShownConfig(text) {
1354
+ let shown;
1355
+ try {
1356
+ shown = JSON.parse(text);
1357
+ } catch {
1358
+ return;
1359
+ }
1360
+ if (typeof shown !== "object" || shown === null) return void 0;
1361
+ const { compilerOptions, exclude, references } = shown;
1362
+ return {
1363
+ options: emitOptions(compilerOptions),
1364
+ exclude: strings(exclude),
1365
+ references: Array.isArray(references) ? references.flatMap((reference) => {
1366
+ const path = reference?.path;
1367
+ return typeof path === "string" ? [path] : [];
1368
+ }) : []
1369
+ };
1370
+ }
1371
+ function emitOptions(options) {
1372
+ if (typeof options !== "object" || options === null) return {};
1373
+ const record = options;
1374
+ return {
1375
+ declaration: optionalBoolean(record.declaration),
1376
+ composite: optionalBoolean(record.composite),
1377
+ incremental: optionalBoolean(record.incremental),
1378
+ declarationDir: optionalString(record.declarationDir),
1379
+ outDir: optionalString(record.outDir),
1380
+ outFile: optionalString(record.outFile),
1381
+ rootDir: optionalString(record.rootDir),
1382
+ tsBuildInfoFile: optionalString(record.tsBuildInfoFile),
1383
+ noEmit: optionalBoolean(record.noEmit),
1384
+ emitDeclarationOnly: optionalBoolean(record.emitDeclarationOnly),
1385
+ sourceMap: optionalBoolean(record.sourceMap),
1386
+ declarationMap: optionalBoolean(record.declarationMap)
1387
+ };
1388
+ }
1389
+ /**
1390
+ * What the root project's tsc writes inside the package, for the build to
1391
+ * snapshot and restore: its build info first, then the files `outFile`
1392
+ * writes, then its declaration and output directories, the build's own
1393
+ * output directory or one holding it included. A directory holding
1394
+ * `buildDirectory`, where the build keeps its runs and their snapshots, is
1395
+ * left out and unprotected, as without staging: a snapshot of it would copy
1396
+ * itself. This says what to protect, not what to carry into the stage.
1397
+ */
1398
+ function compilerOutputInventory(options, at) {
1399
+ const inPackage = (path) => Boolean(pathWithin(at.packageRoot, path));
1400
+ const directories = outputDirectories$1(options, dirname(at.configFile)).filter(inPackage).filter((dir) => pathWithin(dir, at.buildDirectory) === null);
1401
+ return [
1402
+ ...[buildInfoFile(options, at.configFile)].filter(inPackage).map((path) => ({
1403
+ path,
1404
+ kind: "build-info"
1405
+ })),
1406
+ ...outFileOutputs(options, at.configFile).filter(inPackage).map((path) => ({
1407
+ path,
1408
+ kind: "file"
1409
+ })),
1410
+ ...[...new Set(directories)].map((path) => ({
1411
+ path,
1412
+ kind: "directory"
1413
+ }))
1414
+ ];
1415
+ }
1416
+ //#endregion
1417
+ //#region src/services/package-build/staging/compiler.ts
1418
+ function writesBesideSources(options) {
1419
+ if (options.noEmit || options.outFile !== void 0) return false;
1420
+ if (options.outDir !== void 0) return false;
1421
+ const declares = options.declaration === true || options.composite === true;
1422
+ return !options.emitDeclarationOnly || declares && !options.declarationDir;
1423
+ }
1424
+ const redirectable = ({ references, options }) => references.length === 0 && Boolean(options.incremental || options.composite || options.tsBuildInfoFile);
1425
+ async function compilerOutputs(config, at) {
1426
+ const root = compilerOutputInventory(config.options, at);
1427
+ const real = (path) => realPathThroughExistingParent(path);
1428
+ const packageIdentity = real(at.packageRoot);
1429
+ const inPackage = (path) => pathWithin(packageIdentity, real(path)) !== null;
1430
+ const referencesInPackage = config.references.some((reference) => inPackage(resolve(dirname(at.configFile), reference)));
1431
+ const holdsOutput = (dir) => pathWithin(real(dir), at.output) !== null;
1432
+ const protectsOutput = root.some(({ kind, path }) => kind === "directory" && holdsOutput(path) && !(redirectable(config) && real(path) === at.output));
1433
+ if (!referencesInPackage && !writesBesideSources(config.options) && !protectsOutput) return root;
1434
+ const prepared = await prepareCompile(at.packageRoot, at.agent);
1435
+ if (!prepared.ok) return root;
1436
+ const { directories, files } = prepared.plan.outputs;
1437
+ const absolute = (path) => resolve(at.packageRoot, path);
1438
+ const owned = (path) => inPackage(path) && pathWithin(path, at.buildDirectory) === null;
1439
+ const dirs = directories.map(absolute).filter((dir) => owned(dir) && !holdsOutput(dir));
1440
+ return [...files.map(absolute).filter((file) => owned(file) && !dirs.some((dir) => pathWithin(dir, file) !== null)).map((path) => ({
1441
+ path,
1442
+ kind: path.endsWith(".tsbuildinfo") ? "build-info" : "file"
1443
+ })).sort((a, b) => Number(b.kind === "build-info") - Number(a.kind === "build-info")), ...dirs.map((path) => ({
1444
+ path,
1445
+ kind: "directory"
1446
+ }))];
1447
+ }
1448
+ function redirectRootProject(config, at) {
1449
+ if (!redirectable(config)) return void 0;
1450
+ const { options } = config;
1451
+ const configDir = dirname(at.configFile);
1452
+ const real = (path) => realPathThroughExistingParent(path);
1453
+ const inOutput = (path) => pathWithin(at.output, real(path));
1454
+ const compilerOptions = {};
1455
+ const staged = [];
1456
+ for (const key of [
1457
+ "declarationDir",
1458
+ "outDir",
1459
+ "outFile"
1460
+ ]) {
1461
+ const value = options[key];
1462
+ if (value === void 0 || key === "outFile" && options.noEmit) continue;
1463
+ const rel = inOutput(resolve(configDir, value));
1464
+ if (rel === null) continue;
1465
+ compilerOptions[key] = join(at.stage, rel);
1466
+ staged.push(...(key === "outFile" ? outFileOutputs(options, at.configFile) : [resolve(configDir, value)]).map(real));
1467
+ }
1468
+ const target = buildInfoFile(options, at.configFile);
1469
+ const rel = inOutput(target);
1470
+ let pendingBuildInfo;
1471
+ if (rel !== null) {
1472
+ compilerOptions.tsBuildInfoFile = join(at.stage, rel);
1473
+ staged.push(real(target));
1474
+ } else if (pathWithin(at.packageRoot, target) !== null && !lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()) {
1475
+ pendingBuildInfo = {
1476
+ path: at.pending(target),
1477
+ target
1478
+ };
1479
+ compilerOptions.tsBuildInfoFile = pendingBuildInfo.path;
1480
+ staged.push(real(target));
1481
+ } else compilerOptions.tsBuildInfoFile = target;
1482
+ return {
1483
+ compilerOptions,
1484
+ exclude: config.exclude,
1485
+ pendingBuildInfo,
1486
+ staged
1487
+ };
751
1488
  }
1489
+ //#endregion
1490
+ //#region src/services/package-build/staging/session.ts
752
1491
  const isUnreadable = (error) => {
753
1492
  const code = error?.code;
754
1493
  return code === "EACCES" || code === "EPERM";
755
1494
  };
756
1495
  /** `path` is `dir` or holds it. */
757
- const isOrHolds = (path, dir) => path === dir || within(path, dir) !== void 0;
1496
+ const isOrHolds = (path, dir) => pathWithin(path, dir) !== null;
758
1497
  /** The outermost directory of `path`, inside the package, that does not exist. */
759
1498
  function outermostMissing(packageRoot, path) {
760
1499
  let missing = path;
761
- for (let parent = dirname(path); within(packageRoot, parent) !== void 0 && !exists(parent); parent = dirname(parent)) missing = parent;
1500
+ for (let parent = dirname(path); pathWithin(packageRoot, parent) && !exists(parent); parent = dirname(parent)) missing = parent;
762
1501
  return missing;
763
1502
  }
764
1503
  /** A path as messages name it: from the package root, which is named so. */
765
1504
  const shownPath = (packageRoot, path) => toJournalPath(packageRoot, path) || "the package root";
1505
+ const scratchBeside = (path, kind, runId) => join(dirname(path), `.${basename(path)}.ph-${kind}-${runId}`);
766
1506
  /**
767
1507
  * One `ph build` of one package: the output is written to a stage beside the
768
1508
  * output directory and replaces it only on commit. Until then the previous
@@ -783,6 +1523,7 @@ var StagedBuildSession = class StagedBuildSession {
783
1523
  seeded = false;
784
1524
  compilerWritten = false;
785
1525
  restored = false;
1526
+ redirected = [];
786
1527
  cleanedEntries;
787
1528
  linkCleanedEntries;
788
1529
  constructor(fields) {
@@ -807,7 +1548,7 @@ var StagedBuildSession = class StagedBuildSession {
807
1548
  const { packageRoot, logical, runId } = options;
808
1549
  const runDir = join(packageRoot, RUNS_DIRECTORY, runId);
809
1550
  try {
810
- const beside = (kind) => join(dirname(logical), `.${basename(logical)}.ph-${kind}-${runId}`);
1551
+ const beside = (kind) => scratchBeside(logical, kind, runId);
811
1552
  const journal = {
812
1553
  format: 1,
813
1554
  runId,
@@ -855,8 +1596,8 @@ var StagedBuildSession = class StagedBuildSession {
855
1596
  */
856
1597
  compilerOutputsInOutput() {
857
1598
  return (this.journal.compiler ?? []).flatMap(({ path }) => {
858
- const rel = within(this.output, fromJournalPath(this.packageRoot, path));
859
- return rel === void 0 ? [] : [rel];
1599
+ const rel = pathWithin(this.output, fromJournalPath(this.packageRoot, path));
1600
+ return rel ? [rel] : [];
860
1601
  });
861
1602
  }
862
1603
  /**
@@ -874,13 +1615,80 @@ var StagedBuildSession = class StagedBuildSession {
874
1615
  if (exists(output)) {
875
1616
  const skipped = new Set(this.compilerWritten ? [] : this.compilerOutputsInOutput().map((rel) => join(output, rel)));
876
1617
  const keep = (source) => !skipped.has(source);
877
- const linked = (this.linkCleanedEntries ? this.cleanedEntries : []).map((dir) => join(output, dir)).filter((dir) => keep(dir) && lstatSync(dir, { throwIfNoEntry: false })?.isDirectory());
1618
+ const linked = (this.linkCleanedEntries ? this.cleanedEntries : []).filter((entry) => {
1619
+ const real = join(this.output, entry);
1620
+ return !this.redirected.some((path) => isOrHolds(real, path) || isOrHolds(path, real));
1621
+ }).map((entry) => join(output, entry)).filter((dir) => keep(dir) && lstatSync(dir, { throwIfNoEntry: false })?.isDirectory());
878
1622
  cloneTree(output, stage, (source) => keep(source) && !linked.includes(source));
879
1623
  for (const dir of linked) linkTree(dir, join(stage, basename(dir)), keep);
880
1624
  } else mkdirSync(stage);
881
1625
  this.seeded = true;
882
1626
  return stage;
883
1627
  }
1628
+ async prepareCompiler(compiler) {
1629
+ this.assertOpen();
1630
+ const redirect = redirectRootProject(compiler.config, {
1631
+ configFile: compiler.configFile,
1632
+ packageRoot: this.packageRoot,
1633
+ output: this.output,
1634
+ stage: this.paths.stage,
1635
+ pending: (target) => scratchBeside(target, "stage", this.runId)
1636
+ });
1637
+ let config;
1638
+ let staged = [];
1639
+ if (redirect) {
1640
+ config = await this.writeCompilerConfig(compiler.configFile, redirect);
1641
+ if (config) staged = redirect.staged;
1642
+ }
1643
+ const real = (path) => realPathThroughExistingParent(path);
1644
+ this.protectCompilerOutputs(compiler.outputs.filter(({ path }) => !staged.some((dir) => isOrHolds(dir, real(path)))));
1645
+ if (!config) return void 0;
1646
+ this.redirected = staged;
1647
+ this.stage();
1648
+ return config;
1649
+ }
1650
+ /**
1651
+ * Writes the config that sends the root project's outputs into the stage,
1652
+ * beside the package's so `${configDir}` and its relative paths mean the
1653
+ * same, with the package config's modification time so tsc finds the
1654
+ * project up to date when it would. The pending build info starts as a
1655
+ * copy of the real one. Undefined when the package does not let the run
1656
+ * write them: tsc then writes in place.
1657
+ */
1658
+ async writeCompilerConfig(configFile, redirect) {
1659
+ const generated = join(dirname(configFile), `.${basename(configFile, extname(configFile))}.ph-stage-${this.runId}.json`);
1660
+ const pending = redirect.pendingBuildInfo;
1661
+ const recorded = (path) => toJournalPath(this.packageRoot, path);
1662
+ this.record({
1663
+ generatedConfig: recorded(generated),
1664
+ ...pending && { pendingBuildInfo: {
1665
+ path: recorded(pending.path),
1666
+ target: recorded(pending.target)
1667
+ } }
1668
+ });
1669
+ try {
1670
+ await creating(shownPath(this.packageRoot, dirname(configFile)), () => {
1671
+ writeFileSync(generated, `${JSON.stringify({
1672
+ extends: `./${basename(configFile)}`,
1673
+ compilerOptions: redirect.compilerOptions,
1674
+ ...redirect.exclude && { exclude: redirect.exclude }
1675
+ }, null, 2)}\n`);
1676
+ const { atime, mtime } = statSync(configFile);
1677
+ utimesSync(generated, atime, mtime);
1678
+ if (pending && exists(pending.target)) cloneTree(pending.target, pending.path);
1679
+ });
1680
+ return generated;
1681
+ } catch (error) {
1682
+ if (!(error instanceof CannotStage)) throw error;
1683
+ removeTree(generated);
1684
+ if (pending) removeTree(pending.path);
1685
+ this.record({
1686
+ generatedConfig: void 0,
1687
+ pendingBuildInfo: void 0
1688
+ });
1689
+ return;
1690
+ }
1691
+ }
884
1692
  /**
885
1693
  * Copies what tsc is about to rewrite into the run, or notes it absent, so
886
1694
  * a build that does not finish puts it back. Call before tsc runs. An
@@ -892,8 +1700,7 @@ var StagedBuildSession = class StagedBuildSession {
892
1700
  * their modes for a restore.
893
1701
  */
894
1702
  protectCompilerOutputs(outputs) {
895
- this.assertOpen();
896
- const real = (path) => canonicalPath(path, { resolveMissingLinks: true });
1703
+ const real = (path) => realPathThroughExistingParent(path);
897
1704
  const control = [real(join(this.packageRoot, BUILD_DIRECTORY)), real(this.runDir)];
898
1705
  const snapshots = [...this.journal.compiler ?? []];
899
1706
  for (const { path, kind } of outputs) {
@@ -933,7 +1740,11 @@ var StagedBuildSession = class StagedBuildSession {
933
1740
  });
934
1741
  }
935
1742
  }
936
- this.record({ compiler: snapshots });
1743
+ const digest = snapshots.length > 0 ? outputDigest(this.packageRoot, this.paths.output, snapshots) : void 0;
1744
+ this.record({
1745
+ compiler: snapshots,
1746
+ ...digest !== void 0 && { outputDigest: digest }
1747
+ });
937
1748
  }
938
1749
  /**
939
1750
  * tsc wrote into the real output directory; the stage takes its fresh
@@ -943,6 +1754,8 @@ var StagedBuildSession = class StagedBuildSession {
943
1754
  compilerOutputsWritten() {
944
1755
  this.assertOpen();
945
1756
  this.compilerWritten = true;
1757
+ const generated = this.journal.generatedConfig;
1758
+ if (generated) removeTree(fromJournalPath(this.packageRoot, generated));
946
1759
  if (this.seeded) this.carryOverCompilerOutputs(this.paths.stage);
947
1760
  }
948
1761
  carryOverCompilerOutputs(stage) {
@@ -993,6 +1806,7 @@ var StagedBuildSession = class StagedBuildSession {
993
1806
  moveEntries(stage, output);
994
1807
  removeTree(stage);
995
1808
  }
1809
+ installBuildInfo(this.packageRoot, this.journal.pendingBuildInfo);
996
1810
  this.status = "committed";
997
1811
  if (entryByEntry) this.warnNotAtomic();
998
1812
  } catch (error) {
@@ -1068,14 +1882,40 @@ var StagedBuildSession = class StagedBuildSession {
1068
1882
  * a stage beside its target would change the paths the bundlers record.
1069
1883
  */
1070
1884
  function symlinkOnPath(packageRoot, output) {
1071
- const root = canonicalPath(packageRoot);
1885
+ const root = realPathThroughExistingParent(packageRoot);
1072
1886
  for (let dir = output;; dir = dirname(dir)) {
1073
1887
  if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) return dir;
1074
- const parent = canonicalPath(dirname(dir), { resolveMissingLinks: true });
1888
+ const parent = realPathThroughExistingParent(dirname(dir));
1075
1889
  if (parent === root || pathWithin(root, parent) === null) return;
1076
1890
  }
1077
1891
  }
1078
1892
  /**
1893
+ * The output is a mount point, or otherwise on another filesystem than the
1894
+ * directory beside it: the stage's rename cannot replace it.
1895
+ */
1896
+ function onAnotherFilesystem(output) {
1897
+ const dev = statSync(output, { throwIfNoEntry: false })?.dev;
1898
+ return dev !== void 0 && dev !== statSync(dirname(output)).dev;
1899
+ }
1900
+ function linkIntoOutput(logical, output, stage) {
1901
+ const visit = (dir) => {
1902
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1903
+ const path = join(dir, entry.name);
1904
+ if (entry.isDirectory()) {
1905
+ const found = visit(path);
1906
+ if (found) return found;
1907
+ continue;
1908
+ }
1909
+ if (!entry.isSymbolicLink()) continue;
1910
+ const target = readlinkSync(path);
1911
+ const copied = isAbsolute(target) ? target : resolve(stage, relative(logical, dirname(path)), target);
1912
+ if (pathWithin(logical, copied) !== null) return path;
1913
+ if (pathWithin(output, copied) !== null) return path;
1914
+ }
1915
+ };
1916
+ return lstatSync(logical, { throwIfNoEntry: false })?.isDirectory() ? visit(logical) : void 0;
1917
+ }
1918
+ /**
1079
1919
  * Writes the output in place, as builds did before staging: no stage or
1080
1920
  * snapshot, and nothing to commit or roll back. It holds the package's lock
1081
1921
  * until `close` when `.ph/build` can hold one. A stop signal does not stop
@@ -1095,7 +1935,9 @@ var InPlaceSession = class {
1095
1935
  stage() {
1096
1936
  return this.logical;
1097
1937
  }
1098
- protectCompilerOutputs() {}
1938
+ prepareCompiler() {
1939
+ return Promise.resolve(void 0);
1940
+ }
1099
1941
  compilerOutputsWritten() {}
1100
1942
  commit() {}
1101
1943
  close() {
@@ -1122,18 +1964,18 @@ function newRunId() {
1122
1964
  * Takes the package's lock and finishes what dead builds left, then opens a
1123
1965
  * staged session, or an in-place one when staging cannot run as an unstaged
1124
1966
  * build would: the output or a directory on its path in the package is a
1125
- * symlink, the output holds an entry a copy cannot take (a FIFO, socket or
1126
- * device, or one this process cannot read), the output holds `.ph/build`,
1127
- * whose lock and journal a swap would move away, or the stage beside the
1128
- * output cannot be written. Only when `.ph/build` cannot hold the lock does the
1129
- * build run without one, as builds did before staging. One warning says why
1130
- * a build writes in place.
1967
+ * symlink, the output is on another filesystem than its parent, it holds an
1968
+ * entry a copy cannot take (a FIFO, socket or device, or one this process
1969
+ * cannot read) or a symlink into itself, it holds `.ph/build`, whose lock and
1970
+ * journal a swap would move away, or the stage beside it cannot be written.
1971
+ * Only when `.ph/build` cannot hold the lock does the build run without one,
1972
+ * as builds did before staging. One warning says why a build writes in place.
1131
1973
  */
1132
1974
  async function openBuildSession(options) {
1133
1975
  const { packageRoot, outDir, cleanedEntries, linkCleanedEntries } = options;
1134
1976
  const logical = resolve(packageRoot, outDir);
1135
- const output = canonicalPath(logical, { resolveMissingLinks: true });
1136
- const writesPackageDist = output === canonicalPath(join(packageRoot, "dist"), { resolveMissingLinks: true });
1977
+ const output = realPathThroughExistingParent(logical);
1978
+ const writesPackageDist = output === realPathThroughExistingParent(join(packageRoot, "dist"));
1137
1979
  const shown = (path) => shownPath(packageRoot, path);
1138
1980
  const inPlace = (reason, lock) => {
1139
1981
  console.warn(`⚠ ${reason}, so this build writes ${shown(logical)} in place: if it does not finish, ${shown(logical)} can be left part old, part new.`);
@@ -1151,9 +1993,12 @@ async function openBuildSession(options) {
1151
1993
  recoverStaleRuns(packageRoot, logical);
1152
1994
  const link = symlinkOnPath(packageRoot, logical);
1153
1995
  if (link !== void 0) return inPlace(`${shown(link)} is a symbolic link`, lock);
1996
+ if (onAnotherFilesystem(logical)) return inPlace(`${shown(logical)} is on another filesystem than the directory that holds it`, lock);
1154
1997
  const unstageable = unstageableEntryIn(logical);
1155
1998
  if (unstageable !== void 0) return inPlace(`${shown(unstageable.path)} ${unstageable.reason}`, lock);
1156
- const control = [BUILD_DIRECTORY, join(RUNS_DIRECTORY, runId)].find((dir) => pathWithin(output, canonicalPath(join(packageRoot, dir), { resolveMissingLinks: true })) !== null);
1999
+ const intoOutput = linkIntoOutput(logical, output, scratchBeside(logical, "stage", runId));
2000
+ if (intoOutput !== void 0) return inPlace(`${shown(intoOutput)} is a symbolic link into ${shown(logical)}`, lock);
2001
+ const control = [BUILD_DIRECTORY, join(RUNS_DIRECTORY, runId)].find((dir) => pathWithin(output, realPathThroughExistingParent(join(packageRoot, dir))) !== null);
1157
2002
  if (control !== void 0) return inPlace(`${shown(logical)} holds ${control}`, lock);
1158
2003
  try {
1159
2004
  return await StagedBuildSession.open({
@@ -1441,7 +2286,7 @@ function definitionsStepWithin(timeoutMs) {
1441
2286
  });
1442
2287
  if (selection.status !== "ready" || selection.sourceSet.sources.length === 0) return;
1443
2288
  }
1444
- const { renderCheckReport } = await import("./render-CTQG4359.mjs");
2289
+ const { renderCheckReport } = await import("./render-DdieUjtg.mjs");
1445
2290
  const printReport = (report) => {
1446
2291
  const text = renderCheckReport(report);
1447
2292
  if (report.diagnostics.length > 0) console.warn(`⚠ The definition check reported problems; the build goes on:\n${text}`);
@@ -1550,6 +2395,212 @@ const offeredRoutesStep = {
1550
2395
  }
1551
2396
  };
1552
2397
  //#endregion
2398
+ //#region src/services/release/consumer.ts
2399
+ const CONDITIONS = {
2400
+ node: /* @__PURE__ */ new Set([
2401
+ "node",
2402
+ "import",
2403
+ "module-sync",
2404
+ "default"
2405
+ ]),
2406
+ browser: /* @__PURE__ */ new Set([
2407
+ "browser",
2408
+ "import",
2409
+ "module",
2410
+ "default"
2411
+ ])
2412
+ };
2413
+ const IMPORTABLE = /\.(m?js|cjs)$/;
2414
+ function resolveTarget(value, conditions) {
2415
+ if (typeof value === "string") return value;
2416
+ if (Array.isArray(value)) {
2417
+ for (const item of value) {
2418
+ const target = resolveTarget(item, conditions);
2419
+ if (target !== void 0) return target;
2420
+ }
2421
+ return;
2422
+ }
2423
+ if (value === null || typeof value !== "object") return void 0;
2424
+ for (const [key, nested] of Object.entries(value)) {
2425
+ if (!conditions.has(key)) continue;
2426
+ const target = resolveTarget(nested, conditions);
2427
+ if (target !== void 0) return target;
2428
+ }
2429
+ }
2430
+ function targetsOf(value) {
2431
+ if (typeof value === "string") return [value];
2432
+ if (Array.isArray(value)) return value.flatMap(targetsOf);
2433
+ if (value === null || typeof value !== "object") return [];
2434
+ return Object.values(value).flatMap(targetsOf);
2435
+ }
2436
+ function subpaths(manifest) {
2437
+ const { exports } = manifest;
2438
+ if (exports === void 0) return [];
2439
+ if (exports !== null && typeof exports === "object" && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith("."))) return Object.entries(exports);
2440
+ return [[".", exports]];
2441
+ }
2442
+ const packedPath = (target) => target.replace(/^\.\//, "");
2443
+ function packedEntries(manifest, files, unbuilt) {
2444
+ const imports = {
2445
+ node: [],
2446
+ browser: []
2447
+ };
2448
+ const missing = [];
2449
+ const entries = subpaths(manifest);
2450
+ if (entries.length === 0) {
2451
+ imports.node.push(manifest.name);
2452
+ return {
2453
+ imports,
2454
+ missing
2455
+ };
2456
+ }
2457
+ for (const [subpath, value] of entries) {
2458
+ const targets = targetsOf(value).filter((target) => !target.includes("*"));
2459
+ const absent = targets.filter((target) => !files.has(packedPath(target)));
2460
+ if (unbuilt.has(subpath) && absent.length === targets.length) continue;
2461
+ missing.push(...absent.map((target) => `exports["${subpath}"] names ${target}`));
2462
+ if (subpath === "./package.json") continue;
2463
+ for (const consumer of ["node", "browser"]) {
2464
+ const target = resolveTarget(value, CONDITIONS[consumer]);
2465
+ if (target === void 0 || !IMPORTABLE.test(target)) continue;
2466
+ const specifier = `${manifest.name}${subpath.slice(1)}`;
2467
+ if (!subpath.includes("*")) {
2468
+ imports[consumer].push(specifier);
2469
+ continue;
2470
+ }
2471
+ const [before, after] = packedPath(target).split("*");
2472
+ const [subBefore, subAfter] = specifier.split("*");
2473
+ for (const file of [...files].sort()) {
2474
+ if (!file.startsWith(before) || !file.endsWith(after)) continue;
2475
+ const star = file.slice(before.length, file.length - after.length);
2476
+ if (star !== "") imports[consumer].push(`${subBefore}${star}${subAfter}`);
2477
+ }
2478
+ }
2479
+ }
2480
+ return {
2481
+ imports,
2482
+ missing
2483
+ };
2484
+ }
2485
+ function installed(projectRoot, name) {
2486
+ for (let directory = projectRoot;; directory = dirname(directory)) {
2487
+ const candidate = join(directory, "node_modules", ...name.split("/"));
2488
+ if (existsSync(join(candidate, "package.json"))) return realpathSync.native(candidate);
2489
+ if (dirname(directory) === directory) return void 0;
2490
+ }
2491
+ }
2492
+ const IMPORT_EACH = `import { writeFileSync } from "node:fs";
2493
+ import { registerHooks } from "node:module";
2494
+ const { specifiers, conditions, resultFile } = JSON.parse(process.argv[1]);
2495
+ if (conditions) {
2496
+ registerHooks({
2497
+ resolve: (specifier, context, next) => next(specifier, {
2498
+ ...context,
2499
+ conditions: context.conditions.includes("require")
2500
+ ? conditions.map((name) => (name === "import" ? "require" : name))
2501
+ : conditions,
2502
+ }),
2503
+ });
2504
+ }
2505
+ const failed = [];
2506
+ for (const specifier of specifiers) {
2507
+ try { await import(specifier); }
2508
+ catch (error) { failed.push(specifier + ": " + (error instanceof Error ? error.message : String(error)).split("\\n")[0]); }
2509
+ }
2510
+ writeFileSync(resultFile, JSON.stringify(failed));
2511
+ process.exit(0);
2512
+ `;
2513
+ const TIMEOUT_MS = 12e4;
2514
+ const STDERR_LIMIT = 65536;
2515
+ async function importAll(consumerRoot, consumer, specifiers, signal) {
2516
+ if (specifiers.length === 0) return [];
2517
+ const env = { ...process.env };
2518
+ delete env.NODE_OPTIONS;
2519
+ delete env.NODE_PATH;
2520
+ const resultFile = join(dirname(consumerRoot), `${consumer}-result.json`);
2521
+ const input = {
2522
+ specifiers,
2523
+ conditions: consumer === "browser" ? [...CONDITIONS.browser] : null,
2524
+ resultFile
2525
+ };
2526
+ const ended = await new Promise((done) => {
2527
+ const child = spawn(process.execPath, [
2528
+ "--input-type=module",
2529
+ "-e",
2530
+ IMPORT_EACH,
2531
+ JSON.stringify(input)
2532
+ ], {
2533
+ cwd: consumerRoot,
2534
+ env,
2535
+ signal,
2536
+ stdio: [
2537
+ "ignore",
2538
+ "ignore",
2539
+ "pipe"
2540
+ ]
2541
+ });
2542
+ let timedOut = false;
2543
+ const timer = setTimeout(() => {
2544
+ timedOut = true;
2545
+ child.kill();
2546
+ }, TIMEOUT_MS);
2547
+ let stderr = "";
2548
+ child.stderr.setEncoding("utf8");
2549
+ child.stderr.on("data", (chunk) => {
2550
+ if (stderr.length < STDERR_LIMIT) stderr += chunk;
2551
+ });
2552
+ child.on("error", (error) => done(error.message));
2553
+ child.on("close", (code, killedBy) => {
2554
+ clearTimeout(timer);
2555
+ if (timedOut) {
2556
+ done(`did not finish its imports within ${TIMEOUT_MS / 1e3} seconds`);
2557
+ return;
2558
+ }
2559
+ const how = killedBy === null ? `exited with ${code}` : `got ${killedBy}`;
2560
+ const why = stderr.trim().split("\n")[0];
2561
+ done(why ? `${how}: ${why}` : how);
2562
+ });
2563
+ });
2564
+ if (!existsSync(resultFile)) return [`${consumer} consumer did not finish: it ${ended}`];
2565
+ return JSON.parse(readFileSync(resultFile, "utf8")).map((failure) => `${consumer} consumer cannot import ${failure.replace(/ imported from \S*\[eval\d*\]$/, "")}`);
2566
+ }
2567
+ async function checkPackedConsumer(projectRoot, packed, unbuilt, signal) {
2568
+ const { manifest, files } = packed;
2569
+ const consumerRoot = join(packed.directory, "consumer");
2570
+ const modules = join(consumerRoot, "node_modules");
2571
+ const installRoot = join(modules, ...manifest.name.split("/"));
2572
+ for (const [path, bytes] of files) {
2573
+ const target = resolve(installRoot, path);
2574
+ if (!target.startsWith(`${installRoot}${sep}`)) return [`the tarball has an entry outside the package: ${path}`];
2575
+ mkdirSync(dirname(target), { recursive: true });
2576
+ writeFileSync(target, bytes);
2577
+ }
2578
+ writeFileSync(join(consumerRoot, "package.json"), `${JSON.stringify({
2579
+ name: "ph-packed-consumer",
2580
+ private: true,
2581
+ type: "module"
2582
+ })}\n`);
2583
+ const runtime = /* @__PURE__ */ new Set([
2584
+ ...Object.keys(manifest.dependencies ?? {}),
2585
+ ...Object.keys(manifest.optionalDependencies ?? {}),
2586
+ ...Object.keys(manifest.peerDependencies ?? {})
2587
+ ]);
2588
+ for (const name of runtime) {
2589
+ if (name === manifest.name) continue;
2590
+ const from = installed(projectRoot, name);
2591
+ if (from === void 0) continue;
2592
+ const link = join(modules, ...name.split("/"));
2593
+ mkdirSync(dirname(link), { recursive: true });
2594
+ symlinkSync(from, link, process.platform === "win32" ? "junction" : "dir");
2595
+ }
2596
+ const { imports, missing } = packedEntries(manifest, new Set(files.keys()), unbuilt);
2597
+ const failures = await Promise.all(["node", "browser"].map((consumer) => importAll(consumerRoot, consumer, imports[consumer], signal)));
2598
+ return [...missing.map((entry) => `${entry}, which the package does not contain`), ...failures.flat()].map((failure) => {
2599
+ const shown = failure.replaceAll(`${consumerRoot}${sep}`, "").replaceAll(consumerRoot, ".");
2600
+ return sep === "\\" ? shown.replaceAll("\\", "/") : shown;
2601
+ });
2602
+ }
2603
+ //#endregion
1553
2604
  //#region src/services/release/issuance.ts
1554
2605
  const under$1 = (path, directory) => path === directory || path.startsWith(`${directory}/`);
1555
2606
  /**
@@ -1584,7 +2635,7 @@ const under = (path, directory) => path === directory || path.startsWith(`${dire
1584
2635
  * The output directory as given, then the directory the build replaces when
1585
2636
  * that is a symlink to another place in the package: neither is a source.
1586
2637
  */
1587
- function outputDirectories$1(projectRoot, outDir, target) {
2638
+ function outputDirectories(projectRoot, outDir, target) {
1588
2639
  const output = packagePath(projectRoot, outDir);
1589
2640
  const real = packagePath(projectRoot, target);
1590
2641
  return real !== ".." && !real.startsWith("../") && !isAbsolute(real) && !under(real, output) ? [output, real] : [output];
@@ -1593,25 +2644,31 @@ function outputDirectories$1(projectRoot, outDir, target) {
1593
2644
  const releaseStartStep = {
1594
2645
  id: "release-start",
1595
2646
  run: ({ args, projectRoot, outDir, session, findings }) => {
1596
- if (args.release) findings.releaseStart = revisionFiles(projectRoot, outputDirectories$1(projectRoot, outDir, session.output));
2647
+ if (args.release) findings.releaseStart = revisionFiles(projectRoot, outputDirectories(projectRoot, outDir, session.output));
1597
2648
  return Promise.resolve();
1598
2649
  }
1599
2650
  };
2651
+ /** Exports `ph init` declares whose entry the build skips when its source is absent. */
2652
+ const OPTIONAL_EXPORTS = {
2653
+ "./scalars": "scalars/index.ts",
2654
+ "./pieces": "pieces/index.ts"
2655
+ };
2656
+ const unbuiltExports = (projectRoot, findings) => /* @__PURE__ */ new Set([...Object.entries(OPTIONAL_EXPORTS).filter(([, source]) => !existsSync(join(projectRoot, source))).map(([subpath]) => subpath), ...findings.offersRoutes ? [] : ["./connect-routes"]]);
1600
2657
  const notWritten = (why) => new BuildRefusal(`✘ No release approval was written: ${why}. The new output is in place; build again with --release to approve it.`);
1601
2658
  /**
1602
2659
  * With `--release`, once the output is replaced: records what the release
1603
2660
  * check approved and what `npm pack` publishes from the new output, unless
1604
- * tsc's errors were accepted or the package changed while it was built.
2661
+ * tsc's errors were accepted, the package changed while it was built, or the
2662
+ * packed tarball fails to install and import in a scratch consumer.
1605
2663
  */
1606
2664
  const releaseApprovalStep = {
1607
2665
  id: "release-approval",
1608
2666
  when: "committed",
1609
- run: ({ args, projectRoot, outDir, session, findings }) => {
1610
- if (args.release) recordApproval(projectRoot, outputDirectories$1(projectRoot, outDir, session.output), findings);
1611
- return Promise.resolve();
2667
+ run: async ({ args, projectRoot, outDir, session, findings }) => {
2668
+ if (args.release) await recordApproval(projectRoot, outputDirectories(projectRoot, outDir, session.output), findings, session);
1612
2669
  }
1613
2670
  };
1614
- function recordApproval(projectRoot, outputs, findings) {
2671
+ async function recordApproval(projectRoot, outputs, findings, session) {
1615
2672
  const plan = planApproval({
1616
2673
  typesOk: findings.typesOk,
1617
2674
  release: findings.release,
@@ -1625,12 +2682,26 @@ function recordApproval(projectRoot, outputs, findings) {
1625
2682
  const files = revisionFiles(projectRoot, [output, ...excluded]);
1626
2683
  const changed = changedWhileBuilt(plan, files);
1627
2684
  if (changed !== void 0) throw notWritten(changed);
1628
- let published;
2685
+ let packed;
1629
2686
  try {
1630
- published = publishedFiles(projectRoot);
2687
+ packed = packRelease(projectRoot);
1631
2688
  } catch (error) {
1632
2689
  throw notWritten(error instanceof Error ? error.message : String(error));
1633
2690
  }
2691
+ let published;
2692
+ const stop = new AbortController();
2693
+ const unwatch = session.onCancel(() => {
2694
+ stop.abort();
2695
+ packed.dispose();
2696
+ });
2697
+ try {
2698
+ const failures = await checkPackedConsumer(projectRoot, packed, unbuiltExports(projectRoot, findings), stop.signal);
2699
+ if (failures.length > 0) throw notWritten(`the packed package does not install and import in a scratch consumer: ${listed(failures)}`);
2700
+ published = packedDigests(packed);
2701
+ } finally {
2702
+ unwatch();
2703
+ packed.dispose();
2704
+ }
1634
2705
  const phCliVersion = getVersion();
1635
2706
  writeReleaseApproval(projectRoot, {
1636
2707
  kind: "powerhouse.release-approval",
@@ -1691,116 +2762,11 @@ const stylesheetStep = {
1691
2762
  }
1692
2763
  };
1693
2764
  //#endregion
1694
- //#region src/services/compiler-output/emit.ts
1695
- const withoutExtension = (path) => path.replace(/\.[^./\\]+$/, "");
1696
- const declares = (options) => options.declaration === true || options.composite === true;
1697
- /**
1698
- * Where tsc keeps the build info of `configFile`, by TypeScript's rule:
1699
- * `tsBuildInfoFile`; else beside `outFile`; else in `outDir`, at the
1700
- * config's place relative to `rootDir` when that is set; else beside the
1701
- * config.
1702
- */
1703
- function buildInfoFile(options, configFile) {
1704
- const configDir = dirname(configFile);
1705
- const name = `${basename(configFile, extname(configFile))}.tsbuildinfo`;
1706
- if (options.tsBuildInfoFile !== void 0) return resolve(configDir, options.tsBuildInfoFile);
1707
- if (options.outFile !== void 0) return resolve(configDir, `${withoutExtension(options.outFile)}.tsbuildinfo`);
1708
- if (options.outDir === void 0) return resolve(configDir, name);
1709
- const fromRoot = options.rootDir === void 0 ? "" : relative(resolve(configDir, options.rootDir), configDir);
1710
- return resolve(configDir, options.outDir, fromRoot, name);
1711
- }
1712
- /**
1713
- * The files tsc writes for `outFile`: the bundle and its map unless it
1714
- * emits declarations only, then the declaration and its map when it
1715
- * declares. None without `outFile` or with `noEmit`.
1716
- */
1717
- function outFileOutputs(options, configFile) {
1718
- if (options.outFile === void 0 || options.noEmit) return [];
1719
- const output = resolve(dirname(configFile), options.outFile);
1720
- const files = [];
1721
- if (!options.emitDeclarationOnly) files.push(output, ...options.sourceMap ? [`${output}.map`] : []);
1722
- if (declares(options)) {
1723
- const declaration = `${withoutExtension(output)}.d.ts`;
1724
- files.push(declaration, ...options.declarationMap ? [`${declaration}.map`] : []);
1725
- }
1726
- return files;
1727
- }
1728
- /** The declaration and output directories the options name, resolved. */
1729
- function outputDirectories(options, configDir) {
1730
- return [options.declarationDir, options.outDir].filter((dir) => dir !== void 0).map((dir) => resolve(configDir, dir));
1731
- }
1732
- /** Where tsc writes declarations, when it writes them to a directory of their own. */
1733
- function declarationDirectory(options, configDir) {
1734
- const dir = options.declarationDir ?? options.outDir;
1735
- if (!dir || !declares(options)) return void 0;
1736
- return resolve(configDir, dir);
1737
- }
1738
- //#endregion
1739
- //#region src/services/package-build/staging/inventory.ts
1740
- const optionalString = (value) => typeof value === "string" ? value : void 0;
1741
- const optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
1742
- /** The options in `tsc --showConfig` output, or undefined when it is not JSON. */
1743
- function parseShownConfig(text) {
1744
- let shown;
1745
- try {
1746
- shown = JSON.parse(text);
1747
- } catch {
1748
- return;
1749
- }
1750
- if (typeof shown !== "object" || shown === null) return void 0;
1751
- const options = shown.compilerOptions;
1752
- if (typeof options !== "object" || options === null) return {};
1753
- const record = options;
1754
- return {
1755
- declaration: optionalBoolean(record.declaration),
1756
- composite: optionalBoolean(record.composite),
1757
- declarationDir: optionalString(record.declarationDir),
1758
- outDir: optionalString(record.outDir),
1759
- outFile: optionalString(record.outFile),
1760
- rootDir: optionalString(record.rootDir),
1761
- tsBuildInfoFile: optionalString(record.tsBuildInfoFile),
1762
- noEmit: optionalBoolean(record.noEmit),
1763
- emitDeclarationOnly: optionalBoolean(record.emitDeclarationOnly),
1764
- sourceMap: optionalBoolean(record.sourceMap),
1765
- declarationMap: optionalBoolean(record.declarationMap)
1766
- };
1767
- }
1768
- function inside(root, path) {
1769
- const rel = relative(root, path);
1770
- return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
1771
- }
1772
- /**
1773
- * What the root project's tsc writes inside the package, for the build to
1774
- * snapshot and restore: its build info first, then the files `outFile`
1775
- * writes, then its declaration and output directories, the build's own
1776
- * output directory or one holding it included. A directory holding
1777
- * `buildDirectory`, where the build keeps its runs and their snapshots, is
1778
- * left out and unprotected, as without staging: a snapshot of it would copy
1779
- * itself. This says what to protect, not what to carry into the stage.
1780
- */
1781
- function compilerOutputInventory(options, at) {
1782
- const inPackage = (path) => inside(at.packageRoot, path);
1783
- const directories = outputDirectories(options, dirname(at.configFile)).filter(inPackage).filter((dir) => dir !== at.buildDirectory && !inside(dir, at.buildDirectory));
1784
- return [
1785
- ...[buildInfoFile(options, at.configFile)].filter(inPackage).map((path) => ({
1786
- path,
1787
- kind: "build-info"
1788
- })),
1789
- ...outFileOutputs(options, at.configFile).filter(inPackage).map((path) => ({
1790
- path,
1791
- kind: "file"
1792
- })),
1793
- ...[...new Set(directories)].map((path) => ({
1794
- path,
1795
- kind: "directory"
1796
- }))
1797
- ];
1798
- }
1799
- //#endregion
1800
2765
  //#region src/services/package-build/steps/typecheck.ts
1801
2766
  const TYPE_ERROR_RISK = "A package built with type errors can load and still fail at runtime.";
1802
2767
  const UNSAFE_BUILD_WARNING = "⚠ Built despite type errors. " + TYPE_ERROR_RISK + " Fix them before you publish or deploy it.";
1803
- function showCompilerOptions(agent, projectRoot) {
2768
+ /** The root project's config, as `tsc --showConfig` prints it. */
2769
+ function showCompilerConfig(agent, projectRoot) {
1804
2770
  const showConfig = resolveCommand(agent, "execute-local", ["tsc", "--showConfig"]);
1805
2771
  if (showConfig === null) return void 0;
1806
2772
  try {
@@ -1856,23 +2822,32 @@ const standardBuildSteps = [
1856
2822
  {
1857
2823
  id: "typecheck",
1858
2824
  run: async ({ agent, args, outDir, projectRoot, session, findings }) => {
1859
- const options = showCompilerOptions(agent, projectRoot);
1860
- const force = options !== void 0 && declarationsMissing(options, projectRoot);
2825
+ const config = showCompilerConfig(agent, projectRoot);
2826
+ const force = config !== void 0 && declarationsMissing(config.options, projectRoot);
2827
+ let generated;
2828
+ if (config !== void 0) {
2829
+ const configFile = join(projectRoot, "tsconfig.json");
2830
+ const outputs = await compilerOutputs(config, {
2831
+ configFile,
2832
+ packageRoot: projectRoot,
2833
+ buildDirectory: join(projectRoot, BUILD_DIRECTORY),
2834
+ agent,
2835
+ output: session.output
2836
+ });
2837
+ generated = await session.prepareCompiler({
2838
+ configFile,
2839
+ config,
2840
+ outputs
2841
+ });
2842
+ findings.compilerOutputs = outputs.map(({ path }) => path);
2843
+ }
1861
2844
  const tscCommand = resolveCommand(agent, "execute-local", [
1862
2845
  "tsc",
1863
2846
  "--build",
1864
- ...force ? ["--force"] : []
2847
+ ...force ? ["--force"] : [],
2848
+ ...generated ? [relative(projectRoot, generated)] : []
1865
2849
  ]);
1866
2850
  if (tscCommand === null) throw new BuildRefusal("You need to have typescript installed to use the `build` command.");
1867
- if (options !== void 0) {
1868
- const outputs = compilerOutputInventory(options, {
1869
- configFile: join(projectRoot, "tsconfig.json"),
1870
- packageRoot: projectRoot,
1871
- buildDirectory: join(projectRoot, BUILD_DIRECTORY)
1872
- });
1873
- session.protectCompilerOutputs(outputs);
1874
- findings.compilerOutputs = outputs.map(({ path }) => path);
1875
- }
1876
2851
  console.log("\n▶ Type-checking and emitting types via tsc...");
1877
2852
  try {
1878
2853
  execSync(`${tscCommand.command} ${tscCommand.args.join(" ")}`, { stdio: "inherit" });
@@ -2032,5 +3007,5 @@ async function runBuild(args, options = {}) {
2032
3007
  //#endregion
2033
3008
  export { assertExternalDependenciesDeclared as i, createTraceFiles as n, assertManifestNameMatchesPackage as r, runBuild as t };
2034
3009
 
2035
- //# sourceMappingURL=build-CVEsxazW.mjs.map
2036
- //# debugId=0939018c-cae4-50f2-804c-a7ec85183c00
3010
+ //# sourceMappingURL=build-BlubqQME.mjs.map
3011
+ //# debugId=8efa3bd1-04ef-5d3a-8bcd-0da6b4001c3a