@naseej/blox 1.7.0 → 1.9.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.
package/dist/run.js CHANGED
@@ -201,10 +201,7 @@ var checkForCliUpdate = async (currentVersion, argv = []) => {
201
201
  };
202
202
 
203
203
  // package.json
204
- var version = "1.7.0";
205
-
206
- // src/commands/add/index.ts
207
- var import_fs_extra11 = __toESM(require("fs-extra"));
204
+ var version = "1.9.0";
208
205
 
209
206
  // src/migrations/index.ts
210
207
  var import_node_path11 = __toESM(require("path"));
@@ -551,6 +548,16 @@ function updateCheckpoint(name, checkpoint, cwd = ".") {
551
548
  info.checkpoints[name] = checkpoint;
552
549
  saveBloxFile(info, cwd);
553
550
  }
551
+ function getBlockPath(name) {
552
+ if (import_fs_extra5.default.existsSync(blocksDir)) {
553
+ for (const entry of import_fs_extra5.default.readdirSync(blocksDir, { withFileTypes: true })) {
554
+ if (!entry.isDirectory()) continue;
555
+ const dir = import_node_path7.default.join(blocksDir, entry.name);
556
+ if (getBloxFile(dir).definition?.name === name) return dir;
557
+ }
558
+ }
559
+ throw new Error(`Block is not installed: ${name}`);
560
+ }
554
561
  function getUsedBlocksDef() {
555
562
  return getUsedBlocks().map((b) => b.definition);
556
563
  }
@@ -577,12 +584,22 @@ var import_prompts3 = require("@clack/prompts");
577
584
  var spinner = () => {
578
585
  const s = (0, import_prompts3.spinner)();
579
586
  const minimal = isMinimalMode() || isDebugMode();
587
+ const stop = (msg = "error", code) => {
588
+ minimal ? code ? import_prompts2.log.error(msg) : import_prompts2.log.step(msg || "success") : s.stop(code ? fmt.red(msg) : fmt.green(msg), code);
589
+ };
580
590
  return {
581
591
  start: (msg) => {
582
592
  minimal ? import_prompts2.log.step(`${msg || "start"}...`) : s.start(msg);
583
593
  },
584
- stop: (msg = "error", code) => {
585
- minimal ? code ? import_prompts2.log.error(msg) : import_prompts2.log.step(msg || "success") : s.stop(code ? fmt.red(msg) : fmt.green(msg), code);
594
+ stop,
595
+ success: (msg = "success") => {
596
+ stop(msg, 0);
597
+ },
598
+ fail: (msg = "error", code = 1) => {
599
+ stop(msg, code);
600
+ },
601
+ finish: (msg = "success") => {
602
+ stop(msg, 0);
586
603
  },
587
604
  message: (msg) => {
588
605
  minimal ? import_prompts2.log.message(msg) : s.message(msg);
@@ -614,11 +631,14 @@ function getLifecycleHookScript(cwd, hook) {
614
631
  }
615
632
  async function runLifecycleHookScript(cwd, script) {
616
633
  const isWin = process.platform === "win32";
634
+ const onStdout = (data) => {
635
+ process.stdout.write(data);
636
+ };
617
637
  if (isWin) {
618
- await $("cmd.exe", ["/d", "/s", "/c", script], { cwd });
638
+ await $("cmd.exe", ["/d", "/s", "/c", script], { cwd, onStdout });
619
639
  return;
620
640
  }
621
- await $("/bin/sh", ["-lc", script], { cwd });
641
+ await $("/bin/sh", ["-lc", script], { cwd, onStdout });
622
642
  }
623
643
  async function runLifecycleHookWithTask(cwd, hook, message) {
624
644
  const script = getLifecycleHookScript(cwd, hook);
@@ -725,7 +745,6 @@ var updatedRemotes = /* @__PURE__ */ new Set();
725
745
  var updateRemote = async (name, source, shellOptions = {}) => {
726
746
  const remoteId = `${name}:${source}`;
727
747
  if (updatedRemotes.has(remoteId)) return;
728
- updatedRemotes.add(remoteId);
729
748
  debug("updateRemote");
730
749
  debug({ name, source });
731
750
  try {
@@ -740,6 +759,7 @@ var updateRemote = async (name, source, shellOptions = {}) => {
740
759
  ...shellOptions
741
760
  });
742
761
  await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
762
+ updatedRemotes.add(remoteId);
743
763
  };
744
764
  var readJsonFromCommit = async (commit2, file, cwd = ".") => {
745
765
  try {
@@ -774,9 +794,9 @@ var readJsonFromIndex = async (file, cwd = ".") => {
774
794
  var readJsonFromRemote = async (remote, file, branch = defaultBranch, commit2) => {
775
795
  return readJsonFromCommit(commit2 || `${remote}/${branch}`, file);
776
796
  };
777
- var isCommitOlder = async (a, b) => {
797
+ var isCommitOlder = async (a, b, cwd = ".") => {
778
798
  try {
779
- await $("git", ["merge-base", "--is-ancestor", a, b]);
799
+ await $("git", ["merge-base", "--is-ancestor", a, b], { cwd });
780
800
  return true;
781
801
  } catch {
782
802
  return false;
@@ -1019,15 +1039,44 @@ var getUnmergedFiles = async (cwd = ".") => {
1019
1039
  var fetchRepo = async (cwd = ".") => {
1020
1040
  await $("git", ["fetch", "--progress", "origin"], { cwd });
1021
1041
  };
1022
- var getStagedFiles = async (cwd = ".") => {
1042
+ var getChangedFilesInCommit = async (commit2, cwd = ".") => {
1043
+ let out = "";
1044
+ await $(
1045
+ "git",
1046
+ ["diff-tree", "--no-commit-id", "--name-only", "-r", "--root", normalizeCommitRef(commit2)],
1047
+ {
1048
+ cwd,
1049
+ onStdout: (text2) => {
1050
+ out += text2;
1051
+ }
1052
+ }
1053
+ );
1054
+ return out.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
1055
+ };
1056
+ var getChangedFilesFromHead = async (cwd = ".") => {
1023
1057
  let out = "";
1024
- await $("git", ["diff", "--cached", "--name-only"], {
1058
+ await $("git", ["diff", "--name-status", "-z", "HEAD"], {
1025
1059
  cwd,
1026
1060
  onStdout: (text2) => {
1027
1061
  out += text2;
1028
1062
  }
1029
1063
  });
1030
- return out.split("\n").map((l) => l.trim()).filter(Boolean);
1064
+ const entries = out.split("\0").filter(Boolean);
1065
+ const files = /* @__PURE__ */ new Set();
1066
+ for (let i = 0; i < entries.length; ) {
1067
+ const status = entries[i++] || "";
1068
+ const code = status.trim().toUpperCase();
1069
+ if (code.startsWith("R") || code.startsWith("C")) {
1070
+ const oldPath = entries[i++];
1071
+ const newPath = entries[i++];
1072
+ if (oldPath) files.add(oldPath);
1073
+ if (newPath) files.add(newPath);
1074
+ continue;
1075
+ }
1076
+ const file = entries[i++];
1077
+ if (file) files.add(file);
1078
+ }
1079
+ return [...files];
1031
1080
  };
1032
1081
  var git = {
1033
1082
  clone,
@@ -1070,7 +1119,8 @@ var git = {
1070
1119
  commitAll,
1071
1120
  getUnmergedFiles,
1072
1121
  fetchRepo,
1073
- getStagedFiles
1122
+ getChangedFilesFromHead,
1123
+ getChangedFilesInCommit
1074
1124
  };
1075
1125
 
1076
1126
  // src/shared/prompts/index.ts
@@ -1211,6 +1261,11 @@ async function migrateAll(autoCommit) {
1211
1261
  }
1212
1262
  }
1213
1263
 
1264
+ // src/services/add.ts
1265
+ var import_node_os2 = __toESM(require("os"));
1266
+ var import_node_path14 = __toESM(require("path"));
1267
+ var import_fs_extra11 = __toESM(require("fs-extra"));
1268
+
1214
1269
  // src/services/fs.ts
1215
1270
  var import_node_path12 = __toESM(require("path"));
1216
1271
  var import_fs_extra9 = __toESM(require("fs-extra"));
@@ -1233,6 +1288,97 @@ var deletePattern = async (cwd, patterns = []) => {
1233
1288
  }
1234
1289
  };
1235
1290
 
1291
+ // src/services/versions/checkCompatibility.ts
1292
+ function processDependencyVersion(dep) {
1293
+ if (!dep.version) dep.version = 0;
1294
+ return dep;
1295
+ }
1296
+ function processTemplate(def) {
1297
+ debug("processTemplate");
1298
+ if (!def.version) def.version = 0;
1299
+ Object.values(def.bases || {}).forEach(processDependencyVersion);
1300
+ return def;
1301
+ }
1302
+ function processBases(info) {
1303
+ debug("processBases");
1304
+ if (!info || !info.checkpoints) return {};
1305
+ Object.values(info.checkpoints).forEach((base) => {
1306
+ if (!base.version) base.version = 0;
1307
+ });
1308
+ return info.checkpoints;
1309
+ }
1310
+ function processBlocks(defs) {
1311
+ debug("processBlocks");
1312
+ defs.forEach((def) => {
1313
+ if (!def.version) def.version = 0;
1314
+ def.dependencies?.forEach(processDependencyVersion);
1315
+ def.templates?.forEach(processDependencyVersion);
1316
+ });
1317
+ return defs;
1318
+ }
1319
+ 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]}`;
1326
+ throw new Error(
1327
+ normalizeLogMessage(`
1328
+ ${mismatchMessage}
1329
+ current version: ${version2}
1330
+ required version: ${requiredVersionText}
1331
+ `)
1332
+ );
1333
+ }
1334
+ }
1335
+ async function _checkVersionsCompatibility(template, usedBlocks, basesVersion) {
1336
+ for (const templateBaseDep of template.bases || []) {
1337
+ const currentVersion = basesVersion[templateBaseDep.name]?.version;
1338
+ ensureVersionOverlap(
1339
+ currentVersion,
1340
+ templateBaseDep.version,
1341
+ `Template "${template.name}" version: ${template.version} is not compatible with base "${templateBaseDep.name}"`
1342
+ );
1343
+ }
1344
+ for (const block of usedBlocks) {
1345
+ for (const blockTemplateDep of block.templates || []) {
1346
+ const currentTemplate = basesVersion[blockTemplateDep.name];
1347
+ if (!currentTemplate) {
1348
+ throw new Error(
1349
+ `Block "${block.name}" version: ${block.version} depends on missing template "${blockTemplateDep.name}" `
1350
+ );
1351
+ }
1352
+ ensureVersionOverlap(
1353
+ currentTemplate?.version,
1354
+ blockTemplateDep.version,
1355
+ `Block "${block.name}" version: ${block.version} is not compatible with template "${blockTemplateDep.name}" `
1356
+ );
1357
+ }
1358
+ for (const blockDep of block.dependencies || []) {
1359
+ const blockDepDef = usedBlocks.find((b) => b.name === blockDep.name);
1360
+ if (!blockDepDef) {
1361
+ throw new Error(
1362
+ `Block "${block.name}" version: ${block.version} depends on missing block "${blockDep.name}" `
1363
+ );
1364
+ }
1365
+ ensureVersionOverlap(
1366
+ blockDepDef?.version,
1367
+ blockDep.version,
1368
+ `Block "${block.name}" version: ${block.version} is not compatible with block "${blockDep.name}" `
1369
+ );
1370
+ }
1371
+ }
1372
+ }
1373
+ async function checkVersionsCompatibility() {
1374
+ debug("checkVersionsCompatibility");
1375
+ const template = processTemplate(getTemplateDef());
1376
+ const usedBlocks = processBlocks(getUsedBlocksDef());
1377
+ const basesVersion = processBases(getBloxFile());
1378
+ basesVersion[template.name] = { version: template.version, commit: "" };
1379
+ await _checkVersionsCompatibility(template, usedBlocks, basesVersion);
1380
+ }
1381
+
1236
1382
  // src/services/registry.ts
1237
1383
  var import_node_path13 = __toESM(require("path"));
1238
1384
  var import_fs_extra10 = __toESM(require("fs-extra"));
@@ -1246,7 +1392,7 @@ var getConfiguredRegistryDirs = () => {
1246
1392
  const config = getLocalConfig();
1247
1393
  return config.registries.map((registry) => ({
1248
1394
  registry,
1249
- dir: import_node_path13.default.join(registriesDataPath, cacheDirNameForRegistry(registry))
1395
+ dir: import_node_path13.default.isAbsolute(registry) ? registry : import_node_path13.default.join(registriesDataPath, cacheDirNameForRegistry(registry))
1250
1396
  }));
1251
1397
  };
1252
1398
  var syncRegistries = async (branch) => {
@@ -1259,6 +1405,10 @@ var syncRegistries = async (branch) => {
1259
1405
  await Promise.all(
1260
1406
  config.registries.map(async (registry) => {
1261
1407
  debug(`update registry: ${registry}`);
1408
+ if (import_node_path13.default.isAbsolute(registry)) {
1409
+ debug(`local registry (absolute path): ${registry}`);
1410
+ return;
1411
+ }
1262
1412
  const repoName = cacheDirNameForRegistry(registry);
1263
1413
  const repoDir = import_node_path13.default.join(registriesDataPath, repoName);
1264
1414
  if (!import_fs_extra10.default.existsSync(repoDir)) {
@@ -1266,10 +1416,26 @@ var syncRegistries = async (branch) => {
1266
1416
  cwd: registriesDataPath,
1267
1417
  depth: 1
1268
1418
  });
1269
- } else if (import_fs_extra10.default.existsSync(import_node_path13.default.join(repoDir, ".git"))) {
1419
+ return;
1420
+ }
1421
+ if (!import_fs_extra10.default.existsSync(import_node_path13.default.join(repoDir, ".git"))) {
1422
+ debug(`local registry: ${registry}`);
1423
+ return;
1424
+ }
1425
+ try {
1270
1426
  await git.update({ cwd: repoDir });
1271
- } else {
1272
- debug(`local registry`);
1427
+ } catch (e) {
1428
+ const hasConflicts2 = await git.hasConflicts(repoDir);
1429
+ if (hasConflicts2) {
1430
+ debug(`Registry has conflicts, recreating: ${registry}`);
1431
+ await import_fs_extra10.default.remove(repoDir);
1432
+ await git.clone(registry, repoName, branch, {
1433
+ cwd: registriesDataPath,
1434
+ depth: 1
1435
+ });
1436
+ return;
1437
+ }
1438
+ import_prompts2.log.error(`Failed to update registry: ${e}`);
1273
1439
  }
1274
1440
  })
1275
1441
  );
@@ -1297,10 +1463,11 @@ var getAvailableTemplates = async () => {
1297
1463
  block.source = data.baseUrl + block.source;
1298
1464
  }
1299
1465
  });
1466
+ const resolvedTemplate = template;
1300
1467
  if (templates[templateName]) {
1301
- templates[templateName] = (0, import_merge.default)(templates[templateName], template);
1468
+ templates[templateName] = (0, import_merge.default)(templates[templateName], resolvedTemplate);
1302
1469
  } else {
1303
- templates[templateName] = template;
1470
+ templates[templateName] = resolvedTemplate;
1304
1471
  }
1305
1472
  });
1306
1473
  }
@@ -1338,97 +1505,6 @@ var getAvailableVersions = async (source) => {
1338
1505
  }
1339
1506
  };
1340
1507
 
1341
- // src/services/versions/checkCompatibility.ts
1342
- function processDependencyVersion(dep) {
1343
- if (!dep.version) dep.version = 0;
1344
- return dep;
1345
- }
1346
- function processTemplate(def) {
1347
- debug("processTemplate");
1348
- if (!def.version) def.version = 0;
1349
- Object.values(def.bases || {}).forEach(processDependencyVersion);
1350
- return def;
1351
- }
1352
- function processBases(info) {
1353
- debug("processBases");
1354
- if (!info || !info.checkpoints) return {};
1355
- Object.values(info.checkpoints).forEach((base) => {
1356
- if (!base.version) base.version = 0;
1357
- });
1358
- return info.checkpoints;
1359
- }
1360
- function processBlocks(defs) {
1361
- debug("processBlocks");
1362
- defs.forEach((def) => {
1363
- if (!def.version) def.version = 0;
1364
- def.dependencies?.forEach(processDependencyVersion);
1365
- def.templates?.forEach(processDependencyVersion);
1366
- });
1367
- return defs;
1368
- }
1369
- function ensureVersionOverlap(version2 = 0, range = 0, mismatchMessage) {
1370
- if (typeof range === "number") {
1371
- range = [range, range];
1372
- }
1373
- const match = version2 >= range[0] && version2 <= range[1];
1374
- if (!match) {
1375
- const requiredVersionText = range[0] === range[1] ? `${range[0]}` : `min: ${range[0]}, max: ${range[1]}`;
1376
- throw new Error(
1377
- normalizeLogMessage(`
1378
- ${mismatchMessage}
1379
- current version: ${version2}
1380
- required version: ${requiredVersionText}
1381
- `)
1382
- );
1383
- }
1384
- }
1385
- async function _checkVersionsCompatibility(template, usedBlocks, basesVersion) {
1386
- for (const templateBaseDep of template.bases || []) {
1387
- const currentVersion = basesVersion[templateBaseDep.name]?.version;
1388
- ensureVersionOverlap(
1389
- currentVersion,
1390
- templateBaseDep.version,
1391
- `Template "${template.name}" version: ${template.version} is not compatible with base "${templateBaseDep.name}"`
1392
- );
1393
- }
1394
- for (const block of usedBlocks) {
1395
- for (const blockTemplateDep of block.templates || []) {
1396
- const currentTemplate = basesVersion[blockTemplateDep.name];
1397
- if (!currentTemplate) {
1398
- throw new Error(
1399
- `Block "${block.name}" version: ${block.version} depends on missing template "${blockTemplateDep.name}" `
1400
- );
1401
- }
1402
- ensureVersionOverlap(
1403
- currentTemplate?.version,
1404
- blockTemplateDep.version,
1405
- `Block "${block.name}" version: ${block.version} is not compatible with template "${blockTemplateDep.name}" `
1406
- );
1407
- }
1408
- for (const blockDep of block.dependencies || []) {
1409
- const blockDepDef = usedBlocks.find((b) => b.name === blockDep.name);
1410
- if (!blockDepDef) {
1411
- throw new Error(
1412
- `Block "${block.name}" version: ${block.version} depends on missing block "${blockDep.name}" `
1413
- );
1414
- }
1415
- ensureVersionOverlap(
1416
- blockDepDef?.version,
1417
- blockDep.version,
1418
- `Block "${block.name}" version: ${block.version} is not compatible with block "${blockDep.name}" `
1419
- );
1420
- }
1421
- }
1422
- }
1423
- async function checkVersionsCompatibility() {
1424
- debug("checkVersionsCompatibility");
1425
- const template = processTemplate(getTemplateDef());
1426
- const usedBlocks = processBlocks(getUsedBlocksDef());
1427
- const basesVersion = processBases(getBloxFile());
1428
- basesVersion[template.name] = { version: template.version, commit: "" };
1429
- await _checkVersionsCompatibility(template, usedBlocks, basesVersion);
1430
- }
1431
-
1432
1508
  // src/services/versions/select.ts
1433
1509
  async function selectVersion(source, fromCommit) {
1434
1510
  const versionsData = await getAvailableVersions(source);
@@ -1461,89 +1537,348 @@ async function selectVersion(source, fromCommit) {
1461
1537
  return versionsData[version2]?.lastCommit;
1462
1538
  }
1463
1539
 
1464
- // src/commands/add/index.ts
1465
- var addBlock = async (block, blocks, branch, destination) => {
1466
- const blockRegistryData = blocks[block];
1467
- if (!destination) {
1468
- destination = blockRegistryData?.destination || block;
1540
+ // src/services/add.ts
1541
+ function recordResult(results, result) {
1542
+ const index = results.findIndex((previous) => previous.block === result.block);
1543
+ if (index === -1) {
1544
+ results.push(result);
1545
+ } else if (result.status !== "skipped") {
1546
+ results[index] = result;
1469
1547
  }
1470
- const blockPath = `blocks/${destination}`;
1471
- let newBlockAdded = false;
1472
- if (!import_fs_extra11.default.existsSync(blockPath)) {
1473
- newBlockAdded = true;
1474
- await runTask(
1475
- { start: `Fetching block: ${block}`, end: `Added block: ${block}` },
1476
- async () => {
1477
- const blockSource = blockRegistryData?.source || "";
1478
- await git.clone(blockSource, blockPath, branch);
1479
- let commit2 = await selectVersion(blockSource);
1480
- if (commit2) {
1481
- await git.resetToCommit(commit2, blockPath);
1482
- } else {
1483
- commit2 = await git.getLatestCommitFromPath(blockPath);
1484
- }
1485
- await git.unInit(blockPath);
1486
- await replacePlaceholders(blockPath, {});
1487
- await migrateAll();
1488
- const def = getBlockDef(blockPath);
1489
- await deletePattern(blockPath, def.ignore);
1490
- updateCheckpoint(block, { commit: commit2, branch }, blockPath);
1491
- }
1492
- );
1493
- await runLifecycleHookWithTask(blockPath, "init", "Run block init");
1494
- await runLifecycleHookWithTask(blockPath, "add", "Run block add");
1495
- } else {
1496
- debug(`${block} already exists`);
1548
+ }
1549
+ function getInstalledBlockNames() {
1550
+ return new Set(
1551
+ getUsedBlocks().flatMap(({ definition, checkpoints }) => [
1552
+ definition.name,
1553
+ ...Object.keys(checkpoints || {})
1554
+ ])
1555
+ );
1556
+ }
1557
+ function findDependents(oldNames, ownedDir) {
1558
+ if (!import_fs_extra11.default.existsSync(blocksDir)) return [];
1559
+ return import_fs_extra11.default.readdirSync(blocksDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => import_node_path14.default.join(blocksDir, entry.name)).filter((dir) => import_node_path14.default.resolve(dir) !== import_node_path14.default.resolve(ownedDir)).filter(
1560
+ (dir) => getBloxFile(dir).definition?.dependencies?.some(
1561
+ (d) => oldNames.has(d.name)
1562
+ )
1563
+ );
1564
+ }
1565
+ function renameDependency(dir, oldNames, newName) {
1566
+ const file = getBloxFile(dir);
1567
+ for (const dependency of file.definition.dependencies || []) {
1568
+ if (oldNames.has(dependency.name)) dependency.name = newName;
1497
1569
  }
1498
- const blockDef = getBlockDef(blockPath);
1499
- for (const dep of blockDef?.dependencies || []) {
1500
- const depNew = await addBlock(dep.name, blocks);
1501
- newBlockAdded = newBlockAdded || depNew;
1570
+ saveBloxFile(file, dir);
1571
+ }
1572
+ function errorMessage(cause) {
1573
+ return cause instanceof Error ? cause.message : String(cause);
1574
+ }
1575
+ function assertNoSymlinkParents(filename) {
1576
+ const root = import_node_path14.default.resolve(".");
1577
+ for (let parent = import_node_path14.default.dirname(import_node_path14.default.resolve(filename)); parent !== root; parent = import_node_path14.default.dirname(parent)) {
1578
+ if (parent === import_node_path14.default.dirname(parent)) throw new Error(`Path outside project: ${filename}`);
1579
+ if (import_fs_extra11.default.existsSync(parent) && import_fs_extra11.default.lstatSync(parent).isSymbolicLink()) {
1580
+ throw new Error(`Symbolic link in block destination: ${filename}`);
1581
+ }
1502
1582
  }
1503
- return newBlockAdded;
1504
- };
1505
- var add2 = command("add").description("Add block to app").alias("a").argument("[blocks...]", "Blocks to be added").option("--branch <name>", "branch name").option("--dest <name>", "destination dir").action(async (selectedBlocks, { branch, dest }) => {
1506
- if (await git.hasUncommittedChanges()) {
1507
- import_prompts2.log.warn(fmt.yellow("Make sure to commit any changes first"));
1508
- return;
1583
+ }
1584
+ async function snapshot(ownedPath, directory = import_node_path14.default.resolve("."), entries = /* @__PURE__ */ new Map()) {
1585
+ for (const entry of await import_fs_extra11.default.readdir(directory, { withFileTypes: true })) {
1586
+ const filename = import_node_path14.default.join(directory, entry.name);
1587
+ const owned = filename === ownedPath || filename.startsWith(ownedPath + import_node_path14.default.sep);
1588
+ if (!owned && (entry.name === ".git" || entry.name === "node_modules")) continue;
1589
+ entries.set(filename, {
1590
+ directory: entry.isDirectory(),
1591
+ metadata: entry.isFile() && entry.name === ".blox" ? await import_fs_extra11.default.readFile(filename) : void 0
1592
+ });
1593
+ if (entry.isDirectory()) await snapshot(ownedPath, filename, entries);
1509
1594
  }
1510
- await migrateAll();
1511
- await syncRegistries();
1595
+ return entries;
1596
+ }
1597
+ async function cleanup(before, after) {
1598
+ const failures = [];
1599
+ const deletedMetadata = [...before].filter(
1600
+ ([filename, entry]) => entry.metadata && !after.has(filename)
1601
+ );
1602
+ for (const [filename, entry] of [...after, ...deletedMetadata].reverse()) {
1603
+ try {
1604
+ assertNoSymlinkParents(filename);
1605
+ if (!before.has(filename)) {
1606
+ if (entry.directory) {
1607
+ await import_fs_extra11.default.rmdir(filename);
1608
+ } else {
1609
+ await import_fs_extra11.default.unlink(filename);
1610
+ }
1611
+ } else {
1612
+ const original = before.get(filename)?.metadata;
1613
+ if (original && !await import_fs_extra11.default.pathExists(filename)) {
1614
+ const existing = await import_fs_extra11.default.lstat(filename).catch((cause) => {
1615
+ if (cause.code !== "ENOENT") throw cause;
1616
+ return void 0;
1617
+ });
1618
+ if (existing) {
1619
+ throw new Error(`Cannot restore metadata through a symbolic link: ${filename}`);
1620
+ }
1621
+ await import_fs_extra11.default.outputFile(filename, original);
1622
+ } else if (original && entry.metadata && !original.equals(entry.metadata) && (await import_fs_extra11.default.lstat(filename)).isFile() && (await import_fs_extra11.default.readFile(filename)).equals(entry.metadata)) {
1623
+ await import_fs_extra11.default.writeFile(filename, original);
1624
+ }
1625
+ }
1626
+ } catch (cause) {
1627
+ const code = cause.code;
1628
+ if (code !== "ENOENT" && code !== "ENOTEMPTY" && code !== "EEXIST") {
1629
+ failures.push(`${filename}: ${errorMessage(cause)}`);
1630
+ }
1631
+ }
1632
+ }
1633
+ if (failures.length) throw new Error(`Cleanup incomplete: ${failures.join("; ")}`);
1634
+ }
1635
+ async function addBlockWithResult(block, blocks, results, branch, destination, visiting = /* @__PURE__ */ new Set(), isDependency = false) {
1636
+ if (visiting.has(block)) return false;
1637
+ const warnings = [];
1638
+ let before;
1639
+ let after;
1640
+ let backupPath;
1641
+ let oldNames;
1642
+ debug(`blocks[block]: ${blocks[block]?.destination}`);
1643
+ const blockPath = `${blocksDir}/${destination || blocks[block]?.destination || block}`;
1644
+ debug(`Block path resolved to: ${blockPath}`);
1645
+ try {
1646
+ const installed = getInstalledBlockNames().has(block);
1647
+ if (!installed && !blocks[block]) {
1648
+ throw new Error(`Selected blocks not available in registries: ${block}`);
1649
+ }
1650
+ const occupied = await import_fs_extra11.default.pathExists(blockPath);
1651
+ if (installed && (isDependency || !occupied)) {
1652
+ recordResult(results, { block, status: "skipped", reason: "Already installed" });
1653
+ return false;
1654
+ }
1655
+ if (!blocks[block]) throw new Error(`Selected blocks not available in registries: ${block}`);
1656
+ const relative = import_node_path14.default.relative(import_node_path14.default.resolve(blocksDir), import_node_path14.default.resolve(blockPath));
1657
+ if (!relative || relative === ".." || relative.startsWith(`..${import_node_path14.default.sep}`) || import_node_path14.default.isAbsolute(relative)) {
1658
+ throw new Error(`Invalid block destination: ${blockPath}`);
1659
+ }
1660
+ assertNoSymlinkParents(blockPath);
1661
+ visiting.add(block);
1662
+ if (occupied) {
1663
+ const replace = await confirm({
1664
+ message: `Block destination already exists: ${blockPath}. Replace it?`,
1665
+ initialValue: false
1666
+ });
1667
+ if (!replace) {
1668
+ recordResult(results, { block, status: "skipped", reason: "Destination already exists" });
1669
+ return false;
1670
+ }
1671
+ const old = getBloxFile(blockPath);
1672
+ oldNames = new Set(
1673
+ [old.definition?.name, ...Object.keys(old.checkpoints || {})].filter(
1674
+ (name) => !!name && name !== block
1675
+ )
1676
+ );
1677
+ }
1678
+ before = await snapshot(import_node_path14.default.resolve(blockPath));
1679
+ if (occupied) {
1680
+ backupPath = await import_fs_extra11.default.mkdtemp(import_node_path14.default.join(import_node_os2.default.tmpdir(), "blox-replaced-"));
1681
+ await import_fs_extra11.default.move(blockPath, import_node_path14.default.join(backupPath, "block"));
1682
+ }
1683
+ await runTask(
1684
+ { start: `Fetching block: ${block}`, end: `Fetched block: ${block}` },
1685
+ async () => {
1686
+ const source = blocks[block]?.source || "";
1687
+ await git.clone(source, blockPath, branch);
1688
+ let commit2 = await selectVersion(source);
1689
+ if (commit2) {
1690
+ await git.resetToCommit(commit2, blockPath);
1691
+ } else {
1692
+ commit2 = await git.getLatestCommitFromPath(blockPath);
1693
+ }
1694
+ await git.unInit(blockPath);
1695
+ await replacePlaceholders(blockPath, {});
1696
+ await migrateAll();
1697
+ const definition = getBlockDef(blockPath);
1698
+ if (!definition) throw new Error(`Missing block definition: ${blockPath}/.blox`);
1699
+ await deletePattern(blockPath, definition.ignore);
1700
+ updateCheckpoint(block, { commit: commit2, branch }, blockPath);
1701
+ }
1702
+ );
1703
+ if (oldNames?.size) {
1704
+ const replaced = oldNames;
1705
+ const dependents = findDependents(replaced, blockPath);
1706
+ if (dependents.length) {
1707
+ const names = [...oldNames].join(", ");
1708
+ const rewrite = await confirm({
1709
+ message: `${dependents.length} block(s) depend on "${names}". Point them to "${block}"?`,
1710
+ initialValue: false
1711
+ });
1712
+ if (rewrite) {
1713
+ dependents.forEach((dir) => renameDependency(dir, replaced, block));
1714
+ } else {
1715
+ import_prompts2.log.warn(`Blocks still referencing replaced "${names}": ${dependents.join(", ")}`);
1716
+ }
1717
+ }
1718
+ }
1719
+ for (const hook of ["init", "add"]) {
1720
+ try {
1721
+ await runLifecycleHookWithTask(blockPath, hook, `Run block ${hook}`);
1722
+ } catch (cause) {
1723
+ const message = `${block}: ${hook} hook failed: ${errorMessage(cause)}`;
1724
+ import_prompts2.log.error(message);
1725
+ const shouldContinue = await confirm({
1726
+ message: `Continue adding ${block} despite the failed ${hook} hook?`,
1727
+ initialValue: true
1728
+ });
1729
+ if (!shouldContinue) {
1730
+ throw new Error(message, { cause });
1731
+ }
1732
+ warnings.push(message);
1733
+ import_prompts2.log.warn(`Adding ${block} with a warning: ${message}`);
1734
+ }
1735
+ }
1736
+ after = await snapshot(import_node_path14.default.resolve(blockPath));
1737
+ for (const dependency of getBlockDef(blockPath).dependencies || []) {
1738
+ await addBlockWithResult(dependency.name, blocks, results, void 0, void 0, visiting, true);
1739
+ }
1740
+ if (backupPath) await import_fs_extra11.default.remove(backupPath);
1741
+ recordResult(results, { block, status: warnings.length ? "warning" : "added", warnings });
1742
+ return true;
1743
+ } catch (cause) {
1744
+ let reason = errorMessage(cause);
1745
+ if (before) {
1746
+ try {
1747
+ await cleanup(before, after || await snapshot(import_node_path14.default.resolve(blockPath)));
1748
+ } catch (cleanupError) {
1749
+ reason += `; ${errorMessage(cleanupError)}`;
1750
+ }
1751
+ }
1752
+ if (backupPath) {
1753
+ try {
1754
+ await import_fs_extra11.default.remove(blockPath);
1755
+ await import_fs_extra11.default.move(import_node_path14.default.join(backupPath, "block"), blockPath);
1756
+ await import_fs_extra11.default.remove(backupPath);
1757
+ } catch (restoreError) {
1758
+ reason += `; failed to restore previous block (kept at ${backupPath}): ${errorMessage(restoreError)}`;
1759
+ }
1760
+ }
1761
+ recordResult(results, { block, status: "failed", reason });
1762
+ throw new Error(reason, { cause });
1763
+ } finally {
1764
+ visiting.delete(block);
1765
+ }
1766
+ }
1767
+ async function addBlocks(selected, blocks, branch, destination) {
1768
+ const results = [];
1769
+ for (const block of new Set(selected)) {
1770
+ try {
1771
+ await addBlockWithResult(block, blocks, results, branch, destination);
1772
+ } catch {
1773
+ continue;
1774
+ }
1775
+ }
1776
+ return results;
1777
+ }
1778
+
1779
+ // src/commands/add/utils.ts
1780
+ var import_node_util = require("util");
1781
+ function formatAddSummary(results, terminalWidth = 80) {
1782
+ const count = (status) => results.filter((result) => result.status === status).length;
1783
+ const styles = {
1784
+ added: { symbol: "\u2713", paint: fmt.green },
1785
+ warning: { symbol: "\u26A0", paint: fmt.yellow },
1786
+ failed: { symbol: "\u2717", paint: fmt.red },
1787
+ skipped: { symbol: "\u25CB", paint: fmt.dim }
1788
+ };
1789
+ const rows = [
1790
+ ["Results", fmt.bold],
1791
+ [`\u2713 ${count("added")} added successfully`, fmt.green],
1792
+ [`\u26A0 ${count("warning")} added with warnings`, fmt.yellow],
1793
+ [`\u2717 ${count("failed")} failed`, fmt.red],
1794
+ [`\u25CB ${count("skipped")} skipped`, fmt.dim],
1795
+ ["", fmt.white],
1796
+ ["Details", fmt.bold]
1797
+ ];
1798
+ for (const result of results) {
1799
+ const { symbol, paint } = styles[result.status];
1800
+ rows.push(["", fmt.white], [`${symbol} ${result.block}`, paint]);
1801
+ const details = result.status === "warning" ? result.warnings : [result.reason];
1802
+ for (const detail of details ?? []) {
1803
+ if (!detail) continue;
1804
+ const description = result.status === "skipped" ? `Skipped: ${detail === "Already installed" ? "already installed." : detail}` : detail.startsWith(`${result.block}: `) ? detail.slice(result.block.length + 2) : detail;
1805
+ for (const text2 of description.split(/\r?\n/)) {
1806
+ rows.push([` ${text2}`, fmt.white]);
1807
+ }
1808
+ }
1809
+ if (result.status === "warning") {
1810
+ rows.push([" The block was added, but a lifecycle hook failed.", fmt.white]);
1811
+ }
1812
+ }
1813
+ const title = " BLOX ADD SUMMARY ";
1814
+ const innerWidth = Math.min(
1815
+ Math.max(1, terminalWidth - 6),
1816
+ Math.max(54, ...rows.map(([text2]) => (0, import_node_util.stripVTControlCharacters)(text2).length))
1817
+ );
1818
+ const line = (text2, paint) => `\u2502 ${paint(text2)}${" ".repeat(innerWidth - text2.length)} \u2502`;
1819
+ const lines = [];
1820
+ for (const [text2, paint] of rows) {
1821
+ const plain = (0, import_node_util.stripVTControlCharacters)(text2);
1822
+ const indent = " ".repeat(Math.min(plain.length - plain.trimStart().length, innerWidth - 1));
1823
+ const available = innerWidth - indent.length;
1824
+ let remaining = plain.trimStart();
1825
+ do {
1826
+ const space = remaining.lastIndexOf(" ", available);
1827
+ const end = remaining.length <= available ? remaining.length : space > 0 ? space : available;
1828
+ lines.push(line(indent + remaining.slice(0, end), paint));
1829
+ remaining = remaining.slice(end).trimStart();
1830
+ } while (remaining);
1831
+ }
1832
+ const heading = title.slice(0, innerWidth);
1833
+ return [
1834
+ "",
1835
+ `\u250C\u2500${fmt.bold(heading)}${"\u2500".repeat(innerWidth - heading.length + 3)}\u2510`,
1836
+ line("", fmt.white),
1837
+ ...lines,
1838
+ line("", fmt.white),
1839
+ `\u2514${"\u2500".repeat(innerWidth + 4)}\u2518`,
1840
+ ""
1841
+ ].join("\n");
1842
+ }
1843
+
1844
+ // src/commands/add/index.ts
1845
+ var add2 = command("add").description("Add block to app").alias("a").argument("[blocks...]", "Blocks to be added").option("--branch <name>", "branch name").option("--dest <name>", "destination dir").action(async (selectedBlocks, { branch, dest }) => {
1512
1846
  try {
1847
+ if (await git.hasUncommittedChanges()) {
1848
+ import_prompts2.log.warn(fmt.yellow("Make sure to commit any changes first"));
1849
+ return;
1850
+ }
1851
+ await migrateAll();
1852
+ await syncRegistries();
1513
1853
  const templateDef = getTemplateDef();
1514
1854
  const blocks = await getAvailableBlocks(templateDef);
1855
+ const installed = getInstalledBlockNames();
1515
1856
  let blocksToAdd = Array.isArray(selectedBlocks) ? selectedBlocks : [];
1516
1857
  if (!blocksToAdd.length) {
1517
1858
  blocksToAdd = await multiselect({
1518
1859
  message: "Select blocks to add",
1519
1860
  options: Object.entries(blocks).map(([tmpl, { description }]) => ({
1520
1861
  value: tmpl,
1521
- label: tmpl,
1862
+ label: tmpl + (installed.has(tmpl) ? ` ${fmt.green("(Already installed)")}` : ""),
1522
1863
  hint: description
1523
1864
  }))
1524
1865
  });
1525
1866
  }
1526
1867
  if (!blocksToAdd.length) {
1527
1868
  error("No blocks selected");
1869
+ return;
1528
1870
  }
1529
- const invalidBlocks = blocksToAdd.filter((blockName) => !blocks[blockName]);
1530
- if (invalidBlocks.length) {
1531
- error(`Selected blocks not available in registries: ${invalidBlocks.join(", ")}`);
1532
- }
1533
- let added = false;
1534
- for (const blockName of blocksToAdd) {
1535
- const blockAdded = await addBlock(blockName, blocks, branch, dest);
1536
- added = added || blockAdded;
1537
- }
1538
- if (added) {
1539
- await runLifecycleHookWithTask(".", "add", "Run template add");
1871
+ const results = await addBlocks(blocksToAdd, blocks, branch, dest);
1872
+ if (results.some((result) => result.status === "failed")) process.exitCode = 1;
1873
+ try {
1874
+ if (results.some((result) => result.status === "added" || result.status === "warning")) {
1875
+ await runLifecycleHookWithTask(".", "add", "Run template add");
1876
+ }
1877
+ await checkVersionsCompatibility();
1878
+ } finally {
1879
+ process.stdout.write(formatAddSummary(results, process.stdout.columns || 80));
1540
1880
  }
1541
- await checkVersionsCompatibility();
1542
1881
  } catch (e) {
1543
- if (!isDebugMode()) {
1544
- import_prompts2.log.warn("Error happened, Will rollback changes");
1545
- await git.rollback();
1546
- }
1547
1882
  error(e);
1548
1883
  }
1549
1884
  });
@@ -1573,11 +1908,6 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
1573
1908
 
1574
1909
  // src/services/contribute/constants/index.ts
1575
1910
  var UI_PAGE_SIZE = 15;
1576
- var TARGET_SELECT_PAGE = {
1577
- PREV: "__prev__",
1578
- NEXT: "__next__",
1579
- SEARCH_AGAIN: "__search__"
1580
- };
1581
1911
  var COMMIT_TYPES = [
1582
1912
  { value: "fix", label: "fix: A bug fix (PATCH)" },
1583
1913
  { value: "feat", label: "feat: A new feature (MINOR)" },
@@ -1589,16 +1919,8 @@ var COMMIT_TYPES = [
1589
1919
  { value: "ci", label: "ci: CI configuration (GitLab/GitHub)" }
1590
1920
  ];
1591
1921
 
1592
- // src/services/contribute/types.ts
1593
- var ContributionTargetType = /* @__PURE__ */ ((ContributionTargetType2) => {
1594
- ContributionTargetType2["TEMPLATE"] = "template";
1595
- ContributionTargetType2["BASE"] = "base";
1596
- ContributionTargetType2["BLOCK"] = "block";
1597
- return ContributionTargetType2;
1598
- })(ContributionTargetType || {});
1599
-
1600
1922
  // src/services/contribute/utils/bloxCheckpoint.ts
1601
- var import_node_path14 = __toESM(require("path"));
1923
+ var import_node_path15 = __toESM(require("path"));
1602
1924
  function getCheckpointForTarget(cwd, target) {
1603
1925
  const bloxDir = getBloxDirForTarget(cwd, target);
1604
1926
  const blox = getBloxFile(bloxDir);
@@ -1608,18 +1930,147 @@ function getCheckpointForTarget(cwd, target) {
1608
1930
  }
1609
1931
  function getBloxDirForTarget(cwd, target) {
1610
1932
  if (target.type === "block" /* BLOCK */) {
1611
- return import_node_path14.default.join(cwd, blocksDir, target.name);
1933
+ return import_node_path15.default.join(cwd, blocksDir, target.dir);
1612
1934
  }
1613
1935
  return cwd;
1614
1936
  }
1615
1937
 
1938
+ // src/services/contribute/utils/slugifyTitle.ts
1939
+ function slugifyTitle(title) {
1940
+ const s = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1941
+ return (s || "contribution").slice(0, 80);
1942
+ }
1943
+
1944
+ // src/services/contribute/utils/buildBranchName.ts
1945
+ function buildBranchName(commitType, title) {
1946
+ return `${commitType}/${slugifyTitle(title)}`;
1947
+ }
1948
+
1949
+ // src/services/contribute/utils/getExcludedPrefixesForTarget.ts
1950
+ var import_node_path16 = __toESM(require("path"));
1951
+ var import_fs_extra12 = __toESM(require("fs-extra"));
1952
+ function getExcludedPrefixesForTarget(target, cwd) {
1953
+ if (target.type === "block" /* BLOCK */) {
1954
+ return [];
1955
+ }
1956
+ const excluded = [];
1957
+ const blocksPath = import_node_path16.default.join(cwd, blocksDir);
1958
+ if (import_fs_extra12.default.existsSync(blocksPath)) {
1959
+ const entries = import_fs_extra12.default.readdirSync(blocksPath, { withFileTypes: true });
1960
+ for (const entry of entries) {
1961
+ if (!entry.isDirectory()) continue;
1962
+ const blockBloxFile = import_node_path16.default.join(blocksPath, entry.name, bloxFilePath);
1963
+ if (import_fs_extra12.default.existsSync(blockBloxFile)) {
1964
+ excluded.push(normalizePath(`${blocksDir}/${entry.name}/`));
1965
+ }
1966
+ }
1967
+ }
1968
+ return excluded;
1969
+ }
1970
+
1971
+ // src/services/contribute/utils/getPathPrefixToStrip.ts
1972
+ function getPathPrefixToStrip(target) {
1973
+ if (target.type === "block" /* BLOCK */) {
1974
+ return normalizePath(`${blocksDir}/${target.dir}/`);
1975
+ }
1976
+ return "";
1977
+ }
1978
+
1979
+ // src/services/contribute/utils/shouldExcludeFile.ts
1980
+ function shouldExcludeFile(file, excludedPrefixes) {
1981
+ const f = normalizePath(file);
1982
+ return excludedPrefixes.some((p) => f.startsWith(p));
1983
+ }
1984
+
1985
+ // src/services/contribute/utils/computeTargetChangeHints.ts
1986
+ function targetHintKey(target) {
1987
+ return `${target.type}:${target.name}`;
1988
+ }
1989
+ async function computeTargetChangeHints(opts) {
1990
+ const changedFilesPerCommit = await Promise.all(
1991
+ opts.commits.map((commit2) => git.getChangedFilesInCommit(commit2, opts.cwd))
1992
+ );
1993
+ const changedFiles = [...new Set(changedFilesPerCommit.flat())].map((f) => normalizePath(f));
1994
+ const hints = /* @__PURE__ */ new Map();
1995
+ for (const target of opts.targets) {
1996
+ const subtreePath = getPathPrefixToStrip(target);
1997
+ const exclusion = getExcludedPrefixesForTarget(target, opts.cwd);
1998
+ const hasChanges = changedFiles.some((file) => {
1999
+ if (subtreePath && !file.startsWith(subtreePath)) return false;
2000
+ if (shouldExcludeFile(file, exclusion)) return false;
2001
+ return true;
2002
+ });
2003
+ hints.set(targetHintKey(target), hasChanges);
2004
+ }
2005
+ return hints;
2006
+ }
2007
+
2008
+ // src/services/contribute/utils/discoverContributionTargets.ts
2009
+ var import_node_path17 = __toESM(require("path"));
2010
+ var import_fs_extra13 = __toESM(require("fs-extra"));
2011
+ var readBloxFileIfExists = (cwd) => {
2012
+ const p = import_node_path17.default.join(cwd, bloxFilePath);
2013
+ if (!import_fs_extra13.default.existsSync(p)) return;
2014
+ try {
2015
+ return import_fs_extra13.default.readJSONSync(p);
2016
+ } catch {
2017
+ return;
2018
+ }
2019
+ };
2020
+ var discoverContributionTargets = (cwd) => {
2021
+ const targets = [];
2022
+ const rootBlox = readBloxFileIfExists(cwd);
2023
+ const appTemplateName = rootBlox?.definition?.name;
2024
+ const appTemplateDef = rootBlox?.definition;
2025
+ if (rootBlox?.definition?.name) {
2026
+ targets.push({
2027
+ type: "template" /* TEMPLATE */,
2028
+ name: rootBlox.definition.name,
2029
+ templateName: rootBlox.definition.name,
2030
+ templateDef: appTemplateDef,
2031
+ label: `template/${rootBlox.definition.name}`
2032
+ });
2033
+ for (const base of rootBlox.definition.bases || []) {
2034
+ targets.push({
2035
+ type: "base" /* BASE */,
2036
+ name: base.name,
2037
+ templateDef: appTemplateDef,
2038
+ label: `base/${base.name}`,
2039
+ hint: base.version !== void 0 ? `version: ${JSON.stringify(base.version)}` : void 0
2040
+ });
2041
+ }
2042
+ }
2043
+ const blocksPath = import_node_path17.default.join(cwd, blocksDir);
2044
+ if (import_fs_extra13.default.existsSync(blocksPath)) {
2045
+ const entries = import_fs_extra13.default.readdirSync(blocksPath, { withFileTypes: true });
2046
+ for (const entry of entries) {
2047
+ if (!entry.isDirectory()) continue;
2048
+ const blockDir = entry.name;
2049
+ const blockBlox = readBloxFileIfExists(import_node_path17.default.join(blocksPath, blockDir));
2050
+ if (!blockBlox?.definition?.name) continue;
2051
+ targets.push({
2052
+ type: "block" /* BLOCK */,
2053
+ name: blockBlox.definition.name,
2054
+ dir: blockDir,
2055
+ templateName: appTemplateName,
2056
+ templateDef: appTemplateDef,
2057
+ label: `block/${blockBlox.definition.name}`,
2058
+ hint: blockBlox.definition.version !== void 0 ? `v${blockBlox.definition.version}` : void 0
2059
+ });
2060
+ }
2061
+ }
2062
+ return targets;
2063
+ };
2064
+
1616
2065
  // src/services/contribute/utils/getRepoUrl.ts
2066
+ var MissingRegistrySourceError = class extends Error {
2067
+ };
1617
2068
  var getTargetRepoUrl = async (target) => {
1618
2069
  if (target.type === "template" /* TEMPLATE */ || target.type === "base" /* BASE */) {
1619
2070
  const templates = await getAvailableTemplates();
1620
2071
  const t = templates[target.name];
1621
2072
  if (!t?.source) {
1622
- throw new Error(`No registry source found for template/base: ${target.name}`);
2073
+ throw new MissingRegistrySourceError(`No registry source found for template/base: ${target.name}`);
1623
2074
  }
1624
2075
  return t.source;
1625
2076
  }
@@ -1633,15 +2084,58 @@ var getTargetRepoUrl = async (target) => {
1633
2084
  const blocks = await getAvailableBlocks(templateDef);
1634
2085
  const blockSource = blocks?.[target.name]?.source;
1635
2086
  if (!blockSource) {
1636
- throw new Error(`No registry source found for block: ${target.name}`);
2087
+ throw new MissingRegistrySourceError(`No registry source found for block: ${target.name}`);
1637
2088
  }
1638
2089
  return blockSource;
1639
2090
  };
1640
2091
 
1641
- // src/services/contribute/utils/slugifyTitle.ts
1642
- function slugifyTitle(title) {
1643
- const s = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1644
- return (s || "contribution").slice(0, 80);
2092
+ // src/services/contribute/utils/getUpdateCommand.ts
2093
+ function getUpdateCommand(target) {
2094
+ switch (target.type) {
2095
+ case "block" /* BLOCK */:
2096
+ return `blox update -s block -b ${target.name}`;
2097
+ case "base" /* BASE */:
2098
+ return "blox update -s bases";
2099
+ default:
2100
+ return "blox update";
2101
+ }
2102
+ }
2103
+
2104
+ // src/services/contribute/utils/promptContributionMeta.ts
2105
+ async function promptContributionMeta(flags) {
2106
+ let title = flags.title?.trim();
2107
+ let description = flags.description?.trim();
2108
+ if (!title) {
2109
+ title = await text({
2110
+ message: "Contribution title (conventional commit style recommended)",
2111
+ validate: (v) => v.trim() ? void 0 : "Title is required"
2112
+ });
2113
+ }
2114
+ if (description === void 0) {
2115
+ description = await text({ message: "Description (optional)", defaultValue: "" });
2116
+ }
2117
+ return { title, description };
2118
+ }
2119
+
2120
+ // src/services/contribute/utils/remoteBranchExists.ts
2121
+ async function remoteBranchExists(repoUrl, branch) {
2122
+ try {
2123
+ await git.lsRemote(repoUrl, branch);
2124
+ return true;
2125
+ } catch {
2126
+ return false;
2127
+ }
2128
+ }
2129
+
2130
+ // src/services/contribute/utils/resolveRemoteHead.ts
2131
+ async function resolveRemoteHead(repoUrl, remoteBranch) {
2132
+ try {
2133
+ return await git.lsRemote(repoUrl, remoteBranch);
2134
+ } catch (e) {
2135
+ throw new Error(
2136
+ `Failed to read remote ref for ${repoUrl} (branch ${remoteBranch}). ${e instanceof Error ? e.message : String(e)}`
2137
+ );
2138
+ }
1645
2139
  }
1646
2140
 
1647
2141
  // src/services/contribute/ContributionWorkflow.ts
@@ -1658,25 +2152,219 @@ var ContributionWorkflow = class {
1658
2152
  }
1659
2153
  async runFromFlags(flags) {
1660
2154
  await this.assertAppRepoClean();
1661
- const target = await this.targetSelector.selectTargetInteractive();
1662
- const mode = flags.existing ? "existing" : "new";
1663
- const { title, description } = await this.promptContributionMeta(flags);
1664
2155
  const commits = await this.resolveCommitsFromFlags(flags);
1665
- const branch = await this.resolveContributionBranch({ mode, target, title });
1666
- return this.run({
1667
- target,
1668
- mode,
1669
- title,
1670
- description,
1671
- branch,
1672
- commits
2156
+ const targets = await this.selectTargetsForCommits(commits, flags);
2157
+ await this.assertTargetsUpToDate(targets);
2158
+ const mode = flags.existing ? "existing" : "new";
2159
+ const { title, description } = await promptContributionMeta(flags);
2160
+ const commitType = mode === "new" && title ? await this.promptCommitType() : void 0;
2161
+ const skipped = mode === "new" && title && commitType ? await this.assertNoRemoteBranchConflicts(targets, buildBranchName(commitType, title)) : /* @__PURE__ */ new Map();
2162
+ const results = [];
2163
+ for (const target of targets) {
2164
+ const reason = skipped.get(target);
2165
+ if (reason) {
2166
+ results.push({ target, success: true, skipped: reason });
2167
+ continue;
2168
+ }
2169
+ results.push(
2170
+ await this.contributeToTarget(target, commits, {
2171
+ mode,
2172
+ title,
2173
+ description,
2174
+ commitType
2175
+ })
2176
+ );
2177
+ }
2178
+ this.logSummary(results);
2179
+ await this.reportAndOpenPullRequests(results);
2180
+ return results;
2181
+ }
2182
+ async selectTargetsForCommits(commits, flags) {
2183
+ const allTargets = discoverContributionTargets(this.ctx.cwd);
2184
+ if (flags.type && flags.name) {
2185
+ const target = allTargets.find((item) => item.type === flags.type && item.name === flags.name);
2186
+ if (target) return [target];
2187
+ this.logger.warn(
2188
+ `Contribution target ${flags.type}/${flags.name} not found. Select from the available targets.`
2189
+ );
2190
+ } else if (flags.type || flags.name) {
2191
+ this.logger.warn("Both --type and --name are needed to select a target. Select from the available targets.");
2192
+ }
2193
+ const changeHints = await computeTargetChangeHints({
2194
+ cwd: this.ctx.cwd,
2195
+ commits,
2196
+ targets: allTargets
2197
+ });
2198
+ return this.targetSelector.selectMultipleTargetsInteractive({ changeHints });
2199
+ }
2200
+ async assertTargetsUpToDate(targets) {
2201
+ if (this.ctx.force) {
2202
+ return;
2203
+ }
2204
+ const outdated = [];
2205
+ await runTask(
2206
+ {
2207
+ start: "Checking whether selected targets are up to date",
2208
+ end: "Checked whether selected targets are up to date"
2209
+ },
2210
+ async () => {
2211
+ for (const target of targets) {
2212
+ if (target.type === "template" /* TEMPLATE */) continue;
2213
+ try {
2214
+ const repoUrl = await getTargetRepoUrl(target);
2215
+ const checkpoint = getCheckpointForTarget(this.ctx.cwd, target);
2216
+ if (!checkpoint.commit) continue;
2217
+ const remoteHead = await resolveRemoteHead(
2218
+ repoUrl,
2219
+ checkpoint.branch || defaultBranch
2220
+ );
2221
+ if (checkpoint.commit !== remoteHead) outdated.push(target);
2222
+ } catch (cause) {
2223
+ if (!(cause instanceof MissingRegistrySourceError)) throw cause;
2224
+ }
2225
+ }
2226
+ }
2227
+ );
2228
+ if (!outdated.length) {
2229
+ return;
2230
+ }
2231
+ const blocks = outdated.filter((t) => t.type === "block" /* BLOCK */);
2232
+ const others = outdated.filter((t) => t.type !== "block" /* BLOCK */);
2233
+ const lines = others.map(
2234
+ (t) => `The selected target "${t.name}" is outdated. Please run "${getUpdateCommand(t)}", then retry "blox contribute".`
2235
+ );
2236
+ if (blocks.length) {
2237
+ const plural = blocks.length > 1;
2238
+ lines.unshift(
2239
+ `The selected ${plural ? "targets" : "target"} ${blocks.map((t) => `"${t.name}"`).join(", ")} ${plural ? "are" : "is"} outdated. Please run "blox update -s block -b ${blocks.map((t) => t.name).join(" ")}", then retry "blox contribute".`
2240
+ );
2241
+ }
2242
+ throw new Error(lines.join("\n"));
2243
+ }
2244
+ async assertNoRemoteBranchConflicts(targets, branch) {
2245
+ const conflicts = [];
2246
+ const clear = [];
2247
+ const skipped = /* @__PURE__ */ new Map();
2248
+ await runTask(
2249
+ {
2250
+ start: `Checking remote branches for conflicts with ${branch}`,
2251
+ end: `Checked remote branches for conflicts with ${branch}`
2252
+ },
2253
+ async () => {
2254
+ for (const target of targets) {
2255
+ try {
2256
+ const repoUrl = await getTargetRepoUrl(target);
2257
+ const exists = await remoteBranchExists(repoUrl, branch);
2258
+ (exists ? conflicts : clear).push(target);
2259
+ } catch (cause) {
2260
+ if (!(cause instanceof MissingRegistrySourceError)) throw cause;
2261
+ skipped.set(target, cause.message);
2262
+ this.logger.warn(`Skipping ${target.type}/${target.name}: ${cause.message}`);
2263
+ }
2264
+ }
2265
+ }
2266
+ );
2267
+ if (!conflicts.length) {
2268
+ return skipped;
2269
+ }
2270
+ import_prompts2.log.message(
2271
+ [
2272
+ `
2273
+ ${fmt.bold("Branch conflict check")} for ${fmt.cyan(branch)}`,
2274
+ ...conflicts.map(
2275
+ (t) => ` ${fmt.red("\u2717")} ${t.type}/${t.name} - branch already exists on remote. Use --existing to contribute to it.`
2276
+ ),
2277
+ ...clear.map(
2278
+ (t) => ` ${fmt.green("\u2713")} ${t.type}/${t.name} - no conflict, ready to contribute.`
2279
+ ),
2280
+ ""
2281
+ ].join("\n")
2282
+ );
2283
+ throw new Error(
2284
+ `Branch "${branch}" already exists on remote for ${conflicts.length} target(s). Re-run with --existing to contribute to them, or choose a different title.`
2285
+ );
2286
+ }
2287
+ async resolveBranchForTarget(target, mode, title, commitType) {
2288
+ if (mode === "new" && title && commitType) {
2289
+ return buildBranchName(commitType, title);
2290
+ }
2291
+ if (mode === "existing") {
2292
+ return this.resolveExistingBranch(target);
2293
+ }
2294
+ return void 0;
2295
+ }
2296
+ async contributeToTarget(target, commits, opts) {
2297
+ this.logger.info(`Starting contribution for ${target.type}/${target.name}`);
2298
+ try {
2299
+ const branch = await this.resolveBranchForTarget(
2300
+ target,
2301
+ opts.mode,
2302
+ opts.title,
2303
+ opts.commitType
2304
+ );
2305
+ const result = await this.run({
2306
+ target,
2307
+ mode: opts.mode,
2308
+ title: opts.title,
2309
+ description: opts.description,
2310
+ branch,
2311
+ commits
2312
+ });
2313
+ return { target, success: true, result };
2314
+ } catch (e) {
2315
+ const message = e instanceof Error ? e.message : String(e);
2316
+ if (e instanceof MissingRegistrySourceError) {
2317
+ this.logger.warn(`Skipping ${target.type}/${target.name}: ${message}`);
2318
+ return { target, success: true, skipped: message };
2319
+ }
2320
+ this.logger.error(
2321
+ `Contribution failed for ${target.type}/${target.name}. Skipping to next target.`,
2322
+ message
2323
+ );
2324
+ return { target, success: false, error: message };
2325
+ }
2326
+ }
2327
+ logSummary(results) {
2328
+ const succeeded = results.filter((r) => r.success && !r.skipped);
2329
+ const failed = results.filter((r) => !r.success);
2330
+ const lines = results.map((r) => {
2331
+ if (r.skipped) {
2332
+ return ` ${fmt.yellow("\u279C ")} ${r.target.type}/${r.target.name} - skipped (${r.skipped})`;
2333
+ }
2334
+ if (!r.success) {
2335
+ return ` ${fmt.red("\u2717 ")} ${r.target.type}/${r.target.name} - ${r.error}`;
2336
+ }
2337
+ if (r.result?.skipped) {
2338
+ return ` ${fmt.yellow("\u279C ")} ${r.target.type}/${r.target.name} - skipped (no changes applied)`;
2339
+ }
2340
+ return ` ${fmt.green("\u2713 ")} ${r.target.type}/${r.target.name}`;
1673
2341
  });
2342
+ import_prompts2.log.message(
2343
+ `
2344
+ ${fmt.bold("Contribution summary")} (${succeeded.length}/${results.length} succeeded)
2345
+ ` + lines.join("\n") + "\n"
2346
+ );
2347
+ if (failed.length) {
2348
+ this.logger.warn(`${failed.length} target(s) failed. See details above.`);
2349
+ }
2350
+ }
2351
+ async reportAndOpenPullRequests(results) {
2352
+ const prUrls = results.filter((r) => r.success && r.result?.prUrl).map((r) => r.result.prUrl);
2353
+ if (!prUrls.length) {
2354
+ return;
2355
+ }
2356
+ import_prompts2.log.message(
2357
+ `
2358
+ ${fmt.bold("Pull Request URLs")}
2359
+ ` + prUrls.map((url) => ` ${fmt.cyan(url)}`).join("\n") + "\n"
2360
+ );
2361
+ await this.pullRequest.openPullRequestUrls(prUrls);
1674
2362
  }
1675
2363
  async run(input) {
1676
2364
  const repoUrl = await getTargetRepoUrl(input.target);
1677
2365
  const checkpoint = getCheckpointForTarget(this.ctx.cwd, input.target);
1678
2366
  const remoteBranch = checkpoint.branch || defaultBranch;
1679
- const remoteHead = await this.resolveRemoteHeadOrThrow(repoUrl, remoteBranch);
2367
+ const remoteHead = await resolveRemoteHead(repoUrl, remoteBranch);
1680
2368
  this.ensureCheckpointValid(input, checkpoint, remoteHead);
1681
2369
  this.logger.debug("preflight.resolved", {
1682
2370
  repoUrl,
@@ -1701,7 +2389,9 @@ var ContributionWorkflow = class {
1701
2389
  branch,
1702
2390
  title: input.title
1703
2391
  });
1704
- const { title, description } = this.deriveTitleAndDescription(input);
2392
+ const title = input.title || "contribution title";
2393
+ const description = input.description || "";
2394
+ const beforeHead = await git.getLatestCommitFromPath(tmpCwd);
1705
2395
  await this.commitApplier.applyCommits({
1706
2396
  appRepoCwd: this.ctx.cwd,
1707
2397
  tmpRepoCwd: tmpCwd,
@@ -1710,6 +2400,13 @@ var ContributionWorkflow = class {
1710
2400
  title,
1711
2401
  description
1712
2402
  });
2403
+ const afterHead = await git.getLatestCommitFromPath(tmpCwd);
2404
+ if (beforeHead === afterHead) {
2405
+ this.logger.warn(
2406
+ `Skipped opening a PR for ${input.target.type}/${input.target.name}: no changes were left for this target after filtering.`
2407
+ );
2408
+ return { branch, commits: input.commits, skipped: true };
2409
+ }
1713
2410
  await this.pullRequest.pushBranch({
1714
2411
  cwd: tmpCwd,
1715
2412
  remote: "origin",
@@ -1728,16 +2425,18 @@ var ContributionWorkflow = class {
1728
2425
  title,
1729
2426
  description
1730
2427
  });
1731
- const pr = await this.pullRequest.openPullRequestPage({
2428
+ const prUrl = this.pullRequest.resolvePullRequestUrl({
1732
2429
  repoUrl,
1733
2430
  sourceBranch: branch,
1734
2431
  targetBranch: remoteBranch
1735
2432
  });
1736
- this.logCompletion(pr.prUrl);
2433
+ import_prompts2.log.success(
2434
+ fmt.green(`Contribution flow completed for ${input.target.type}/${input.target.name}.`)
2435
+ );
1737
2436
  return {
1738
2437
  branch,
1739
2438
  commits: input.commits,
1740
- prUrl: pr.prUrl
2439
+ prUrl
1741
2440
  };
1742
2441
  }
1743
2442
  async assertAppRepoClean() {
@@ -1747,20 +2446,6 @@ var ContributionWorkflow = class {
1747
2446
  );
1748
2447
  }
1749
2448
  }
1750
- async promptContributionMeta(flags) {
1751
- let title = flags.title?.trim();
1752
- let description = flags.description?.trim();
1753
- if (!title) {
1754
- title = await text({
1755
- message: "Contribution title (conventional commit style recommended)",
1756
- validate: (v) => v.trim() ? void 0 : "Title is required"
1757
- });
1758
- }
1759
- if (description === void 0) {
1760
- description = await text({ message: "Description (optional)", defaultValue: "" });
1761
- }
1762
- return { title, description };
1763
- }
1764
2449
  async resolveCommitsFromFlags(flags) {
1765
2450
  if (flags.commits) {
1766
2451
  const commits = flags.commits.split(",").map((c) => c.trim()).filter(Boolean);
@@ -1773,46 +2458,32 @@ var ContributionWorkflow = class {
1773
2458
  cwd: this.ctx.cwd
1774
2459
  });
1775
2460
  }
1776
- async resolveContributionBranch(opts) {
1777
- const { mode, target, title } = opts;
1778
- if (mode === "new" && title) {
1779
- const commitType = await select({
1780
- message: "Select the commit type for this contribution:",
1781
- options: COMMIT_TYPES
1782
- });
1783
- return `${commitType}/${slugifyTitle(title)}`;
2461
+ async promptCommitType() {
2462
+ return select({
2463
+ message: "Select the commit type for this contribution:",
2464
+ options: COMMIT_TYPES
2465
+ });
2466
+ }
2467
+ async resolveExistingBranch(target) {
2468
+ import_prompts2.log.info("Fetching remote branches for the existing contribution...");
2469
+ const repoUrl = await getTargetRepoUrl(target);
2470
+ const remoteBranches = await git.listRemoteBranches(repoUrl);
2471
+ if (remoteBranches.length === 0) {
2472
+ throw new Error("No remote branches found to contribute to.");
1784
2473
  }
1785
- if (mode === "existing") {
1786
- import_prompts2.log.info("Fetching remote branches for the existing contribution...");
1787
- const repoUrl = await getTargetRepoUrl(target);
1788
- const remoteBranches = await git.listRemoteBranches(repoUrl);
1789
- if (remoteBranches.length === 0) {
1790
- throw new Error("No remote branches found to contribute to.");
1791
- }
1792
- const selectedBranch = await select({
1793
- message: "Select the existing contribution branch:",
1794
- options: [
1795
- ...remoteBranches.map((b) => ({ label: b, value: b })),
1796
- { label: "Type branch name manually...", value: MANUAL_BRANCH_OPTION }
1797
- ]
2474
+ const selectedBranch = await select({
2475
+ message: "Select the existing contribution branch:",
2476
+ options: [
2477
+ ...remoteBranches.map((b) => ({ label: b, value: b })),
2478
+ { label: "Type branch name manually...", value: MANUAL_BRANCH_OPTION }
2479
+ ]
2480
+ });
2481
+ if (selectedBranch === MANUAL_BRANCH_OPTION) {
2482
+ return await text({
2483
+ message: "Enter branch name:"
1798
2484
  });
1799
- if (selectedBranch === MANUAL_BRANCH_OPTION) {
1800
- return await text({
1801
- message: "Enter branch name:"
1802
- });
1803
- }
1804
- return selectedBranch;
1805
- }
1806
- return void 0;
1807
- }
1808
- async resolveRemoteHeadOrThrow(repoUrl, remoteBranch) {
1809
- try {
1810
- return await git.lsRemote(repoUrl, remoteBranch);
1811
- } catch (e) {
1812
- throw new Error(
1813
- `Failed to read remote ref for ${repoUrl} (branch ${remoteBranch}). ${e instanceof Error ? e.message : String(e)}`
1814
- );
1815
2485
  }
2486
+ return selectedBranch;
1816
2487
  }
1817
2488
  ensureCheckpointValid(input, checkpoint, remoteHead) {
1818
2489
  if (input.target.type === "template" /* TEMPLATE */ && !checkpoint.commit) {
@@ -1829,7 +2500,7 @@ var ContributionWorkflow = class {
1829
2500
  return;
1830
2501
  }
1831
2502
  if (checkpoint.commit !== remoteHead && !this.ctx.force) {
1832
- const hint = input.target.type === "block" /* BLOCK */ ? `Block (${input.target.name}) is outdated. Please run \`blox update -s block -b ${input.target.name}\`.` : `Local checkpoint does not match remote HEAD for ${input.target.type}/${input.target.name}. Run \`blox update\` first.`;
2503
+ const hint = input.target.type === "block" /* BLOCK */ ? `Block (${input.target.name}) is outdated. Please run \`${getUpdateCommand(input.target)}\`.` : `Local checkpoint does not match remote HEAD for ${input.target.type}/${input.target.name}. Run \`${getUpdateCommand(input.target)}\` first.`;
1833
2504
  throw new Error(
1834
2505
  `${hint}
1835
2506
  Expected remote ${remoteHead}, local checkpoint ${checkpoint.commit}.`
@@ -1852,68 +2523,26 @@ Expected remote ${remoteHead}, local checkpoint ${checkpoint.commit}.`
1852
2523
  {
1853
2524
  start: `Create new branch ${branch} from ${checkpointCommit}`,
1854
2525
  end: `Created new branch ${branch}`
1855
- },
1856
- async () => {
1857
- await git.checkout(checkpointCommit, tmpCwd);
1858
- this.logger.debug("branch.create", { branch, from: checkpointCommit });
1859
- await git.createBranch(branch, checkpointCommit, tmpCwd);
1860
- }
1861
- );
1862
- return;
1863
- }
1864
- await git.checkout(branch, tmpCwd);
1865
- }
1866
- deriveTitleAndDescription(input) {
1867
- const title = input.title || "contribution title";
1868
- const description = input.description || "";
1869
- return { title, description };
1870
- }
1871
- logCompletion(prUrl) {
1872
- import_prompts2.log.success(
1873
- fmt.green("Contribution flow completed.") + (prUrl ? `
1874
- Pull Request (new):
1875
- ${prUrl}` : "\nPush completed.")
1876
- );
1877
- }
1878
- };
1879
-
1880
- // src/services/contribute/services/CommitApplierService.ts
1881
- var import_node_path16 = __toESM(require("path"));
1882
- var import_fs_extra13 = __toESM(require("fs-extra"));
1883
-
1884
- // src/services/contribute/config/index.ts
1885
- var tempRepoName = "tmp";
1886
- var bloxConfigControlledKeys = ["checkpoints", "project"];
1887
-
1888
- // src/services/contribute/utils/getExcludedPrefixesForTarget.ts
1889
- var import_node_path15 = __toESM(require("path"));
1890
- var import_fs_extra12 = __toESM(require("fs-extra"));
1891
- function getExcludedPrefixesForTarget(target, cwd) {
1892
- if (target.type === "block" /* BLOCK */) {
1893
- return [];
1894
- }
1895
- const excluded = [];
1896
- const blocksPath = import_node_path15.default.join(cwd, blocksDir);
1897
- if (import_fs_extra12.default.existsSync(blocksPath)) {
1898
- const entries = import_fs_extra12.default.readdirSync(blocksPath, { withFileTypes: true });
1899
- for (const entry of entries) {
1900
- if (!entry.isDirectory()) continue;
1901
- const blockBloxFile = import_node_path15.default.join(blocksPath, entry.name, bloxFilePath);
1902
- if (import_fs_extra12.default.existsSync(blockBloxFile)) {
1903
- excluded.push(normalizePath(`${blocksDir}/${entry.name}/`));
1904
- }
2526
+ },
2527
+ async () => {
2528
+ await git.checkout(checkpointCommit, tmpCwd);
2529
+ this.logger.debug("branch.create", { branch, from: checkpointCommit });
2530
+ await git.createBranch(branch, checkpointCommit, tmpCwd);
2531
+ }
2532
+ );
2533
+ return;
1905
2534
  }
2535
+ await git.checkout(branch, tmpCwd);
1906
2536
  }
1907
- return excluded;
1908
- }
2537
+ };
1909
2538
 
1910
- // src/services/contribute/utils/getPathPrefixToStrip.ts
1911
- function getPathPrefixToStrip(target) {
1912
- if (target.type === "block" /* BLOCK */) {
1913
- return normalizePath(`${blocksDir}/${target.name}/`);
1914
- }
1915
- return "";
1916
- }
2539
+ // src/services/contribute/services/CommitApplierService.ts
2540
+ var import_node_path18 = __toESM(require("path"));
2541
+ var import_fs_extra14 = __toESM(require("fs-extra"));
2542
+
2543
+ // src/services/contribute/config/index.ts
2544
+ var tempRepoName = "tmp";
2545
+ var bloxConfigControlledKeys = ["checkpoints", "project"];
1917
2546
 
1918
2547
  // src/services/contribute/utils/orderCommitsOldestToNewest.ts
1919
2548
  var orderCommitsOldestToNewest = (commits, history) => {
@@ -1932,12 +2561,6 @@ var orderCommitsOldestToNewest = (commits, history) => {
1932
2561
  });
1933
2562
  };
1934
2563
 
1935
- // src/services/contribute/utils/shouldExcludeFile.ts
1936
- function shouldExcludeFile(file, excludedPrefixes) {
1937
- const f = normalizePath(file);
1938
- return excludedPrefixes.some((p) => f.startsWith(p));
1939
- }
1940
-
1941
2564
  // src/services/contribute/services/CommitApplierService.ts
1942
2565
  var CommitApplierService = class {
1943
2566
  constructor(logger) {
@@ -1953,6 +2576,11 @@ var CommitApplierService = class {
1953
2576
  this.logger.debug("Prepare for apply commits", {
1954
2577
  appRepo: opts.appRepoCwd,
1955
2578
  tmpRepo: opts.tmpRepoCwd,
2579
+ target: {
2580
+ type: opts.target.type,
2581
+ name: opts.target.name,
2582
+ dir: opts.target.dir
2583
+ },
1956
2584
  subtree: subtreePath || "(root)",
1957
2585
  exclusion,
1958
2586
  projectIgnore
@@ -1998,6 +2626,10 @@ var CommitApplierService = class {
1998
2626
  files: remainingConflicts
1999
2627
  });
2000
2628
  await this.waitUntilUserResolvesConflicts(opts.tmpRepoCwd, commit2);
2629
+ await this.filterGovernedKeysFromResolvedBloxFiles(
2630
+ remainingConflicts.filter(isBloxConfigFile),
2631
+ opts.tmpRepoCwd
2632
+ );
2001
2633
  }
2002
2634
  const committed = await this.commitStagedIfAny(opts, commit2);
2003
2635
  if (committed) {
@@ -2018,10 +2650,24 @@ Resolve manually in the temp repo:
2018
2650
  ${e instanceof Error ? e.message : String(e)}`);
2019
2651
  }
2020
2652
  }
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
+ }
2021
2667
  async revertExcludedStagedFiles(tmpRepoCwd, commit2, exclusion, projectIgnoreMatcher, target) {
2022
- const stagedFiles = await git.getStagedFiles(tmpRepoCwd);
2668
+ const changedFromHeadFiles = await git.getChangedFilesFromHead(tmpRepoCwd);
2023
2669
  const unmergedFiles = await git.getUnmergedFiles(tmpRepoCwd);
2024
- const allTouchedFiles = [.../* @__PURE__ */ new Set([...stagedFiles, ...unmergedFiles])];
2670
+ const allTouchedFiles = [.../* @__PURE__ */ new Set([...changedFromHeadFiles, ...unmergedFiles])];
2025
2671
  for (const file of allTouchedFiles) {
2026
2672
  const isBloxFile = isBloxConfigFile(file);
2027
2673
  const isExcludedByTarget = shouldExcludeFile(file, exclusion);
@@ -2057,8 +2703,6 @@ ${e instanceof Error ? e.message : String(e)}`);
2057
2703
  return;
2058
2704
  }
2059
2705
  if (unmergedFiles.includes(file)) {
2060
- this.logger.debug("apply.commit.blox_merge_fallback", { file });
2061
- await git.revertPathToHead(file, tmpRepoCwd);
2062
2706
  return;
2063
2707
  }
2064
2708
  const headJson = await git.readJsonFromCommit("HEAD", file, tmpRepoCwd);
@@ -2077,8 +2721,8 @@ ${e instanceof Error ? e.message : String(e)}`);
2077
2721
  }
2078
2722
  const withoutGovernedKeys = omitKeys(stagedJson, bloxConfigControlledKeys);
2079
2723
  try {
2080
- const outPath = import_node_path16.default.join(tmpRepoCwd, file);
2081
- await import_fs_extra13.default.outputFile(outPath, JSON.stringify(withoutGovernedKeys, null, 2));
2724
+ const outPath = import_node_path18.default.join(tmpRepoCwd, file);
2725
+ await import_fs_extra14.default.outputFile(outPath, JSON.stringify(withoutGovernedKeys, null, 2));
2082
2726
  await git.add(file, tmpRepoCwd);
2083
2727
  } catch (e) {
2084
2728
  this.logger.warn("apply.commit.blox_merge_fallback", {
@@ -2140,130 +2784,200 @@ ${opts.description}`;
2140
2784
  };
2141
2785
 
2142
2786
  // src/services/contribute/services/CommitSelectorService.ts
2787
+ var NAV_PREV = "__prev__";
2788
+ var NAV_NEXT = "__next__";
2789
+ var NAV_FINISH = "__finish__";
2143
2790
  var CommitSelectorService = class {
2144
2791
  constructor(logger) {
2145
2792
  this.logger = logger;
2146
2793
  }
2147
2794
  async selectCommitsInteractive(opts) {
2148
- const selected = [];
2795
+ const selected = /* @__PURE__ */ new Set();
2796
+ const pages = /* @__PURE__ */ new Map();
2149
2797
  let page = 0;
2150
- let hasMore = true;
2151
- while (hasMore) {
2152
- const commits = await git.listCommits(UI_PAGE_SIZE, page * UI_PAGE_SIZE, opts.cwd);
2798
+ while (true) {
2799
+ let commits = pages.get(page);
2800
+ if (!commits) {
2801
+ commits = await git.listCommits(UI_PAGE_SIZE, page * UI_PAGE_SIZE, opts.cwd);
2802
+ pages.set(page, commits);
2803
+ }
2153
2804
  if (!commits.length) {
2154
2805
  if (page === 0) {
2155
2806
  throw new Error("No commits found in app repository.");
2156
2807
  }
2157
- break;
2808
+ page -= 1;
2809
+ continue;
2158
2810
  }
2811
+ const initialValues = commits.filter((c) => selected.has(c.hash)).map((c) => c.hash);
2159
2812
  const value = await multiselect({
2160
2813
  message: `Select commits (Press <space> to select, <enter> to continue) ${fmt.gray(`(page ${page + 1})`)}`,
2161
2814
  options: commits.map((c) => ({
2162
2815
  value: c.hash,
2163
2816
  label: `${c.hash.slice(0, 7)} ${c.subject}`
2164
2817
  })),
2165
- required: true
2818
+ initialValues,
2819
+ required: false
2166
2820
  });
2167
- for (const h of value) {
2168
- if (!selected.includes(h)) {
2169
- selected.push(h);
2821
+ for (const c of commits) {
2822
+ if (value.includes(c.hash)) {
2823
+ selected.add(c.hash);
2824
+ } else {
2825
+ selected.delete(c.hash);
2170
2826
  }
2171
2827
  }
2172
- hasMore = commits.length === UI_PAGE_SIZE;
2173
- if (!hasMore) {
2174
- break;
2175
- }
2176
- const loadMore = await confirm({
2177
- message: "Load next page of commits?",
2178
- initialValue: false
2828
+ const hasPrev = page > 0;
2829
+ const hasNext = commits.length === UI_PAGE_SIZE;
2830
+ const navigation = await select({
2831
+ message: `${selected.size} commit(s) selected. Choose an action:`,
2832
+ options: [
2833
+ ...hasPrev ? [{ label: "Previous page", value: NAV_PREV }] : [],
2834
+ ...hasNext ? [{ label: "Next page", value: NAV_NEXT }] : [],
2835
+ { label: "Finish selection", value: NAV_FINISH }
2836
+ ]
2179
2837
  });
2180
- if (!loadMore) {
2181
- break;
2838
+ if (navigation === NAV_PREV) {
2839
+ page -= 1;
2840
+ continue;
2182
2841
  }
2183
- page += 1;
2184
- }
2185
- if (!selected.length) {
2186
- throw new Error("No commits selected.");
2842
+ if (navigation === NAV_NEXT) {
2843
+ page += 1;
2844
+ continue;
2845
+ }
2846
+ if (!selected.size) {
2847
+ this.logger.warn("You must select at least one commit before finishing.");
2848
+ continue;
2849
+ }
2850
+ break;
2187
2851
  }
2188
- this.logger.debug("commits.selected", { count: selected.length });
2189
- this.logger.info(`${selected.length} Commits selected`);
2190
- return selected;
2852
+ const result = Array.from(selected);
2853
+ this.logger.debug("commits.selected", { count: result.length });
2854
+ this.logger.info(`${result.length} Commits selected`);
2855
+ return result;
2191
2856
  }
2192
2857
  };
2193
2858
 
2194
- // src/services/contribute/utils/discoverContributionTargets.ts
2195
- var import_node_path17 = __toESM(require("path"));
2196
- var import_fs_extra14 = __toESM(require("fs-extra"));
2197
- var readBloxFileIfExists = (cwd) => {
2198
- const p = import_node_path17.default.join(cwd, bloxFilePath);
2199
- if (!import_fs_extra14.default.existsSync(p)) return;
2200
- try {
2201
- return import_fs_extra14.default.readJSONSync(p);
2202
- } catch {
2203
- return;
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");
2204
2879
  }
2205
- };
2206
- var discoverContributionTargets = (cwd) => {
2207
- const targets = [];
2208
- const rootBlox = readBloxFileIfExists(cwd);
2209
- const appTemplateName = rootBlox?.definition?.name;
2210
- const appTemplateDef = rootBlox?.definition;
2211
- if (rootBlox?.definition?.name) {
2212
- targets.push({
2213
- type: "template" /* TEMPLATE */,
2214
- name: rootBlox.definition.name,
2215
- templateName: rootBlox.definition.name,
2216
- templateDef: appTemplateDef,
2217
- label: `template/${rootBlox.definition.name}`
2218
- });
2219
- for (const base of rootBlox.definition.bases || []) {
2220
- targets.push({
2221
- type: "base" /* BASE */,
2222
- name: base.name,
2223
- templateDef: appTemplateDef,
2224
- label: `base/${base.name}`,
2225
- hint: base.version !== void 0 ? `version: ${JSON.stringify(base.version)}` : void 0
2226
- });
2227
- }
2880
+ }
2881
+ function exitIfRealCancel(result) {
2882
+ if ((0, import_prompts15.isCancel)(result)) {
2883
+ (0, import_prompts15.cancel)("Canceled");
2884
+ process.exit(0);
2228
2885
  }
2229
- const blocksPath = import_node_path17.default.join(cwd, blocksDir);
2230
- if (import_fs_extra14.default.existsSync(blocksPath)) {
2231
- const entries = import_fs_extra14.default.readdirSync(blocksPath, { withFileTypes: true });
2232
- for (const entry of entries) {
2233
- if (!entry.isDirectory()) continue;
2234
- const blockName = entry.name;
2235
- const blockBlox = readBloxFileIfExists(import_node_path17.default.join(blocksPath, blockName));
2236
- if (!blockBlox?.definition?.name) continue;
2237
- const def = blockBlox.definition;
2238
- const templateName = def.templates?.[0]?.name || appTemplateName;
2239
- targets.push({
2240
- type: "block" /* BLOCK */,
2241
- name: blockName,
2242
- templateName,
2243
- templateDef: appTemplateDef,
2244
- label: `block/${blockName}`,
2245
- hint: blockBlox.definition.version !== void 0 ? `v${blockBlox.definition.version}` : void 0
2246
- });
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();
2247
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;
2248
2966
  }
2249
- return targets;
2250
- };
2251
-
2252
- // src/services/contribute/utils/parseContributionTargetType.ts
2253
- var parseContributionTargetType = (segment) => {
2254
- if (segment === "template" /* TEMPLATE */ || segment === "base" /* BASE */ || segment === "block" /* BLOCK */) {
2255
- return segment;
2256
- }
2257
- return;
2258
- };
2967
+ exitIfRealCancel(result);
2968
+ return result;
2969
+ }
2259
2970
 
2260
2971
  // src/services/contribute/services/ContributionTargetSelector.ts
2972
+ var MULTI_NAV_PREV = "__prev__";
2973
+ var MULTI_NAV_NEXT = "__next__";
2974
+ var MULTI_NAV_FINISH = "__finish__";
2261
2975
  var ContributionTargetSelector = class {
2262
2976
  constructor(opts, logger) {
2263
2977
  this.opts = opts;
2264
2978
  this.logger = logger;
2265
2979
  }
2266
- async selectTargetInteractive() {
2980
+ async selectMultipleTargetsInteractive(opts) {
2267
2981
  const all = discoverContributionTargets(this.opts.cwd);
2268
2982
  if (!all.length) {
2269
2983
  throw new Error(
@@ -2271,58 +2985,104 @@ var ContributionTargetSelector = class {
2271
2985
  );
2272
2986
  }
2273
2987
  let query = "";
2274
- for (; ; ) {
2275
- query = await text({
2276
- message: `Search targets ${fmt.gray("(empty for all)")}`,
2277
- placeholder: "auth, template, base, ...",
2278
- defaultValue: query
2279
- });
2280
- const filtered = filterTargetsByQuery(all, query);
2281
- if (!filtered.length) {
2282
- this.logger.warn(`No matches for search: "${query}"`);
2283
- const again = await confirm({ message: "Search again?" });
2284
- if (again) {
2285
- query = " ";
2286
- continue;
2287
- }
2288
- throw new Error("Aborted: no target selected.");
2988
+ let filtered = all;
2989
+ const selectedKeys = /* @__PURE__ */ new Set();
2990
+ const selectedTargets = () => Array.from(selectedKeys).map((key) => {
2991
+ const found = all.find((target) => targetHintKey(target) === key);
2992
+ if (!found) {
2993
+ throw new Error(`Invalid selection: ${key}`);
2994
+ }
2995
+ if (found.type === "block" /* BLOCK */) {
2996
+ return {
2997
+ type: found.type,
2998
+ name: found.name,
2999
+ dir: found.dir,
3000
+ templateName: found.templateName,
3001
+ templateDef: found.templateDef
3002
+ };
2289
3003
  }
2290
- const pageSize = UI_PAGE_SIZE;
3004
+ return {
3005
+ type: found.type,
3006
+ name: found.name,
3007
+ templateName: found.templateName,
3008
+ templateDef: found.templateDef
3009
+ };
3010
+ });
3011
+ while (true) {
3012
+ const shouldPaginate = filtered.length > UI_PAGE_SIZE;
3013
+ const pageSize = shouldPaginate ? UI_PAGE_SIZE : filtered.length || 1;
2291
3014
  let page = 0;
2292
3015
  const maxPage = Math.max(0, Math.ceil(filtered.length / pageSize) - 1);
2293
3016
  while (true) {
2294
3017
  const start = page * pageSize;
2295
3018
  const slice = filtered.slice(start, start + pageSize);
2296
- const value = await select({
2297
- message: `Select contribution target ${fmt.gray(
2298
- `(page ${page + 1}/${maxPage + 1})`
2299
- )}`,
2300
- options: buildTargetPageSelectOptions(slice, page, maxPage)
3019
+ const initialValues = slice.map((t) => targetHintKey(t)).filter((key) => selectedKeys.has(key));
3020
+ const value = await multiselectWithSearch({
3021
+ message: shouldPaginate ? `Select contribution targets ${fmt.gray(`(page ${page + 1}/${maxPage + 1})`)} ${fmt.gray("(press s to search)")}` : `Select contribution targets ${fmt.gray("(press s to search)")}`,
3022
+ options: buildMultiTargetPageSelectOptions(slice, opts?.changeHints),
3023
+ initialValues,
3024
+ required: false
3025
+ });
3026
+ if (value === SEARCH_REQUESTED) {
3027
+ query = await text({
3028
+ message: `Search targets ${fmt.gray("(empty for all)")}`,
3029
+ placeholder: "auth, template, base, ...",
3030
+ defaultValue: query
3031
+ });
3032
+ filtered = filterTargetsByQuery(all, query);
3033
+ if (!filtered.length) {
3034
+ this.logger.warn(`No matches for search: "${query}"`);
3035
+ const again = await confirm({ message: "Search again?" });
3036
+ if (again) {
3037
+ query = " ";
3038
+ break;
3039
+ }
3040
+ filtered = all;
3041
+ }
3042
+ page = 0;
3043
+ break;
3044
+ }
3045
+ for (const t of slice) {
3046
+ const key = targetHintKey(t);
3047
+ if (value.includes(key)) {
3048
+ selectedKeys.add(key);
3049
+ } else {
3050
+ selectedKeys.delete(key);
3051
+ }
3052
+ }
3053
+ if (!shouldPaginate) {
3054
+ if (!selectedKeys.size) {
3055
+ this.logger.warn("You must select at least one target before continuing.");
3056
+ continue;
3057
+ }
3058
+ return selectedTargets();
3059
+ }
3060
+ const hasPrev = page > 0;
3061
+ const hasNext = page < maxPage;
3062
+ const navigation = await select({
3063
+ message: `${selectedKeys.size} target(s) selected. Choose an action:`,
3064
+ options: [
3065
+ ...hasPrev ? [{ label: "Previous page", value: MULTI_NAV_PREV }] : [],
3066
+ ...hasNext ? [{ label: "Next page", value: MULTI_NAV_NEXT }] : [],
3067
+ { label: "Done", value: MULTI_NAV_FINISH }
3068
+ ]
2301
3069
  });
2302
- if (value === TARGET_SELECT_PAGE.PREV) {
3070
+ if (navigation === MULTI_NAV_PREV) {
2303
3071
  page = Math.max(0, page - 1);
2304
3072
  continue;
2305
3073
  }
2306
- if (value === TARGET_SELECT_PAGE.NEXT) {
3074
+ if (navigation === MULTI_NAV_NEXT) {
2307
3075
  page = Math.min(maxPage, page + 1);
2308
3076
  continue;
2309
3077
  }
2310
- if (value === TARGET_SELECT_PAGE.SEARCH_AGAIN) {
2311
- query = " ";
2312
- break;
2313
- }
2314
- const [typeRaw, name, templateNameRaw] = value.split(":");
2315
- const type = typeRaw ? parseContributionTargetType(typeRaw) : void 0;
2316
- if (!type || !name) {
2317
- throw new Error(`Invalid selection: ${value}`);
3078
+ if (!selectedKeys.size) {
3079
+ this.logger.warn("You must select at least one target before continuing.");
3080
+ continue;
2318
3081
  }
2319
- const found = all.find((t) => t.type === type && t.name === name);
2320
- return {
2321
- type,
2322
- name,
2323
- templateName: templateNameRaw || void 0,
2324
- templateDef: found?.templateDef
2325
- };
3082
+ return selectedTargets();
3083
+ }
3084
+ if (!filtered.length) {
3085
+ filtered = all;
2326
3086
  }
2327
3087
  }
2328
3088
  }
@@ -2334,17 +3094,16 @@ function filterTargetsByQuery(all, query) {
2334
3094
  }
2335
3095
  return all.filter((t) => `${t.type}/${t.name}`.toLowerCase().includes(q));
2336
3096
  }
2337
- function buildTargetPageSelectOptions(slice, page, maxPage) {
2338
- return [
2339
- ...slice.map((t) => ({
2340
- value: `${t.type}:${t.name}:${t.templateName || ""}`,
2341
- label: t.label,
2342
- hint: t.hint
2343
- })),
2344
- ...page > 0 ? [{ value: TARGET_SELECT_PAGE.PREV, label: "\u25C0 prev page" }] : [],
2345
- ...page < maxPage ? [{ value: TARGET_SELECT_PAGE.NEXT, label: "next page \u25B6" }] : [],
2346
- { value: TARGET_SELECT_PAGE.SEARCH_AGAIN, label: "search again" }
2347
- ];
3097
+ function buildMultiTargetPageSelectOptions(slice, changeHints) {
3098
+ return slice.map((t) => {
3099
+ const hasChanges = changeHints?.get(targetHintKey(t));
3100
+ const changeHint = hasChanges === void 0 ? void 0 : hasChanges ? fmt.green("has changes in selected commits") : fmt.gray("no changes in selected commits");
3101
+ return {
3102
+ value: targetHintKey(t),
3103
+ label: hasChanges ? `${fmt.green("+")} ${t.label}` : t.label,
3104
+ hint: [t.hint, changeHint].filter(Boolean).join(" \xB7 ")
3105
+ };
3106
+ });
2348
3107
  }
2349
3108
 
2350
3109
  // src/services/contribute/services/LoggerService.ts
@@ -2465,57 +3224,80 @@ var PullRequestService = class {
2465
3224
  }
2466
3225
  }
2467
3226
  printPushSummary(opts) {
2468
- const line = "\u2501".repeat(60);
2469
- const header = fmt.bold(fmt.cyan("BRANCH PUSHED"));
3227
+ const description = opts.description.trim();
3228
+ const rows = [
3229
+ ["Target", opts.targetBranch, fmt.green],
3230
+ ["Source", opts.sourceBranch, fmt.yellow],
3231
+ ["Remote", opts.repoUrl, fmt.blue],
3232
+ ["Title", opts.title, (v) => v]
3233
+ ];
3234
+ const labelWidth = Math.max(...rows.map(([label]) => label.length));
3235
+ const plainLines = [
3236
+ ...rows.map(([label, value]) => `${label.padEnd(labelWidth)}: ${value}`),
3237
+ ...description ? ["Description:", ...description.split("\n")] : []
3238
+ ];
3239
+ const titleText = " BRANCH PUSHED ";
3240
+ const terminalWidth = process.stdout.columns || 80;
3241
+ const innerWidth = Math.min(
3242
+ Math.max(...plainLines.map((l) => l.length), titleText.length),
3243
+ terminalWidth - 6
3244
+ );
3245
+ const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
3246
+ const padVisible = (s) => s + " ".repeat(Math.max(innerWidth - stripAnsi(s).length, 0));
3247
+ const topBorder = `\u250C\u2500${fmt.bold(titleText)}${"\u2500".repeat(Math.max(innerWidth - titleText.length + 2, 0))}\u2500\u2510`;
3248
+ const bottomBorder = `\u2514${"\u2500".repeat(innerWidth + 4)}\u2518`;
3249
+ const emptyLine = `\u2502${" ".repeat(innerWidth + 4)}\u2502`;
3250
+ const line = (content) => `\u2502 ${padVisible(content)} \u2502`;
3251
+ const rowLines = rows.map(
3252
+ ([label, value, paint]) => line(`${fmt.bold(`${label}:`.padEnd(labelWidth + 1))} ${paint(value)}`)
3253
+ );
3254
+ const descriptionLines = description ? [line(fmt.gray("Description:")), ...description.split("\n").map((l) => line(l))] : [];
2470
3255
  import_prompts2.log.message(
2471
- `
2472
- ${fmt.cyan("\u25E2")}${line}${fmt.cyan("\u25E3")}
2473
- ${header}
2474
-
2475
- ${fmt.bold("Target:")} ${fmt.green(opts.targetBranch)}
2476
- ${fmt.bold("Source:")} ${fmt.yellow(opts.sourceBranch)}
2477
- ${fmt.bold("Remote:")} ${fmt.blue(opts.repoUrl)}
2478
- ${fmt.bold("Title:")} ${opts.title}
2479
- ` + (opts.description.trim() ? `
2480
- ${fmt.gray("Description:")}
2481
- ${opts.description.trim()}
2482
- ` : "") + `${fmt.cyan("\u25E5")}${line}${fmt.cyan("\u25E4")}
2483
- `
3256
+ [
3257
+ "",
3258
+ topBorder,
3259
+ emptyLine,
3260
+ ...rowLines,
3261
+ ...descriptionLines.length ? [emptyLine, ...descriptionLines] : [],
3262
+ emptyLine,
3263
+ bottomBorder,
3264
+ ""
3265
+ ].join("\n")
2484
3266
  );
2485
3267
  }
2486
- async openPullRequestPage(opts) {
3268
+ resolvePullRequestUrl(opts) {
2487
3269
  const parsed = extractAzureRepoInfoFromGit(opts.repoUrl);
2488
3270
  if (!parsed) {
2489
3271
  this.logger.info("pr.skipped", { reason: "remote_not_azure_devops_git" });
2490
- return { prUrl: void 0 };
3272
+ return void 0;
3273
+ }
3274
+ return buildPullRequestUrl(parsed, opts.sourceBranch, opts.targetBranch);
3275
+ }
3276
+ async openPullRequestUrls(urls) {
3277
+ if (!urls.length) {
3278
+ return;
2491
3279
  }
2492
3280
  const wantsPr = await confirm({
2493
- message: "Do you want to open a Pull Request?",
3281
+ message: urls.length > 1 ? "Do you want to open the Pull Requests?" : "Do you want to open the Pull Request?",
2494
3282
  initialValue: true
2495
3283
  });
2496
3284
  if (!wantsPr) {
2497
3285
  this.logger.info("pr.declined");
2498
- return { prUrl: void 0 };
3286
+ return;
2499
3287
  }
2500
- const createPageUrl = buildPullRequestUrl(parsed, opts.sourceBranch, opts.targetBranch);
2501
- try {
2502
- await openUrlInBrowser(createPageUrl);
2503
- } catch (e) {
2504
- this.logger.warn("Could not open browser", e);
3288
+ for (const url of urls) {
3289
+ try {
3290
+ await openUrlInBrowser(url);
3291
+ } catch (e) {
3292
+ this.logger.warn("Could not open browser", e);
3293
+ }
2505
3294
  }
2506
- import_prompts2.log.message(
2507
- `
2508
- ${fmt.green("Opening Pull Request creation in your browser.")}
2509
- ${fmt.cyan(createPageUrl)}
2510
- `
2511
- );
2512
- return { prUrl: createPageUrl };
2513
3295
  }
2514
3296
  };
2515
3297
 
2516
3298
  // src/services/contribute/services/TmpRepoService.ts
2517
- var import_node_os2 = require("os");
2518
- var import_node_path18 = __toESM(require("path"));
3299
+ var import_node_os3 = require("os");
3300
+ var import_node_path19 = __toESM(require("path"));
2519
3301
  var import_fs_extra15 = __toESM(require("fs-extra"));
2520
3302
  var TmpRepoService = class {
2521
3303
  constructor(logger) {
@@ -2532,8 +3314,10 @@ var TmpRepoService = class {
2532
3314
  await git.update({ cwd: dir });
2533
3315
  }
2534
3316
  async getTmpDir(target) {
2535
- const slug = `${target.type}-${target.name}`.replace(/[^a-zA-Z0-9._-]+/g, "-");
2536
- return import_node_path18.default.join((0, import_node_os2.homedir)(), bloxFilePath, tempRepoName, slug);
3317
+ const isBlock = target.type === "block" /* BLOCK */;
3318
+ const slugParts = isBlock && target.templateName ? [target.type, target.templateName, target.name] : [target.type, target.name];
3319
+ 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);
2537
3321
  }
2538
3322
  async prepare(opts) {
2539
3323
  const taskSpinner = spinner();
@@ -2559,7 +3343,7 @@ var TmpRepoService = class {
2559
3343
  await import_fs_extra15.default.remove(dir);
2560
3344
  }
2561
3345
  }
2562
- await import_fs_extra15.default.ensureDir(import_node_path18.default.dirname(dir));
3346
+ await import_fs_extra15.default.ensureDir(import_node_path19.default.dirname(dir));
2563
3347
  await git.clone(opts.repoUrl, dir, opts.branch);
2564
3348
  taskSpinner.stop("Prepared tmp repo");
2565
3349
  return dir;
@@ -2573,34 +3357,35 @@ var TmpRepoService = class {
2573
3357
  // src/services/contribute/index.ts
2574
3358
  async function buildContributionWorkflow(opts) {
2575
3359
  const logger = new LoggerService();
2576
- const targetSelector = new ContributionTargetSelector({ cwd: opts.cwd }, logger);
2577
- const tmpRepo = new TmpRepoService(logger);
2578
- const commitSelector = new CommitSelectorService(logger);
2579
- const commitApplier = new CommitApplierService(logger);
2580
- const pullRequest = new PullRequestService(logger);
2581
3360
  return new ContributionWorkflow(
2582
3361
  { cwd: opts.cwd, force: opts.force },
2583
3362
  logger,
2584
- targetSelector,
2585
- tmpRepo,
2586
- commitSelector,
2587
- commitApplier,
2588
- pullRequest
3363
+ new ContributionTargetSelector({ cwd: opts.cwd }, logger),
3364
+ new TmpRepoService(logger),
3365
+ new CommitSelectorService(logger),
3366
+ new CommitApplierService(logger),
3367
+ new PullRequestService(logger)
2589
3368
  );
2590
3369
  }
2591
3370
 
2592
3371
  // src/commands/contribute/index.ts
2593
- var contribute = command("contribute").description("Contribute changes back to template/base/block repositories").alias("cb").option("--existing", "add changes to an existing contribution PR").option("--title <title>", "contribution title").option("--description <description>", "contribution description").option("--commits <commits>", "comma-separated commit hashes from app repo").option("--force", "bypass safety pre-flight checks").addOption(
2594
- option("--type <type>", "target type").choices(Object.values(ContributionTargetType))
2595
- ).option("--name <name>", "target name").action(async (flags) => {
3372
+ var contribute = command("contribute").description("Contribute changes back to template/base/block repositories").alias("cb").option("--existing", "add changes to an existing contribution PR").option("--title <title>", "contribution title").option("--description <description>", "contribution description").option("--commits <commits>", "comma-separated commit hashes from app repo").option("--type <type>", "target type (template, base, or block)").option("--name <name>", "target name (used with --type)").option("--force", "bypass safety pre-flight checks").action(async (flags) => {
2596
3373
  try {
3374
+ if (await git.hasUncommittedChanges()) {
3375
+ throw new Error(
3376
+ "Make sure to commit or stash any changes in the app repo before contributing."
3377
+ );
3378
+ }
2597
3379
  await migrateAll(true);
2598
3380
  await syncRegistries();
2599
3381
  const workflow = await buildContributionWorkflow({
2600
3382
  cwd: process.cwd(),
2601
3383
  force: !!flags.force
2602
3384
  });
2603
- await workflow.runFromFlags(flags);
3385
+ const results = await workflow.runFromFlags(flags);
3386
+ if (results.some((r) => !r.success)) {
3387
+ process.exitCode = 1;
3388
+ }
2604
3389
  } catch (e) {
2605
3390
  error(e);
2606
3391
  }
@@ -2709,9 +3494,9 @@ var migrateSchema = command("migrate").description("Migrate blox schema").action
2709
3494
  });
2710
3495
 
2711
3496
  // src/commands/remove/index.ts
2712
- var import_node_path19 = __toESM(require("path"));
3497
+ var import_node_path20 = __toESM(require("path"));
2713
3498
  var import_fs_extra17 = __toESM(require("fs-extra"));
2714
- var blocksAbsolutePath = () => import_node_path19.default.resolve(process.cwd(), blocksDir);
3499
+ var blocksAbsolutePath = () => import_node_path20.default.resolve(process.cwd(), blocksDir);
2715
3500
  function listInstalledBlockRelPaths() {
2716
3501
  const root = blocksAbsolutePath();
2717
3502
  if (!import_fs_extra17.default.existsSync(root)) {
@@ -2722,17 +3507,17 @@ function listInstalledBlockRelPaths() {
2722
3507
  if (!entry.isDirectory()) {
2723
3508
  continue;
2724
3509
  }
2725
- const abs = import_node_path19.default.join(root, entry.name);
3510
+ const abs = import_node_path20.default.join(root, entry.name);
2726
3511
  if (!isBlockDirectory(abs)) {
2727
3512
  continue;
2728
3513
  }
2729
- paths2.push(import_node_path19.default.join(blocksDir, entry.name));
3514
+ paths2.push(import_node_path20.default.join(blocksDir, entry.name));
2730
3515
  }
2731
3516
  return paths2;
2732
3517
  }
2733
3518
  function getInstalledBlockSelectOptions() {
2734
3519
  return listInstalledBlockRelPaths().map((rel) => {
2735
- const folder = import_node_path19.default.basename(rel);
3520
+ const folder = import_node_path20.default.basename(rel);
2736
3521
  const def = getBlockDef(rel);
2737
3522
  const label = def?.name && def.name !== folder ? `${def.name} (${folder})` : folder;
2738
3523
  return { value: folder, label, hint: def?.name };
@@ -2740,7 +3525,7 @@ function getInstalledBlockSelectOptions() {
2740
3525
  }
2741
3526
  function assertNoDependents(blockPathAbs, targetBlockName) {
2742
3527
  for (const rel of listInstalledBlockRelPaths()) {
2743
- const abs = import_node_path19.default.resolve(process.cwd(), rel);
3528
+ const abs = import_node_path20.default.resolve(process.cwd(), rel);
2744
3529
  if (abs === blockPathAbs) {
2745
3530
  continue;
2746
3531
  }
@@ -2756,19 +3541,19 @@ function assertNoDependents(blockPathAbs, targetBlockName) {
2756
3541
  }
2757
3542
  function assertUnderBlocksRoot(blockPathAbs) {
2758
3543
  const root = blocksAbsolutePath();
2759
- const rel = import_node_path19.default.relative(root, blockPathAbs);
2760
- if (!rel || rel.startsWith("..") || import_node_path19.default.isAbsolute(rel)) {
3544
+ const rel = import_node_path20.default.relative(root, blockPathAbs);
3545
+ if (!rel || rel.startsWith("..") || import_node_path20.default.isAbsolute(rel)) {
2761
3546
  throw new Error("Block path escapes the blocks directory");
2762
3547
  }
2763
3548
  }
2764
3549
  async function removeBlock(block, blocks, force = false) {
2765
3550
  const reg = blocks[block];
2766
3551
  const destination = reg ? reg.destination ?? block : block;
2767
- const blockPathRel = import_node_path19.default.join(blocksDir, destination);
2768
- const blockPathAbs = import_node_path19.default.resolve(process.cwd(), blockPathRel);
3552
+ const blockPathRel = import_node_path20.default.join(blocksDir, destination);
3553
+ const blockPathAbs = import_node_path20.default.resolve(process.cwd(), blockPathRel);
2769
3554
  assertUnderBlocksRoot(blockPathAbs);
2770
3555
  if (!import_fs_extra17.default.existsSync(blockPathAbs) || !isBlockDirectory(blockPathAbs)) {
2771
- throw new Error(`Block is not installed at ${import_node_path19.default.relative(process.cwd(), blockPathAbs)}`);
3556
+ throw new Error(`Block is not installed at ${import_node_path20.default.relative(process.cwd(), blockPathAbs)}`);
2772
3557
  }
2773
3558
  const targetDef = getBlockDef(blockPathRel);
2774
3559
  if (!targetDef?.name) {
@@ -2837,17 +3622,16 @@ var remove = command("remove").description("Remove block from app").alias("rm").
2837
3622
 
2838
3623
  // src/commands/skills/index.ts
2839
3624
  var import_node_crypto = require("crypto");
2840
- var import_node_os3 = __toESM(require("os"));
2841
- var import_node_path21 = __toESM(require("path"));
3625
+ var import_node_os4 = __toESM(require("os"));
3626
+ var import_node_path22 = __toESM(require("path"));
2842
3627
  var import_cross_spawn2 = __toESM(require("cross-spawn"));
2843
3628
  var import_fs_extra19 = __toESM(require("fs-extra"));
2844
3629
 
2845
3630
  // src/commands/skills/constants.ts
2846
- var SKILLS_REPO_URL = "https://tfs.aas.com.sa/Medad/BLOX/_git/cli";
2847
- var SKILLS_TEMP_ROOT_PREFIX = "blox-skills";
3631
+ var SKILLS_REPO_URL = "https://github.com/Naseej-its/blox.git";
2848
3632
 
2849
3633
  // src/commands/skills/utils/cliCompatibility.ts
2850
- var import_node_path20 = __toESM(require("path"));
3634
+ var import_node_path21 = __toESM(require("path"));
2851
3635
  var import_fs_extra18 = __toESM(require("fs-extra"));
2852
3636
  var import_semver = __toESM(require("semver"));
2853
3637
  var SKILLS_CLI_COMPATIBILITY_COMMANDS = ["add", "update"];
@@ -2872,14 +3656,14 @@ function getAddCommandIndex(args) {
2872
3656
  return getSkillscommandIndex(args, "add");
2873
3657
  }
2874
3658
  async function loadSkillsData(cloneRoot) {
2875
- const skillsDir = import_node_path20.default.join(cloneRoot, "skills");
3659
+ const skillsDir = import_node_path21.default.join(cloneRoot, "skills");
2876
3660
  if (!await import_fs_extra18.default.pathExists(skillsDir)) {
2877
3661
  return [];
2878
3662
  }
2879
3663
  const entries = await import_fs_extra18.default.readdir(skillsDir, { withFileTypes: true });
2880
3664
  const manifests = await Promise.all(
2881
3665
  entries.filter((entry) => entry.isDirectory()).map(async (entry) => {
2882
- const filePath = import_node_path20.default.join(skillsDir, entry.name, "skill.json");
3666
+ const filePath = import_node_path21.default.join(skillsDir, entry.name, "skill.json");
2883
3667
  if (!await import_fs_extra18.default.pathExists(filePath)) {
2884
3668
  return null;
2885
3669
  }
@@ -2934,12 +3718,11 @@ var skills = command("skills").description("Install, update, and manage BLOX CLI
2934
3718
  async function runSkills() {
2935
3719
  const idx = process.argv.indexOf("skills");
2936
3720
  const args = idx === -1 ? [] : process.argv.slice(idx + 1);
2937
- const tempDir = import_node_path21.default.join(import_node_os3.default.tmpdir(), `${SKILLS_TEMP_ROOT_PREFIX}-${(0, import_node_crypto.randomUUID)()}`);
2938
- await import_fs_extra19.default.mkdir(tempDir);
2939
- let exitCode = 1;
2940
- try {
2941
- await git.clone(SKILLS_REPO_URL, tempDir);
2942
- if (needsCliCompatibilityCheck(args)) {
3721
+ 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);
3724
+ try {
3725
+ await git.clone(SKILLS_REPO_URL, tempDir);
2943
3726
  const skills2 = await loadSkillsData(tempDir);
2944
3727
  const cliVersion = getBloxCliVersion();
2945
3728
  const uncompatibleSkill = getFirstIncompatibleSkill(skills2, cliVersion);
@@ -2953,19 +3736,18 @@ async function runSkills() {
2953
3736
  return 1;
2954
3737
  }
2955
3738
  }
2956
- }
2957
- const finalArgs = injectRepoPathIfAdd(args, import_node_path21.default.resolve(tempDir));
2958
- exitCode = await runSkillsCommand(finalArgs, process.cwd());
2959
- } finally {
2960
- try {
2961
- await import_fs_extra19.default.remove(tempDir);
2962
- } catch {
2963
- debug(`Failed to cleanup temp dir: ${tempDir}`);
3739
+ } finally {
3740
+ try {
3741
+ await import_fs_extra19.default.remove(tempDir);
3742
+ } catch {
3743
+ debug(`Failed to cleanup temp dir: ${tempDir}`);
3744
+ }
2964
3745
  }
2965
3746
  }
2966
- return exitCode;
3747
+ const finalArgs = injectRepoUrlIfAdd(args, SKILLS_REPO_URL);
3748
+ return runSkillsCommand(finalArgs, process.cwd());
2967
3749
  }
2968
- function injectRepoPathIfAdd(args, repoPath) {
3750
+ function injectRepoUrlIfAdd(args, repoPath) {
2969
3751
  const addIndex = getAddCommandIndex(args);
2970
3752
  if (addIndex === -1) return args;
2971
3753
  const next = args[addIndex + 1];
@@ -2989,13 +3771,10 @@ function runSkillsCommand(args, cwd) {
2989
3771
  }
2990
3772
 
2991
3773
  // src/commands/update/index.ts
2992
- var import_prompts23 = require("@clack/prompts");
2993
-
2994
- // src/commands/update/utils.ts
2995
- var import_node_path23 = __toESM(require("path"));
3774
+ var import_prompts26 = require("@clack/prompts");
2996
3775
 
2997
3776
  // src/services/updater.ts
2998
- var import_node_path22 = __toESM(require("path"));
3777
+ var import_node_path23 = __toESM(require("path"));
2999
3778
  var import_fs_extra20 = __toESM(require("fs-extra"));
3000
3779
  var import_klaw3 = __toESM(require("klaw"));
3001
3780
  async function updateFromRemote({
@@ -3043,7 +3822,7 @@ async function updateFromRemote({
3043
3822
  const remoteIgnore = remoteBloxFile.definition?.ignore || [];
3044
3823
  const projectIgnore = bloxFile.project?.ignore || [];
3045
3824
  ignore3.push(...remoteIgnore, ...projectIgnore, bloxFilePath, `**/${bloxFilePath}`);
3046
- const gitIgnorePath = import_node_path22.default.join(dir, ".gitignore");
3825
+ const gitIgnorePath = import_node_path23.default.join(dir, ".gitignore");
3047
3826
  if (await import_fs_extra20.default.pathExists(gitIgnorePath)) {
3048
3827
  const gitIgnoreContent = await import_fs_extra20.default.readFile(gitIgnorePath, "utf8");
3049
3828
  const gitIgnorePatterns = gitIgnoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
@@ -3064,7 +3843,7 @@ async function updateFromRemote({
3064
3843
  if (file.path.includes("/node_modules/") || file.path.includes("\\node_modules\\"))
3065
3844
  continue;
3066
3845
  if (file.stats.isFile()) {
3067
- files.push(import_node_path22.default.relative(d, file.path));
3846
+ files.push(import_node_path23.default.relative(d, file.path));
3068
3847
  }
3069
3848
  }
3070
3849
  }
@@ -3083,16 +3862,16 @@ async function updateFromRemote({
3083
3862
  for (const file of filesToProcess) {
3084
3863
  if (file === ".git" || file.startsWith(".git/") || file.startsWith(".git\\")) continue;
3085
3864
  if (ignoredMatcher.ignores(toIgnorePath(file))) continue;
3086
- const localPath = import_node_path22.default.join(dir, file);
3087
- const basePath = import_node_path22.default.join(baseDir, file);
3088
- const remotePath = import_node_path22.default.join(remoteDir, file);
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);
3089
3868
  const existsLocal = await import_fs_extra20.default.pathExists(localPath);
3090
3869
  const existsBase = await import_fs_extra20.default.pathExists(basePath);
3091
3870
  const existsRemote = await import_fs_extra20.default.pathExists(remotePath);
3092
- const ext = import_node_path22.default.extname(file);
3871
+ const ext = import_node_path23.default.extname(file);
3093
3872
  const isBinary = isBinaryFile(ext);
3094
3873
  if (existsRemote) {
3095
- await import_fs_extra20.default.ensureDir(import_node_path22.default.dirname(localPath));
3874
+ await import_fs_extra20.default.ensureDir(import_node_path23.default.dirname(localPath));
3096
3875
  }
3097
3876
  if (hard) {
3098
3877
  if (existsRemote) {
@@ -3111,7 +3890,7 @@ async function updateFromRemote({
3111
3890
  await import_fs_extra20.default.copy(remotePath, localPath, { overwrite: true });
3112
3891
  logWarningSection(`Overwrote binary file collision: ${file}`);
3113
3892
  } else {
3114
- const emptyBase = import_node_path22.default.join(baseDir, `${file}.empty`);
3893
+ const emptyBase = import_node_path23.default.join(baseDir, `${file}.empty`);
3115
3894
  await import_fs_extra20.default.ensureFile(emptyBase);
3116
3895
  const result = await git.mergeFile(localPath, emptyBase, remotePath);
3117
3896
  if (!result) {
@@ -3182,6 +3961,13 @@ It has been recreated to apply upstream changes.`
3182
3961
  }
3183
3962
 
3184
3963
  // src/commands/update/utils.ts
3964
+ var isRecoverableBlockUpdateError = (error2) => {
3965
+ if (!(error2 instanceof Error)) return false;
3966
+ if (!error2.message.startsWith('Command "git fetch ')) return false;
3967
+ return /could not resolve host|failed to connect|connection (?:timed out|reset|refused)|network is unreachable|temporary failure in name resolution|operation timed out|remote end hung up unexpectedly|early EOF/i.test(
3968
+ error2.message
3969
+ );
3970
+ };
3185
3971
  async function confirmContinueWhenMissing(itemType, name) {
3186
3972
  return confirm({
3187
3973
  message: `${itemType}: ${name} does not exist in registries. Continue updating remaining parts?`,
@@ -3227,7 +4013,7 @@ async function updateApp({
3227
4013
  continue;
3228
4014
  }
3229
4015
  await git.updateRemote(block.name, blockRegistryData.source);
3230
- const blockPath = import_node_path23.default.join(blocksDir, block.name);
4016
+ const blockPath = getBlockPath(block.name);
3231
4017
  const currentBloxFile = getBloxFile(blockPath);
3232
4018
  const remoteBloxFile = (await migrateOnRemote(block.name, toAppCommit, blockPath)).output[".blox"];
3233
4019
  const blockFromCommit = currentBloxFile.checkpoints?.[block.name]?.commit;
@@ -3249,7 +4035,10 @@ async function updateAppBases(templateDef, templates, ignore3, hard = false) {
3249
4035
  let shouldContinue = true;
3250
4036
  for (const base of templateDef.bases || []) {
3251
4037
  await runTask(
3252
- { start: `Update App base: ${base.name}`, end: `Updated App base: ${base.name}` },
4038
+ {
4039
+ start: `Update App base: ${base.name}`,
4040
+ end: `Updated App base: ${base.name}`
4041
+ },
3253
4042
  async () => {
3254
4043
  const template = templates[base.name];
3255
4044
  if (!template) {
@@ -3274,33 +4063,90 @@ async function updateAppBases(templateDef, templates, ignore3, hard = false) {
3274
4063
  }
3275
4064
  async function updateBlock(block, blocks, ignore3, hard = false) {
3276
4065
  const blockRegistryData = blocks[block];
3277
- const blockPath = import_node_path23.default.join(blocksDir, block);
3278
4066
  let updated = false;
3279
- let shouldContinue = true;
3280
- await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
4067
+ try {
4068
+ const blockPath = getBlockPath(block);
3281
4069
  if (!blockRegistryData) {
3282
- shouldContinue = await confirmContinueWhenMissing("block" /* BLOCK */, block);
3283
- return;
4070
+ throw new Error(
4071
+ `${"block" /* BLOCK */}: ${block} does not exist in registries.`
4072
+ );
3284
4073
  }
3285
- const toCommit = await updateFromRemote({
3286
- name: block,
3287
- source: blockRegistryData.source,
3288
- dir: blockPath,
3289
- ignore: ignore3,
3290
- hard
3291
- });
3292
- if (toCommit) updated = true;
3293
- });
3294
- if (updated) {
3295
- await runLifecycleHookWithTask(blockPath, "update", "Run block update");
4074
+ let toCommit;
4075
+ for (let attempt = 1; attempt <= 3; attempt++) {
4076
+ try {
4077
+ toCommit = await updateFromRemote({
4078
+ name: block,
4079
+ source: blockRegistryData.source,
4080
+ dir: blockPath,
4081
+ ignore: ignore3,
4082
+ hard
4083
+ });
4084
+ break;
4085
+ } catch (error2) {
4086
+ if (attempt === 3 || !isRecoverableBlockUpdateError(error2)) {
4087
+ throw error2;
4088
+ }
4089
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * 2 ** (attempt - 1)));
4090
+ }
4091
+ }
4092
+ if (toCommit) {
4093
+ updated = true;
4094
+ }
4095
+ return {
4096
+ block,
4097
+ updated,
4098
+ shouldContinue: true
4099
+ };
4100
+ } catch (error2) {
4101
+ return {
4102
+ block,
4103
+ updated,
4104
+ shouldContinue: true,
4105
+ error: error2
4106
+ };
3296
4107
  }
3297
- return { updated, shouldContinue };
4108
+ }
4109
+ async function updateBlocks(blocks, availableBlocks, ignoresByName, hard = false) {
4110
+ if (blocks.length === 0) {
4111
+ return [];
4112
+ }
4113
+ if (blocks.length === 1) {
4114
+ const block = blocks[0];
4115
+ if (!block) {
4116
+ return [];
4117
+ }
4118
+ let result;
4119
+ await runTask(
4120
+ {
4121
+ start: `Update block: ${block}`,
4122
+ end: `Updated block: ${block}`
4123
+ },
4124
+ async () => {
4125
+ result = await updateBlock(block, availableBlocks, ignoresByName[block], hard);
4126
+ }
4127
+ );
4128
+ return result ? [result] : [];
4129
+ }
4130
+ const blockNames = blocks.join(", ");
4131
+ import_prompts2.log.info(`Update blocks: ${blockNames}`);
4132
+ const results = await Promise.all(
4133
+ blocks.map((block) => updateBlock(block, availableBlocks, ignoresByName[block], hard))
4134
+ );
4135
+ import_prompts2.log.success(`Updated blocks: ${blockNames}`);
4136
+ return results;
4137
+ }
4138
+ async function runBlockUpdateHook(block) {
4139
+ const blockPath = getBlockPath(block);
4140
+ await runLifecycleHookWithTask(blockPath, "update", "Run block update");
3298
4141
  }
3299
4142
  async function getCurrentCheckpoints() {
3300
4143
  const bloxFile = getBloxFile();
3301
4144
  let checkpoints = { ...bloxFile.checkpoints };
3302
4145
  for (const block of getUsedBlocks()) {
3303
- checkpoints = { ...checkpoints, ...block.checkpoints };
4146
+ checkpoints = {
4147
+ ...checkpoints,
4148
+ ...block.checkpoints
4149
+ };
3304
4150
  }
3305
4151
  return checkpoints;
3306
4152
  }
@@ -3320,7 +4166,7 @@ ${changes}`);
3320
4166
  }
3321
4167
  if (allChanges.length) {
3322
4168
  logWarningSection(
3323
- `ChangeLog, These is the changes from last update, make sure to review for breaking changes`,
4169
+ "ChangeLog, These is the changes from last update, make sure to review for breaking changes",
3324
4170
  allChanges.join(`
3325
4171
  ${fmt.gray("-".repeat(82))}
3326
4172
 
@@ -3334,9 +4180,9 @@ ${fmt.gray("-".repeat(82))}
3334
4180
  // src/commands/update/index.ts
3335
4181
  var update2 = command("update").description("Update app/block").alias("u").addOption(
3336
4182
  option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
3337
- ).option("--ignore <list...>", 'Files ignore list scoped by name i.e "repo:file"').option("-b, --block <name>", "Block to update, valid only with scope block").option("--hard", "Hard update (overwrite local changes)", false).action(async (args) => {
4183
+ ).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) => {
3338
4184
  if (await git.hasUncommittedChanges()) {
3339
- import_prompts23.log.warn(fmt.yellow("Make sure to commit any changes first"));
4185
+ import_prompts26.log.warn(fmt.yellow("Make sure to commit any changes first"));
3340
4186
  return;
3341
4187
  }
3342
4188
  await migrateAll(true);
@@ -3384,46 +4230,95 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
3384
4230
  shouldContinue = basesResult.shouldContinue;
3385
4231
  }
3386
4232
  if (shouldContinue && args.scope === "all") {
3387
- for (const block of usedBlocks) {
3388
- const blockResult = await updateBlock(
3389
- block.name,
4233
+ const missingBlocks = usedBlocks.filter((block) => !availableBlocks[block.name]);
4234
+ for (const block of missingBlocks) {
4235
+ const shouldUpdateRemaining = await select({
4236
+ message: `${block.name} does not exist in registries. Continue updating remaining parts?`,
4237
+ options: [
4238
+ {
4239
+ value: true,
4240
+ label: "Continue"
4241
+ },
4242
+ {
4243
+ value: false,
4244
+ label: "Stop"
4245
+ }
4246
+ ]
4247
+ });
4248
+ if (!shouldUpdateRemaining) {
4249
+ shouldContinue = false;
4250
+ break;
4251
+ }
4252
+ }
4253
+ if (shouldContinue) {
4254
+ const blocksToUpdate = usedBlocks.filter((block) => availableBlocks[block.name]).map((block) => block.name);
4255
+ const blockResults = await updateBlocks(
4256
+ blocksToUpdate,
3390
4257
  availableBlocks,
3391
- ignoresByName[block.name],
4258
+ ignoresByName,
3392
4259
  args.hard
3393
4260
  );
3394
- hasUpdate = hasUpdate || blockResult.updated;
3395
- if (!blockResult.shouldContinue) {
3396
- shouldContinue = false;
3397
- break;
4261
+ hasUpdate = hasUpdate || blockResults.some((result) => result.updated);
4262
+ const failedBlocks = blockResults.filter((result) => result.error);
4263
+ if (failedBlocks.length) {
4264
+ import_prompts26.log.warn(
4265
+ fmt.yellow(
4266
+ `${failedBlocks.length} block update${failedBlocks.length === 1 ? "" : "s"} failed.`
4267
+ )
4268
+ );
4269
+ for (const result of failedBlocks) {
4270
+ import_prompts26.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
4271
+ }
4272
+ import_prompts26.log.warn(
4273
+ "Fix the errors above and rerun the update for the failed blocks."
4274
+ );
4275
+ }
4276
+ for (const result of blockResults) {
4277
+ if (!result.updated) continue;
4278
+ await runBlockUpdateHook(result.block);
3398
4279
  }
3399
4280
  }
3400
4281
  }
3401
4282
  if (shouldContinue && args.scope === "block") {
3402
- if (!args.block) {
3403
- args.block = await select({
4283
+ const requested = args.block?.length ? args.block : [
4284
+ await select({
3404
4285
  message: "Select block to be updated",
3405
4286
  options: usedBlocks.map((block) => ({
3406
4287
  value: block.name,
3407
4288
  label: block.name
3408
4289
  }))
3409
- });
3410
- }
3411
- const blockDef = usedBlocks.find((block) => block.name === args.block);
3412
- if (!blockDef) {
3413
- error("Selected block not used in app");
4290
+ })
4291
+ ];
4292
+ const unknown = requested.filter(
4293
+ (name) => !usedBlocks.some((block) => block.name === name)
4294
+ );
4295
+ if (unknown.length) {
4296
+ error(`Selected block not used in app: ${unknown.join(", ")}`);
3414
4297
  return;
3415
4298
  }
3416
- const blockResult = await updateBlock(
3417
- blockDef.name,
4299
+ const blockResults = await updateBlocks(
4300
+ requested,
3418
4301
  availableBlocks,
3419
- ignoresByName[blockDef.name],
4302
+ ignoresByName,
3420
4303
  args.hard
3421
4304
  );
3422
- hasUpdate = hasUpdate || blockResult.updated;
3423
- shouldContinue = blockResult.shouldContinue;
4305
+ for (const result of blockResults) {
4306
+ if (result.error) {
4307
+ import_prompts26.log.error(fmt.red(`${result.block}: ${getErrorMessage(result.error)}`));
4308
+ }
4309
+ }
4310
+ if (blockResults.some((result) => result.error)) {
4311
+ import_prompts26.log.warn("Fix the errors above and rerun the update for the failed blocks.");
4312
+ }
4313
+ hasUpdate = hasUpdate || blockResults.some((result) => result.updated);
4314
+ for (const result of blockResults) {
4315
+ if (result.updated) {
4316
+ await runBlockUpdateHook(result.block);
4317
+ }
4318
+ }
3424
4319
  }
3425
4320
  if (!shouldContinue) {
3426
- import_prompts23.log.warn(fmt.yellow("Stopped updating remaining parts by user choice"));
4321
+ import_prompts26.log.warn(fmt.yellow("Stopped updating remaining parts by user choice"));
3427
4322
  }
3428
4323
  if (hasUpdate) {
3429
4324
  await runLifecycleHookWithTask(".", "update", "Run template update");
@@ -3433,7 +4328,7 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
3433
4328
  await printChangeLog(startCheckpoints, endCheckpoints);
3434
4329
  } catch (e) {
3435
4330
  if (!isDebugMode()) {
3436
- import_prompts23.log.warn("Error happened, Will rollback changes");
4331
+ import_prompts26.log.warn("Error happened, Will rollback changes");
3437
4332
  await git.rollback();
3438
4333
  }
3439
4334
  error(e);
@@ -3441,6 +4336,12 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
3441
4336
  await git.cleanUpWorktrees();
3442
4337
  }
3443
4338
  });
4339
+ function getErrorMessage(error2) {
4340
+ if (error2 instanceof Error) {
4341
+ return error2.message;
4342
+ }
4343
+ return String(error2);
4344
+ }
3444
4345
 
3445
4346
  // src/commands/upgrade/index.ts
3446
4347
  var upgrade = command("upgrade").description("Upgrade blox cli to latest version").action(async () => {