@naseej/blox 1.9.0 → 1.10.0

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 (3) hide show
  1. package/dist/run.js +2211 -323
  2. package/package.json +2 -2
  3. package/readme.md +22 -0
package/dist/run.js CHANGED
@@ -201,7 +201,7 @@ var checkForCliUpdate = async (currentVersion, argv = []) => {
201
201
  };
202
202
 
203
203
  // package.json
204
- var version = "1.9.0";
204
+ var version = "1.10.0";
205
205
 
206
206
  // src/migrations/index.ts
207
207
  var import_node_path11 = __toESM(require("path"));
@@ -457,18 +457,6 @@ function isBloxConfigFile(file) {
457
457
  return normalized === bloxFilePath || normalized.endsWith(`/${bloxFilePath}`);
458
458
  }
459
459
 
460
- // src/shared/utils/omitKeys.ts
461
- function omitKeys(value, keysToOmit) {
462
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
463
- return value;
464
- }
465
- const result = { ...value };
466
- for (const key of keysToOmit) {
467
- delete result[key];
468
- }
469
- return result;
470
- }
471
-
472
460
  // src/shared/utils/normalizeCommitRef.ts
473
461
  var normalizeCommitRef = (commit2) => commit2.trim().replace(/\r/g, "").replace(/^"+|"+$/g, "");
474
462
 
@@ -612,8 +600,9 @@ async function runTask(message, task) {
612
600
  const taskSpinner = spinner();
613
601
  taskSpinner.start(startMessage);
614
602
  try {
615
- await (typeof task === "function" ? task() : task);
603
+ const result = await (typeof task === "function" ? task() : task);
616
604
  taskSpinner.stop(endMessage);
605
+ return result;
617
606
  } catch (e) {
618
607
  taskSpinner.stop(`Failed: ${startMessage}`, 1);
619
608
  throw e;
@@ -655,6 +644,33 @@ var normalizePath = (_path) => {
655
644
  return _path.split(import_node_path8.default.sep).join("/");
656
645
  };
657
646
 
647
+ // src/services/gitRefConflict.ts
648
+ var REF_CONFLICT_PATTERN = /cannot lock ref|cannot update the ref|unable to update local ref|exists; cannot create/i;
649
+ var CONFLICTING_REFS_PATTERN = /'refs\/remotes\/[^/']+\/([^']+)' exists; cannot create 'refs\/remotes\/[^/']+\/([^']+)'/gi;
650
+ var isRefConflictError = (error2) => error2 instanceof Error && REF_CONFLICT_PATTERN.test(error2.message);
651
+ var buildRefConflictError = (remote, cause) => {
652
+ const conflicts = [
653
+ ...new Set(
654
+ [...cause.message.matchAll(CONFLICTING_REFS_PATTERN)].map(
655
+ ([, a, b]) => ` - \`${a}\` vs \`${b}\``
656
+ )
657
+ )
658
+ ];
659
+ const message = [
660
+ `Unable to update remote "${remote}" because Git encountered conflicting remote-tracking references.`,
661
+ ...conflicts.length ? ["", "Conflicts detected:", ...conflicts] : [],
662
+ "",
663
+ "Suggested actions:",
664
+ " 1. Check whether these branches still exist on the remote.",
665
+ " 2. If they do, rename the conflicting branches on the remote so their names are compatible (e.g. on Windows, names that differ only by case or by file/directory nesting).",
666
+ ` 3. If the conflict is only local, repair the affected remote-tracking references (git remote prune ${remote}) and retry.`,
667
+ "",
668
+ "Git output:",
669
+ cause.message
670
+ ].join("\n");
671
+ return new Error(message, { cause });
672
+ };
673
+
658
674
  // src/services/git.ts
659
675
  var remoteWorktrees = /* @__PURE__ */ new Map();
660
676
  var getChangedFiles = async (fromCommit, toCommit, ignore3 = [], cwd = ".") => {
@@ -741,6 +757,20 @@ var clone = (repoUrl, dir, branch = defaultBranch, options = {}) => {
741
757
  var resetToCommit = async (commit2, cwd = ".") => {
742
758
  await $("git", ["reset", "--hard", commit2], { cwd });
743
759
  };
760
+ var fetchWithRefRecovery = async (remote, args, shellOptions) => {
761
+ try {
762
+ await $("git", args, shellOptions);
763
+ } catch (error2) {
764
+ if (!isRefConflictError(error2)) throw error2;
765
+ debug(`Ref conflict while fetching "${remote}", pruning stale remote-tracking refs`);
766
+ try {
767
+ await $("git", ["remote", "prune", remote], shellOptions);
768
+ await $("git", args, shellOptions);
769
+ } catch (retryError) {
770
+ throw buildRefConflictError(remote, retryError);
771
+ }
772
+ }
773
+ };
744
774
  var updatedRemotes = /* @__PURE__ */ new Set();
745
775
  var updateRemote = async (name, source, shellOptions = {}) => {
746
776
  const remoteId = `${name}:${source}`;
@@ -758,9 +788,42 @@ var updateRemote = async (name, source, shellOptions = {}) => {
758
788
  ...defaultShellOptions,
759
789
  ...shellOptions
760
790
  });
761
- await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
791
+ await fetchWithRefRecovery(name, ["fetch", name], {
792
+ ...defaultShellOptions,
793
+ ...shellOptions
794
+ });
762
795
  updatedRemotes.add(remoteId);
763
796
  };
797
+ var readFileFromCommit = async (commit2, file, cwd = ".") => {
798
+ try {
799
+ let content = "";
800
+ const p = normalizePath(file);
801
+ await $("git", ["show", `${commit2}:${p}`], {
802
+ cwd,
803
+ onStdout: (text2) => {
804
+ content += text2;
805
+ }
806
+ });
807
+ return content;
808
+ } catch {
809
+ return null;
810
+ }
811
+ };
812
+ var readFileFromIndex = async (file, stage = 0, cwd = ".") => {
813
+ try {
814
+ let content = "";
815
+ const p = normalizePath(file);
816
+ await $("git", ["show", `:${stage}:${p}`], {
817
+ cwd,
818
+ onStdout: (text2) => {
819
+ content += text2;
820
+ }
821
+ });
822
+ return content;
823
+ } catch {
824
+ return null;
825
+ }
826
+ };
764
827
  var readJsonFromCommit = async (commit2, file, cwd = ".") => {
765
828
  try {
766
829
  let content = "";
@@ -808,8 +871,8 @@ var update = (shellOptions = {}) => {
808
871
  var getLatestCommitFromRemote = async (remote, branch) => {
809
872
  return getLatestCommit(`${remote}/${branch}`);
810
873
  };
811
- var getLatestCommitFromPath = async (path24) => {
812
- return getLatestCommit("HEAD", path24);
874
+ var getLatestCommitFromPath = async (path31) => {
875
+ return getLatestCommit("HEAD", path31);
813
876
  };
814
877
  var getLatestCommit = async (rev, cwd = ".") => {
815
878
  debug(`Get latest commit for rev: ${rev} and cwd: ${cwd}`);
@@ -867,12 +930,23 @@ var hasUncommittedChanges = async (cwd = ".") => {
867
930
  return status.trim().length > 0;
868
931
  };
869
932
  var hasStagedChanges = async (cwd = ".") => {
870
- try {
871
- await $("git", ["diff-index", "--cached", "--quiet", "HEAD"], { cwd });
872
- return false;
873
- } catch {
874
- return true;
933
+ let lastError;
934
+ for (let attempt = 0; attempt < 4; attempt++) {
935
+ try {
936
+ await $("git", ["diff-index", "--cached", "--quiet", "HEAD"], { cwd });
937
+ return false;
938
+ } catch (e) {
939
+ if (e.code === 1) {
940
+ return true;
941
+ }
942
+ lastError = e;
943
+ if (attempt < 3) {
944
+ debug(`git diff-index failed, retrying (attempt ${attempt + 1})`);
945
+ await new Promise((r) => setTimeout(r, 250 * (attempt + 1)));
946
+ }
947
+ }
875
948
  }
949
+ throw lastError;
876
950
  };
877
951
  var checkout = async (branch, cwd = ".") => {
878
952
  debug(`Git checkout: ${branch}`);
@@ -950,11 +1024,11 @@ var createBranch = async (branch, from, cwd = ".") => {
950
1024
  var push = async (remote, branch, cwd = ".") => {
951
1025
  await $("git", ["push", "--progress", remote, `refs/heads/${branch}`], { cwd });
952
1026
  };
953
- var checkoutFile = async (path24, ref, cwd = ".") => {
1027
+ var checkoutFile = async (path31, ref, cwd = ".") => {
954
1028
  const args = ["checkout"];
955
1029
  if (ref) args.push(ref);
956
1030
  else args.push("HEAD");
957
- args.push("--", path24);
1031
+ args.push("--", path31);
958
1032
  await $("git", args, { cwd });
959
1033
  };
960
1034
  var pathExistsAsBlobInRev = async (rev, filePath, cwd = ".") => {
@@ -1016,10 +1090,10 @@ var cherryPick = async (commitHash, subtree, noCommit, cwd = ".") => {
1016
1090
  args.push(normalizeCommitRef(commitHash));
1017
1091
  await $("git", args, { cwd });
1018
1092
  };
1019
- var reset = async (path24, hard, cwd = ".") => {
1093
+ var reset = async (path31, hard, cwd = ".") => {
1020
1094
  const args = ["reset"];
1021
1095
  if (hard) args.push("--hard");
1022
- if (path24) args.push(path24);
1096
+ if (path31) args.push(path31);
1023
1097
  await $("git", args, { cwd });
1024
1098
  };
1025
1099
  var commitAll = async (message, cwd = ".") => {
@@ -1037,7 +1111,7 @@ var getUnmergedFiles = async (cwd = ".") => {
1037
1111
  return out.split("\n").filter((l) => /^(U.|.U|AA|DD)/.test(l)).map((l) => l.slice(3).trim());
1038
1112
  };
1039
1113
  var fetchRepo = async (cwd = ".") => {
1040
- await $("git", ["fetch", "--progress", "origin"], { cwd });
1114
+ await fetchWithRefRecovery("origin", ["fetch", "--progress", "origin"], { cwd });
1041
1115
  };
1042
1116
  var getChangedFilesInCommit = async (commit2, cwd = ".") => {
1043
1117
  let out = "";
@@ -1087,6 +1161,8 @@ var git = {
1087
1161
  getLatestCommitFromPath,
1088
1162
  getChangesLog,
1089
1163
  updateRemote,
1164
+ readFileFromCommit,
1165
+ readFileFromIndex,
1090
1166
  readJsonFromCommit,
1091
1167
  readJsonFromIndex,
1092
1168
  readJsonFromRemote,
@@ -1288,14 +1364,36 @@ var deletePattern = async (cwd, patterns = []) => {
1288
1364
  }
1289
1365
  };
1290
1366
 
1367
+ // src/services/versions/compatibility.ts
1368
+ var DEFAULT_VERSION = 0;
1369
+ function normalizeVersion(version2) {
1370
+ return version2 || DEFAULT_VERSION;
1371
+ }
1372
+ function normalizeDependencyVersion(version2) {
1373
+ return version2 || DEFAULT_VERSION;
1374
+ }
1375
+ function toVersionRange(range) {
1376
+ const normalized = normalizeDependencyVersion(range);
1377
+ return typeof normalized === "number" ? [normalized, normalized] : normalized;
1378
+ }
1379
+ function isVersionCompatible(version2, range) {
1380
+ const [min, max] = toVersionRange(range);
1381
+ const current = normalizeVersion(version2);
1382
+ return current >= min && current <= max;
1383
+ }
1384
+ function formatVersionRange(range) {
1385
+ const [min, max] = toVersionRange(range);
1386
+ return min === max ? `${min}` : `min: ${min}, max: ${max}`;
1387
+ }
1388
+
1291
1389
  // src/services/versions/checkCompatibility.ts
1292
1390
  function processDependencyVersion(dep) {
1293
- if (!dep.version) dep.version = 0;
1391
+ dep.version = normalizeDependencyVersion(dep.version);
1294
1392
  return dep;
1295
1393
  }
1296
1394
  function processTemplate(def) {
1297
1395
  debug("processTemplate");
1298
- if (!def.version) def.version = 0;
1396
+ def.version = normalizeVersion(def.version);
1299
1397
  Object.values(def.bases || {}).forEach(processDependencyVersion);
1300
1398
  return def;
1301
1399
  }
@@ -1303,31 +1401,26 @@ function processBases(info) {
1303
1401
  debug("processBases");
1304
1402
  if (!info || !info.checkpoints) return {};
1305
1403
  Object.values(info.checkpoints).forEach((base) => {
1306
- if (!base.version) base.version = 0;
1404
+ base.version = normalizeVersion(base.version);
1307
1405
  });
1308
1406
  return info.checkpoints;
1309
1407
  }
1310
1408
  function processBlocks(defs) {
1311
1409
  debug("processBlocks");
1312
1410
  defs.forEach((def) => {
1313
- if (!def.version) def.version = 0;
1411
+ def.version = normalizeVersion(def.version);
1314
1412
  def.dependencies?.forEach(processDependencyVersion);
1315
1413
  def.templates?.forEach(processDependencyVersion);
1316
1414
  });
1317
1415
  return defs;
1318
1416
  }
1319
1417
  function ensureVersionOverlap(version2 = 0, range = 0, mismatchMessage) {
1320
- if (typeof range === "number") {
1321
- range = [range, range];
1322
- }
1323
- const match = version2 >= range[0] && version2 <= range[1];
1324
- if (!match) {
1325
- const requiredVersionText = range[0] === range[1] ? `${range[0]}` : `min: ${range[0]}, max: ${range[1]}`;
1418
+ if (!isVersionCompatible(version2, range)) {
1326
1419
  throw new Error(
1327
1420
  normalizeLogMessage(`
1328
1421
  ${mismatchMessage}
1329
1422
  current version: ${version2}
1330
- required version: ${requiredVersionText}
1423
+ required version: ${formatVersionRange(range)}
1331
1424
  `)
1332
1425
  );
1333
1426
  }
@@ -2537,13 +2630,291 @@ Expected remote ${remoteHead}, local checkpoint ${checkpoint.commit}.`
2537
2630
  };
2538
2631
 
2539
2632
  // src/services/contribute/services/CommitApplierService.ts
2633
+ var import_node_path19 = __toESM(require("path"));
2634
+ var import_fs_extra15 = __toESM(require("fs-extra"));
2635
+ var import_isEqual2 = __toESM(require("lodash/isEqual"));
2636
+
2637
+ // src/services/ide.ts
2540
2638
  var import_node_path18 = __toESM(require("path"));
2541
2639
  var import_fs_extra14 = __toESM(require("fs-extra"));
2640
+ var KNOWN_IDES = [
2641
+ { id: "vscode", name: "Visual Studio Code", command: "code" },
2642
+ { id: "cursor", name: "Cursor", command: "cursor" },
2643
+ { id: "antigravity", name: "Antigravity", command: "agy", altCommands: ["antigravity"] },
2644
+ { id: "webstorm", name: "WebStorm", command: "webstorm" },
2645
+ { id: "idea", name: "IntelliJ IDEA", command: "idea" }
2646
+ ];
2647
+ var DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
2648
+ var windowsExecutableNames = (command2, pathext) => {
2649
+ const extensions = (pathext || DEFAULT_PATHEXT).split(";").filter(Boolean);
2650
+ return [command2, ...extensions.map((ext) => `${command2}${ext.toLowerCase()}`)];
2651
+ };
2652
+ var isExecutableFile = async (filePath) => {
2653
+ try {
2654
+ const stat = await import_fs_extra14.default.stat(filePath);
2655
+ if (!stat.isFile()) {
2656
+ return false;
2657
+ }
2658
+ await import_fs_extra14.default.access(filePath, import_fs_extra14.default.constants.X_OK);
2659
+ return true;
2660
+ } catch {
2661
+ return false;
2662
+ }
2663
+ };
2664
+ var isCommandOnPath = async (command2, env = process.env, platform = process.platform) => {
2665
+ const pathEnv = env.PATH ?? env.Path ?? env.path ?? "";
2666
+ const dirs = pathEnv.split(import_node_path18.default.delimiter).filter(Boolean);
2667
+ for (const dir of dirs) {
2668
+ if (platform === "win32") {
2669
+ for (const name of windowsExecutableNames(command2, env.PATHEXT)) {
2670
+ if (await import_fs_extra14.default.pathExists(import_node_path18.default.join(dir, name))) {
2671
+ return true;
2672
+ }
2673
+ }
2674
+ continue;
2675
+ }
2676
+ if (await isExecutableFile(import_node_path18.default.join(dir, command2))) {
2677
+ return true;
2678
+ }
2679
+ }
2680
+ return false;
2681
+ };
2682
+ var detectAvailableIdes = async (env = process.env, platform = process.platform) => {
2683
+ const available = [];
2684
+ for (const ide of KNOWN_IDES) {
2685
+ for (const command2 of [ide.command, ...ide.altCommands ?? []]) {
2686
+ if (await isCommandOnPath(command2, env, platform)) {
2687
+ available.push({ ...ide, command: command2 });
2688
+ break;
2689
+ }
2690
+ }
2691
+ }
2692
+ return available;
2693
+ };
2694
+ var openPathInIde = async (ide, dir) => {
2695
+ await $(ide.command, [dir]);
2696
+ };
2542
2697
 
2543
2698
  // src/services/contribute/config/index.ts
2544
2699
  var tempRepoName = "tmp";
2545
2700
  var bloxConfigControlledKeys = ["checkpoints", "project"];
2546
2701
 
2702
+ // src/services/contribute/utils/conflictResolutionPrompt.ts
2703
+ var import_core2 = require("@clack/core");
2704
+
2705
+ // src/shared/prompts/selectWithSearch.ts
2706
+ var import_core = require("@clack/core");
2707
+ var import_prompts13 = require("@clack/prompts");
2708
+ var SEARCH_REQUESTED = Symbol("search-requested");
2709
+ function isSelectedOption(option2, selectedValues) {
2710
+ return selectedValues.includes(option2.value);
2711
+ }
2712
+ function selectedOptionLabels(options, selectedValues) {
2713
+ return options.filter((option2) => isSelectedOption(option2, selectedValues)).map((option2) => option2.label);
2714
+ }
2715
+ function stateSymbol(state) {
2716
+ switch (state) {
2717
+ case "cancel":
2718
+ return fmt.red("\u25A0");
2719
+ case "error":
2720
+ return fmt.yellow("\u25B2");
2721
+ case "submit":
2722
+ return fmt.green("\u25C7");
2723
+ default:
2724
+ return fmt.cyan("\u25C6");
2725
+ }
2726
+ }
2727
+ function exitIfRealCancel(result) {
2728
+ if ((0, import_prompts13.isCancel)(result)) {
2729
+ (0, import_prompts13.cancel)("Canceled");
2730
+ process.exit(0);
2731
+ }
2732
+ }
2733
+ function watchForSearchKey(prompt) {
2734
+ let searchRequested = false;
2735
+ prompt.on("key", (char) => {
2736
+ if (char.toLowerCase() === "s") {
2737
+ searchRequested = true;
2738
+ prompt.state = "cancel";
2739
+ prompt.close();
2740
+ }
2741
+ });
2742
+ return () => searchRequested;
2743
+ }
2744
+ async function multiselectWithSearch(opts) {
2745
+ const required = opts.required ?? false;
2746
+ const optLabel = (option2, state) => {
2747
+ switch (state) {
2748
+ case "active":
2749
+ return `${fmt.cyan("\u25FB")} ${option2.label}${option2.hint ? ` ${fmt.dim(`(${option2.hint})`)}` : ""}`;
2750
+ case "selected":
2751
+ return `${fmt.green("\u25FC")} ${fmt.dim(option2.label)}`;
2752
+ case "active-selected":
2753
+ return `${fmt.green("\u25FC")} ${option2.label}${option2.hint ? ` ${fmt.dim(`(${option2.hint})`)}` : ""}`;
2754
+ default:
2755
+ return `${fmt.dim("\u25FB")} ${fmt.dim(option2.label)}`;
2756
+ }
2757
+ };
2758
+ const prompt = new import_core.MultiSelectPrompt({
2759
+ options: opts.options,
2760
+ initialValues: opts.initialValues,
2761
+ required,
2762
+ validate(selected) {
2763
+ if (required && (!selected || selected.length === 0)) {
2764
+ return `Please select at least one option.
2765
+ ${fmt.dim(
2766
+ `Press ${fmt.gray("space")} to select, ${fmt.gray("enter")} to continue`
2767
+ )}`;
2768
+ }
2769
+ return void 0;
2770
+ },
2771
+ render() {
2772
+ const title = `${fmt.gray("\u2502")}
2773
+ ${stateSymbol(this.state)} ${opts.message}
2774
+ `;
2775
+ const value = this.value ?? [];
2776
+ const styleOption = (option2, active) => {
2777
+ const selected = isSelectedOption(option2, value);
2778
+ if (active && selected) return optLabel(option2, "active-selected");
2779
+ if (selected) return optLabel(option2, "selected");
2780
+ return optLabel(option2, active ? "active" : "inactive");
2781
+ };
2782
+ switch (this.state) {
2783
+ case "submit":
2784
+ return `${title}${fmt.gray("\u2502")} ${selectedOptionLabels(this.options, value).map((label) => fmt.dim(label)).join(fmt.dim(", ")) || fmt.dim("none")}`;
2785
+ case "cancel": {
2786
+ const selectedLabels = selectedOptionLabels(this.options, value).map((label) => fmt.strikethrough(fmt.dim(label))).join(fmt.dim(", "));
2787
+ return `${title}${fmt.gray("\u2502")}${selectedLabels.trim() ? ` ${selectedLabels}
2788
+ ${fmt.gray("\u2502")}` : ""}`;
2789
+ }
2790
+ case "error": {
2791
+ const lines = this.options.map((o, i) => styleOption(o, i === this.cursor));
2792
+ return `${title}${fmt.yellow("\u2502")} ${lines.join(`
2793
+ ${fmt.yellow("\u2502")} `)}
2794
+ ${fmt.yellow("\u2514")} ${fmt.yellow(this.error)}
2795
+ `;
2796
+ }
2797
+ default: {
2798
+ const lines = this.options.map((o, i) => styleOption(o, i === this.cursor));
2799
+ return `${title}${fmt.cyan("\u2502")} ${lines.join(`
2800
+ ${fmt.cyan("\u2502")} `)}
2801
+ ${fmt.cyan("\u2514")} ${fmt.dim(
2802
+ `Press ${fmt.gray("space")} to select, ${fmt.gray("enter")} to continue`
2803
+ )}`;
2804
+ }
2805
+ }
2806
+ }
2807
+ });
2808
+ const searchRequested = watchForSearchKey(prompt);
2809
+ const result = await prompt.prompt();
2810
+ if (searchRequested()) {
2811
+ return SEARCH_REQUESTED;
2812
+ }
2813
+ exitIfRealCancel(result);
2814
+ return result;
2815
+ }
2816
+
2817
+ // src/services/contribute/utils/conflictResolutionPrompt.ts
2818
+ var MANUAL_IDE_VALUE = "__manual__";
2819
+ var buildManualInstructions = (tmpRepoCwd) => [
2820
+ "1. Open a new terminal and go to:",
2821
+ ` ${fmt.green(`cd "${tmpRepoCwd}"`)}`,
2822
+ "2. Resolve the conflicts manually.",
2823
+ `3. Stage your changes with: ${fmt.green("git add .")}`
2824
+ ].join("\n");
2825
+ var stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
2826
+ var drawBox = (styledTitle, bodyLines) => {
2827
+ const titleLen = stripAnsi(styledTitle).length;
2828
+ const terminalWidth = process.stdout.columns || 80;
2829
+ const innerWidth = Math.min(
2830
+ Math.max(...bodyLines.map((l) => stripAnsi(l).length), titleLen),
2831
+ terminalWidth - 6
2832
+ );
2833
+ const padVisible = (s) => s + " ".repeat(Math.max(innerWidth - stripAnsi(s).length, 0));
2834
+ return [
2835
+ `\u250C\u2500${styledTitle}${"\u2500".repeat(Math.max(innerWidth - titleLen + 2, 0))}\u2500\u2510`,
2836
+ ...bodyLines.map((l) => `\u2502 ${padVisible(l)} \u2502`),
2837
+ `\u2514${"\u2500".repeat(innerWidth + 4)}\u2518`
2838
+ ];
2839
+ };
2840
+ var boxedManualInstructions = (tmpRepoCwd) => drawBox(
2841
+ fmt.bold(" Manual conflict resolution "),
2842
+ buildManualInstructions(tmpRepoCwd).split("\n")
2843
+ );
2844
+ var showManualInstructionsBox = (tmpRepoCwd) => {
2845
+ import_prompts2.log.message(["", ...boxedManualInstructions(tmpRepoCwd), ""].join("\n"));
2846
+ };
2847
+ var showConflictSummary = (commit2, files, stillRemaining) => {
2848
+ const fileLabel = files.length === 1 ? "file" : "files";
2849
+ const title = stillRemaining ? fmt.yellow(fmt.bold(" Conflicts still detected ")) : fmt.red(fmt.bold(" Conflicts detected "));
2850
+ const bodyLines = [
2851
+ `Commit ${fmt.yellow(commit2.slice(0, 7))} ${stillRemaining ? "still has" : "has"} conflicts in ${files.length} ${fileLabel}:`,
2852
+ "",
2853
+ ...files.map((f) => ` ${fmt.red("\u2022 " + f)}`),
2854
+ "",
2855
+ ...stillRemaining ? [
2856
+ `Stage resolved files with ${fmt.green("git add .")} or keep resolving,`,
2857
+ "then press Enter again."
2858
+ ] : [
2859
+ "Resolve them in an IDE or another terminal,",
2860
+ `stage with ${fmt.green("git add .")}, then press Enter.`
2861
+ ]
2862
+ ];
2863
+ import_prompts2.log.message(["", ...drawBox(title, bodyLines), ""].join("\n"));
2864
+ };
2865
+ var selectIdeForConflictResolution = async (ides, tmpRepoCwd) => {
2866
+ const options = [
2867
+ ...ides.map((ide) => ({ value: ide.id, label: ide.name })),
2868
+ { value: MANUAL_IDE_VALUE, label: "Resolve manually without opening an IDE" }
2869
+ ];
2870
+ const boxLines = boxedManualInstructions(tmpRepoCwd);
2871
+ const message = "Select an IDE to open the temporary contribution project:";
2872
+ const optLabel = (option2, state) => {
2873
+ if (!option2) return "";
2874
+ switch (state) {
2875
+ case "selected":
2876
+ return fmt.dim(option2.label);
2877
+ case "active":
2878
+ return `${fmt.green("\u25CF")} ${option2.label}`;
2879
+ case "cancelled":
2880
+ return fmt.strikethrough(fmt.dim(option2.label));
2881
+ default:
2882
+ return `${fmt.dim("\u25CB")} ${fmt.dim(option2.label)}`;
2883
+ }
2884
+ };
2885
+ const prompt = new import_core2.SelectPrompt({
2886
+ options,
2887
+ render() {
2888
+ const title = `${fmt.gray("\u2502")}
2889
+ ${stateSymbol(this.state)} ${message}
2890
+ `;
2891
+ switch (this.state) {
2892
+ case "submit":
2893
+ return `${title}${fmt.gray("\u2502")} ${optLabel(this.options[this.cursor], "selected")}`;
2894
+ case "cancel":
2895
+ return `${title}${fmt.gray("\u2502")} ${optLabel(this.options[this.cursor], "cancelled")}
2896
+ ${fmt.gray("\u2502")}`;
2897
+ default: {
2898
+ const lines = this.options.map(
2899
+ (o, i) => optLabel(o, i === this.cursor ? "active" : "inactive")
2900
+ );
2901
+ const boxed = boxLines.map((l) => `${fmt.cyan("\u2502")} ${l}`).join("\n");
2902
+ return `${title}${fmt.cyan("\u2502")} ${lines.join(`
2903
+ ${fmt.cyan("\u2502")} `)}
2904
+ ${boxed}
2905
+ ${fmt.cyan("\u2514")}`;
2906
+ }
2907
+ }
2908
+ }
2909
+ });
2910
+ const result = await prompt.prompt();
2911
+ checkIfCanceled(result);
2912
+ if (result === MANUAL_IDE_VALUE) {
2913
+ return null;
2914
+ }
2915
+ return ides.find((ide) => ide.id === result) ?? null;
2916
+ };
2917
+
2547
2918
  // src/services/contribute/utils/orderCommitsOldestToNewest.ts
2548
2919
  var orderCommitsOldestToNewest = (commits, history) => {
2549
2920
  const historyIndex = new Map(history.map((commit2, index) => [commit2, index]));
@@ -2561,22 +2932,93 @@ var orderCommitsOldestToNewest = (commits, history) => {
2561
2932
  });
2562
2933
  };
2563
2934
 
2564
- // src/services/contribute/services/CommitApplierService.ts
2565
- var CommitApplierService = class {
2566
- constructor(logger) {
2567
- this.logger = logger;
2935
+ // src/services/contribute/utils/bloxConfigMerge.ts
2936
+ var import_isEqual = __toESM(require("lodash/isEqual"));
2937
+ var MISSING = Symbol("bloxConfigMerge.missing");
2938
+ function isPlainObject(value) {
2939
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2940
+ }
2941
+ function parseJsonObject(raw) {
2942
+ try {
2943
+ const parsed = JSON.parse(raw);
2944
+ return isPlainObject(parsed) ? parsed : void 0;
2945
+ } catch {
2946
+ return void 0;
2568
2947
  }
2569
- async applyCommits(opts) {
2570
- const prepareSpinner = spinner();
2571
- prepareSpinner.start("Prepare for apply commits");
2572
- const subtreePath = getPathPrefixToStrip(opts.target).replace(/\/$/, "");
2573
- const exclusion = getExcludedPrefixesForTarget(opts.target, opts.appRepoCwd);
2574
- const projectIgnore = getBloxFile(opts.appRepoCwd).project?.ignore || [];
2575
- const projectIgnoreMatcher = createGitignoreMatcher(projectIgnore);
2576
- this.logger.debug("Prepare for apply commits", {
2577
- appRepo: opts.appRepoCwd,
2578
- tmpRepo: opts.tmpRepoCwd,
2579
- target: {
2948
+ }
2949
+ function hasGitConflictMarkers(content) {
2950
+ return /^(<{7}|\|{7}|={7}|>{7})/m.test(content);
2951
+ }
2952
+ function withGovernedKeysFrom(value, source, governedKeys) {
2953
+ const result = { ...value };
2954
+ const sourceObj = isPlainObject(source) ? source : {};
2955
+ for (const key of governedKeys) {
2956
+ if (Object.prototype.hasOwnProperty.call(sourceObj, key)) {
2957
+ result[key] = sourceObj[key];
2958
+ } else {
2959
+ delete result[key];
2960
+ }
2961
+ }
2962
+ return result;
2963
+ }
2964
+ var equal = (a, b) => {
2965
+ if (a === MISSING || b === MISSING) return a === b;
2966
+ return (0, import_isEqual.default)(a, b);
2967
+ };
2968
+ var mergeValue = (base, ours, theirs, keyPath) => {
2969
+ if (equal(ours, theirs)) return { resolved: true, value: ours };
2970
+ if (equal(ours, base)) return { resolved: true, value: theirs };
2971
+ if (equal(theirs, base)) return { resolved: true, value: ours };
2972
+ if (isPlainObject(ours) && isPlainObject(theirs)) {
2973
+ const baseObj = isPlainObject(base) ? base : {};
2974
+ const merged = {};
2975
+ const conflicts = [];
2976
+ const keys = /* @__PURE__ */ new Set([...Object.keys(ours), ...Object.keys(theirs)]);
2977
+ for (const key of keys) {
2978
+ const result = mergeValue(
2979
+ Object.prototype.hasOwnProperty.call(baseObj, key) ? baseObj[key] : MISSING,
2980
+ Object.prototype.hasOwnProperty.call(ours, key) ? ours[key] : MISSING,
2981
+ Object.prototype.hasOwnProperty.call(theirs, key) ? theirs[key] : MISSING,
2982
+ [...keyPath, key]
2983
+ );
2984
+ if (!result.resolved) {
2985
+ conflicts.push(...result.conflicts);
2986
+ } else if (result.value !== MISSING) {
2987
+ merged[key] = result.value;
2988
+ }
2989
+ }
2990
+ return conflicts.length ? { resolved: false, conflicts } : { resolved: true, value: merged };
2991
+ }
2992
+ return { resolved: false, conflicts: [keyPath.join(".") || "(root)"] };
2993
+ };
2994
+ function mergeBloxConfigJson(base, ours, theirs, governedKeys) {
2995
+ if (!isPlainObject(ours) || !isPlainObject(theirs)) {
2996
+ return { resolved: false, conflicts: ["(root)"] };
2997
+ }
2998
+ const normalizedTheirs = withGovernedKeysFrom(theirs, ours, governedKeys);
2999
+ const result = mergeValue(isPlainObject(base) ? base : MISSING, ours, normalizedTheirs, []);
3000
+ if (!result.resolved) {
3001
+ return { resolved: false, conflicts: result.conflicts };
3002
+ }
3003
+ return { resolved: true, value: result.value };
3004
+ }
3005
+
3006
+ // src/services/contribute/services/CommitApplierService.ts
3007
+ var CommitApplierService = class {
3008
+ constructor(logger) {
3009
+ this.logger = logger;
3010
+ }
3011
+ async applyCommits(opts) {
3012
+ const prepareSpinner = spinner();
3013
+ prepareSpinner.start("Prepare for apply commits");
3014
+ const subtreePath = getPathPrefixToStrip(opts.target).replace(/\/$/, "");
3015
+ const exclusion = getExcludedPrefixesForTarget(opts.target, opts.appRepoCwd);
3016
+ const projectIgnore = getBloxFile(opts.appRepoCwd).project?.ignore || [];
3017
+ const projectIgnoreMatcher = createGitignoreMatcher(projectIgnore);
3018
+ this.logger.debug("Prepare for apply commits", {
3019
+ appRepo: opts.appRepoCwd,
3020
+ tmpRepo: opts.tmpRepoCwd,
3021
+ target: {
2580
3022
  type: opts.target.type,
2581
3023
  name: opts.target.name,
2582
3024
  dir: opts.target.dir
@@ -2617,16 +3059,17 @@ var CommitApplierService = class {
2617
3059
  commit2,
2618
3060
  exclusion,
2619
3061
  projectIgnoreMatcher,
2620
- opts.target
3062
+ opts.target,
3063
+ subtreePath
2621
3064
  );
2622
3065
  const remainingConflicts = await git.getUnmergedFiles(opts.tmpRepoCwd);
2623
3066
  if (remainingConflicts.length) {
2624
- this.logger.error("apply.commit.conflicts", {
3067
+ this.logger.debug("apply.commit.conflicts", {
2625
3068
  commit: commit2.slice(0, 7),
2626
3069
  files: remainingConflicts
2627
3070
  });
2628
3071
  await this.waitUntilUserResolvesConflicts(opts.tmpRepoCwd, commit2);
2629
- await this.filterGovernedKeysFromResolvedBloxFiles(
3072
+ await this.enforceGovernedKeysOnResolvedBloxFiles(
2630
3073
  remainingConflicts.filter(isBloxConfigFile),
2631
3074
  opts.tmpRepoCwd
2632
3075
  );
@@ -2650,21 +3093,7 @@ Resolve manually in the temp repo:
2650
3093
  ${e instanceof Error ? e.message : String(e)}`);
2651
3094
  }
2652
3095
  }
2653
- async filterGovernedKeysFromResolvedBloxFiles(files, tmpRepoCwd) {
2654
- for (const file of files) {
2655
- const stagedJson = await git.readJsonFromIndex(file, tmpRepoCwd);
2656
- if (stagedJson === null) {
2657
- throw new Error(`Unable to read resolved .blox file from git index: ${file}`);
2658
- }
2659
- const withoutGovernedKeys = omitKeys(stagedJson, bloxConfigControlledKeys);
2660
- await import_fs_extra14.default.outputFile(
2661
- import_node_path18.default.join(tmpRepoCwd, file),
2662
- JSON.stringify(withoutGovernedKeys, null, 2)
2663
- );
2664
- await git.add(file, tmpRepoCwd);
2665
- }
2666
- }
2667
- async revertExcludedStagedFiles(tmpRepoCwd, commit2, exclusion, projectIgnoreMatcher, target) {
3096
+ async revertExcludedStagedFiles(tmpRepoCwd, commit2, exclusion, projectIgnoreMatcher, target, subtreePath) {
2668
3097
  const changedFromHeadFiles = await git.getChangedFilesFromHead(tmpRepoCwd);
2669
3098
  const unmergedFiles = await git.getUnmergedFiles(tmpRepoCwd);
2670
3099
  const allTouchedFiles = [.../* @__PURE__ */ new Set([...changedFromHeadFiles, ...unmergedFiles])];
@@ -2683,18 +3112,19 @@ ${e instanceof Error ? e.message : String(e)}`);
2683
3112
  continue;
2684
3113
  }
2685
3114
  if (isBloxFile) {
2686
- await this.applyBloxConfigFileRevertPolicy(
3115
+ await this.applyBloxConfigFilePolicy(
2687
3116
  file,
2688
3117
  tmpRepoCwd,
2689
3118
  commit2,
2690
3119
  unmergedFiles,
2691
- target
3120
+ target,
3121
+ subtreePath
2692
3122
  );
2693
3123
  continue;
2694
3124
  }
2695
3125
  }
2696
3126
  }
2697
- async applyBloxConfigFileRevertPolicy(file, tmpRepoCwd, commit2, unmergedFiles, target) {
3127
+ async applyBloxConfigFilePolicy(file, tmpRepoCwd, commit2, unmergedFiles, target, subtreePath) {
2698
3128
  if (target.type === "base" /* BASE */) {
2699
3129
  this.logger.warn(
2700
3130
  "[.blox] revert policy: You cannot contribute the .blox file of a base from a template."
@@ -2703,64 +3133,174 @@ ${e instanceof Error ? e.message : String(e)}`);
2703
3133
  return;
2704
3134
  }
2705
3135
  if (unmergedFiles.includes(file)) {
3136
+ const resolved = await this.tryResolveBloxConflictSemantically(file, tmpRepoCwd);
3137
+ if (!resolved) {
3138
+ this.logger.debug("apply.commit.blox_merge_manual", {
3139
+ commit: commit2.slice(0, 7),
3140
+ file
3141
+ });
3142
+ }
2706
3143
  return;
2707
3144
  }
2708
- const headJson = await git.readJsonFromCommit("HEAD", file, tmpRepoCwd);
2709
- const headObj = headJson !== null && typeof headJson === "object" && !Array.isArray(headJson) ? headJson : null;
2710
- const headDefinesAllGovernedKeys = bloxConfigControlledKeys.every(
2711
- (key) => headObj !== null && Object.prototype.hasOwnProperty.call(headObj, key)
2712
- );
2713
- if (headDefinesAllGovernedKeys) {
2714
- return;
3145
+ await this.enforceGovernedKeysOnStagedBloxFile(file, tmpRepoCwd, commit2, subtreePath);
3146
+ }
3147
+ /**
3148
+ * Resolves a Git-conflicted `.blox` file by merging the three conflict
3149
+ * stages semantically instead of relying on Git's line-based merge.
3150
+ * Returns true when the file was merged and staged automatically.
3151
+ */
3152
+ async tryResolveBloxConflictSemantically(file, tmpRepoCwd) {
3153
+ const [base, ours, theirs] = await Promise.all([
3154
+ git.readFileFromIndex(file, 1, tmpRepoCwd),
3155
+ git.readFileFromIndex(file, 2, tmpRepoCwd),
3156
+ git.readFileFromIndex(file, 3, tmpRepoCwd)
3157
+ ]);
3158
+ return this.semanticMergeBloxVersions(file, tmpRepoCwd, { base, ours, theirs });
3159
+ }
3160
+ /**
3161
+ * Rebuilds a `.blox` merge result from the commits involved in the
3162
+ * cherry-pick (base = FETCH_HEAD^, ours = HEAD, theirs = FETCH_HEAD).
3163
+ * Used as a fallback when Git produced a staged `.blox` that is not valid
3164
+ * JSON. Paths in the app repo live under the subtree prefix.
3165
+ */
3166
+ async mergeBloxFileFromCommits(file, tmpRepoCwd, subtreePath) {
3167
+ const appRepoPath = subtreePath ? `${subtreePath}/${file}` : file;
3168
+ const [base, ours, theirs] = await Promise.all([
3169
+ git.readFileFromCommit("FETCH_HEAD^", appRepoPath, tmpRepoCwd),
3170
+ git.readFileFromCommit("HEAD", file, tmpRepoCwd),
3171
+ git.readFileFromCommit("FETCH_HEAD", appRepoPath, tmpRepoCwd)
3172
+ ]);
3173
+ return this.semanticMergeBloxVersions(file, tmpRepoCwd, { base, ours, theirs });
3174
+ }
3175
+ async semanticMergeBloxVersions(file, tmpRepoCwd, versions) {
3176
+ const { base, ours, theirs } = versions;
3177
+ if (ours === null || theirs === null) {
3178
+ this.logger.debug("apply.commit.blox_merge_skipped", {
3179
+ file,
3180
+ reason: "deleted-on-one-side"
3181
+ });
3182
+ return false;
2715
3183
  }
2716
- const stagedJson = await git.readJsonFromIndex(file, tmpRepoCwd);
2717
- if (stagedJson === null) {
2718
- this.logger.debug("apply.commit.blox_merge_fallback", { file });
2719
- await git.revertPathToHead(file, tmpRepoCwd);
2720
- return;
3184
+ const baseJson = base === null ? {} : parseJsonObject(base);
3185
+ const oursJson = parseJsonObject(ours);
3186
+ const theirsJson = parseJsonObject(theirs);
3187
+ if (baseJson === void 0 || oursJson === void 0 || theirsJson === void 0) {
3188
+ this.logger.debug("apply.commit.blox_merge_skipped", {
3189
+ file,
3190
+ reason: "unparseable-version"
3191
+ });
3192
+ return false;
2721
3193
  }
2722
- const withoutGovernedKeys = omitKeys(stagedJson, bloxConfigControlledKeys);
2723
- try {
2724
- const outPath = import_node_path18.default.join(tmpRepoCwd, file);
2725
- await import_fs_extra14.default.outputFile(outPath, JSON.stringify(withoutGovernedKeys, null, 2));
2726
- await git.add(file, tmpRepoCwd);
2727
- } catch (e) {
2728
- this.logger.warn("apply.commit.blox_merge_fallback", {
2729
- commit: commit2.slice(0, 7),
3194
+ const merge3 = mergeBloxConfigJson(baseJson, oursJson, theirsJson, bloxConfigControlledKeys);
3195
+ if (!merge3.resolved) {
3196
+ this.logger.debug("apply.commit.blox_merge_conflicts", {
2730
3197
  file,
2731
- reason: "write-failed",
2732
- message: e instanceof Error ? e.message : String(e)
3198
+ conflicts: merge3.conflicts
3199
+ });
3200
+ return false;
3201
+ }
3202
+ this.logger.debug("apply.commit.blox_merge_resolved", { file });
3203
+ await import_fs_extra15.default.outputFile(import_node_path19.default.join(tmpRepoCwd, file), JSON.stringify(merge3.value, null, 2));
3204
+ await git.add(file, tmpRepoCwd);
3205
+ return true;
3206
+ }
3207
+ /**
3208
+ * Applies the governed-key policy to a `.blox` file that Git staged without
3209
+ * conflicts: governed keys are restored to the target's HEAD values so they
3210
+ * are never contributed, while incoming user-maintained changes are kept.
3211
+ */
3212
+ async enforceGovernedKeysOnStagedBloxFile(file, tmpRepoCwd, commit2, subtreePath) {
3213
+ const stagedRaw = await git.readFileFromIndex(file, 0, tmpRepoCwd);
3214
+ if (stagedRaw === null) {
3215
+ this.logger.debug("apply.commit.blox_deletion_reverted", {
3216
+ commit: commit2.slice(0, 7),
3217
+ file
2733
3218
  });
2734
3219
  await git.revertPathToHead(file, tmpRepoCwd);
3220
+ return;
3221
+ }
3222
+ const stagedJson = parseJsonObject(stagedRaw);
3223
+ if (stagedJson === void 0) {
3224
+ const merged = await this.mergeBloxFileFromCommits(file, tmpRepoCwd, subtreePath);
3225
+ if (!merged) {
3226
+ this.logger.warn("apply.commit.blox_merge_fallback", {
3227
+ commit: commit2.slice(0, 7),
3228
+ file,
3229
+ reason: "unparseable-merge-result"
3230
+ });
3231
+ await git.revertPathToHead(file, tmpRepoCwd);
3232
+ }
3233
+ return;
3234
+ }
3235
+ await this.writeGovernedEnforcedBloxFile(file, tmpRepoCwd, stagedJson);
3236
+ }
3237
+ /**
3238
+ * Validates `.blox` files the user resolved manually and re-applies the
3239
+ * governed-key policy on the staged resolution.
3240
+ */
3241
+ async enforceGovernedKeysOnResolvedBloxFiles(files, tmpRepoCwd) {
3242
+ for (const file of files) {
3243
+ const stagedRaw = await git.readFileFromIndex(file, 0, tmpRepoCwd);
3244
+ if (stagedRaw === null) {
3245
+ throw new Error(
3246
+ `Unable to read resolved .blox file "${file}" from the git index. Make sure the file exists and stage it with "git add ${file}".`
3247
+ );
3248
+ }
3249
+ if (hasGitConflictMarkers(stagedRaw)) {
3250
+ throw new Error(
3251
+ `Resolved .blox file "${file}" still contains Git conflict markers. Remove all <<<<<<<, =======, and >>>>>>> markers and stage the file again.`
3252
+ );
3253
+ }
3254
+ const stagedJson = parseJsonObject(stagedRaw);
3255
+ if (stagedJson === void 0) {
3256
+ throw new Error(
3257
+ `Resolved .blox file "${file}" is not a valid JSON object. Fix the file contents and stage it again.`
3258
+ );
3259
+ }
3260
+ await this.writeGovernedEnforcedBloxFile(file, tmpRepoCwd, stagedJson);
3261
+ }
3262
+ }
3263
+ async writeGovernedEnforcedBloxFile(file, tmpRepoCwd, stagedJson) {
3264
+ const headJson = await git.readJsonFromCommit("HEAD", file, tmpRepoCwd);
3265
+ const enforced = withGovernedKeysFrom(stagedJson, headJson, bloxConfigControlledKeys);
3266
+ if ((0, import_isEqual2.default)(enforced, stagedJson)) {
3267
+ return;
2735
3268
  }
3269
+ this.logger.debug("apply.commit.blox_governed_keys_restored", { file });
3270
+ await import_fs_extra15.default.outputFile(import_node_path19.default.join(tmpRepoCwd, file), JSON.stringify(enforced, null, 2));
3271
+ await git.add(file, tmpRepoCwd);
2736
3272
  }
2737
3273
  async waitUntilUserResolvesConflicts(tmpRepoCwd, commit2) {
2738
3274
  let remainingConflicts = await git.getUnmergedFiles(tmpRepoCwd);
3275
+ if (!remainingConflicts.length) {
3276
+ return;
3277
+ }
3278
+ const ides = await detectAvailableIdes();
3279
+ let stillRemaining = false;
2739
3280
  while (remainingConflicts.length) {
2740
- console.log(`
2741
- ${fmt.red(fmt.bold("!! CONFLICTS DETECTED !!"))}`);
2742
- console.log(
2743
- fmt.yellow(`Commit ${commit2.slice(0, 7)} has conflicts in the following files:`)
2744
- );
2745
- remainingConflicts.forEach((f) => console.log(fmt.red(` - ${f}`)));
2746
- console.log(`
2747
- ${fmt.cyan("Instructions:")}`);
2748
- console.log(fmt.white(" 1. Open a new terminal and go to:"));
2749
- console.log(fmt.green(` cd "${tmpRepoCwd}"`));
2750
- console.log(fmt.white(" 2. Resolve the conflicts manually."));
2751
- console.log(fmt.white(" 3. Stage your changes with: ") + fmt.green("git add ."));
2752
- console.log("\n");
3281
+ showConflictSummary(commit2, remainingConflicts, stillRemaining);
3282
+ if (ides.length) {
3283
+ const ide = await selectIdeForConflictResolution(ides, tmpRepoCwd);
3284
+ if (ide) {
3285
+ try {
3286
+ await openPathInIde(ide, tmpRepoCwd);
3287
+ this.logger.info(
3288
+ `Opened the temporary contribution project in ${ide.name}.`
3289
+ );
3290
+ } catch (e) {
3291
+ this.logger.warn(
3292
+ `Failed to open ${ide.name}: ${e instanceof Error ? e.message : String(e)}
3293
+ Resolve the conflicts manually using the instructions below.`
3294
+ );
3295
+ }
3296
+ }
3297
+ }
3298
+ showManualInstructionsBox(tmpRepoCwd);
2753
3299
  await text({
2754
3300
  message: "Press Enter once you have resolved and staged all changes to continue..."
2755
3301
  });
2756
3302
  remainingConflicts = await git.getUnmergedFiles(tmpRepoCwd);
2757
- if (remainingConflicts.length) {
2758
- console.log(
2759
- `
2760
- ${fmt.red("Still detected conflicts in: " + remainingConflicts.join(", "))}`
2761
- );
2762
- console.log(fmt.yellow("Please make sure to 'git add' your resolved files."));
2763
- }
3303
+ stillRemaining = true;
2764
3304
  }
2765
3305
  }
2766
3306
  async commitStagedIfAny(opts, commit2) {
@@ -2771,7 +3311,18 @@ ${fmt.red("Still detected conflicts in: " + remainingConflicts.join(", "))}`
2771
3311
 
2772
3312
  ${opts.description}`;
2773
3313
  }
2774
- await git.commitAll(commitMsg, opts.tmpRepoCwd);
3314
+ try {
3315
+ await git.commit(commitMsg, opts.tmpRepoCwd);
3316
+ } catch (e) {
3317
+ if (await git.hasStagedChanges(opts.tmpRepoCwd)) {
3318
+ throw e;
3319
+ }
3320
+ this.logger.debug("apply.commit.skip_empty", {
3321
+ commit: commit2.slice(0, 7),
3322
+ message: "No changes left for this target after filtering."
3323
+ });
3324
+ return false;
3325
+ }
2775
3326
  this.logger.debug("apply.commit.success", { commit: commit2.slice(0, 7) });
2776
3327
  return true;
2777
3328
  }
@@ -2856,118 +3407,6 @@ var CommitSelectorService = class {
2856
3407
  }
2857
3408
  };
2858
3409
 
2859
- // src/shared/prompts/selectWithSearch.ts
2860
- var import_core = require("@clack/core");
2861
- var import_prompts15 = require("@clack/prompts");
2862
- var SEARCH_REQUESTED = Symbol("search-requested");
2863
- function isSelectedOption(option2, selectedValues) {
2864
- return selectedValues.includes(option2.value);
2865
- }
2866
- function selectedOptionLabels(options, selectedValues) {
2867
- return options.filter((option2) => isSelectedOption(option2, selectedValues)).map((option2) => option2.label);
2868
- }
2869
- function stateSymbol(state) {
2870
- switch (state) {
2871
- case "cancel":
2872
- return fmt.red("\u25A0");
2873
- case "error":
2874
- return fmt.yellow("\u25B2");
2875
- case "submit":
2876
- return fmt.green("\u25C7");
2877
- default:
2878
- return fmt.cyan("\u25C6");
2879
- }
2880
- }
2881
- function exitIfRealCancel(result) {
2882
- if ((0, import_prompts15.isCancel)(result)) {
2883
- (0, import_prompts15.cancel)("Canceled");
2884
- process.exit(0);
2885
- }
2886
- }
2887
- function watchForSearchKey(prompt) {
2888
- let searchRequested = false;
2889
- prompt.on("key", (char) => {
2890
- if (char.toLowerCase() === "s") {
2891
- searchRequested = true;
2892
- prompt.state = "cancel";
2893
- prompt.close();
2894
- }
2895
- });
2896
- return () => searchRequested;
2897
- }
2898
- async function multiselectWithSearch(opts) {
2899
- const required = opts.required ?? false;
2900
- const optLabel = (option2, state) => {
2901
- switch (state) {
2902
- case "active":
2903
- return `${fmt.cyan("\u25FB")} ${option2.label}${option2.hint ? ` ${fmt.dim(`(${option2.hint})`)}` : ""}`;
2904
- case "selected":
2905
- return `${fmt.green("\u25FC")} ${fmt.dim(option2.label)}`;
2906
- case "active-selected":
2907
- return `${fmt.green("\u25FC")} ${option2.label}${option2.hint ? ` ${fmt.dim(`(${option2.hint})`)}` : ""}`;
2908
- default:
2909
- return `${fmt.dim("\u25FB")} ${fmt.dim(option2.label)}`;
2910
- }
2911
- };
2912
- const prompt = new import_core.MultiSelectPrompt({
2913
- options: opts.options,
2914
- initialValues: opts.initialValues,
2915
- required,
2916
- validate(selected) {
2917
- if (required && (!selected || selected.length === 0)) {
2918
- return `Please select at least one option.
2919
- ${fmt.dim(
2920
- `Press ${fmt.gray("space")} to select, ${fmt.gray("enter")} to continue`
2921
- )}`;
2922
- }
2923
- return void 0;
2924
- },
2925
- render() {
2926
- const title = `${fmt.gray("\u2502")}
2927
- ${stateSymbol(this.state)} ${opts.message}
2928
- `;
2929
- const value = this.value ?? [];
2930
- const styleOption = (option2, active) => {
2931
- const selected = isSelectedOption(option2, value);
2932
- if (active && selected) return optLabel(option2, "active-selected");
2933
- if (selected) return optLabel(option2, "selected");
2934
- return optLabel(option2, active ? "active" : "inactive");
2935
- };
2936
- switch (this.state) {
2937
- case "submit":
2938
- return `${title}${fmt.gray("\u2502")} ${selectedOptionLabels(this.options, value).map((label) => fmt.dim(label)).join(fmt.dim(", ")) || fmt.dim("none")}`;
2939
- case "cancel": {
2940
- const selectedLabels = selectedOptionLabels(this.options, value).map((label) => fmt.strikethrough(fmt.dim(label))).join(fmt.dim(", "));
2941
- return `${title}${fmt.gray("\u2502")}${selectedLabels.trim() ? ` ${selectedLabels}
2942
- ${fmt.gray("\u2502")}` : ""}`;
2943
- }
2944
- case "error": {
2945
- const lines = this.options.map((o, i) => styleOption(o, i === this.cursor));
2946
- return `${title}${fmt.yellow("\u2502")} ${lines.join(`
2947
- ${fmt.yellow("\u2502")} `)}
2948
- ${fmt.yellow("\u2514")} ${fmt.yellow(this.error)}
2949
- `;
2950
- }
2951
- default: {
2952
- const lines = this.options.map((o, i) => styleOption(o, i === this.cursor));
2953
- return `${title}${fmt.cyan("\u2502")} ${lines.join(`
2954
- ${fmt.cyan("\u2502")} `)}
2955
- ${fmt.cyan("\u2514")} ${fmt.dim(
2956
- `Press ${fmt.gray("space")} to select, ${fmt.gray("enter")} to continue`
2957
- )}`;
2958
- }
2959
- }
2960
- }
2961
- });
2962
- const searchRequested = watchForSearchKey(prompt);
2963
- const result = await prompt.prompt();
2964
- if (searchRequested()) {
2965
- return SEARCH_REQUESTED;
2966
- }
2967
- exitIfRealCancel(result);
2968
- return result;
2969
- }
2970
-
2971
3410
  // src/services/contribute/services/ContributionTargetSelector.ts
2972
3411
  var MULTI_NAV_PREV = "__prev__";
2973
3412
  var MULTI_NAV_NEXT = "__next__";
@@ -3242,8 +3681,8 @@ var PullRequestService = class {
3242
3681
  Math.max(...plainLines.map((l) => l.length), titleText.length),
3243
3682
  terminalWidth - 6
3244
3683
  );
3245
- const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
3246
- const padVisible = (s) => s + " ".repeat(Math.max(innerWidth - stripAnsi(s).length, 0));
3684
+ const stripAnsi2 = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
3685
+ const padVisible = (s) => s + " ".repeat(Math.max(innerWidth - stripAnsi2(s).length, 0));
3247
3686
  const topBorder = `\u250C\u2500${fmt.bold(titleText)}${"\u2500".repeat(Math.max(innerWidth - titleText.length + 2, 0))}\u2500\u2510`;
3248
3687
  const bottomBorder = `\u2514${"\u2500".repeat(innerWidth + 4)}\u2518`;
3249
3688
  const emptyLine = `\u2502${" ".repeat(innerWidth + 4)}\u2502`;
@@ -3297,8 +3736,8 @@ var PullRequestService = class {
3297
3736
 
3298
3737
  // src/services/contribute/services/TmpRepoService.ts
3299
3738
  var import_node_os3 = require("os");
3300
- var import_node_path19 = __toESM(require("path"));
3301
- var import_fs_extra15 = __toESM(require("fs-extra"));
3739
+ var import_node_path20 = __toESM(require("path"));
3740
+ var import_fs_extra16 = __toESM(require("fs-extra"));
3302
3741
  var TmpRepoService = class {
3303
3742
  constructor(logger) {
3304
3743
  this.logger = logger;
@@ -3317,7 +3756,7 @@ var TmpRepoService = class {
3317
3756
  const isBlock = target.type === "block" /* BLOCK */;
3318
3757
  const slugParts = isBlock && target.templateName ? [target.type, target.templateName, target.name] : [target.type, target.name];
3319
3758
  const slug = slugParts.join("-").replace(/[^a-zA-Z0-9._-]+/g, "-");
3320
- return import_node_path19.default.join((0, import_node_os3.homedir)(), bloxFilePath, tempRepoName, slug);
3759
+ return import_node_path20.default.join((0, import_node_os3.homedir)(), bloxFilePath, tempRepoName, slug);
3321
3760
  }
3322
3761
  async prepare(opts) {
3323
3762
  const taskSpinner = spinner();
@@ -3329,7 +3768,7 @@ var TmpRepoService = class {
3329
3768
  repoUrl: opts.repoUrl,
3330
3769
  branch: opts.branch
3331
3770
  });
3332
- if (await import_fs_extra15.default.pathExists(dir)) {
3771
+ if (await import_fs_extra16.default.pathExists(dir)) {
3333
3772
  this.logger.debug(`${tempRepoName} reuse_tmp_local_repo`, { dir });
3334
3773
  try {
3335
3774
  await this.refreshExistingTmpRepo(dir, opts.branch);
@@ -3340,10 +3779,10 @@ var TmpRepoService = class {
3340
3779
  dir,
3341
3780
  message: e instanceof Error ? e.message : String(e)
3342
3781
  });
3343
- await import_fs_extra15.default.remove(dir);
3782
+ await import_fs_extra16.default.remove(dir);
3344
3783
  }
3345
3784
  }
3346
- await import_fs_extra15.default.ensureDir(import_node_path19.default.dirname(dir));
3785
+ await import_fs_extra16.default.ensureDir(import_node_path20.default.dirname(dir));
3347
3786
  await git.clone(opts.repoUrl, dir, opts.branch);
3348
3787
  taskSpinner.stop("Prepared tmp repo");
3349
3788
  return dir;
@@ -3431,26 +3870,1471 @@ var detach = command("detach").description("Migrate blox schema").option("--basi
3431
3870
  }
3432
3871
  });
3433
3872
 
3434
- // src/commands/init/index.ts
3435
- var import_fs_extra16 = __toESM(require("fs-extra"));
3436
- var init2 = command("init").description("Init new app").alias("i").option("-n, --name <name>", "App name").option("-t, --template <template>", "Template to use").option("--branch <name>", "branch name").action(async ({ name, template, branch }) => {
3437
- await syncRegistries();
3873
+ // src/commands/doctor/checks/schema-validation/fix.ts
3874
+ var import_node_path21 = __toESM(require("path"));
3875
+ var import_fs_extra17 = __toESM(require("fs-extra"));
3876
+ async function fixMetadataSchema(context, diagnostic) {
3877
+ if (!diagnostic.filePath) {
3878
+ return { status: "skipped", message: "Diagnostic has no associated file." };
3879
+ }
3438
3880
  try {
3439
- if (!name) {
3440
- name = await text({ message: "Select app name" });
3881
+ switch (diagnostic.id) {
3882
+ case "outdated-schema":
3883
+ return await migrateBloxFile(context, diagnostic.filePath);
3884
+ case "stale-schema-url": {
3885
+ const changed = await updateSchemaUrls(context.projectRoot);
3886
+ return changed ? { status: "fixed", message: `Updated $schema URL in ${diagnostic.filePath}` } : { status: "skipped", message: "No applicable automatic repair." };
3887
+ }
3888
+ default:
3889
+ return { status: "skipped", message: "No applicable automatic repair." };
3441
3890
  }
3442
- const templates = await getAvailableTemplates();
3443
- if (!template) {
3444
- template = await select({
3445
- message: "Select template to be used",
3446
- options: Object.entries(templates).map(([tmpl, { description }]) => ({
3447
- value: tmpl,
3448
- label: tmpl,
3449
- hint: description
3450
- }))
3891
+ } catch (e) {
3892
+ return { status: "failed", message: e instanceof Error ? e.message : String(e) };
3893
+ }
3894
+ }
3895
+ async function migrateBloxFile(context, filePath) {
3896
+ const dir = import_node_path21.default.dirname(import_node_path21.default.join(context.projectRoot, filePath));
3897
+ const name = filePath === bloxFilePath ? "app" : import_node_path21.default.basename(dir);
3898
+ const current = await import_fs_extra17.default.readJson(import_node_path21.default.join(dir, bloxFilePath));
3899
+ const schemaVersion = typeof current?.schemaVersion === "number" ? current.schemaVersion : 0;
3900
+ if (schemaVersion >= migrationsList.length) {
3901
+ return {
3902
+ status: "skipped",
3903
+ message: "Schema version no longer requires migration."
3904
+ };
3905
+ }
3906
+ const { filesChanged } = await migrateOnLocal(name, dir);
3907
+ const urlsChanged = await updateSchemaUrls(context.projectRoot);
3908
+ if (!filesChanged && !urlsChanged) {
3909
+ return { status: "skipped", message: "Migration produced no changes." };
3910
+ }
3911
+ return { status: "fixed", message: `Migrated ${filePath} to schema v${migrationsList.length}` };
3912
+ }
3913
+
3914
+ // src/commands/doctor/checks/utils/discoverBloxFiles.ts
3915
+ var import_node_path22 = __toESM(require("path"));
3916
+ var import_fs_extra18 = __toESM(require("fs-extra"));
3917
+ function discoverBloxFiles(projectRoot) {
3918
+ const targets = [];
3919
+ const rootPath = import_node_path22.default.join(projectRoot, bloxFilePath);
3920
+ if (import_fs_extra18.default.existsSync(rootPath)) {
3921
+ targets.push({ filePath: bloxFilePath, absPath: rootPath, kind: "template", name: "app" });
3922
+ }
3923
+ const blocksPath = import_node_path22.default.join(projectRoot, blocksDir);
3924
+ if (import_fs_extra18.default.existsSync(blocksPath)) {
3925
+ for (const entry of import_fs_extra18.default.readdirSync(blocksPath, { withFileTypes: true })) {
3926
+ if (!entry.isDirectory()) continue;
3927
+ const absPath = import_node_path22.default.join(blocksPath, entry.name, bloxFilePath);
3928
+ if (!import_fs_extra18.default.existsSync(absPath)) continue;
3929
+ targets.push({
3930
+ filePath: normalizePath(import_node_path22.default.join(blocksDir, entry.name, bloxFilePath)),
3931
+ absPath,
3932
+ kind: "block",
3933
+ name: entry.name
3451
3934
  });
3452
3935
  }
3453
- if (!templates[template]) {
3936
+ }
3937
+ return targets;
3938
+ }
3939
+
3940
+ // src/commands/doctor/checks/utils/createDiagnostic.ts
3941
+ function createDiagnostic(fields) {
3942
+ return {
3943
+ checkId: fields.checkId,
3944
+ id: fields.id,
3945
+ classification: fields.classification ?? "invalid",
3946
+ title: fields.title,
3947
+ message: fields.message,
3948
+ filePath: fields.filePath,
3949
+ fixAvailable: fields.fixAvailable ?? false
3950
+ };
3951
+ }
3952
+
3953
+ // src/commands/doctor/checks/schema-validation/validate.ts
3954
+ var import_fs_extra19 = __toESM(require("fs-extra"));
3955
+
3956
+ // src/commands/doctor/checks/schema-validation/utils/validateSchemaVersion.ts
3957
+ function extractSchemaVersion(raw) {
3958
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
3959
+ return null;
3960
+ }
3961
+ const obj = raw;
3962
+ const version2 = obj["schemaVersion"];
3963
+ if (version2 === void 0) {
3964
+ return 0;
3965
+ }
3966
+ if (typeof version2 !== "number" || !Number.isFinite(version2) || version2 < 0) {
3967
+ return null;
3968
+ }
3969
+ return version2;
3970
+ }
3971
+ function evaluateSchemaVersion(version2) {
3972
+ if (version2 === null) {
3973
+ return {
3974
+ version: null,
3975
+ isCurrent: false,
3976
+ isOutdatedWithMigration: false,
3977
+ isTooNew: false,
3978
+ message: "schemaVersion must be a non-negative integer."
3979
+ };
3980
+ }
3981
+ if (version2 === CURRENT_SCHEMA_VERSION) {
3982
+ return {
3983
+ version: version2,
3984
+ isCurrent: true,
3985
+ isOutdatedWithMigration: false,
3986
+ isTooNew: false,
3987
+ message: "Schema version is current."
3988
+ };
3989
+ }
3990
+ if (version2 > CURRENT_SCHEMA_VERSION) {
3991
+ return {
3992
+ version: version2,
3993
+ isCurrent: false,
3994
+ isOutdatedWithMigration: false,
3995
+ isTooNew: true,
3996
+ message: `File declares schema v${version2}, but this CLI supports up to v${CURRENT_SCHEMA_VERSION}. Update BLOX CLI.`
3997
+ };
3998
+ }
3999
+ const applicableMigrations = getApplicableMigrations(version2);
4000
+ const hasMigrationPath = applicableMigrations.length > 0;
4001
+ return {
4002
+ version: version2,
4003
+ isCurrent: false,
4004
+ isOutdatedWithMigration: hasMigrationPath,
4005
+ isTooNew: false,
4006
+ message: `File uses schema v${version2}; current is v${CURRENT_SCHEMA_VERSION}.${hasMigrationPath ? " A migration is available." : " No migration path available."}`
4007
+ };
4008
+ }
4009
+
4010
+ // src/commands/doctor/checks/schema-validation/utils/reportSchemaVersionCompatibility.ts
4011
+ function reportSchemaVersionCompatibility(base, evaluation, diagnostics) {
4012
+ if (evaluation.version === null) {
4013
+ diagnostics.push(
4014
+ createDiagnostic({
4015
+ ...base,
4016
+ id: "missing-schema-version",
4017
+ title: ".blox has an invalid schemaVersion",
4018
+ message: evaluation.message
4019
+ })
4020
+ );
4021
+ } else if (evaluation.isTooNew) {
4022
+ diagnostics.push(
4023
+ createDiagnostic({
4024
+ ...base,
4025
+ id: "schema-too-new",
4026
+ title: ".blox uses a newer schema than this CLI supports",
4027
+ message: evaluation.message
4028
+ })
4029
+ );
4030
+ } else if (!evaluation.isCurrent) {
4031
+ diagnostics.push(
4032
+ createDiagnostic({
4033
+ ...base,
4034
+ id: "outdated-schema",
4035
+ classification: "outdated",
4036
+ title: ".blox schema is outdated",
4037
+ message: evaluation.message,
4038
+ fixAvailable: evaluation.isOutdatedWithMigration
4039
+ })
4040
+ );
4041
+ }
4042
+ }
4043
+
4044
+ // src/models/template.ts
4045
+ var import_zod = require("zod");
4046
+ var DependencyVersionSchema = import_zod.z.union([import_zod.z.number(), import_zod.z.tuple([import_zod.z.number(), import_zod.z.number()])]).describe(
4047
+ "Version selector for a dependency. Use a single number for an exact version, or [minVersion, maxVersion] for an inclusive range."
4048
+ );
4049
+ var LifecycleHooksSchema = import_zod.z.strictObject({
4050
+ init: import_zod.z.string().describe(
4051
+ "Shell command executed after files are rendered during init or add operations."
4052
+ ).optional(),
4053
+ add: import_zod.z.string().describe("Shell command executed when this block or template is added to a project.").optional(),
4054
+ update: import_zod.z.string().describe(
4055
+ "Shell command executed after this block or template is updated to a newer checkpoint."
4056
+ ).optional(),
4057
+ remove: import_zod.z.string().describe(
4058
+ "Shell command executed when this block or template is removed from a project."
4059
+ ).optional()
4060
+ }).describe("Lifecycle hook commands that can be run by the CLI at specific workflow stages.");
4061
+ var TemplateDefSchema = LifecycleHooksSchema.extend({
4062
+ name: import_zod.z.string().describe("Stable template identifier used in registry entries and checkpoint keys."),
4063
+ version: import_zod.z.number().describe("Optional major version number for this template definition.").optional(),
4064
+ ignore: import_zod.z.array(import_zod.z.string()).describe("Glob patterns excluded from template file init and update operations.").optional(),
4065
+ bases: import_zod.z.array(
4066
+ import_zod.z.strictObject({
4067
+ name: import_zod.z.string().describe("Name of a base template that this template extends."),
4068
+ version: DependencyVersionSchema.optional()
4069
+ }).describe("Reference to a single base template and optional version selector.")
4070
+ ).describe(
4071
+ "Optional list of base templates that this template extends. Each entry can point to a specific version or a version range."
4072
+ ).optional()
4073
+ }).describe("Template definition used in .blox files and resolved by template-based workflows.");
4074
+ var BlockDefSchema = TemplateDefSchema.extend({
4075
+ templates: import_zod.z.array(
4076
+ import_zod.z.strictObject({
4077
+ name: import_zod.z.string().describe("Template dependency name required by this block."),
4078
+ version: DependencyVersionSchema.optional()
4079
+ }).describe("Reference to one template dependency and optional version selector.")
4080
+ ).describe(
4081
+ "Template dependencies required before this block can be safely added or updated."
4082
+ ).optional(),
4083
+ dependencies: import_zod.z.array(
4084
+ import_zod.z.strictObject({
4085
+ name: import_zod.z.string().describe("Block dependency name required by this block."),
4086
+ version: DependencyVersionSchema.optional()
4087
+ }).describe("Reference to one block dependency and optional version selector.")
4088
+ ).describe("Block dependencies that should exist for this block to function correctly.").optional()
4089
+ }).describe(
4090
+ "Block definition that extends template fields with template and block dependency lists."
4091
+ );
4092
+ var TemplateCheckpointSchema = import_zod.z.strictObject({
4093
+ commit: import_zod.z.string().describe(
4094
+ "Git commit hash representing the exact checkpoint snapshot for this dependency."
4095
+ ),
4096
+ version: import_zod.z.number().describe("Optional numeric version label associated with this checkpoint.").optional(),
4097
+ branch: import_zod.z.string().describe(
4098
+ "Optional source branch name used when resolving or updating this checkpoint."
4099
+ ).optional()
4100
+ }).describe("Checkpoint metadata describing where a template or block dependency is pinned.");
4101
+ var TemplateCheckpointsSchema = import_zod.z.record(import_zod.z.string(), TemplateCheckpointSchema).describe("Dictionary of checkpoint entries keyed by dependency name.");
4102
+ var BloxFileSchema = import_zod.z.strictObject({
4103
+ $schema: import_zod.z.string().describe("Optional JSON Schema URI used by editors for validation and autocomplete.").optional(),
4104
+ schemaVersion: import_zod.z.number().describe("Optional internal schema revision of the .blox document format.").optional(),
4105
+ // BlockDefSchema is a superset of TemplateDefSchema (templates/dependencies are
4106
+ // optional), so trying BlockDef first means both plain templates and blocks
4107
+ // are accepted without needing a discriminator field.
4108
+ definition: import_zod.z.union([BlockDefSchema, TemplateDefSchema]).describe("Primary definition payload for this .blox file (template or block)."),
4109
+ checkpoints: TemplateCheckpointsSchema.describe(
4110
+ "Resolved checkpoint map used to track dependency revisions across updates."
4111
+ ),
4112
+ project: import_zod.z.strictObject({
4113
+ ignore: import_zod.z.array(import_zod.z.string()).describe(
4114
+ "Project-level glob patterns excluded from migration and update operations."
4115
+ ).optional()
4116
+ }).describe("Optional project-scoped settings applied while running BLOX commands.").optional()
4117
+ }).describe(
4118
+ "Root .blox document containing schema metadata, a template or block definition, and checkpoint state."
4119
+ );
4120
+
4121
+ // src/commands/doctor/checks/schema-validation/utils/formatIssues.ts
4122
+ function formatIssues(issues) {
4123
+ const shown = issues.slice(0, 5).map((issue) => {
4124
+ const location = issue.path.map(String).join(".") || "(root)";
4125
+ return `${location}: ${issue.message}`;
4126
+ });
4127
+ const remaining = issues.length - shown.length;
4128
+ if (remaining > 0) {
4129
+ shown.push(`and ${remaining} more`);
4130
+ }
4131
+ return shown.join("\n");
4132
+ }
4133
+
4134
+ // src/commands/doctor/checks/schema-validation/utils/reportSchemaValidationFinding.ts
4135
+ function reportSchemaValidationFinding(base, raw, evaluation, diagnostics) {
4136
+ if (!evaluation.isCurrent) {
4137
+ return;
4138
+ }
4139
+ const parsed = BloxFileSchema.safeParse(raw);
4140
+ if (!parsed.success) {
4141
+ diagnostics.push(
4142
+ createDiagnostic({
4143
+ ...base,
4144
+ id: "schema-validation",
4145
+ title: ".blox failed schema validation",
4146
+ message: formatIssues(parsed.error.issues)
4147
+ })
4148
+ );
4149
+ }
4150
+ }
4151
+
4152
+ // src/commands/doctor/checks/schema-validation/validate.ts
4153
+ async function validateBloxFile(target) {
4154
+ const base = { checkId: "schema.validation", filePath: target.filePath };
4155
+ let raw;
4156
+ try {
4157
+ raw = await import_fs_extra19.default.readJson(target.absPath);
4158
+ } catch (e) {
4159
+ return [
4160
+ createDiagnostic({
4161
+ ...base,
4162
+ id: "invalid-json",
4163
+ title: ".blox is not valid JSON",
4164
+ message: e instanceof Error ? e.message : String(e)
4165
+ })
4166
+ ];
4167
+ }
4168
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
4169
+ return [
4170
+ createDiagnostic({
4171
+ ...base,
4172
+ id: "invalid-root-type",
4173
+ title: ".blox must be a JSON object",
4174
+ message: "Expected a JSON object at the root of .blox."
4175
+ })
4176
+ ];
4177
+ }
4178
+ const schemaVersion = extractSchemaVersion(raw);
4179
+ const evaluation = evaluateSchemaVersion(schemaVersion);
4180
+ const obj = raw;
4181
+ const diagnostics = [];
4182
+ reportSchemaVersionCompatibility(base, evaluation, diagnostics);
4183
+ reportSchemaValidationFinding(base, raw, evaluation, diagnostics);
4184
+ const expectedSchemaUrl = buildSchemaUrl(target.kind);
4185
+ if (obj["$schema"] !== expectedSchemaUrl) {
4186
+ diagnostics.push(
4187
+ createDiagnostic({
4188
+ ...base,
4189
+ id: "stale-schema-url",
4190
+ classification: "outdated",
4191
+ title: "$schema URL is outdated",
4192
+ message: `Expected ${expectedSchemaUrl}`,
4193
+ fixAvailable: true
4194
+ })
4195
+ );
4196
+ }
4197
+ return diagnostics;
4198
+ }
4199
+
4200
+ // src/commands/doctor/checks/schema-validation/index.ts
4201
+ var metadataSchemaCheck = {
4202
+ id: "schema.validation",
4203
+ name: ".blox Schema validation",
4204
+ description: "Validate .blox metadata against the current schema",
4205
+ async run(context) {
4206
+ const targets = discoverBloxFiles(context.projectRoot);
4207
+ if (targets.length === 0) {
4208
+ return [
4209
+ createDiagnostic({
4210
+ checkId: "schema.validation",
4211
+ id: "no-blox-files",
4212
+ classification: "informational",
4213
+ title: "No .blox files found",
4214
+ message: "This does not look like a BLOX project. Run `blox init` to create one."
4215
+ })
4216
+ ];
4217
+ }
4218
+ const diagnostics = [];
4219
+ for (const target of targets) {
4220
+ diagnostics.push(...await validateBloxFile(target));
4221
+ }
4222
+ return diagnostics;
4223
+ },
4224
+ fix: fixMetadataSchema
4225
+ };
4226
+
4227
+ // src/commands/doctor/checks/dependencies/utils/readBlocksMetadata.ts
4228
+ var import_fs_extra20 = __toESM(require("fs-extra"));
4229
+ var import_node_path23 = __toESM(require("path"));
4230
+ async function readBlockMetadata(target) {
4231
+ const raw = await import_fs_extra20.default.readJson(target.absPath);
4232
+ const definition = raw.definition;
4233
+ const dependencies = definition?.dependencies ?? [];
4234
+ const templates = definition?.templates ?? [];
4235
+ return {
4236
+ filePath: target.filePath,
4237
+ absPath: target.absPath,
4238
+ name: definition?.name ?? target.name,
4239
+ dirName: target.name,
4240
+ version: definition?.version,
4241
+ dependencies,
4242
+ templates,
4243
+ blockDir: import_node_path23.default.dirname(target.absPath)
4244
+ };
4245
+ }
4246
+ async function readBlocksMetadata(projectRoot) {
4247
+ const bloxTargets = discoverBloxFiles(projectRoot);
4248
+ const blockTargets = bloxTargets.filter((t) => t.kind === "block");
4249
+ const blocks = /* @__PURE__ */ new Map();
4250
+ for (const target of blockTargets) {
4251
+ const metadata = await readBlockMetadata(target);
4252
+ blocks.set(metadata.name, metadata);
4253
+ }
4254
+ return blocks;
4255
+ }
4256
+
4257
+ // src/commands/doctor/checks/dependencies/missing/utils/collectImports.ts
4258
+ var ts2 = __toESM(require("typescript"));
4259
+ var import_fs_extra22 = __toESM(require("fs-extra"));
4260
+
4261
+ // src/commands/doctor/checks/utils/findSourceFiles.ts
4262
+ var import_node_path24 = __toESM(require("path"));
4263
+ var import_fs_extra21 = __toESM(require("fs-extra"));
4264
+ var SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".d.ts"];
4265
+ var EXCLUDED_DIRECTORIES = /* @__PURE__ */ new Set([
4266
+ "node_modules",
4267
+ ".git",
4268
+ "dist",
4269
+ "build",
4270
+ "coverage",
4271
+ ".cache",
4272
+ ".turbo",
4273
+ ".vercel",
4274
+ ".next",
4275
+ "out",
4276
+ ".nyc_output"
4277
+ ]);
4278
+ function findSourceFiles(blockDir) {
4279
+ const sourceFiles = [];
4280
+ if (!import_fs_extra21.default.existsSync(blockDir)) return sourceFiles;
4281
+ const stack = [blockDir];
4282
+ while (stack.length > 0) {
4283
+ const currentDir = stack.pop();
4284
+ let entries;
4285
+ try {
4286
+ entries = import_fs_extra21.default.readdirSync(currentDir, { withFileTypes: true });
4287
+ } catch {
4288
+ continue;
4289
+ }
4290
+ for (const entry of entries) {
4291
+ const fullPath = import_node_path24.default.join(currentDir, entry.name);
4292
+ if (entry.isDirectory()) {
4293
+ if (!EXCLUDED_DIRECTORIES.has(entry.name)) {
4294
+ stack.push(fullPath);
4295
+ }
4296
+ } else if (entry.isFile()) {
4297
+ const ext = import_node_path24.default.extname(entry.name);
4298
+ if (SOURCE_EXTENSIONS.includes(ext)) {
4299
+ sourceFiles.push(fullPath);
4300
+ }
4301
+ }
4302
+ }
4303
+ }
4304
+ return sourceFiles;
4305
+ }
4306
+ function getBlockDirFromSourceFile(projectRoot, sourceFile) {
4307
+ const blocksPath = import_node_path24.default.join(projectRoot, "blocks");
4308
+ const relative = import_node_path24.default.relative(blocksPath, sourceFile);
4309
+ if (relative.startsWith("..") || import_node_path24.default.isAbsolute(relative)) {
4310
+ return null;
4311
+ }
4312
+ const blockName = relative.split(import_node_path24.default.sep)[0];
4313
+ if (!blockName) return null;
4314
+ return import_node_path24.default.join(blocksPath, blockName);
4315
+ }
4316
+
4317
+ // src/commands/doctor/checks/dependencies/missing/utils/parseImports.ts
4318
+ var ts = __toESM(require("typescript"));
4319
+ function parseImports(sourceFile, containingFile, importingBlock) {
4320
+ const imports = [];
4321
+ function visit(node) {
4322
+ if (ts.isImportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
4323
+ imports.push({
4324
+ specifier: node.moduleSpecifier.text,
4325
+ containingFile,
4326
+ importingBlock,
4327
+ isReExport: false
4328
+ });
4329
+ }
4330
+ if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
4331
+ imports.push({
4332
+ specifier: node.moduleSpecifier.text,
4333
+ containingFile,
4334
+ importingBlock,
4335
+ isReExport: true
4336
+ });
4337
+ }
4338
+ ts.forEachChild(node, visit);
4339
+ }
4340
+ visit(sourceFile);
4341
+ return imports;
4342
+ }
4343
+
4344
+ // src/commands/doctor/checks/dependencies/missing/utils/collectImports.ts
4345
+ var sourceFileCache = /* @__PURE__ */ new Map();
4346
+ function collectImports(blocks) {
4347
+ const allImports = [];
4348
+ for (const block of blocks.values()) {
4349
+ for (const sourceFile of findSourceFiles(block.blockDir)) {
4350
+ try {
4351
+ let sourceFileAst = sourceFileCache.get(sourceFile);
4352
+ if (!sourceFileAst) {
4353
+ const sourceText = import_fs_extra22.default.readFileSync(sourceFile, "utf8");
4354
+ sourceFileAst = ts2.createSourceFile(
4355
+ sourceFile,
4356
+ sourceText,
4357
+ ts2.ScriptTarget.Latest,
4358
+ true,
4359
+ ts2.ScriptKind.TS
4360
+ );
4361
+ sourceFileCache.set(sourceFile, sourceFileAst);
4362
+ }
4363
+ allImports.push(...parseImports(sourceFileAst, sourceFile, block));
4364
+ } catch {
4365
+ continue;
4366
+ }
4367
+ }
4368
+ }
4369
+ return allImports;
4370
+ }
4371
+
4372
+ // src/commands/doctor/checks/utils/resolveModuleName.ts
4373
+ var import_node_path25 = __toESM(require("path"));
4374
+ var import_fs_extra23 = __toESM(require("fs-extra"));
4375
+ var ts3 = __toESM(require("typescript"));
4376
+ var tsconfigCache = /* @__PURE__ */ new Map();
4377
+ var compilerOptionsByDirCache = /* @__PURE__ */ new Map();
4378
+ var hostCache = /* @__PURE__ */ new Map();
4379
+ var SKIP_DIRECTORIES = /* @__PURE__ */ new Set([
4380
+ "node_modules",
4381
+ ".git",
4382
+ "dist",
4383
+ "build",
4384
+ "coverage",
4385
+ ".cache",
4386
+ ".turbo",
4387
+ ".vercel",
4388
+ ".next",
4389
+ "out"
4390
+ ]);
4391
+ function parseTsconfig(configPath) {
4392
+ if (tsconfigCache.has(configPath)) {
4393
+ return tsconfigCache.get(configPath) ?? null;
4394
+ }
4395
+ const configDir = import_node_path25.default.dirname(configPath);
4396
+ const configFileName = import_node_path25.default.basename(configPath);
4397
+ let configText;
4398
+ try {
4399
+ configText = import_fs_extra23.default.readFileSync(configPath, "utf8");
4400
+ } catch {
4401
+ tsconfigCache.set(configPath, null);
4402
+ return null;
4403
+ }
4404
+ const parseResult = ts3.parseConfigFileTextToJson(configFileName, configText);
4405
+ if (!parseResult.config) {
4406
+ tsconfigCache.set(configPath, null);
4407
+ return null;
4408
+ }
4409
+ const rawConfig = parseResult.config;
4410
+ if (typeof rawConfig.extends === "string") {
4411
+ const extendedPath = import_node_path25.default.resolve(configDir, rawConfig.extends);
4412
+ const extendedConfig = parseTsconfig(extendedPath);
4413
+ if (extendedConfig) {
4414
+ const mergedConfig = { ...extendedConfig.options, ...rawConfig };
4415
+ const mergedResult = ts3.parseJsonConfigFileContent(
4416
+ mergedConfig,
4417
+ ts3.sys,
4418
+ configDir,
4419
+ void 0,
4420
+ configFileName
4421
+ );
4422
+ tsconfigCache.set(configPath, mergedResult);
4423
+ return mergedResult;
4424
+ }
4425
+ }
4426
+ const references = rawConfig.references;
4427
+ if (Array.isArray(references) && references.length > 0) {
4428
+ let mergedOptions = {};
4429
+ for (const ref of references) {
4430
+ if (typeof ref.path === "string") {
4431
+ const refPath = import_node_path25.default.resolve(configDir, ref.path);
4432
+ const refConfig = parseTsconfig(refPath);
4433
+ if (refConfig?.options) {
4434
+ mergedOptions = { ...refConfig.options, ...mergedOptions };
4435
+ }
4436
+ }
4437
+ }
4438
+ const rawCompilerOptions = rawConfig.compilerOptions ?? {};
4439
+ const finalCompilerOptions = { ...mergedOptions, ...rawCompilerOptions };
4440
+ const finalConfig = { ...rawConfig, compilerOptions: finalCompilerOptions };
4441
+ const mergedResult = ts3.parseJsonConfigFileContent(
4442
+ finalConfig,
4443
+ ts3.sys,
4444
+ configDir,
4445
+ void 0,
4446
+ configFileName
4447
+ );
4448
+ tsconfigCache.set(configPath, mergedResult);
4449
+ return mergedResult;
4450
+ }
4451
+ const result = ts3.parseJsonConfigFileContent(
4452
+ rawConfig,
4453
+ ts3.sys,
4454
+ configDir,
4455
+ void 0,
4456
+ configFileName
4457
+ );
4458
+ tsconfigCache.set(configPath, result);
4459
+ return result;
4460
+ }
4461
+ function getCompilerOptionsForDirectory(fileDir, projectRoot) {
4462
+ const normalizedFileDir = import_node_path25.default.resolve(fileDir);
4463
+ const normalizedProjectRoot = import_node_path25.default.resolve(projectRoot);
4464
+ const cached = compilerOptionsByDirCache.get(normalizedFileDir);
4465
+ if (cached) {
4466
+ return cached;
4467
+ }
4468
+ let currentDir = normalizedFileDir;
4469
+ while (currentDir.startsWith(normalizedProjectRoot) && currentDir !== normalizedProjectRoot) {
4470
+ const configPath = import_node_path25.default.join(currentDir, "tsconfig.json");
4471
+ if (import_fs_extra23.default.existsSync(configPath)) {
4472
+ const parsed = parseTsconfig(configPath);
4473
+ if (parsed?.options) {
4474
+ compilerOptionsByDirCache.set(normalizedFileDir, parsed.options);
4475
+ return parsed.options;
4476
+ }
4477
+ }
4478
+ currentDir = import_node_path25.default.dirname(currentDir);
4479
+ }
4480
+ const rootConfigPath = import_node_path25.default.join(normalizedProjectRoot, "tsconfig.json");
4481
+ if (import_fs_extra23.default.existsSync(rootConfigPath)) {
4482
+ const parsed = parseTsconfig(rootConfigPath);
4483
+ if (parsed?.options) {
4484
+ compilerOptionsByDirCache.set(normalizedFileDir, parsed.options);
4485
+ return parsed.options;
4486
+ }
4487
+ }
4488
+ const defaults = {
4489
+ moduleResolution: ts3.ModuleResolutionKind.Node16,
4490
+ target: ts3.ScriptTarget.ES2020,
4491
+ module: ts3.ModuleKind.ESNext
4492
+ };
4493
+ compilerOptionsByDirCache.set(normalizedFileDir, defaults);
4494
+ return defaults;
4495
+ }
4496
+ function createCompilerOptionsKey(options) {
4497
+ return JSON.stringify({
4498
+ baseUrl: options.baseUrl,
4499
+ paths: options.paths,
4500
+ rootDirs: options.rootDirs,
4501
+ moduleResolution: options.moduleResolution,
4502
+ module: options.module,
4503
+ target: options.target,
4504
+ jsx: options.jsx,
4505
+ allowJs: options.allowJs,
4506
+ checkJs: options.checkJs,
4507
+ resolveJsonModule: options.resolveJsonModule,
4508
+ typeRoots: options.typeRoots,
4509
+ types: options.types
4510
+ });
4511
+ }
4512
+ var CachedModuleResolutionHost = class {
4513
+ constructor(projectRoot) {
4514
+ this.projectRoot = projectRoot;
4515
+ }
4516
+ fileExistsCache = /* @__PURE__ */ new Map();
4517
+ directoryExistsCache = /* @__PURE__ */ new Map();
4518
+ getDirectoriesCache = /* @__PURE__ */ new Map();
4519
+ realpathCache = /* @__PURE__ */ new Map();
4520
+ fileExists(fileName) {
4521
+ const cached = this.fileExistsCache.get(fileName);
4522
+ if (cached !== void 0) {
4523
+ return cached;
4524
+ }
4525
+ const exists = import_fs_extra23.default.existsSync(fileName);
4526
+ this.fileExistsCache.set(fileName, exists);
4527
+ return exists;
4528
+ }
4529
+ readFile(fileName) {
4530
+ try {
4531
+ return import_fs_extra23.default.readFileSync(fileName, "utf8");
4532
+ } catch {
4533
+ return void 0;
4534
+ }
4535
+ }
4536
+ directoryExists(directoryName) {
4537
+ const cached = this.directoryExistsCache.get(directoryName);
4538
+ if (cached !== void 0) {
4539
+ return cached;
4540
+ }
4541
+ const exists = import_fs_extra23.default.existsSync(directoryName) && import_fs_extra23.default.statSync(directoryName).isDirectory();
4542
+ this.directoryExistsCache.set(directoryName, exists);
4543
+ return exists;
4544
+ }
4545
+ getDirectories(directoryName) {
4546
+ const cached = this.getDirectoriesCache.get(directoryName);
4547
+ if (cached !== void 0) {
4548
+ return cached;
4549
+ }
4550
+ try {
4551
+ const dirs = import_fs_extra23.default.readdirSync(directoryName, { withFileTypes: true }).filter((d) => d.isDirectory() && !SKIP_DIRECTORIES.has(d.name)).map((d) => d.name);
4552
+ this.getDirectoriesCache.set(directoryName, dirs);
4553
+ return dirs;
4554
+ } catch {
4555
+ const empty = [];
4556
+ this.getDirectoriesCache.set(directoryName, empty);
4557
+ return empty;
4558
+ }
4559
+ }
4560
+ getCurrentDirectory() {
4561
+ return this.projectRoot;
4562
+ }
4563
+ realpath(fileName) {
4564
+ const cached = this.realpathCache.get(fileName);
4565
+ if (cached !== void 0) {
4566
+ return cached;
4567
+ }
4568
+ try {
4569
+ const resolved = import_fs_extra23.default.realpathSync(fileName);
4570
+ this.realpathCache.set(fileName, resolved);
4571
+ return resolved;
4572
+ } catch {
4573
+ this.realpathCache.set(fileName, fileName);
4574
+ return fileName;
4575
+ }
4576
+ }
4577
+ };
4578
+ function getOrCreateHost(projectRoot, options) {
4579
+ const key = createCompilerOptionsKey(options);
4580
+ let host = hostCache.get(key);
4581
+ if (!host) {
4582
+ host = new CachedModuleResolutionHost(projectRoot);
4583
+ hostCache.set(key, host);
4584
+ }
4585
+ return host;
4586
+ }
4587
+ function resolveRelativeImport(moduleSpecifier, containingFile, projectRoot) {
4588
+ const containingDir = import_node_path25.default.dirname(containingFile);
4589
+ const relativePath = moduleSpecifier;
4590
+ let currentDir = containingDir;
4591
+ while (currentDir.startsWith(projectRoot)) {
4592
+ const resolvedPath = import_node_path25.default.resolve(currentDir, relativePath);
4593
+ const extensions = [".ts", ".tsx", ".d.ts", ".js", ".jsx"];
4594
+ for (const ext of extensions) {
4595
+ const filePath = resolvedPath + ext;
4596
+ if (import_fs_extra23.default.existsSync(filePath)) {
4597
+ return filePath;
4598
+ }
4599
+ }
4600
+ if (import_fs_extra23.default.existsSync(resolvedPath) && import_fs_extra23.default.statSync(resolvedPath).isDirectory()) {
4601
+ for (const ext of extensions) {
4602
+ const indexPath = import_node_path25.default.join(resolvedPath, "index" + ext);
4603
+ if (import_fs_extra23.default.existsSync(indexPath)) {
4604
+ return indexPath;
4605
+ }
4606
+ }
4607
+ }
4608
+ const parentDir = import_node_path25.default.dirname(currentDir);
4609
+ if (parentDir === currentDir) {
4610
+ break;
4611
+ }
4612
+ currentDir = parentDir;
4613
+ }
4614
+ return void 0;
4615
+ }
4616
+ function resolveModuleName2(moduleSpecifier, containingFile, projectRoot) {
4617
+ if (moduleSpecifier.startsWith("./") || moduleSpecifier.startsWith("../")) {
4618
+ return resolveRelativeImport(moduleSpecifier, containingFile, projectRoot);
4619
+ }
4620
+ const containingDir = import_node_path25.default.dirname(containingFile);
4621
+ const compilerOptions = getCompilerOptionsForDirectory(containingDir, projectRoot);
4622
+ const host = getOrCreateHost(projectRoot, compilerOptions);
4623
+ const result = ts3.resolveModuleName(moduleSpecifier, containingFile, compilerOptions, host);
4624
+ if (result.resolvedModule) {
4625
+ return result.resolvedModule.resolvedFileName;
4626
+ }
4627
+ return void 0;
4628
+ }
4629
+
4630
+ // src/commands/doctor/checks/dependencies/missing/utils/matchDependencies.ts
4631
+ var blockDirCache = /* @__PURE__ */ new Map();
4632
+ function resolveImportsToBlocks(imports, allBlocks, projectRoot) {
4633
+ const resolved = [];
4634
+ const blocksByDir = /* @__PURE__ */ new Map();
4635
+ for (const block of allBlocks.values()) {
4636
+ blocksByDir.set(block.blockDir, block);
4637
+ }
4638
+ for (const importInfo of imports) {
4639
+ const resolvedPath = resolveModuleName2(
4640
+ importInfo.specifier,
4641
+ importInfo.containingFile,
4642
+ projectRoot
4643
+ );
4644
+ if (!resolvedPath) {
4645
+ continue;
4646
+ }
4647
+ let targetBlockDir = blockDirCache.get(resolvedPath);
4648
+ if (targetBlockDir === void 0) {
4649
+ targetBlockDir = getBlockDirFromSourceFile(projectRoot, resolvedPath);
4650
+ blockDirCache.set(resolvedPath, targetBlockDir);
4651
+ }
4652
+ if (!targetBlockDir) {
4653
+ continue;
4654
+ }
4655
+ const targetBlock = blocksByDir.get(targetBlockDir);
4656
+ if (!targetBlock) {
4657
+ continue;
4658
+ }
4659
+ if (targetBlock.name === importInfo.importingBlock.name) {
4660
+ continue;
4661
+ }
4662
+ resolved.push({
4663
+ importInfo,
4664
+ targetBlock
4665
+ });
4666
+ }
4667
+ return resolved;
4668
+ }
4669
+ function checkMissingDependencies(resolvedImports) {
4670
+ const resultsByBlock = /* @__PURE__ */ new Map();
4671
+ for (const resolved of resolvedImports) {
4672
+ const { importInfo, targetBlock } = resolved;
4673
+ const importingBlock = importInfo.importingBlock;
4674
+ const isDeclared = importingBlock.dependencies.some((dep) => dep.name === targetBlock.name);
4675
+ if (!isDeclared) {
4676
+ let result = resultsByBlock.get(importingBlock.name);
4677
+ if (!result) {
4678
+ result = {
4679
+ block: importingBlock,
4680
+ missingDependencies: []
4681
+ };
4682
+ resultsByBlock.set(importingBlock.name, result);
4683
+ }
4684
+ const alreadyReported = result.missingDependencies.some(
4685
+ (m) => m.targetBlock.name === targetBlock.name
4686
+ );
4687
+ if (!alreadyReported) {
4688
+ result.missingDependencies.push({
4689
+ targetBlock,
4690
+ importSpecifier: importInfo.specifier,
4691
+ containingFile: importInfo.containingFile
4692
+ });
4693
+ }
4694
+ }
4695
+ }
4696
+ return Array.from(resultsByBlock.values());
4697
+ }
4698
+
4699
+ // src/commands/doctor/checks/dependencies/missing/utils/reportFinding.ts
4700
+ var import_node_path26 = __toESM(require("path"));
4701
+ function createMissingDependencyDiagnostics(results, projectRoot) {
4702
+ const diagnostics = [];
4703
+ for (const result of results) {
4704
+ for (const missing of result.missingDependencies) {
4705
+ diagnostics.push(
4706
+ createDiagnostic({
4707
+ checkId: "dependencies.missing-dependency",
4708
+ id: "missing-dependency",
4709
+ title: "Missing block dependency declaration",
4710
+ classification: "invalid",
4711
+ message: `Block "${result.block.name}" imports "${missing.targetBlock.name}" via "${missing.importSpecifier}" but "${missing.targetBlock.name}" is not declared in definition.dependencies`,
4712
+ filePath: normalizePath(import_node_path26.default.relative(projectRoot, missing.containingFile))
4713
+ })
4714
+ );
4715
+ }
4716
+ }
4717
+ return diagnostics;
4718
+ }
4719
+
4720
+ // src/commands/doctor/checks/dependencies/missing/validate.ts
4721
+ async function runMissingDependencyCheck(context) {
4722
+ const projectRoot = context.projectRoot;
4723
+ const blocks = await readBlocksMetadata(projectRoot);
4724
+ if (blocks.size === 0) {
4725
+ return [];
4726
+ }
4727
+ const imports = collectImports(blocks);
4728
+ const resolvedImports = resolveImportsToBlocks(imports, blocks, projectRoot);
4729
+ const missingResults = checkMissingDependencies(resolvedImports);
4730
+ return createMissingDependencyDiagnostics(missingResults, projectRoot);
4731
+ }
4732
+
4733
+ // src/commands/doctor/checks/dependencies/missing/fix.ts
4734
+ async function fixMissingDependency(_context, _diagnostic) {
4735
+ return {
4736
+ status: "skipped",
4737
+ message: "Missing dependencies must be declared manually in the .blox file"
4738
+ };
4739
+ }
4740
+
4741
+ // src/commands/doctor/checks/dependencies/missing/index.ts
4742
+ var missingDependencyCheck = {
4743
+ id: "dependencies.missing-dependency",
4744
+ name: "Missing Block dependencies",
4745
+ description: "Check for missing block dependency declarations",
4746
+ async run(context) {
4747
+ return runMissingDependencyCheck(context);
4748
+ },
4749
+ fix: fixMissingDependency
4750
+ };
4751
+
4752
+ // src/commands/doctor/checks/dependencies/circular/utils/findCycles.ts
4753
+ function buildDependencyGraph(blocks) {
4754
+ const graph = /* @__PURE__ */ new Map();
4755
+ for (const block of blocks.values()) {
4756
+ const targets = [];
4757
+ for (const dependency of block.dependencies) {
4758
+ if (blocks.has(dependency.name) && !targets.includes(dependency.name)) {
4759
+ targets.push(dependency.name);
4760
+ }
4761
+ }
4762
+ graph.set(block.name, targets);
4763
+ }
4764
+ return graph;
4765
+ }
4766
+ function findCircularDependencies(blocks) {
4767
+ const graph = buildDependencyGraph(blocks);
4768
+ const state = /* @__PURE__ */ new Map();
4769
+ const stack = [];
4770
+ const reported = /* @__PURE__ */ new Set();
4771
+ const cycles = [];
4772
+ const addCycle = (cyclePath) => {
4773
+ let minIndex = 0;
4774
+ for (let i = 1; i < cyclePath.length; i++) {
4775
+ if (cyclePath[i] < cyclePath[minIndex]) {
4776
+ minIndex = i;
4777
+ }
4778
+ }
4779
+ const normalized = [...cyclePath.slice(minIndex), ...cyclePath.slice(0, minIndex)];
4780
+ const key = JSON.stringify(normalized);
4781
+ if (reported.has(key)) return;
4782
+ reported.add(key);
4783
+ cycles.push({
4784
+ path: normalized,
4785
+ blocks: normalized.map((name) => blocks.get(name))
4786
+ });
4787
+ };
4788
+ const visit = (name) => {
4789
+ state.set(name, "visiting");
4790
+ stack.push(name);
4791
+ for (const target of graph.get(name) ?? []) {
4792
+ const targetState = state.get(target);
4793
+ if (targetState === "visiting") {
4794
+ addCycle(stack.slice(stack.indexOf(target)));
4795
+ } else if (targetState === void 0) {
4796
+ visit(target);
4797
+ }
4798
+ }
4799
+ stack.pop();
4800
+ state.set(name, "visited");
4801
+ };
4802
+ for (const name of [...blocks.keys()].sort()) {
4803
+ if (!state.has(name)) {
4804
+ visit(name);
4805
+ }
4806
+ }
4807
+ return cycles.sort((a, b) => a.path.join(">").localeCompare(b.path.join(">")));
4808
+ }
4809
+
4810
+ // src/commands/doctor/checks/dependencies/circular/utils/reportFinding.ts
4811
+ function createCircularDependencyDiagnostics(cycles) {
4812
+ return cycles.map((cycle) => {
4813
+ const cyclePath = [...cycle.path, cycle.path[0]].join(" -> ");
4814
+ return createDiagnostic({
4815
+ checkId: "dependencies.circular",
4816
+ id: `circular-dependency:${cycle.path.join(">")}`,
4817
+ title: "Circular block dependency",
4818
+ message: `Circular dependency detected: ${cyclePath}. Remove one of the declared dependencies in definition.dependencies to break the cycle.`,
4819
+ filePath: cycle.blocks[0]?.filePath
4820
+ });
4821
+ });
4822
+ }
4823
+
4824
+ // src/commands/doctor/checks/dependencies/circular/validate.ts
4825
+ async function runCircularDependencyCheck(context) {
4826
+ const blocks = await readBlocksMetadata(context.projectRoot);
4827
+ if (blocks.size === 0) {
4828
+ return [];
4829
+ }
4830
+ const cycles = findCircularDependencies(blocks);
4831
+ return createCircularDependencyDiagnostics(cycles);
4832
+ }
4833
+
4834
+ // src/commands/doctor/checks/dependencies/circular/index.ts
4835
+ var circularDependencyCheck = {
4836
+ id: "dependencies.circular",
4837
+ name: "Circular block dependencies",
4838
+ description: "Check for circular block dependency declarations",
4839
+ async run(context) {
4840
+ return runCircularDependencyCheck(context);
4841
+ }
4842
+ };
4843
+
4844
+ // src/commands/doctor/checks/dependencies/unresolved/utils/findUnresolved.ts
4845
+ function findUnresolvedDependencies(blocks) {
4846
+ const results = [];
4847
+ const sortedBlocks = [...blocks.values()].sort((a, b) => a.name.localeCompare(b.name));
4848
+ for (const block of sortedBlocks) {
4849
+ const reported = /* @__PURE__ */ new Set();
4850
+ for (const dependency of block.dependencies) {
4851
+ if (!dependency.name || blocks.has(dependency.name) || reported.has(dependency.name)) {
4852
+ continue;
4853
+ }
4854
+ reported.add(dependency.name);
4855
+ results.push({ block, dependencyName: dependency.name });
4856
+ }
4857
+ }
4858
+ return results;
4859
+ }
4860
+
4861
+ // src/commands/doctor/checks/dependencies/unresolved/utils/reportFinding.ts
4862
+ function createUnresolvedDependencyDiagnostics(results) {
4863
+ return results.map(
4864
+ (result) => createDiagnostic({
4865
+ checkId: "dependencies.unresolved-dependency",
4866
+ id: `unresolved-dependency:${result.block.name}>${result.dependencyName}`,
4867
+ title: "Unresolved block dependency",
4868
+ message: `Block "${result.block.name}" declares dependency "${result.dependencyName}" but no local block named "${result.dependencyName}" exists. Add the missing block or remove the declaration from definition.dependencies.`,
4869
+ filePath: result.block.filePath
4870
+ })
4871
+ );
4872
+ }
4873
+
4874
+ // src/commands/doctor/checks/dependencies/unresolved/validate.ts
4875
+ async function runUnresolvedDependencyCheck(context) {
4876
+ const blocks = await readBlocksMetadata(context.projectRoot);
4877
+ if (blocks.size === 0) {
4878
+ return [];
4879
+ }
4880
+ const unresolved = findUnresolvedDependencies(blocks);
4881
+ return createUnresolvedDependencyDiagnostics(unresolved);
4882
+ }
4883
+
4884
+ // src/commands/doctor/checks/dependencies/unresolved/index.ts
4885
+ var unresolvedDependencyCheck = {
4886
+ id: "dependencies.unresolved-dependency",
4887
+ name: "Unresolved block dependencies",
4888
+ description: "Check for block dependencies that do not resolve to a local block",
4889
+ async run(context) {
4890
+ return runUnresolvedDependencyCheck(context);
4891
+ }
4892
+ };
4893
+
4894
+ // src/commands/doctor/checks/dependencies/dependency-version/utils/findIncompatibilities.ts
4895
+ function findVersionIncompatibilities(blocks, template) {
4896
+ const templateVersions = /* @__PURE__ */ new Map();
4897
+ if (template) {
4898
+ for (const [name, checkpoint] of Object.entries(template.checkpoints)) {
4899
+ templateVersions.set(name, normalizeVersion(checkpoint.version));
4900
+ }
4901
+ templateVersions.set(template.name, normalizeVersion(template.version));
4902
+ }
4903
+ const incompatibilities = [];
4904
+ const missingTemplates = [];
4905
+ if (template) {
4906
+ for (const base of template.bases) {
4907
+ if (!base.name) continue;
4908
+ const available = templateVersions.get(base.name) ?? DEFAULT_VERSION;
4909
+ if (!isVersionCompatible(available, base.version)) {
4910
+ incompatibilities.push({
4911
+ targetKind: "base",
4912
+ declaringName: template.name,
4913
+ declaringFilePath: template.filePath,
4914
+ dependencyName: base.name,
4915
+ required: base.version,
4916
+ available
4917
+ });
4918
+ }
4919
+ }
4920
+ }
4921
+ for (const block of [...blocks.values()].sort((a, b) => a.name.localeCompare(b.name))) {
4922
+ const reportedTemplates = /* @__PURE__ */ new Set();
4923
+ const reportedDependencies = /* @__PURE__ */ new Set();
4924
+ for (const dep of block.templates) {
4925
+ if (!dep.name || reportedTemplates.has(dep.name)) continue;
4926
+ reportedTemplates.add(dep.name);
4927
+ if (!templateVersions.has(dep.name)) {
4928
+ missingTemplates.push({
4929
+ declaringName: block.name,
4930
+ declaringFilePath: block.filePath,
4931
+ templateName: dep.name
4932
+ });
4933
+ continue;
4934
+ }
4935
+ const available = templateVersions.get(dep.name);
4936
+ if (!isVersionCompatible(available, dep.version)) {
4937
+ incompatibilities.push({
4938
+ targetKind: "template",
4939
+ declaringName: block.name,
4940
+ declaringFilePath: block.filePath,
4941
+ dependencyName: dep.name,
4942
+ required: dep.version,
4943
+ available
4944
+ });
4945
+ }
4946
+ }
4947
+ for (const dep of block.dependencies) {
4948
+ if (!dep.name || reportedDependencies.has(dep.name)) continue;
4949
+ reportedDependencies.add(dep.name);
4950
+ const target = blocks.get(dep.name);
4951
+ if (!target) {
4952
+ continue;
4953
+ }
4954
+ const available = normalizeVersion(target.version);
4955
+ if (!isVersionCompatible(available, dep.version)) {
4956
+ incompatibilities.push({
4957
+ targetKind: "block",
4958
+ declaringName: block.name,
4959
+ declaringFilePath: block.filePath,
4960
+ dependencyName: dep.name,
4961
+ required: dep.version,
4962
+ available
4963
+ });
4964
+ }
4965
+ }
4966
+ }
4967
+ return { incompatibilities, missingTemplates };
4968
+ }
4969
+
4970
+ // src/commands/doctor/checks/dependencies/dependency-version/utils/readProjectTemplate.ts
4971
+ var import_fs_extra24 = __toESM(require("fs-extra"));
4972
+ async function readProjectTemplate(projectRoot) {
4973
+ const target = discoverBloxFiles(projectRoot).find((t) => t.kind === "template");
4974
+ if (!target) {
4975
+ return null;
4976
+ }
4977
+ const raw = await import_fs_extra24.default.readJson(target.absPath);
4978
+ const definition = raw.definition;
4979
+ const checkpoints = raw.checkpoints ?? {};
4980
+ return {
4981
+ name: definition?.name ?? "app",
4982
+ version: definition?.version,
4983
+ bases: definition?.bases ?? [],
4984
+ checkpoints,
4985
+ filePath: target.filePath
4986
+ };
4987
+ }
4988
+
4989
+ // src/commands/doctor/checks/dependencies/dependency-version/utils/reportFinding.ts
4990
+ function createDependencyVersionDiagnostics(results) {
4991
+ const diagnostics = [];
4992
+ for (const item of results.incompatibilities) {
4993
+ const declaringLabel = item.targetKind === "base" ? "Template" : "Block";
4994
+ diagnostics.push(
4995
+ createDiagnostic({
4996
+ checkId: "dependencies.dependency-version",
4997
+ id: `dependency-version:${item.targetKind}:${item.declaringName}>${item.dependencyName}`,
4998
+ title: `Incompatible ${item.targetKind} dependency version`,
4999
+ message: `${declaringLabel} "${item.declaringName}" requires ${item.targetKind} "${item.dependencyName}" version ${formatVersionRange(item.required)}, but version ${item.available} is installed.`,
5000
+ filePath: item.declaringFilePath
5001
+ })
5002
+ );
5003
+ }
5004
+ for (const item of results.missingTemplates) {
5005
+ diagnostics.push(
5006
+ createDiagnostic({
5007
+ checkId: "dependencies.dependency-version",
5008
+ id: `missing-template-dependency:${item.declaringName}>${item.templateName}`,
5009
+ title: "Missing template dependency",
5010
+ message: `Block "${item.declaringName}" depends on template "${item.templateName}" which is not installed or pinned in the project checkpoints.`,
5011
+ filePath: item.declaringFilePath
5012
+ })
5013
+ );
5014
+ }
5015
+ return diagnostics;
5016
+ }
5017
+
5018
+ // src/commands/doctor/checks/dependencies/dependency-version/validate.ts
5019
+ async function runDependencyVersionCheck(context) {
5020
+ const [blocks, template] = await Promise.all([
5021
+ readBlocksMetadata(context.projectRoot),
5022
+ readProjectTemplate(context.projectRoot)
5023
+ ]);
5024
+ if (blocks.size === 0 && !template) {
5025
+ return [];
5026
+ }
5027
+ const results = findVersionIncompatibilities(blocks, template);
5028
+ return createDependencyVersionDiagnostics(results);
5029
+ }
5030
+
5031
+ // src/commands/doctor/checks/dependencies/dependency-version/index.ts
5032
+ var dependencyVersionCheck = {
5033
+ id: "dependencies.dependency-version",
5034
+ name: "Dependency versions",
5035
+ description: "Check that installed dependencies satisfy declared version ranges",
5036
+ async run(context) {
5037
+ return runDependencyVersionCheck(context);
5038
+ }
5039
+ };
5040
+
5041
+ // src/commands/doctor/checks/dependencies/index.ts
5042
+ var dependenciesChecks = [
5043
+ missingDependencyCheck,
5044
+ circularDependencyCheck,
5045
+ unresolvedDependencyCheck,
5046
+ dependencyVersionCheck
5047
+ ];
5048
+
5049
+ // src/commands/doctor/registry.ts
5050
+ var doctorChecks = [metadataSchemaCheck, ...dependenciesChecks];
5051
+
5052
+ // src/commands/doctor/reporter.ts
5053
+ var import_node_util2 = require("util");
5054
+ var diagnosticIcon = {
5055
+ invalid: fmt.red("\u2718"),
5056
+ outdated: fmt.yellow("\u25B2"),
5057
+ informational: fmt.blue("\u2139")
5058
+ };
5059
+ var repairIcon = {
5060
+ fixed: fmt.green("\u2714"),
5061
+ skipped: fmt.gray("\u2013"),
5062
+ failed: fmt.red("\u2718")
5063
+ };
5064
+ var MAX_MESSAGE_WIDTH = 100;
5065
+ function getDoctorExitCode(report) {
5066
+ if (report.checkErrors.length > 0) return 2;
5067
+ if (report.diagnostics.some((d) => d.classification === "invalid")) {
5068
+ return 1;
5069
+ }
5070
+ if (report.repairs.some((r) => r.result.status === "failed")) {
5071
+ return 1;
5072
+ }
5073
+ return 0;
5074
+ }
5075
+ function printDoctorReport(report) {
5076
+ if (report.checkErrors.length > 0) {
5077
+ import_prompts2.log.error("Some checks could not complete");
5078
+ for (const error2 of report.checkErrors) {
5079
+ console.log(` ${fmt.red("\u2718")} ${fmt.bold(error2.checkId)}: ${error2.message}`);
5080
+ }
5081
+ console.log("");
5082
+ }
5083
+ printDiagnostics(report.diagnostics);
5084
+ if (report.repairs.length > 0) {
5085
+ printRepairs(report);
5086
+ }
5087
+ printSummary(report);
5088
+ }
5089
+ function printDiagnostics(diagnostics) {
5090
+ if (diagnostics.length === 0) return;
5091
+ const groups = /* @__PURE__ */ new Map();
5092
+ for (const diagnostic of diagnostics) {
5093
+ const checkDisplay = diagnostic.checkName ?? diagnostic.checkId;
5094
+ const group = groups.get(checkDisplay) ?? [];
5095
+ group.push(diagnostic);
5096
+ groups.set(checkDisplay, group);
5097
+ }
5098
+ for (const [checkDisplay, group] of groups) {
5099
+ printDiagnosticGroup(checkDisplay, group);
5100
+ console.log("");
5101
+ }
5102
+ }
5103
+ function printDiagnosticGroup(checkDisplay, diagnostics) {
5104
+ const rows = [];
5105
+ diagnostics.forEach((diagnostic, index) => {
5106
+ if (index > 0) {
5107
+ rows.push({ text: "", render: () => "" });
5108
+ }
5109
+ rows.push(...getDiagnosticLines(diagnostic));
5110
+ });
5111
+ const contentWidth = Math.max(
5112
+ 100,
5113
+ checkDisplay.length + 2,
5114
+ ...rows.map((row) => visibleLength(row.render()))
5115
+ );
5116
+ const title = `\u250C\u2500 ${checkDisplay} `;
5117
+ const topBorder = title + "\u2500".repeat(Math.max(0, contentWidth - visibleLength(title) + 1)) + "\u2500\u2500\u2510";
5118
+ console.log(fmt.gray(topBorder));
5119
+ for (const row of rows) {
5120
+ if (row.text === "") {
5121
+ console.log(`${fmt.gray("\u2502")} ${fmt.gray("\u2500".repeat(contentWidth))} ${fmt.gray("\u2502")}`);
5122
+ continue;
5123
+ }
5124
+ const rendered = row.render();
5125
+ const padding = " ".repeat(Math.max(0, contentWidth - visibleLength(rendered)));
5126
+ console.log(`${fmt.gray("\u2502")} ${rendered}${padding} ${fmt.gray("\u2502")}`);
5127
+ }
5128
+ console.log(fmt.gray(`\u2514${"\u2500".repeat(contentWidth + 2)}\u2518`));
5129
+ }
5130
+ function visibleLength(value) {
5131
+ return (0, import_node_util2.stripVTControlCharacters)(value).length;
5132
+ }
5133
+ function wrapText(line, width) {
5134
+ if (line.length <= width) return [line];
5135
+ const wrapped = [];
5136
+ let current = "";
5137
+ for (const word of line.split(" ")) {
5138
+ let rest = word;
5139
+ while (rest.length > width) {
5140
+ if (current) {
5141
+ wrapped.push(current);
5142
+ current = "";
5143
+ }
5144
+ wrapped.push(rest.slice(0, width));
5145
+ rest = rest.slice(width);
5146
+ }
5147
+ if (current === "") {
5148
+ current = rest;
5149
+ } else if (current.length + 1 + rest.length <= width) {
5150
+ current += ` ${rest}`;
5151
+ } else {
5152
+ wrapped.push(current);
5153
+ current = rest;
5154
+ }
5155
+ }
5156
+ if (current) wrapped.push(current);
5157
+ return wrapped.length > 0 ? wrapped : [""];
5158
+ }
5159
+ function getDiagnosticLines(diagnostic) {
5160
+ const icon = diagnosticIcon[diagnostic.classification];
5161
+ const lines = [
5162
+ {
5163
+ text: `${diagnostic.classification.toUpperCase()}: ${diagnostic.title}`,
5164
+ render: () => `${icon} ${fmt.bold(diagnostic.title)}`
5165
+ }
5166
+ ];
5167
+ if (diagnostic.filePath) {
5168
+ lines.push({
5169
+ text: `File path: ${diagnostic.filePath}`,
5170
+ render: () => `${fmt.gray("File path:")} ${fmt.cyan(diagnostic.filePath)}`
5171
+ });
5172
+ }
5173
+ for (const messageLine of diagnostic.message.split("\n")) {
5174
+ for (const wrapped of wrapText(messageLine, MAX_MESSAGE_WIDTH)) {
5175
+ lines.push({
5176
+ text: wrapped,
5177
+ render: () => wrapped
5178
+ });
5179
+ }
5180
+ }
5181
+ if (diagnostic.fixAvailable) {
5182
+ lines.push({
5183
+ text: "Repair available",
5184
+ render: () => fmt.green("\u2713 Repair available")
5185
+ });
5186
+ }
5187
+ return lines;
5188
+ }
5189
+ function printRepairs(report) {
5190
+ import_prompts2.log.step("Repairs");
5191
+ for (const repair of report.repairs) {
5192
+ const { result } = repair;
5193
+ const diagnostic = report.diagnostics.find(
5194
+ (d) => d.checkId === repair.checkId && d.id === repair.diagnosticId
5195
+ );
5196
+ const checkDisplay = diagnostic?.checkName ?? repair.checkId;
5197
+ console.log(
5198
+ ` ${repairIcon[result.status]} ${fmt.gray(
5199
+ `${checkDisplay}#${repair.diagnosticId}`
5200
+ )} ${result.message}`
5201
+ );
5202
+ }
5203
+ console.log("");
5204
+ }
5205
+ function getDiagnosticCounts(diagnostics) {
5206
+ const counts = {
5207
+ invalid: 0,
5208
+ outdated: 0,
5209
+ informational: 0
5210
+ };
5211
+ for (const diagnostic of diagnostics) {
5212
+ counts[diagnostic.classification] += 1;
5213
+ }
5214
+ return counts;
5215
+ }
5216
+ function printSummary(report) {
5217
+ const counts = getDiagnosticCounts(report.diagnostics);
5218
+ const exitCode = getDoctorExitCode(report);
5219
+ const invalid = counts.invalid > 0 ? fmt.red(`${counts.invalid} invalid`) : fmt.green("0 invalid");
5220
+ const outdated = counts.outdated > 0 ? fmt.yellow(`${counts.outdated} outdated`) : fmt.green("0 outdated");
5221
+ const informational = fmt.blue(`${counts.informational} informational`);
5222
+ const summary = `${invalid}, ${outdated}, ${informational}`;
5223
+ if (exitCode === 2) {
5224
+ import_prompts2.log.error(`Doctor could not complete reliably: ${summary}`);
5225
+ } else if (exitCode === 1) {
5226
+ import_prompts2.log.error(`Doctor finished with unresolved problems: ${summary}`);
5227
+ } else if (counts.outdated > 0) {
5228
+ import_prompts2.log.warn(`Doctor finished: ${summary}`);
5229
+ } else if (report.diagnostics.length > 0) {
5230
+ import_prompts2.log.success(`Doctor finished: ${summary}`);
5231
+ } else if (report.repairs.some((r) => r.result.status === "fixed")) {
5232
+ import_prompts2.log.success("Doctor finished: all detected issues have been repaired");
5233
+ } else {
5234
+ import_prompts2.log.success("No issues found");
5235
+ }
5236
+ if (report.diagnostics.some((d) => d.fixAvailable)) {
5237
+ console.log(` ${fmt.cyan("Run `blox doctor --fix` to apply available repairs.")}`);
5238
+ }
5239
+ }
5240
+
5241
+ // src/commands/doctor/runner.ts
5242
+ var errorMessage2 = (e) => e instanceof Error ? e.message : String(e);
5243
+ async function executeCheck(check, context, checkErrors, taskText) {
5244
+ try {
5245
+ const diagnostics = await runTask(taskText, () => check.run(context));
5246
+ return diagnostics.map((d) => ({ ...d, checkName: check.name }));
5247
+ } catch (e) {
5248
+ checkErrors.push({ checkId: check.id, message: errorMessage2(e) });
5249
+ return [];
5250
+ }
5251
+ }
5252
+ async function runDoctor(checks, context) {
5253
+ const checkErrors = [];
5254
+ const repairs = [];
5255
+ const diagnosticsByCheck = /* @__PURE__ */ new Map();
5256
+ for (const check of checks) {
5257
+ const diagnostics = await executeCheck(check, context, checkErrors, {
5258
+ start: check.description,
5259
+ end: `${check.name} ( check complete )`
5260
+ });
5261
+ diagnosticsByCheck.set(check.id, diagnostics);
5262
+ }
5263
+ if (context.fixMode) {
5264
+ const repairedChecks = /* @__PURE__ */ new Set();
5265
+ for (const check of checks) {
5266
+ for (const diagnostic of diagnosticsByCheck.get(check.id) ?? []) {
5267
+ if (!diagnostic.fixAvailable) continue;
5268
+ if (!check.fix) {
5269
+ checkErrors.push({
5270
+ checkId: check.id,
5271
+ message: `Diagnostic "${diagnostic.id}" declares a repair but the check has no fix() implementation`
5272
+ });
5273
+ continue;
5274
+ }
5275
+ let result;
5276
+ try {
5277
+ result = await check.fix(context, diagnostic);
5278
+ } catch (e) {
5279
+ result = { status: "failed", message: errorMessage2(e) };
5280
+ }
5281
+ repairs.push({ checkId: check.id, diagnosticId: diagnostic.id, result });
5282
+ if (result.status !== "skipped") {
5283
+ repairedChecks.add(check.id);
5284
+ }
5285
+ }
5286
+ }
5287
+ for (const check of checks) {
5288
+ if (!repairedChecks.has(check.id)) continue;
5289
+ const diagnostics = await executeCheck(check, context, checkErrors, {
5290
+ start: `Revalidating ${check.id}`,
5291
+ end: `${check.id} revalidated`
5292
+ });
5293
+ diagnosticsByCheck.set(check.id, diagnostics);
5294
+ }
5295
+ }
5296
+ return {
5297
+ diagnostics: checks.flatMap((check) => diagnosticsByCheck.get(check.id) ?? []),
5298
+ repairs,
5299
+ checkErrors
5300
+ };
5301
+ }
5302
+
5303
+ // src/commands/doctor/index.ts
5304
+ var doctor = command("doctor").description("Diagnose BLOX workspace issues").option("--fix", "attempt automatic repairs for findings that support them", false).action(async ({ fix }) => {
5305
+ try {
5306
+ const context = {
5307
+ projectRoot: process.cwd(),
5308
+ fixMode: fix
5309
+ };
5310
+ const report = await runDoctor(doctorChecks, context);
5311
+ printDoctorReport(report);
5312
+ process.exitCode = getDoctorExitCode(report);
5313
+ } catch (e) {
5314
+ error(e);
5315
+ }
5316
+ });
5317
+
5318
+ // src/commands/init/index.ts
5319
+ var import_fs_extra25 = __toESM(require("fs-extra"));
5320
+ var init2 = command("init").description("Init new app").alias("i").option("-n, --name <name>", "App name").option("-t, --template <template>", "Template to use").option("--branch <name>", "branch name").action(async ({ name, template, branch }) => {
5321
+ await syncRegistries();
5322
+ try {
5323
+ if (!name) {
5324
+ name = await text({ message: "Select app name" });
5325
+ }
5326
+ const templates = await getAvailableTemplates();
5327
+ if (!template) {
5328
+ template = await select({
5329
+ message: "Select template to be used",
5330
+ options: Object.entries(templates).map(([tmpl, { description }]) => ({
5331
+ value: tmpl,
5332
+ label: tmpl,
5333
+ hint: description
5334
+ }))
5335
+ });
5336
+ }
5337
+ if (!templates[template]) {
3454
5338
  error("Selected template not available in registries");
3455
5339
  }
3456
5340
  const task = spinner();
@@ -3473,8 +5357,8 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
3473
5357
  task.stop(`App initialized in ${name}`);
3474
5358
  await runLifecycleHookWithTask(name || "", "init", "Run template init");
3475
5359
  } catch (e) {
3476
- if (name && import_fs_extra16.default.existsSync(name)) {
3477
- await import_fs_extra16.default.remove(name);
5360
+ if (name && import_fs_extra25.default.existsSync(name)) {
5361
+ await import_fs_extra25.default.remove(name);
3478
5362
  }
3479
5363
  error(e);
3480
5364
  }
@@ -3494,30 +5378,30 @@ var migrateSchema = command("migrate").description("Migrate blox schema").action
3494
5378
  });
3495
5379
 
3496
5380
  // src/commands/remove/index.ts
3497
- var import_node_path20 = __toESM(require("path"));
3498
- var import_fs_extra17 = __toESM(require("fs-extra"));
3499
- var blocksAbsolutePath = () => import_node_path20.default.resolve(process.cwd(), blocksDir);
5381
+ var import_node_path27 = __toESM(require("path"));
5382
+ var import_fs_extra26 = __toESM(require("fs-extra"));
5383
+ var blocksAbsolutePath = () => import_node_path27.default.resolve(process.cwd(), blocksDir);
3500
5384
  function listInstalledBlockRelPaths() {
3501
5385
  const root = blocksAbsolutePath();
3502
- if (!import_fs_extra17.default.existsSync(root)) {
5386
+ if (!import_fs_extra26.default.existsSync(root)) {
3503
5387
  return [];
3504
5388
  }
3505
5389
  const paths2 = [];
3506
- for (const entry of import_fs_extra17.default.readdirSync(root, { withFileTypes: true })) {
5390
+ for (const entry of import_fs_extra26.default.readdirSync(root, { withFileTypes: true })) {
3507
5391
  if (!entry.isDirectory()) {
3508
5392
  continue;
3509
5393
  }
3510
- const abs = import_node_path20.default.join(root, entry.name);
5394
+ const abs = import_node_path27.default.join(root, entry.name);
3511
5395
  if (!isBlockDirectory(abs)) {
3512
5396
  continue;
3513
5397
  }
3514
- paths2.push(import_node_path20.default.join(blocksDir, entry.name));
5398
+ paths2.push(import_node_path27.default.join(blocksDir, entry.name));
3515
5399
  }
3516
5400
  return paths2;
3517
5401
  }
3518
5402
  function getInstalledBlockSelectOptions() {
3519
5403
  return listInstalledBlockRelPaths().map((rel) => {
3520
- const folder = import_node_path20.default.basename(rel);
5404
+ const folder = import_node_path27.default.basename(rel);
3521
5405
  const def = getBlockDef(rel);
3522
5406
  const label = def?.name && def.name !== folder ? `${def.name} (${folder})` : folder;
3523
5407
  return { value: folder, label, hint: def?.name };
@@ -3525,7 +5409,7 @@ function getInstalledBlockSelectOptions() {
3525
5409
  }
3526
5410
  function assertNoDependents(blockPathAbs, targetBlockName) {
3527
5411
  for (const rel of listInstalledBlockRelPaths()) {
3528
- const abs = import_node_path20.default.resolve(process.cwd(), rel);
5412
+ const abs = import_node_path27.default.resolve(process.cwd(), rel);
3529
5413
  if (abs === blockPathAbs) {
3530
5414
  continue;
3531
5415
  }
@@ -3541,19 +5425,19 @@ function assertNoDependents(blockPathAbs, targetBlockName) {
3541
5425
  }
3542
5426
  function assertUnderBlocksRoot(blockPathAbs) {
3543
5427
  const root = blocksAbsolutePath();
3544
- const rel = import_node_path20.default.relative(root, blockPathAbs);
3545
- if (!rel || rel.startsWith("..") || import_node_path20.default.isAbsolute(rel)) {
5428
+ const rel = import_node_path27.default.relative(root, blockPathAbs);
5429
+ if (!rel || rel.startsWith("..") || import_node_path27.default.isAbsolute(rel)) {
3546
5430
  throw new Error("Block path escapes the blocks directory");
3547
5431
  }
3548
5432
  }
3549
5433
  async function removeBlock(block, blocks, force = false) {
3550
5434
  const reg = blocks[block];
3551
5435
  const destination = reg ? reg.destination ?? block : block;
3552
- const blockPathRel = import_node_path20.default.join(blocksDir, destination);
3553
- const blockPathAbs = import_node_path20.default.resolve(process.cwd(), blockPathRel);
5436
+ const blockPathRel = import_node_path27.default.join(blocksDir, destination);
5437
+ const blockPathAbs = import_node_path27.default.resolve(process.cwd(), blockPathRel);
3554
5438
  assertUnderBlocksRoot(blockPathAbs);
3555
- if (!import_fs_extra17.default.existsSync(blockPathAbs) || !isBlockDirectory(blockPathAbs)) {
3556
- throw new Error(`Block is not installed at ${import_node_path20.default.relative(process.cwd(), blockPathAbs)}`);
5439
+ if (!import_fs_extra26.default.existsSync(blockPathAbs) || !isBlockDirectory(blockPathAbs)) {
5440
+ throw new Error(`Block is not installed at ${import_node_path27.default.relative(process.cwd(), blockPathAbs)}`);
3557
5441
  }
3558
5442
  const targetDef = getBlockDef(blockPathRel);
3559
5443
  if (!targetDef?.name) {
@@ -3565,7 +5449,7 @@ async function removeBlock(block, blocks, force = false) {
3565
5449
  await runLifecycleHookWithTask(blockPathRel, "remove", "Run block remove");
3566
5450
  await runTask("Remove block files", async () => {
3567
5451
  assertUnderBlocksRoot(blockPathAbs);
3568
- await import_fs_extra17.default.remove(blockPathAbs);
5452
+ await import_fs_extra26.default.remove(blockPathAbs);
3569
5453
  });
3570
5454
  return true;
3571
5455
  }
@@ -3623,16 +5507,16 @@ var remove = command("remove").description("Remove block from app").alias("rm").
3623
5507
  // src/commands/skills/index.ts
3624
5508
  var import_node_crypto = require("crypto");
3625
5509
  var import_node_os4 = __toESM(require("os"));
3626
- var import_node_path22 = __toESM(require("path"));
5510
+ var import_node_path29 = __toESM(require("path"));
3627
5511
  var import_cross_spawn2 = __toESM(require("cross-spawn"));
3628
- var import_fs_extra19 = __toESM(require("fs-extra"));
5512
+ var import_fs_extra28 = __toESM(require("fs-extra"));
3629
5513
 
3630
5514
  // src/commands/skills/constants.ts
3631
5515
  var SKILLS_REPO_URL = "https://github.com/Naseej-its/blox.git";
3632
5516
 
3633
5517
  // src/commands/skills/utils/cliCompatibility.ts
3634
- var import_node_path21 = __toESM(require("path"));
3635
- var import_fs_extra18 = __toESM(require("fs-extra"));
5518
+ var import_node_path28 = __toESM(require("path"));
5519
+ var import_fs_extra27 = __toESM(require("fs-extra"));
3636
5520
  var import_semver = __toESM(require("semver"));
3637
5521
  var SKILLS_CLI_COMPATIBILITY_COMMANDS = ["add", "update"];
3638
5522
  function getSkillscommandIndex(args, subcommand) {
@@ -3656,18 +5540,18 @@ function getAddCommandIndex(args) {
3656
5540
  return getSkillscommandIndex(args, "add");
3657
5541
  }
3658
5542
  async function loadSkillsData(cloneRoot) {
3659
- const skillsDir = import_node_path21.default.join(cloneRoot, "skills");
3660
- if (!await import_fs_extra18.default.pathExists(skillsDir)) {
5543
+ const skillsDir = import_node_path28.default.join(cloneRoot, "skills");
5544
+ if (!await import_fs_extra27.default.pathExists(skillsDir)) {
3661
5545
  return [];
3662
5546
  }
3663
- const entries = await import_fs_extra18.default.readdir(skillsDir, { withFileTypes: true });
5547
+ const entries = await import_fs_extra27.default.readdir(skillsDir, { withFileTypes: true });
3664
5548
  const manifests = await Promise.all(
3665
5549
  entries.filter((entry) => entry.isDirectory()).map(async (entry) => {
3666
- const filePath = import_node_path21.default.join(skillsDir, entry.name, "skill.json");
3667
- if (!await import_fs_extra18.default.pathExists(filePath)) {
5550
+ const filePath = import_node_path28.default.join(skillsDir, entry.name, "skill.json");
5551
+ if (!await import_fs_extra27.default.pathExists(filePath)) {
3668
5552
  return null;
3669
5553
  }
3670
- const raw = await import_fs_extra18.default.readJson(filePath);
5554
+ const raw = await import_fs_extra27.default.readJson(filePath);
3671
5555
  const range = raw.cliCompatibility?.trim();
3672
5556
  if (!range) {
3673
5557
  return null;
@@ -3719,8 +5603,8 @@ async function runSkills() {
3719
5603
  const idx = process.argv.indexOf("skills");
3720
5604
  const args = idx === -1 ? [] : process.argv.slice(idx + 1);
3721
5605
  if (needsCliCompatibilityCheck(args)) {
3722
- const tempDir = import_node_path22.default.join(import_node_os4.default.tmpdir(), `blox-skills-compat-${(0, import_node_crypto.randomUUID)()}`);
3723
- await import_fs_extra19.default.mkdir(tempDir);
5606
+ const tempDir = import_node_path29.default.join(import_node_os4.default.tmpdir(), `blox-skills-compat-${(0, import_node_crypto.randomUUID)()}`);
5607
+ await import_fs_extra28.default.mkdir(tempDir);
3724
5608
  try {
3725
5609
  await git.clone(SKILLS_REPO_URL, tempDir);
3726
5610
  const skills2 = await loadSkillsData(tempDir);
@@ -3738,7 +5622,7 @@ async function runSkills() {
3738
5622
  }
3739
5623
  } finally {
3740
5624
  try {
3741
- await import_fs_extra19.default.remove(tempDir);
5625
+ await import_fs_extra28.default.remove(tempDir);
3742
5626
  } catch {
3743
5627
  debug(`Failed to cleanup temp dir: ${tempDir}`);
3744
5628
  }
@@ -3771,11 +5655,11 @@ function runSkillsCommand(args, cwd) {
3771
5655
  }
3772
5656
 
3773
5657
  // src/commands/update/index.ts
3774
- var import_prompts26 = require("@clack/prompts");
5658
+ var import_prompts28 = require("@clack/prompts");
3775
5659
 
3776
5660
  // src/services/updater.ts
3777
- var import_node_path23 = __toESM(require("path"));
3778
- var import_fs_extra20 = __toESM(require("fs-extra"));
5661
+ var import_node_path30 = __toESM(require("path"));
5662
+ var import_fs_extra29 = __toESM(require("fs-extra"));
3779
5663
  var import_klaw3 = __toESM(require("klaw"));
3780
5664
  async function updateFromRemote({
3781
5665
  name,
@@ -3822,9 +5706,9 @@ async function updateFromRemote({
3822
5706
  const remoteIgnore = remoteBloxFile.definition?.ignore || [];
3823
5707
  const projectIgnore = bloxFile.project?.ignore || [];
3824
5708
  ignore3.push(...remoteIgnore, ...projectIgnore, bloxFilePath, `**/${bloxFilePath}`);
3825
- const gitIgnorePath = import_node_path23.default.join(dir, ".gitignore");
3826
- if (await import_fs_extra20.default.pathExists(gitIgnorePath)) {
3827
- const gitIgnoreContent = await import_fs_extra20.default.readFile(gitIgnorePath, "utf8");
5709
+ const gitIgnorePath = import_node_path30.default.join(dir, ".gitignore");
5710
+ if (await import_fs_extra29.default.pathExists(gitIgnorePath)) {
5711
+ const gitIgnoreContent = await import_fs_extra29.default.readFile(gitIgnorePath, "utf8");
3828
5712
  const gitIgnorePatterns = gitIgnoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
3829
5713
  ignore3.push(...gitIgnorePatterns);
3830
5714
  debug(`Added ${gitIgnorePatterns.length} patterns from .gitignore`);
@@ -3836,14 +5720,14 @@ async function updateFromRemote({
3836
5720
  if (hard) {
3837
5721
  const getAllFiles = async (d) => {
3838
5722
  const files = [];
3839
- if (await import_fs_extra20.default.pathExists(d)) {
5723
+ if (await import_fs_extra29.default.pathExists(d)) {
3840
5724
  for await (const file of (0, import_klaw3.default)(d)) {
3841
5725
  if (file.path.includes("/.git/") || file.path.endsWith("/.git") || file.path.includes("\\.git\\") || file.path.endsWith("\\.git"))
3842
5726
  continue;
3843
5727
  if (file.path.includes("/node_modules/") || file.path.includes("\\node_modules\\"))
3844
5728
  continue;
3845
5729
  if (file.stats.isFile()) {
3846
- files.push(import_node_path23.default.relative(d, file.path));
5730
+ files.push(import_node_path30.default.relative(d, file.path));
3847
5731
  }
3848
5732
  }
3849
5733
  }
@@ -3862,23 +5746,23 @@ async function updateFromRemote({
3862
5746
  for (const file of filesToProcess) {
3863
5747
  if (file === ".git" || file.startsWith(".git/") || file.startsWith(".git\\")) continue;
3864
5748
  if (ignoredMatcher.ignores(toIgnorePath(file))) continue;
3865
- const localPath = import_node_path23.default.join(dir, file);
3866
- const basePath = import_node_path23.default.join(baseDir, file);
3867
- const remotePath = import_node_path23.default.join(remoteDir, file);
3868
- const existsLocal = await import_fs_extra20.default.pathExists(localPath);
3869
- const existsBase = await import_fs_extra20.default.pathExists(basePath);
3870
- const existsRemote = await import_fs_extra20.default.pathExists(remotePath);
3871
- const ext = import_node_path23.default.extname(file);
5749
+ const localPath = import_node_path30.default.join(dir, file);
5750
+ const basePath = import_node_path30.default.join(baseDir, file);
5751
+ const remotePath = import_node_path30.default.join(remoteDir, file);
5752
+ const existsLocal = await import_fs_extra29.default.pathExists(localPath);
5753
+ const existsBase = await import_fs_extra29.default.pathExists(basePath);
5754
+ const existsRemote = await import_fs_extra29.default.pathExists(remotePath);
5755
+ const ext = import_node_path30.default.extname(file);
3872
5756
  const isBinary = isBinaryFile(ext);
3873
5757
  if (existsRemote) {
3874
- await import_fs_extra20.default.ensureDir(import_node_path23.default.dirname(localPath));
5758
+ await import_fs_extra29.default.ensureDir(import_node_path30.default.dirname(localPath));
3875
5759
  }
3876
5760
  if (hard) {
3877
5761
  if (existsRemote) {
3878
- await import_fs_extra20.default.copy(remotePath, localPath, { overwrite: true });
5762
+ await import_fs_extra29.default.copy(remotePath, localPath, { overwrite: true });
3879
5763
  debug(`Hard update: Overwrote ${file}`);
3880
5764
  } else if (existsLocal) {
3881
- await import_fs_extra20.default.remove(localPath);
5765
+ await import_fs_extra29.default.remove(localPath);
3882
5766
  debug(`Hard update: Removed ${file}`);
3883
5767
  }
3884
5768
  continue;
@@ -3887,29 +5771,29 @@ async function updateFromRemote({
3887
5771
  if (existsLocal) {
3888
5772
  if (isBinary) {
3889
5773
  debug(`Binary collision: ${file}, overwriting.`);
3890
- await import_fs_extra20.default.copy(remotePath, localPath, { overwrite: true });
5774
+ await import_fs_extra29.default.copy(remotePath, localPath, { overwrite: true });
3891
5775
  logWarningSection(`Overwrote binary file collision: ${file}`);
3892
5776
  } else {
3893
- const emptyBase = import_node_path23.default.join(baseDir, `${file}.empty`);
3894
- await import_fs_extra20.default.ensureFile(emptyBase);
5777
+ const emptyBase = import_node_path30.default.join(baseDir, `${file}.empty`);
5778
+ await import_fs_extra29.default.ensureFile(emptyBase);
3895
5779
  const result = await git.mergeFile(localPath, emptyBase, remotePath);
3896
5780
  if (!result) {
3897
5781
  hasConflicts2 = true;
3898
5782
  conflictFiles.push(file);
3899
5783
  }
3900
- await import_fs_extra20.default.remove(emptyBase);
5784
+ await import_fs_extra29.default.remove(emptyBase);
3901
5785
  }
3902
5786
  } else {
3903
- await import_fs_extra20.default.copy(remotePath, localPath);
5787
+ await import_fs_extra29.default.copy(remotePath, localPath);
3904
5788
  }
3905
5789
  continue;
3906
5790
  }
3907
5791
  if (existsBase && !existsRemote) {
3908
5792
  if (existsLocal) {
3909
- const localBuffer = await import_fs_extra20.default.readFile(localPath);
3910
- const baseBuffer = await import_fs_extra20.default.readFile(basePath);
5793
+ const localBuffer = await import_fs_extra29.default.readFile(localPath);
5794
+ const baseBuffer = await import_fs_extra29.default.readFile(basePath);
3911
5795
  if (localBuffer.equals(baseBuffer)) {
3912
- await import_fs_extra20.default.remove(localPath);
5796
+ await import_fs_extra29.default.remove(localPath);
3913
5797
  } else {
3914
5798
  logWarningSection(
3915
5799
  `File ${file} was deleted in remote but modified locally. Kept local version.`
@@ -3920,7 +5804,7 @@ async function updateFromRemote({
3920
5804
  }
3921
5805
  if (existsBase && existsRemote) {
3922
5806
  if (!existsLocal) {
3923
- await import_fs_extra20.default.copy(remotePath, localPath);
5807
+ await import_fs_extra29.default.copy(remotePath, localPath);
3924
5808
  logWarningSection(
3925
5809
  `File restored: ${file}`,
3926
5810
  `This file was deleted locally but updated in the remote block.
@@ -3929,7 +5813,7 @@ It has been recreated to apply upstream changes.`
3929
5813
  continue;
3930
5814
  }
3931
5815
  if (isBinary) {
3932
- await import_fs_extra20.default.copy(remotePath, localPath, { overwrite: true });
5816
+ await import_fs_extra29.default.copy(remotePath, localPath, { overwrite: true });
3933
5817
  logWarningSection(`Updated binary file: ${file} (overwritten)`);
3934
5818
  } else {
3935
5819
  const result = await git.mergeFile(localPath, basePath, remotePath);
@@ -3942,8 +5826,11 @@ It has been recreated to apply upstream changes.`
3942
5826
  }
3943
5827
  if (hasConflicts2) {
3944
5828
  logWarningSection(
3945
- "Conflicts detected in the following files:",
3946
- conflictFiles.map((f) => fmt.red(f)).join("\n")
5829
+ `Conflicts detected in "${name}":`,
5830
+ conflictFiles.map((file) => {
5831
+ const absolutePath = normalizePath(import_node_path30.default.resolve(dir, file));
5832
+ return `${fmt.red(absolutePath)} (${file})`;
5833
+ }).join("\n")
3947
5834
  );
3948
5835
  await select({
3949
5836
  message: "Please resolve conflicts manually (look for <<<<<<< HEAD) and press enter to continue",
@@ -4182,7 +6069,7 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
4182
6069
  option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
4183
6070
  ).option("--ignore <list...>", 'Files ignore list scoped by name i.e "repo:file"').option("-b, --block <names...>", "Blocks to update, valid only with scope block").option("--hard", "Hard update (overwrite local changes)", false).action(async (args) => {
4184
6071
  if (await git.hasUncommittedChanges()) {
4185
- import_prompts26.log.warn(fmt.yellow("Make sure to commit any changes first"));
6072
+ import_prompts28.log.warn(fmt.yellow("Make sure to commit any changes first"));
4186
6073
  return;
4187
6074
  }
4188
6075
  await migrateAll(true);
@@ -4261,15 +6148,15 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
4261
6148
  hasUpdate = hasUpdate || blockResults.some((result) => result.updated);
4262
6149
  const failedBlocks = blockResults.filter((result) => result.error);
4263
6150
  if (failedBlocks.length) {
4264
- import_prompts26.log.warn(
6151
+ import_prompts28.log.warn(
4265
6152
  fmt.yellow(
4266
6153
  `${failedBlocks.length} block update${failedBlocks.length === 1 ? "" : "s"} failed.`
4267
6154
  )
4268
6155
  );
4269
6156
  for (const result of failedBlocks) {
4270
- import_prompts26.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
6157
+ import_prompts28.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
4271
6158
  }
4272
- import_prompts26.log.warn(
6159
+ import_prompts28.log.warn(
4273
6160
  "Fix the errors above and rerun the update for the failed blocks."
4274
6161
  );
4275
6162
  }
@@ -4304,11 +6191,11 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
4304
6191
  );
4305
6192
  for (const result of blockResults) {
4306
6193
  if (result.error) {
4307
- import_prompts26.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
6194
+ import_prompts28.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
4308
6195
  }
4309
6196
  }
4310
6197
  if (blockResults.some((result) => result.error)) {
4311
- import_prompts26.log.warn("Fix the errors above and rerun the update for the failed blocks.");
6198
+ import_prompts28.log.warn("Fix the errors above and rerun the update for the failed blocks.");
4312
6199
  }
4313
6200
  hasUpdate = hasUpdate || blockResults.some((result) => result.updated);
4314
6201
  for (const result of blockResults) {
@@ -4318,7 +6205,7 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
4318
6205
  }
4319
6206
  }
4320
6207
  if (!shouldContinue) {
4321
- import_prompts26.log.warn(fmt.yellow("Stopped updating remaining parts by user choice"));
6208
+ import_prompts28.log.warn(fmt.yellow("Stopped updating remaining parts by user choice"));
4322
6209
  }
4323
6210
  if (hasUpdate) {
4324
6211
  await runLifecycleHookWithTask(".", "update", "Run template update");
@@ -4328,7 +6215,7 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
4328
6215
  await printChangeLog(startCheckpoints, endCheckpoints);
4329
6216
  } catch (e) {
4330
6217
  if (!isDebugMode()) {
4331
- import_prompts26.log.warn("Error happened, Will rollback changes");
6218
+ import_prompts28.log.warn("Error happened, Will rollback changes");
4332
6219
  await git.rollback();
4333
6220
  }
4334
6221
  error(e);
@@ -4364,7 +6251,8 @@ var commands = [
4364
6251
  migrateSchema,
4365
6252
  detach,
4366
6253
  contribute,
4367
- skills
6254
+ skills,
6255
+ doctor
4368
6256
  ];
4369
6257
 
4370
6258
  // bin/run.ts