@naseej/blox 1.5.0 → 1.5.2

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
@@ -22,6 +22,23 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  mod
23
23
  ));
24
24
 
25
+ // src/shared/command/index.ts
26
+ var import_extra_typings = require("@commander-js/extra-typings");
27
+ var import_extra_typings2 = require("@commander-js/extra-typings");
28
+ var command = (name) => new import_extra_typings.Command(name);
29
+ var option = (flags, description) => {
30
+ return new import_extra_typings.Option(flags, description);
31
+ };
32
+
33
+ // src/config/runtime.ts
34
+ var bloxCliVersion = "0.0.0";
35
+ var setBloxCliVersion = (version2) => {
36
+ bloxCliVersion = version2;
37
+ };
38
+ var getBloxCliVersion = () => bloxCliVersion;
39
+ var isDebugMode = () => !!import_extra_typings2.program.opts()?.debug;
40
+ var isMinimalMode = () => !!import_extra_typings2.program.opts()?.minimal;
41
+
25
42
  // src/services/cliVersion.ts
26
43
  var import_node_https = __toESM(require("https"));
27
44
  var import_node_path2 = __toESM(require("path"));
@@ -45,18 +62,6 @@ var defaultBranch = "main";
45
62
  var console2 = __toESM(require("console"));
46
63
  var import_prompts = require("@clack/prompts");
47
64
 
48
- // src/shared/command/index.ts
49
- var import_extra_typings = require("@commander-js/extra-typings");
50
- var import_extra_typings2 = require("@commander-js/extra-typings");
51
- var command = (name) => new import_extra_typings.Command(name);
52
- var option = (flags, description) => {
53
- return new import_extra_typings.Option(flags, description);
54
- };
55
-
56
- // src/config/runtime.ts
57
- var isDebugMode = () => !!import_extra_typings2.program.opts()?.debug;
58
- var isMinimalMode = () => !!import_extra_typings2.program.opts()?.minimal;
59
-
60
65
  // src/shared/terminal/index.ts
61
66
  var import_ansis = __toESM(require("ansis"));
62
67
  var fmt = import_ansis.default;
@@ -180,18 +185,18 @@ var checkForCliUpdate = async (currentVersion) => {
180
185
  };
181
186
 
182
187
  // package.json
183
- var version = "1.5.0";
188
+ var version = "1.5.2";
184
189
 
185
190
  // src/commands/add/index.ts
186
- var import_fs_extra9 = __toESM(require("fs-extra"));
191
+ var import_fs_extra10 = __toESM(require("fs-extra"));
187
192
 
188
193
  // src/migrations/index.ts
189
- var import_node_path7 = __toESM(require("path"));
190
- var import_fs_extra5 = __toESM(require("fs-extra"));
194
+ var import_node_path10 = __toESM(require("path"));
195
+ var import_fs_extra7 = __toESM(require("fs-extra"));
191
196
 
192
197
  // src/migrations/utils.ts
193
- var import_node_path6 = __toESM(require("path"));
194
- var import_fs_extra4 = __toESM(require("fs-extra"));
198
+ var import_node_path9 = __toESM(require("path"));
199
+ var import_fs_extra6 = __toESM(require("fs-extra"));
195
200
 
196
201
  // src/migrations/list/v1.ts
197
202
  var v1 = {
@@ -228,18 +233,18 @@ var migrationsList = [v1];
228
233
 
229
234
  // src/services/git.ts
230
235
  var import_node_os = __toESM(require("os"));
231
- var import_node_path5 = __toESM(require("path"));
232
- var import_fs_extra3 = __toESM(require("fs-extra"));
236
+ var import_node_path8 = __toESM(require("path"));
237
+ var import_fs_extra5 = __toESM(require("fs-extra"));
233
238
 
234
239
  // src/services/shell.ts
235
- var import_node_child_process = require("child_process");
236
- var $ = async (bin, options = [], { cwd, onStdout } = {}) => {
240
+ var import_cross_spawn = __toESM(require("cross-spawn"));
241
+ var $ = async (bin, options = [], { cwd, onStdout, shell = false } = {}) => {
237
242
  debug(`Command executed: "${bin} ${options.join(" ")}" with cwd = ${cwd}`);
238
243
  return new Promise(function(resolve, reject) {
239
- const child = (0, import_node_child_process.spawn)(bin, options, { cwd, shell: true, stdio: ["pipe", "pipe", "pipe"] });
244
+ const child = (0, import_cross_spawn.default)(bin, options, { cwd, shell, stdio: ["pipe", "pipe", "pipe"] });
240
245
  let stdout = "";
241
246
  let stderr = "";
242
- child.stdout.on("data", (data) => {
247
+ child.stdout?.on("data", (data) => {
243
248
  const str = data.toString();
244
249
  stdout += str;
245
250
  try {
@@ -248,7 +253,7 @@ var $ = async (bin, options = [], { cwd, onStdout } = {}) => {
248
253
  reject(e);
249
254
  }
250
255
  });
251
- child.stderr.on("data", (data) => {
256
+ child.stderr?.on("data", (data) => {
252
257
  stderr += data.toString();
253
258
  });
254
259
  child.on("close", function(code) {
@@ -353,10 +358,214 @@ function isBinaryFile(ext) {
353
358
  return BINARY_EXTENSIONS.has(ext);
354
359
  }
355
360
 
356
- // src/services/path.ts
361
+ // src/shared/utils/openUrlInBrowser.ts
362
+ var import_node_child_process = require("child_process");
363
+ function openUrlInBrowser(url) {
364
+ return new Promise((resolve, reject) => {
365
+ try {
366
+ let cmd;
367
+ let args;
368
+ if (process.platform === "win32") {
369
+ cmd = "cmd";
370
+ args = ["/c", "start", "", url];
371
+ } else if (process.platform === "darwin") {
372
+ cmd = "open";
373
+ args = [url];
374
+ } else {
375
+ cmd = "xdg-open";
376
+ args = [url];
377
+ }
378
+ const child = (0, import_node_child_process.execFile)(cmd, args, { windowsHide: true });
379
+ child.on("error", (err) => {
380
+ reject(err);
381
+ });
382
+ resolve();
383
+ } catch (err) {
384
+ reject(err);
385
+ }
386
+ });
387
+ }
388
+
389
+ // src/shared/utils/isBloxConfigFile.ts
357
390
  var import_node_path4 = __toESM(require("path"));
391
+ function isBloxConfigFile(file) {
392
+ const normalized = file.split(import_node_path4.default.sep).join("/");
393
+ return normalized === bloxFilePath || normalized.endsWith(`/${bloxFilePath}`);
394
+ }
395
+
396
+ // src/shared/utils/omitKeys.ts
397
+ function omitKeys(value, keysToOmit) {
398
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
399
+ return value;
400
+ }
401
+ const result = { ...value };
402
+ for (const key of keysToOmit) {
403
+ delete result[key];
404
+ }
405
+ return result;
406
+ }
407
+
408
+ // src/shared/utils/normalizeCommitRef.ts
409
+ var normalizeCommitRef = (commit2) => commit2.trim().replace(/\r/g, "").replace(/^"+|"+$/g, "");
410
+
411
+ // src/shared/utils/isBlockDirectory.ts
412
+ var import_node_path5 = __toESM(require("path"));
413
+ var import_fs_extra3 = __toESM(require("fs-extra"));
414
+ function isBlockDirectory(blockDir) {
415
+ const bloxPath = import_node_path5.default.join(blockDir, bloxFilePath);
416
+ if (!import_fs_extra3.default.existsSync(bloxPath)) {
417
+ return false;
418
+ }
419
+ try {
420
+ return import_fs_extra3.default.statSync(bloxPath).isFile();
421
+ } catch {
422
+ return false;
423
+ }
424
+ }
425
+
426
+ // src/services/template.ts
427
+ var import_node_path6 = __toESM(require("path"));
428
+ var import_ejs = __toESM(require("ejs"));
429
+ var import_fs_extra4 = __toESM(require("fs-extra"));
430
+ var import_klaw = __toESM(require("klaw"));
431
+ async function replacePlaceholders(dir, context) {
432
+ debug("Replace placeholders");
433
+ for await (const file of (0, import_klaw.default)(dir)) {
434
+ if (!file.stats.isFile()) continue;
435
+ const ext = import_node_path6.default.extname(file.path).toLowerCase();
436
+ if (isBinaryFile(ext)) {
437
+ continue;
438
+ }
439
+ const templateContent = import_fs_extra4.default.readFileSync(file.path, "utf8");
440
+ if (!templateContent.includes("<%")) {
441
+ continue;
442
+ }
443
+ try {
444
+ const rendered = import_ejs.default.render(templateContent, context);
445
+ import_fs_extra4.default.writeFileSync(file.path, rendered, "utf8");
446
+ } catch (err) {
447
+ console.error("\u274C Error rendering EJS for file:", file.path);
448
+ throw err;
449
+ }
450
+ }
451
+ }
452
+ function getTemplateDef(cwd = ".") {
453
+ debug("Get template def");
454
+ const def = getBloxFile(cwd).definition;
455
+ debug(def);
456
+ return def;
457
+ }
458
+ function getBlockDef(cwd = ".") {
459
+ debug("Get block def");
460
+ const def = getBloxFile(cwd).definition;
461
+ def && debug(def);
462
+ return def;
463
+ }
464
+ function getBloxFile(cwd = ".") {
465
+ try {
466
+ const file = import_fs_extra4.default.readJSONSync(import_node_path6.default.join(cwd, bloxFilePath));
467
+ if (!file.checkpoints) {
468
+ file.checkpoints = {};
469
+ }
470
+ return file;
471
+ } catch {
472
+ return {};
473
+ }
474
+ }
475
+ function saveBloxFile(info, cwd = ".") {
476
+ debug("Save info");
477
+ import_fs_extra4.default.writeFileSync(import_node_path6.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
478
+ }
479
+ function updateCheckpoint(name, checkpoint, cwd = ".") {
480
+ const info = getBloxFile(cwd);
481
+ if (!info.checkpoints) {
482
+ info.checkpoints = {};
483
+ }
484
+ info.checkpoints[name] = checkpoint;
485
+ saveBloxFile(info, cwd);
486
+ }
487
+ function getUsedBlocksDef() {
488
+ return getUsedBlocks().map((b) => b.definition);
489
+ }
490
+ function getUsedBlocks() {
491
+ debug("Get used blocks");
492
+ const blocks = [];
493
+ if (import_fs_extra4.default.existsSync(blocksDir)) {
494
+ import_fs_extra4.default.readdirSync(blocksDir, { withFileTypes: true }).forEach((file) => {
495
+ if (!file.isDirectory()) {
496
+ return;
497
+ }
498
+ const blockDef = getBloxFile(import_node_path6.default.join(blocksDir, file.name));
499
+ if (blockDef && blockDef.definition) {
500
+ blocks.push(blockDef);
501
+ }
502
+ });
503
+ }
504
+ debug(blocks);
505
+ return blocks;
506
+ }
507
+
508
+ // src/shared/spinner.ts
509
+ var import_prompts3 = require("@clack/prompts");
510
+ var spinner = () => {
511
+ const s = (0, import_prompts3.spinner)();
512
+ const minimal = isMinimalMode() || isDebugMode();
513
+ return {
514
+ start: (msg) => {
515
+ minimal ? import_prompts2.log.step(`${msg || "start"}...`) : s.start(msg);
516
+ },
517
+ stop: (msg = "error", code) => {
518
+ minimal ? code ? import_prompts2.log.error(msg) : import_prompts2.log.step(msg || "success") : s.stop(code ? fmt.red(msg) : fmt.green(msg), code);
519
+ },
520
+ message: (msg) => {
521
+ minimal ? import_prompts2.log.message(msg) : s.message(msg);
522
+ }
523
+ };
524
+ };
525
+ async function runTask(message, task) {
526
+ const startMessage = typeof message === "string" ? message : message.start;
527
+ const endMessage = typeof message === "string" ? message : message.end;
528
+ const taskSpinner = spinner();
529
+ taskSpinner.start(startMessage);
530
+ try {
531
+ await (typeof task === "function" ? task() : task);
532
+ taskSpinner.stop(endMessage);
533
+ } catch (e) {
534
+ taskSpinner.stop(`Failed: ${startMessage}`, 1);
535
+ throw e;
536
+ }
537
+ }
538
+
539
+ // src/shared/utils/runLifecycleHook.ts
540
+ function getLifecycleHookScript(cwd, hook) {
541
+ const definition = getTemplateDef(cwd);
542
+ const script = definition[hook];
543
+ if (typeof script !== "string" || !script.trim()) {
544
+ return void 0;
545
+ }
546
+ return script.trim();
547
+ }
548
+ async function runLifecycleHookScript(cwd, script) {
549
+ const isWin = process.platform === "win32";
550
+ if (isWin) {
551
+ await $("cmd.exe", ["/d", "/s", "/c", script], { cwd });
552
+ return;
553
+ }
554
+ await $("/bin/sh", ["-lc", script], { cwd });
555
+ }
556
+ async function runLifecycleHookWithTask(cwd, hook, message) {
557
+ const script = getLifecycleHookScript(cwd, hook);
558
+ if (!script) {
559
+ return;
560
+ }
561
+ debug(`Run lifecycle hook ${hook} in: ${cwd}`);
562
+ await runTask(message, async () => runLifecycleHookScript(cwd, script));
563
+ }
564
+
565
+ // src/services/path.ts
566
+ var import_node_path7 = __toESM(require("path"));
358
567
  var normalizePath = (_path) => {
359
- return _path.split(import_node_path4.default.sep).join("/");
568
+ return _path.split(import_node_path7.default.sep).join("/");
360
569
  };
361
570
 
362
571
  // src/services/git.ts
@@ -387,16 +596,16 @@ var getRemoteWorktree = async (remote, commit2) => {
387
596
  return remoteWorktrees.get(key);
388
597
  }
389
598
  const tmpDir = import_node_os.default.tmpdir();
390
- const worktreeDir = import_node_path5.default.join(tmpDir, "blox-cli-worktrees", remote, commit2);
599
+ const worktreeDir = import_node_path8.default.join(tmpDir, "blox-cli-worktrees", remote, commit2);
391
600
  try {
392
601
  await $("git", ["worktree", "prune"]);
393
602
  } catch {
394
603
  }
395
- if (await import_fs_extra3.default.pathExists(worktreeDir)) {
604
+ if (await import_fs_extra5.default.pathExists(worktreeDir)) {
396
605
  try {
397
606
  await $("git", ["worktree", "remove", "--force", worktreeDir]);
398
607
  } catch {
399
- await import_fs_extra3.default.remove(worktreeDir);
608
+ await import_fs_extra5.default.remove(worktreeDir);
400
609
  try {
401
610
  await $("git", ["worktree", "prune"]);
402
611
  } catch {
@@ -430,14 +639,20 @@ var checkAuth = (message) => {
430
639
  var defaultShellOptions = {
431
640
  onStdout: checkAuth
432
641
  };
433
- var clone = (repoUrl, options, branch = defaultBranch, shellOptions = {}) => {
434
- return $("git", ["clone", "--progress", repoUrl, "--branch", branch, options], {
642
+ var clone = (repoUrl, dir, branch = defaultBranch, options = {}) => {
643
+ const { depth, ...shellOptions } = options;
644
+ const args = ["clone", "--progress"];
645
+ if (depth != null && depth > 0) {
646
+ args.push("--depth", String(depth));
647
+ }
648
+ args.push(repoUrl, "--branch", branch, dir);
649
+ return $("git", args, {
435
650
  ...defaultShellOptions,
436
651
  ...shellOptions
437
652
  });
438
653
  };
439
654
  var resetToCommit = async (commit2, cwd = ".") => {
440
- await $("git", ["reset --hard", `${commit2}`], { cwd });
655
+ await $("git", ["reset", "--hard", commit2], { cwd });
441
656
  };
442
657
  var updatedRemotes = /* @__PURE__ */ new Set();
443
658
  var updateRemote = async (name, source, shellOptions = {}) => {
@@ -459,10 +674,12 @@ var updateRemote = async (name, source, shellOptions = {}) => {
459
674
  });
460
675
  await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
461
676
  };
462
- var readJsonFromCommit = async (commit2, file) => {
677
+ var readJsonFromCommit = async (commit2, file, cwd = ".") => {
463
678
  try {
464
679
  let content = "";
465
- await $("git", ["show", `${commit2}:${file}`], {
680
+ const p = normalizePath(file);
681
+ await $("git", ["show", `${commit2}:${p}`], {
682
+ cwd,
466
683
  onStdout: (text2) => {
467
684
  content = text2;
468
685
  }
@@ -472,12 +689,27 @@ var readJsonFromCommit = async (commit2, file) => {
472
689
  return {};
473
690
  }
474
691
  };
692
+ var readJsonFromIndex = async (file, cwd = ".") => {
693
+ try {
694
+ let content = "";
695
+ const p = normalizePath(file);
696
+ await $("git", ["show", `:0:${p}`], {
697
+ cwd,
698
+ onStdout: (text2) => {
699
+ content = text2;
700
+ }
701
+ });
702
+ return JSON.parse(content);
703
+ } catch {
704
+ return null;
705
+ }
706
+ };
475
707
  var readJsonFromRemote = async (remote, file, branch = defaultBranch, commit2) => {
476
708
  return readJsonFromCommit(commit2 || `${remote}/${branch}`, file);
477
709
  };
478
710
  var isCommitOlder = async (a, b) => {
479
711
  try {
480
- await $("git", ["merge-base --is-ancestor", a, b]);
712
+ await $("git", ["merge-base", "--is-ancestor", a, b]);
481
713
  return true;
482
714
  } catch {
483
715
  return false;
@@ -489,8 +721,8 @@ var update = (shellOptions = {}) => {
489
721
  var getLatestCommitFromRemote = async (remote, branch) => {
490
722
  return getLatestCommit(`${remote}/${branch}`);
491
723
  };
492
- var getLatestCommitFromPath = async (path17) => {
493
- return getLatestCommit("HEAD", path17);
724
+ var getLatestCommitFromPath = async (path23) => {
725
+ return getLatestCommit("HEAD", path23);
494
726
  };
495
727
  var getLatestCommit = async (rev, cwd = ".") => {
496
728
  debug(`Get latest commit for rev: ${rev} and cwd: ${cwd}`);
@@ -501,7 +733,7 @@ var getLatestCommit = async (rev, cwd = ".") => {
501
733
  commit2 = text2;
502
734
  }
503
735
  });
504
- return commit2.replace(/\n/g, "");
736
+ return commit2.replace(/\r?\n/g, "").trim();
505
737
  };
506
738
  var getChangesLog = async (fromCommit, toCommit) => {
507
739
  let changes = "";
@@ -514,7 +746,7 @@ var getChangesLog = async (fromCommit, toCommit) => {
514
746
  };
515
747
  var unInit = (cwd) => {
516
748
  debug("UnInit");
517
- return import_fs_extra3.default.remove(import_node_path5.default.join(cwd, ".git"));
749
+ return import_fs_extra5.default.remove(import_node_path8.default.join(cwd, ".git"));
518
750
  };
519
751
  var init = async (cwd) => {
520
752
  debug("Init");
@@ -529,7 +761,7 @@ var add = async (toAdd, cwd = ".") => {
529
761
  };
530
762
  var commit = async (msg, cwd = ".") => {
531
763
  debug(`Git commit: ${msg}`);
532
- await $("git", ["commit", "--no-verify", "-m", `"${msg}"`], { cwd });
764
+ await $("git", ["commit", "--no-verify", "-m", msg], { cwd });
533
765
  };
534
766
  var rollback = async () => {
535
767
  debug("Rollback");
@@ -631,11 +863,11 @@ var createBranch = async (branch, from, cwd = ".") => {
631
863
  var push = async (remote, branch, cwd = ".") => {
632
864
  await $("git", ["push", "--progress", remote, `refs/heads/${branch}`], { cwd });
633
865
  };
634
- var checkoutFile = async (path17, ref, cwd = ".") => {
866
+ var checkoutFile = async (path23, ref, cwd = ".") => {
635
867
  const args = ["checkout"];
636
868
  if (ref) args.push(ref);
637
869
  else args.push("HEAD");
638
- args.push("--", path17);
870
+ args.push("--", path23);
639
871
  await $("git", args, { cwd });
640
872
  };
641
873
  var pathExistsAsBlobInRev = async (rev, filePath, cwd = ".") => {
@@ -659,7 +891,7 @@ var listCommits = async (limit, skip, cwd = ".") => {
659
891
  let out = "";
660
892
  await $(
661
893
  "git",
662
- ["log", '--pretty=format:"%H|%s"', "-n", String(limit), "--skip", String(skip), "HEAD"],
894
+ ["log", "--pretty=format:%H|%s", "-n", String(limit), "--skip", String(skip), "HEAD"],
663
895
  {
664
896
  cwd,
665
897
  onStdout: (text2) => {
@@ -667,28 +899,30 @@ var listCommits = async (limit, skip, cwd = ".") => {
667
899
  }
668
900
  }
669
901
  );
670
- const lines = out.split("\n").filter(Boolean);
902
+ const lines = out.split(/\r?\n/).filter(Boolean);
671
903
  return lines.map((line) => {
672
904
  const pipe = line.indexOf("|");
673
- const hash = pipe >= 0 ? line.slice(0, pipe) : line;
674
- const subject = pipe >= 0 ? line.slice(pipe + 1) : "";
675
- return { hash: hash.trim(), subject: subject.trim() };
905
+ const hashRaw = pipe >= 0 ? line.slice(0, pipe) : line;
906
+ const subjectRaw = pipe >= 0 ? line.slice(pipe + 1) : "";
907
+ const hash = hashRaw.trim().replace(/^"+|"+$/g, "");
908
+ return { hash, subject: subjectRaw.trim() };
676
909
  });
677
910
  };
678
911
  var fetchCommit = async (fromRepo, commit2, cwd = ".") => {
679
- await $("git", ["fetch", fromRepo, commit2], { cwd });
912
+ const ref = normalizeCommitRef(commit2);
913
+ await $("git", ["fetch", fromRepo, `+${ref}:FETCH_HEAD`], { cwd });
680
914
  };
681
915
  var cherryPick = async (commitHash, subtree, noCommit, cwd = ".") => {
682
916
  const args = ["cherry-pick"];
683
917
  if (noCommit) args.push("--no-commit");
684
918
  if (subtree) args.push(`-Xsubtree=${subtree}`);
685
- args.push(commitHash);
919
+ args.push(normalizeCommitRef(commitHash));
686
920
  await $("git", args, { cwd });
687
921
  };
688
- var reset = async (path17, hard, cwd = ".") => {
922
+ var reset = async (path23, hard, cwd = ".") => {
689
923
  const args = ["reset"];
690
924
  if (hard) args.push("--hard");
691
- if (path17) args.push(path17);
925
+ if (path23) args.push(path23);
692
926
  await $("git", args, { cwd });
693
927
  };
694
928
  var commitAll = async (message, cwd = ".") => {
@@ -728,6 +962,7 @@ var git = {
728
962
  getChangesLog,
729
963
  updateRemote,
730
964
  readJsonFromCommit,
965
+ readJsonFromIndex,
731
966
  readJsonFromRemote,
732
967
  isCommitOlder,
733
968
  rollback,
@@ -761,15 +996,15 @@ var git = {
761
996
  };
762
997
 
763
998
  // src/shared/prompts/index.ts
764
- var import_prompts3 = require("@clack/prompts");
999
+ var import_prompts4 = require("@clack/prompts");
765
1000
  var checkIfCanceled = (value) => {
766
- if ((0, import_prompts3.isCancel)(value)) {
767
- (0, import_prompts3.cancel)();
1001
+ if ((0, import_prompts4.isCancel)(value)) {
1002
+ (0, import_prompts4.cancel)();
768
1003
  process.exit(0);
769
1004
  }
770
1005
  };
771
1006
  var error = (error2, exit = true) => {
772
- import_prompts3.log.error(
1007
+ import_prompts4.log.error(
773
1008
  fmt.red(
774
1009
  typeof error2 === "string" ? error2 : error2?.shortMessage || error2?.message || JSON.stringify(error2)
775
1010
  )
@@ -777,28 +1012,28 @@ var error = (error2, exit = true) => {
777
1012
  exit && process.exit(-1);
778
1013
  };
779
1014
  var select = async (opts) => {
780
- const value = await (0, import_prompts3.select)(opts);
1015
+ const value = await (0, import_prompts4.select)(opts);
781
1016
  checkIfCanceled(value);
782
1017
  return value;
783
1018
  };
784
1019
  var text = async (opts) => {
785
- const value = await (0, import_prompts3.text)(opts);
1020
+ const value = await (0, import_prompts4.text)(opts);
786
1021
  checkIfCanceled(value);
787
1022
  return value;
788
1023
  };
789
1024
  var confirm = async (opts) => {
790
- const value = await (0, import_prompts3.confirm)(opts);
1025
+ const value = await (0, import_prompts4.confirm)(opts);
791
1026
  checkIfCanceled(value);
792
1027
  return value;
793
1028
  };
794
1029
  var multiselect = async (opts) => {
795
- const value = await (0, import_prompts3.multiselect)(opts);
1030
+ const value = await (0, import_prompts4.multiselect)(opts);
796
1031
  checkIfCanceled(value);
797
1032
  return value;
798
1033
  };
799
1034
  var textList = async (opts) => {
800
1035
  opts.message = `${opts.message} ${fmt.gray('(separated with ",")')}`;
801
- const value = await (0, import_prompts3.text)(opts);
1036
+ const value = await (0, import_prompts4.text)(opts);
802
1037
  checkIfCanceled(value);
803
1038
  opts.validate?.(value);
804
1039
  return value.split(",");
@@ -869,24 +1104,24 @@ async function migrate(name, { getPath = (f) => f, read, write }) {
869
1104
  }
870
1105
  function migrateOnLocal(name, cwd = ".") {
871
1106
  return migrate(name, {
872
- getPath: (file) => import_node_path6.default.join(cwd, file),
873
- read: import_fs_extra4.default.readJson,
874
- write: import_fs_extra4.default.writeFile
1107
+ getPath: (file) => import_node_path9.default.join(cwd, file),
1108
+ read: import_fs_extra6.default.readJson,
1109
+ write: import_fs_extra6.default.writeFile
875
1110
  });
876
1111
  }
877
1112
  function migrateOnRemote(name, commit2, cwd) {
878
1113
  return migrate(name, {
879
1114
  read: (file) => git.readJsonFromCommit(commit2, file),
880
- getPath: cwd ? (file) => import_node_path6.default.join(cwd, file) : void 0
1115
+ getPath: cwd ? (file) => import_node_path9.default.join(cwd, file) : void 0
881
1116
  });
882
1117
  }
883
1118
 
884
1119
  // src/migrations/index.ts
885
1120
  async function migrateAll(autoCommit) {
886
1121
  let filesChanged = (await migrateOnLocal("app")).filesChanged;
887
- const blocks = import_fs_extra5.default.existsSync(blocksDir) ? import_fs_extra5.default.readdirSync(blocksDir) : [];
1122
+ const blocks = import_fs_extra7.default.existsSync(blocksDir) ? import_fs_extra7.default.readdirSync(blocksDir) : [];
888
1123
  for (const block of blocks) {
889
- const res = await migrateOnLocal(block, import_node_path7.default.join(blocksDir, block));
1124
+ const res = await migrateOnLocal(block, import_node_path10.default.join(blocksDir, block));
890
1125
  filesChanged = filesChanged || res.filesChanged;
891
1126
  }
892
1127
  if (autoCommit && filesChanged && await git.hasUncommittedChanges()) {
@@ -897,81 +1132,51 @@ async function migrateAll(autoCommit) {
897
1132
  }
898
1133
 
899
1134
  // src/services/fs.ts
900
- var import_node_path8 = __toESM(require("path"));
901
- var import_fs_extra6 = __toESM(require("fs-extra"));
1135
+ var import_node_path11 = __toESM(require("path"));
1136
+ var import_fs_extra8 = __toESM(require("fs-extra"));
902
1137
  var import_ignore2 = __toESM(require("ignore"));
903
- var import_klaw = __toESM(require("klaw"));
1138
+ var import_klaw2 = __toESM(require("klaw"));
904
1139
  var filterBlacklisted = (item) => {
905
1140
  return !item.includes("node_modules") && !item.includes(".git");
906
1141
  };
907
1142
  var deletePattern = async (cwd, patterns = []) => {
908
1143
  const ig = (0, import_ignore2.default)().add(patterns);
909
- for await (const file of (0, import_klaw.default)(cwd, { filter: filterBlacklisted })) {
910
- const relativePath = import_node_path8.default.relative(cwd, file.path);
1144
+ for await (const file of (0, import_klaw2.default)(cwd, { filter: filterBlacklisted })) {
1145
+ const relativePath = import_node_path11.default.relative(cwd, file.path);
911
1146
  if (relativePath && ig.ignores(relativePath)) {
912
- if (!await import_fs_extra6.default.exists(file.path)) {
1147
+ if (!await import_fs_extra8.default.exists(file.path)) {
913
1148
  continue;
914
1149
  }
915
1150
  debug(`deleting: ${relativePath}`);
916
- await import_fs_extra6.default.remove(file.path);
1151
+ await import_fs_extra8.default.remove(file.path);
917
1152
  }
918
1153
  }
919
1154
  };
920
1155
 
921
1156
  // src/services/registry.ts
922
- var import_node_path9 = __toESM(require("path"));
923
- var import_fs_extra7 = __toESM(require("fs-extra"));
1157
+ var import_node_path12 = __toESM(require("path"));
1158
+ var import_fs_extra9 = __toESM(require("fs-extra"));
924
1159
  var import_merge = __toESM(require("lodash/merge"));
925
-
926
- // src/shared/spinner.ts
927
- var import_prompts5 = require("@clack/prompts");
928
- var spinner = () => {
929
- const s = (0, import_prompts5.spinner)();
930
- const minimal = isMinimalMode() || isDebugMode();
931
- return {
932
- start: (msg) => {
933
- minimal ? import_prompts2.log.step(`${msg || "start"}...`) : s.start(msg);
934
- },
935
- stop: (msg = "error", code) => {
936
- minimal ? code ? import_prompts2.log.error(msg) : import_prompts2.log.step(msg || "success") : s.stop(code ? fmt.red(msg) : fmt.green(msg), code);
937
- },
938
- message: (msg) => {
939
- minimal ? import_prompts2.log.message(msg) : s.message(msg);
940
- }
941
- };
942
- };
943
- async function runTask(message, task) {
944
- const startMessage = typeof message === "string" ? message : message.start;
945
- const endMessage = typeof message === "string" ? message : message.end;
946
- const taskSpinner = spinner();
947
- taskSpinner.start(startMessage);
948
- try {
949
- await (typeof task === "function" ? task() : task);
950
- taskSpinner.stop(endMessage);
951
- } catch (e) {
952
- taskSpinner.stop(`Failed: ${startMessage}`, 1);
953
- throw e;
954
- }
955
- }
956
-
957
- // src/services/registry.ts
958
- var registriesDataPath = import_node_path9.default.join(appPaths.data, "registries");
1160
+ var registriesDataPath = import_node_path12.default.join(appPaths.data, "registries");
959
1161
  var upeToDate = false;
960
1162
  var syncRegistries = async (branch) => {
961
1163
  if (upeToDate) return;
962
1164
  upeToDate = true;
963
1165
  debug("Sync registries");
964
- import_fs_extra7.default.ensureDirSync(registriesDataPath);
1166
+ import_fs_extra9.default.ensureDirSync(registriesDataPath);
965
1167
  const config = getLocalConfig();
966
1168
  return await runTask("Update registries", async () => {
967
1169
  await Promise.all(
968
1170
  config.registries.map(async (registry) => {
969
1171
  debug(`update registry: ${registry}`);
970
1172
  const repoName = registry.split("/").pop() || "";
971
- const repoDir = import_node_path9.default.join(registriesDataPath, repoName);
972
- if (!import_fs_extra7.default.existsSync(repoDir)) {
973
- await git.clone(registry, "--depth 1", branch, { cwd: registriesDataPath });
974
- } else if (import_fs_extra7.default.existsSync(import_node_path9.default.join(repoDir, ".git"))) {
1173
+ const repoDir = import_node_path12.default.join(registriesDataPath, repoName);
1174
+ if (!import_fs_extra9.default.existsSync(repoDir)) {
1175
+ await git.clone(registry, repoName, branch, {
1176
+ cwd: registriesDataPath,
1177
+ depth: 1
1178
+ });
1179
+ } else if (import_fs_extra9.default.existsSync(import_node_path12.default.join(repoDir, ".git"))) {
975
1180
  await git.update({ cwd: repoDir });
976
1181
  } else {
977
1182
  debug(`local registry`);
@@ -983,11 +1188,11 @@ var syncRegistries = async (branch) => {
983
1188
  var getAvailableTemplates = async () => {
984
1189
  debug("Get available templates");
985
1190
  const templates = {};
986
- const registries = import_fs_extra7.default.readdirSync(registriesDataPath);
1191
+ const registries = import_fs_extra9.default.readdirSync(registriesDataPath);
987
1192
  for (const registry of registries) {
988
- const indexPath = import_node_path9.default.join(registriesDataPath, registry, "index.json");
989
- if (import_fs_extra7.default.existsSync(indexPath)) {
990
- const data = import_fs_extra7.default.readJSONSync(indexPath);
1193
+ const indexPath = import_node_path12.default.join(registriesDataPath, registry, "index.json");
1194
+ if (import_fs_extra9.default.existsSync(indexPath)) {
1195
+ const data = import_fs_extra9.default.readJSONSync(indexPath);
991
1196
  Object.entries(data.templates || {}).forEach(([templateName, template]) => {
992
1197
  if (!template.source) {
993
1198
  template.source = `/template-${templateName}`;
@@ -1011,122 +1216,40 @@ var getAvailableTemplates = async () => {
1011
1216
  });
1012
1217
  }
1013
1218
  }
1014
- debug({ templates });
1015
- return templates;
1016
- };
1017
- var getAvailableBlocks = async (templateInfo) => {
1018
- debug("Get available blocks");
1019
- const templates = await getAvailableTemplates();
1020
- const template = templates[templateInfo.name];
1021
- const blocks = template?.blocks || {};
1022
- for (const base of templateInfo.bases || []) {
1023
- const baseTemplate = templates[base.name];
1024
- Object.entries(baseTemplate?.blocks || {}).forEach(([k, v]) => blocks[k] = v);
1025
- }
1026
- debug({ blocks });
1027
- return blocks;
1028
- };
1029
- var getAvailableVersions = async (source) => {
1030
- const registries = import_fs_extra7.default.readdirSync(registriesDataPath);
1031
- for (const registry of registries) {
1032
- const registryPath = import_node_path9.default.join(registriesDataPath, registry);
1033
- const indexPath = import_node_path9.default.join(registryPath, "index.json");
1034
- if (!import_fs_extra7.default.existsSync(indexPath)) continue;
1035
- const registryData = import_fs_extra7.default.readJSONSync(indexPath);
1036
- const versionDirPath = import_node_path9.default.join(registryPath, "versions");
1037
- const versionsFilePaths = [
1038
- import_node_path9.default.join(versionDirPath, `${source.replace(`${registryData.baseUrl}/`, "")}.json`),
1039
- import_node_path9.default.join(versionDirPath, `${encodeURIComponent(source)}.json`)
1040
- ];
1041
- for (const versionsFile of versionsFilePaths) {
1042
- if (import_fs_extra7.default.existsSync(versionsFile)) {
1043
- return import_fs_extra7.default.readJSONSync(versionsFile);
1044
- }
1045
- }
1046
- }
1047
- };
1048
-
1049
- // src/services/template.ts
1050
- var import_node_path10 = __toESM(require("path"));
1051
- var import_ejs = __toESM(require("ejs"));
1052
- var import_fs_extra8 = __toESM(require("fs-extra"));
1053
- var import_klaw2 = __toESM(require("klaw"));
1054
- async function replacePlaceholders(dir, context) {
1055
- debug("Replace placeholders");
1056
- for await (const file of (0, import_klaw2.default)(dir)) {
1057
- if (!file.stats.isFile()) continue;
1058
- const ext = import_node_path10.default.extname(file.path).toLowerCase();
1059
- if (isBinaryFile(ext)) {
1060
- continue;
1061
- }
1062
- const templateContent = import_fs_extra8.default.readFileSync(file.path, "utf8");
1063
- if (!templateContent.includes("<%")) {
1064
- continue;
1065
- }
1066
- try {
1067
- const rendered = import_ejs.default.render(templateContent, context);
1068
- import_fs_extra8.default.writeFileSync(file.path, rendered, "utf8");
1069
- } catch (err) {
1070
- console.error("\u274C Error rendering EJS for file:", file.path);
1071
- throw err;
1072
- }
1073
- }
1074
- }
1075
- function getTemplateDef(cwd = ".") {
1076
- debug("Get template def");
1077
- const def = getBloxFile(cwd).definition;
1078
- debug(def);
1079
- return def;
1080
- }
1081
- function getBlockDef(cwd = ".") {
1082
- debug("Get block def");
1083
- const def = getBloxFile(cwd).definition;
1084
- def && debug(def);
1085
- return def;
1086
- }
1087
- function getBloxFile(cwd = ".") {
1088
- try {
1089
- const file = import_fs_extra8.default.readJSONSync(import_node_path10.default.join(cwd, bloxFilePath));
1090
- if (!file.checkpoints) {
1091
- file.checkpoints = {};
1092
- }
1093
- return file;
1094
- } catch {
1095
- return {};
1096
- }
1097
- }
1098
- function saveBloxFile(info, cwd = ".") {
1099
- debug("Save info");
1100
- import_fs_extra8.default.writeFileSync(import_node_path10.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
1101
- }
1102
- function updateCheckpoint(name, checkpoint, cwd = ".") {
1103
- const info = getBloxFile(cwd);
1104
- if (!info.checkpoints) {
1105
- info.checkpoints = {};
1219
+ debug({ templates });
1220
+ return templates;
1221
+ };
1222
+ var getAvailableBlocks = async (templateInfo) => {
1223
+ debug("Get available blocks");
1224
+ const templates = await getAvailableTemplates();
1225
+ const template = templates[templateInfo.name];
1226
+ const blocks = template?.blocks || {};
1227
+ for (const base of templateInfo.bases || []) {
1228
+ const baseTemplate = templates[base.name];
1229
+ Object.entries(baseTemplate?.blocks || {}).forEach(([k, v]) => blocks[k] = v);
1106
1230
  }
1107
- info.checkpoints[name] = checkpoint;
1108
- saveBloxFile(info, cwd);
1109
- }
1110
- function getUsedBlocksDef() {
1111
- return getUsedBlocks().map((b) => b.definition);
1112
- }
1113
- function getUsedBlocks() {
1114
- debug("Get used blocks");
1115
- const blocks = [];
1116
- if (import_fs_extra8.default.existsSync(blocksDir)) {
1117
- import_fs_extra8.default.readdirSync(blocksDir, { withFileTypes: true }).forEach((file) => {
1118
- if (!file.isDirectory()) {
1119
- return;
1120
- }
1121
- const blockDef = getBloxFile(import_node_path10.default.join(blocksDir, file.name));
1122
- if (blockDef && blockDef.definition) {
1123
- blocks.push(blockDef);
1231
+ debug({ blocks });
1232
+ return blocks;
1233
+ };
1234
+ var getAvailableVersions = async (source) => {
1235
+ const registries = import_fs_extra9.default.readdirSync(registriesDataPath);
1236
+ for (const registry of registries) {
1237
+ const registryPath = import_node_path12.default.join(registriesDataPath, registry);
1238
+ const indexPath = import_node_path12.default.join(registryPath, "index.json");
1239
+ if (!import_fs_extra9.default.existsSync(indexPath)) continue;
1240
+ const registryData = import_fs_extra9.default.readJSONSync(indexPath);
1241
+ const versionDirPath = import_node_path12.default.join(registryPath, "versions");
1242
+ const versionsFilePaths = [
1243
+ import_node_path12.default.join(versionDirPath, `${source.replace(`${registryData.baseUrl}/`, "")}.json`),
1244
+ import_node_path12.default.join(versionDirPath, `${encodeURIComponent(source)}.json`)
1245
+ ];
1246
+ for (const versionsFile of versionsFilePaths) {
1247
+ if (import_fs_extra9.default.existsSync(versionsFile)) {
1248
+ return import_fs_extra9.default.readJSONSync(versionsFile);
1124
1249
  }
1125
- });
1250
+ }
1126
1251
  }
1127
- debug(blocks);
1128
- return blocks;
1129
- }
1252
+ };
1130
1253
 
1131
1254
  // src/services/versions/checkCompatibility.ts
1132
1255
  function processDependencyVersion(dep) {
@@ -1251,15 +1374,6 @@ async function selectVersion(source, fromCommit) {
1251
1374
  return versionsData[version2]?.lastCommit;
1252
1375
  }
1253
1376
 
1254
- // src/commands/init/utils/index.ts
1255
- function runInitScript(cwd) {
1256
- debug(`Run init script in: ${cwd}`);
1257
- const info = getTemplateDef(cwd);
1258
- if (info.init) {
1259
- return $(info.init, [], { cwd });
1260
- }
1261
- }
1262
-
1263
1377
  // src/commands/add/index.ts
1264
1378
  var addBlock = async (block, blocks, branch, destination) => {
1265
1379
  const blockRegistryData = blocks[block];
@@ -1267,7 +1381,9 @@ var addBlock = async (block, blocks, branch, destination) => {
1267
1381
  destination = blockRegistryData?.destination || block;
1268
1382
  }
1269
1383
  const blockPath = `blocks/${destination}`;
1270
- if (!import_fs_extra9.default.existsSync(blockPath)) {
1384
+ let newBlockAdded = false;
1385
+ if (!import_fs_extra10.default.existsSync(blockPath)) {
1386
+ newBlockAdded = true;
1271
1387
  await runTask(
1272
1388
  { start: `Fetching block: ${block}`, end: `Added block: ${block}` },
1273
1389
  async () => {
@@ -1287,16 +1403,19 @@ var addBlock = async (block, blocks, branch, destination) => {
1287
1403
  updateCheckpoint(block, { commit: commit2, branch }, blockPath);
1288
1404
  }
1289
1405
  );
1290
- await runTask("Run init script", async () => runInitScript(blockPath));
1406
+ await runLifecycleHookWithTask(blockPath, "init", "Run block init");
1407
+ await runLifecycleHookWithTask(blockPath, "add", "Run block add");
1291
1408
  } else {
1292
1409
  debug(`${block} already exists`);
1293
1410
  }
1294
1411
  const blockDef = getBlockDef(blockPath);
1295
1412
  for (const dep of blockDef?.dependencies || []) {
1296
- await addBlock(dep.name, blocks);
1413
+ const depNew = await addBlock(dep.name, blocks);
1414
+ newBlockAdded = newBlockAdded || depNew;
1297
1415
  }
1416
+ return newBlockAdded;
1298
1417
  };
1299
- var add2 = command("add").description("Add block to app").alias("a").argument("[block]", "Block to be added").option("--branch <name>", "branch name").option("--dest <name>", "destination dir").action(async (block, { branch, dest }) => {
1418
+ 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 }) => {
1300
1419
  if (await git.hasUncommittedChanges()) {
1301
1420
  import_prompts2.log.warn(fmt.yellow("Make sure to commit any changes first"));
1302
1421
  return;
@@ -1306,9 +1425,10 @@ var add2 = command("add").description("Add block to app").alias("a").argument("[
1306
1425
  try {
1307
1426
  const templateDef = getTemplateDef();
1308
1427
  const blocks = await getAvailableBlocks(templateDef);
1309
- if (!block) {
1310
- block = await select({
1311
- message: "Select template to be used",
1428
+ let blocksToAdd = Array.isArray(selectedBlocks) ? selectedBlocks : [];
1429
+ if (!blocksToAdd.length) {
1430
+ blocksToAdd = await multiselect({
1431
+ message: "Select blocks to add",
1312
1432
  options: Object.entries(blocks).map(([tmpl, { description }]) => ({
1313
1433
  value: tmpl,
1314
1434
  label: tmpl,
@@ -1316,10 +1436,21 @@ var add2 = command("add").description("Add block to app").alias("a").argument("[
1316
1436
  }))
1317
1437
  });
1318
1438
  }
1319
- if (!blocks[block]) {
1320
- error("Selected block not available in registries");
1439
+ if (!blocksToAdd.length) {
1440
+ error("No blocks selected");
1441
+ }
1442
+ const invalidBlocks = blocksToAdd.filter((blockName) => !blocks[blockName]);
1443
+ if (invalidBlocks.length) {
1444
+ error(`Selected blocks not available in registries: ${invalidBlocks.join(", ")}`);
1445
+ }
1446
+ let added = false;
1447
+ for (const blockName of blocksToAdd) {
1448
+ const blockAdded = await addBlock(blockName, blocks, branch, dest);
1449
+ added = added || blockAdded;
1450
+ }
1451
+ if (added) {
1452
+ await runLifecycleHookWithTask(".", "add", "Run template add");
1321
1453
  }
1322
- await addBlock(block, blocks, branch, dest);
1323
1454
  await checkVersionsCompatibility();
1324
1455
  } catch (e) {
1325
1456
  if (!isDebugMode()) {
@@ -1380,7 +1511,7 @@ var ContributionTargetType = /* @__PURE__ */ ((ContributionTargetType2) => {
1380
1511
  })(ContributionTargetType || {});
1381
1512
 
1382
1513
  // src/services/contribute/utils/bloxCheckpoint.ts
1383
- var import_node_path11 = __toESM(require("path"));
1514
+ var import_node_path13 = __toESM(require("path"));
1384
1515
  function getCheckpointForTarget(cwd, target) {
1385
1516
  const bloxDir = getBloxDirForTarget(cwd, target);
1386
1517
  const blox = getBloxFile(bloxDir);
@@ -1390,7 +1521,7 @@ function getCheckpointForTarget(cwd, target) {
1390
1521
  }
1391
1522
  function getBloxDirForTarget(cwd, target) {
1392
1523
  if (target.type === "block" /* BLOCK */) {
1393
- return import_node_path11.default.join(cwd, blocksDir, target.name);
1524
+ return import_node_path13.default.join(cwd, blocksDir, target.name);
1394
1525
  }
1395
1526
  return cwd;
1396
1527
  }
@@ -1420,11 +1551,6 @@ var getTargetRepoUrl = async (target) => {
1420
1551
  return blockSource;
1421
1552
  };
1422
1553
 
1423
- // src/services/contribute/utils/sleep.ts
1424
- async function sleep(ms2) {
1425
- await new Promise((r) => setTimeout(r, ms2));
1426
- }
1427
-
1428
1554
  // src/services/contribute/utils/slugifyTitle.ts
1429
1555
  function slugifyTitle(title) {
1430
1556
  const s = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -1497,14 +1623,28 @@ var ContributionWorkflow = class {
1497
1623
  title,
1498
1624
  description
1499
1625
  });
1500
- await this.pushWithRetry(tmpCwd, "origin", branch);
1501
- const pr = await this.pullRequest.printPullRequestInstructions({
1626
+ await this.pullRequest.pushBranch({
1627
+ cwd: tmpCwd,
1628
+ remote: "origin",
1629
+ branch,
1630
+ onAttemptFailed: ({ attempt, error: error2 }) => this.logger.warn("push.failed", { attempt, error: error2 })
1631
+ });
1632
+ this.logger.info("branch.pushed", {
1633
+ branch,
1634
+ remote: repoUrl
1635
+ });
1636
+ this.pullRequest.printPushSummary({
1502
1637
  repoUrl,
1503
1638
  sourceBranch: branch,
1504
1639
  targetBranch: remoteBranch,
1505
1640
  title,
1506
1641
  description
1507
1642
  });
1643
+ const pr = await this.pullRequest.openPullRequestPage({
1644
+ repoUrl,
1645
+ sourceBranch: branch,
1646
+ targetBranch: remoteBranch
1647
+ });
1508
1648
  this.logCompletion(pr.prUrl);
1509
1649
  return {
1510
1650
  branch,
@@ -1638,51 +1778,35 @@ Expected remote ${remoteHead}, local checkpoint ${checkpoint.commit}.`
1638
1778
  logCompletion(prUrl) {
1639
1779
  import_prompts2.log.success(
1640
1780
  fmt.green("Contribution flow completed.") + (prUrl ? `
1641
- PR URL:
1642
- ${prUrl}` : "\nPush completed. Create the PR using the instructions above.")
1781
+ Pull Request (new):
1782
+ ${prUrl}` : "\nPush completed.")
1643
1783
  );
1644
1784
  }
1645
- async pushWithRetry(cwd, remote, branch) {
1646
- const maxAttempts = 3;
1647
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1648
- try {
1649
- await git.push(remote, branch, cwd);
1650
- return;
1651
- } catch (e) {
1652
- this.logger.warn("push.failed", {
1653
- attempt,
1654
- error: e instanceof Error ? e.message : String(e)
1655
- });
1656
- if (attempt === maxAttempts) {
1657
- throw new Error(
1658
- `git push failed after ${maxAttempts} attempts: ${e instanceof Error ? e.message : String(e)}`
1659
- );
1660
- }
1661
- await sleep(500 * attempt);
1662
- }
1663
- }
1664
- }
1665
1785
  };
1666
1786
 
1787
+ // src/services/contribute/services/CommitApplierService.ts
1788
+ var import_node_path15 = __toESM(require("path"));
1789
+ var import_fs_extra12 = __toESM(require("fs-extra"));
1790
+
1667
1791
  // src/services/contribute/config/index.ts
1668
1792
  var tempRepoName = "tmp";
1669
- var alwaysSkipPatterns = [/\.blox$/];
1793
+ var bloxConfigControlledKeys = ["checkpoints"];
1670
1794
 
1671
1795
  // src/services/contribute/utils/getExcludedPrefixesForTarget.ts
1672
- var import_node_path12 = __toESM(require("path"));
1673
- var import_fs_extra10 = __toESM(require("fs-extra"));
1796
+ var import_node_path14 = __toESM(require("path"));
1797
+ var import_fs_extra11 = __toESM(require("fs-extra"));
1674
1798
  function getExcludedPrefixesForTarget(target, cwd) {
1675
1799
  if (target.type === "block" /* BLOCK */) {
1676
1800
  return [];
1677
1801
  }
1678
1802
  const excluded = [];
1679
- const blocksPath = import_node_path12.default.join(cwd, blocksDir);
1680
- if (import_fs_extra10.default.existsSync(blocksPath)) {
1681
- const entries = import_fs_extra10.default.readdirSync(blocksPath, { withFileTypes: true });
1803
+ const blocksPath = import_node_path14.default.join(cwd, blocksDir);
1804
+ if (import_fs_extra11.default.existsSync(blocksPath)) {
1805
+ const entries = import_fs_extra11.default.readdirSync(blocksPath, { withFileTypes: true });
1682
1806
  for (const entry of entries) {
1683
1807
  if (!entry.isDirectory()) continue;
1684
- const blockBloxFile = import_node_path12.default.join(blocksPath, entry.name, bloxFilePath);
1685
- if (import_fs_extra10.default.existsSync(blockBloxFile)) {
1808
+ const blockBloxFile = import_node_path14.default.join(blocksPath, entry.name, bloxFilePath);
1809
+ if (import_fs_extra11.default.existsSync(blockBloxFile)) {
1686
1810
  excluded.push(normalizePath(`${blocksDir}/${entry.name}/`));
1687
1811
  }
1688
1812
  }
@@ -1736,7 +1860,7 @@ var CommitApplierService = class {
1736
1860
  message: e instanceof Error ? e.message : String(e)
1737
1861
  });
1738
1862
  }
1739
- await this.revertExcludedStagedFiles(opts.tmpRepoCwd, commit2, exclusion);
1863
+ await this.revertExcludedStagedFiles(opts.tmpRepoCwd, commit2, exclusion, opts.target);
1740
1864
  const remainingConflicts = await git.getUnmergedFiles(opts.tmpRepoCwd);
1741
1865
  if (remainingConflicts.length) {
1742
1866
  this.logger.error("apply.commit.conflicts", {
@@ -1756,23 +1880,72 @@ Resolve manually in the temp repo:
1756
1880
  ${e instanceof Error ? e.message : String(e)}`);
1757
1881
  }
1758
1882
  }
1759
- async revertExcludedStagedFiles(tmpRepoCwd, commit2, exclusion) {
1883
+ async revertExcludedStagedFiles(tmpRepoCwd, commit2, exclusion, target) {
1760
1884
  const stagedFiles = await git.getStagedFiles(tmpRepoCwd);
1761
1885
  const unmergedFiles = await git.getUnmergedFiles(tmpRepoCwd);
1762
1886
  const allTouchedFiles = [.../* @__PURE__ */ new Set([...stagedFiles, ...unmergedFiles])];
1763
1887
  for (const file of allTouchedFiles) {
1764
- const isAlwaysSkipped = alwaysSkipPatterns.some((p) => p.test(file));
1888
+ const isBloxFile = isBloxConfigFile(file);
1765
1889
  const isExcludedByTarget = shouldExcludeFile(file, exclusion);
1766
- if (isAlwaysSkipped || isExcludedByTarget) {
1767
- this.logger.warn("apply.commit.skip_file", {
1768
- commit: commit2.slice(0, 7),
1769
- file,
1770
- reason: isAlwaysSkipped ? "always-skip" : "target-exclusion"
1771
- });
1890
+ if (isExcludedByTarget) {
1891
+ this.logger.warn("apply.commit.skip_file", { file });
1772
1892
  await git.revertPathToHead(file, tmpRepoCwd);
1893
+ continue;
1894
+ }
1895
+ if (isBloxFile) {
1896
+ await this.applyBloxConfigFileRevertPolicy(
1897
+ file,
1898
+ tmpRepoCwd,
1899
+ commit2,
1900
+ unmergedFiles,
1901
+ target
1902
+ );
1903
+ continue;
1773
1904
  }
1774
1905
  }
1775
1906
  }
1907
+ async applyBloxConfigFileRevertPolicy(file, tmpRepoCwd, commit2, unmergedFiles, target) {
1908
+ if (target.type === "base" /* BASE */) {
1909
+ this.logger.warn(
1910
+ "[.blox] revert policy: You cannot contribute the .blox file of a base from a template."
1911
+ );
1912
+ await git.revertPathToHead(file, tmpRepoCwd);
1913
+ return;
1914
+ }
1915
+ if (unmergedFiles.includes(file)) {
1916
+ this.logger.debug("apply.commit.blox_merge_fallback", { file });
1917
+ await git.revertPathToHead(file, tmpRepoCwd);
1918
+ return;
1919
+ }
1920
+ const headJson = await git.readJsonFromCommit("HEAD", file, tmpRepoCwd);
1921
+ const headObj = headJson !== null && typeof headJson === "object" && !Array.isArray(headJson) ? headJson : null;
1922
+ const headDefinesAllGovernedKeys = bloxConfigControlledKeys.every(
1923
+ (key) => headObj !== null && Object.prototype.hasOwnProperty.call(headObj, key)
1924
+ );
1925
+ if (headDefinesAllGovernedKeys) {
1926
+ return;
1927
+ }
1928
+ const stagedJson = await git.readJsonFromIndex(file, tmpRepoCwd);
1929
+ if (stagedJson === null) {
1930
+ this.logger.debug("apply.commit.blox_merge_fallback", { file });
1931
+ await git.revertPathToHead(file, tmpRepoCwd);
1932
+ return;
1933
+ }
1934
+ const withoutGovernedKeys = omitKeys(stagedJson, bloxConfigControlledKeys);
1935
+ try {
1936
+ const outPath = import_node_path15.default.join(tmpRepoCwd, file);
1937
+ await import_fs_extra12.default.outputFile(outPath, JSON.stringify(withoutGovernedKeys, null, 2));
1938
+ await git.add(file, tmpRepoCwd);
1939
+ } catch (e) {
1940
+ this.logger.warn("apply.commit.blox_merge_fallback", {
1941
+ commit: commit2.slice(0, 7),
1942
+ file,
1943
+ reason: "write-failed",
1944
+ message: e instanceof Error ? e.message : String(e)
1945
+ });
1946
+ await git.revertPathToHead(file, tmpRepoCwd);
1947
+ }
1948
+ }
1776
1949
  async waitUntilUserResolvesConflicts(tmpRepoCwd, commit2) {
1777
1950
  let remainingConflicts = await git.getUnmergedFiles(tmpRepoCwd);
1778
1951
  while (remainingConflicts.length) {
@@ -1843,7 +2016,7 @@ var CommitSelectorService = class {
1843
2016
  break;
1844
2017
  }
1845
2018
  const value = await multiselect({
1846
- message: `Select commits ${fmt.gray(`(page ${page + 1})`)}`,
2019
+ message: `Select commits (Press <space> to select, <enter> to continue) ${fmt.gray(`(page ${page + 1})`)}`,
1847
2020
  options: commits.map((c) => ({
1848
2021
  value: c.hash,
1849
2022
  label: `${c.hash.slice(0, 7)} ${c.subject}`
@@ -1878,13 +2051,13 @@ var CommitSelectorService = class {
1878
2051
  };
1879
2052
 
1880
2053
  // src/services/contribute/utils/discoverContributionTargets.ts
1881
- var import_node_path13 = __toESM(require("path"));
1882
- var import_fs_extra11 = __toESM(require("fs-extra"));
2054
+ var import_node_path16 = __toESM(require("path"));
2055
+ var import_fs_extra13 = __toESM(require("fs-extra"));
1883
2056
  var readBloxFileIfExists = (cwd) => {
1884
- const p = import_node_path13.default.join(cwd, bloxFilePath);
1885
- if (!import_fs_extra11.default.existsSync(p)) return;
2057
+ const p = import_node_path16.default.join(cwd, bloxFilePath);
2058
+ if (!import_fs_extra13.default.existsSync(p)) return;
1886
2059
  try {
1887
- return import_fs_extra11.default.readJSONSync(p);
2060
+ return import_fs_extra13.default.readJSONSync(p);
1888
2061
  } catch {
1889
2062
  return;
1890
2063
  }
@@ -1912,13 +2085,13 @@ var discoverContributionTargets = (cwd) => {
1912
2085
  });
1913
2086
  }
1914
2087
  }
1915
- const blocksPath = import_node_path13.default.join(cwd, blocksDir);
1916
- if (import_fs_extra11.default.existsSync(blocksPath)) {
1917
- const entries = import_fs_extra11.default.readdirSync(blocksPath, { withFileTypes: true });
2088
+ const blocksPath = import_node_path16.default.join(cwd, blocksDir);
2089
+ if (import_fs_extra13.default.existsSync(blocksPath)) {
2090
+ const entries = import_fs_extra13.default.readdirSync(blocksPath, { withFileTypes: true });
1918
2091
  for (const entry of entries) {
1919
2092
  if (!entry.isDirectory()) continue;
1920
2093
  const blockName = entry.name;
1921
- const blockBlox = readBloxFileIfExists(import_node_path13.default.join(blocksPath, blockName));
2094
+ const blockBlox = readBloxFileIfExists(import_node_path16.default.join(blocksPath, blockName));
1922
2095
  if (!blockBlox?.definition?.name) continue;
1923
2096
  const def = blockBlox.definition;
1924
2097
  const templateName = def.templates?.[0]?.name || appTemplateName;
@@ -2056,47 +2229,157 @@ ${fmt.gray(
2056
2229
  }
2057
2230
  };
2058
2231
 
2232
+ // src/services/contribute/utils/buildPullRequestUrl.ts
2233
+ function buildPullRequestUrl(parsed, sourceBranch, targetBranch) {
2234
+ const repo = encodeURIComponent(parsed.repositoryId);
2235
+ const base = `${parsed.projectApiRootUrl}/_git/${repo}/pullrequestcreate`;
2236
+ const q = new URLSearchParams({
2237
+ sourceRef: sourceBranch,
2238
+ targetRef: targetBranch
2239
+ });
2240
+ return `${base}?${q.toString()}`;
2241
+ }
2242
+
2243
+ // src/services/contribute/utils/extractAzureRepoInfoFromGit.ts
2244
+ function extractAzureRepoInfoFromGit(rawUrl) {
2245
+ const trimmed = rawUrl.trim().replace(/\.git$/i, "");
2246
+ const ssh = trimmed.match(/^git@ssh\.dev\.azure\.com:v3\/([^/]+)\/([^/]+)\/(.+)$/i);
2247
+ if (ssh?.[1] && ssh[2] && ssh[3]) {
2248
+ const organization = decodeURIComponent(ssh[1]);
2249
+ const project = decodeURIComponent(ssh[2]);
2250
+ const repositoryId2 = decodeURIComponent(ssh[3]);
2251
+ const pathPrefix2 = `/${encodeURIComponent(organization)}/${encodeURIComponent(project)}`;
2252
+ return {
2253
+ projectApiRootUrl: joinProjectRoot("https://dev.azure.com", pathPrefix2),
2254
+ repositoryId: repositoryId2
2255
+ };
2256
+ }
2257
+ let parsed;
2258
+ try {
2259
+ parsed = new URL(trimmed);
2260
+ } catch {
2261
+ return null;
2262
+ }
2263
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2264
+ return null;
2265
+ }
2266
+ const pathname = (parsed.pathname || "/").replace(/\/+$/, "") || "/";
2267
+ const lower = pathname.toLowerCase();
2268
+ const marker = "/_git/";
2269
+ const gitAt = lower.indexOf(marker);
2270
+ if (gitAt === -1) {
2271
+ return null;
2272
+ }
2273
+ const pathPrefix = pathname.slice(0, gitAt);
2274
+ const repoPath = pathname.slice(gitAt + marker.length);
2275
+ if (!pathPrefix || pathPrefix === "/" || !repoPath) {
2276
+ return null;
2277
+ }
2278
+ const depth = pathPrefix.split("/").filter(Boolean).length;
2279
+ if (depth < 2) {
2280
+ return null;
2281
+ }
2282
+ const repositoryId = decodeURIComponent(repoPath.split("/").filter(Boolean).join("/"));
2283
+ if (!repositoryId) {
2284
+ return null;
2285
+ }
2286
+ return {
2287
+ projectApiRootUrl: joinProjectRoot(parsed.origin, pathPrefix),
2288
+ repositoryId
2289
+ };
2290
+ }
2291
+ function joinProjectRoot(origin, pathPrefix) {
2292
+ const prefix = pathPrefix.startsWith("/") ? pathPrefix : `/${pathPrefix}`;
2293
+ return `${origin.replace(/\/$/, "")}${prefix}`.replace(/\/$/, "");
2294
+ }
2295
+
2296
+ // src/services/contribute/utils/sleep.ts
2297
+ async function sleep(ms2) {
2298
+ await new Promise((r) => setTimeout(r, ms2));
2299
+ }
2300
+
2059
2301
  // src/services/contribute/services/PullRequestService.ts
2060
2302
  var PullRequestService = class {
2061
2303
  constructor(logger) {
2062
2304
  this.logger = logger;
2063
2305
  }
2064
- async printPullRequestInstructions(opts) {
2065
- this.logger.debug("pr.instructions", opts);
2066
- const header = fmt.bold(fmt.cyan("NEXT STEPS: CREATE YOUR PULL REQUEST "));
2067
- const subHeader = fmt.gray(" Push successful! Please finalize the PR in Azure DevOps. ");
2306
+ async pushBranch(opts) {
2307
+ const maxAttempts = opts.maxAttempts ?? 3;
2308
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2309
+ try {
2310
+ await git.push(opts.remote, opts.branch, opts.cwd);
2311
+ return;
2312
+ } catch (e) {
2313
+ const message = e instanceof Error ? e.message : String(e);
2314
+ opts.onAttemptFailed?.({ attempt, error: message });
2315
+ if (attempt === maxAttempts) {
2316
+ throw new Error(`git push failed after ${maxAttempts} attempts: ${message}`);
2317
+ }
2318
+ await sleep(500 * attempt);
2319
+ }
2320
+ }
2321
+ }
2322
+ printPushSummary(opts) {
2068
2323
  const line = "\u2501".repeat(60);
2324
+ const header = fmt.bold(fmt.cyan("BRANCH PUSHED"));
2069
2325
  import_prompts2.log.message(
2070
2326
  `
2071
2327
  ${fmt.cyan("\u25E2")}${line}${fmt.cyan("\u25E3")}
2072
2328
  ${header}
2073
- ${subHeader}
2074
2329
 
2075
2330
  ${fmt.bold("Target:")} ${fmt.green(opts.targetBranch)}
2076
2331
  ${fmt.bold("Source:")} ${fmt.yellow(opts.sourceBranch)}
2077
- ${fmt.bold("URL:")} ${fmt.blue(opts.repoUrl)}
2332
+ ${fmt.bold("Remote:")} ${fmt.blue(opts.repoUrl)}
2078
2333
  ${fmt.bold("Title:")} ${opts.title}
2079
- ` + (opts.description ? `
2334
+ ` + (opts.description.trim() ? `
2080
2335
  ${fmt.gray("Description:")}
2081
- ${opts.description}
2336
+ ${opts.description.trim()}
2082
2337
  ` : "") + `${fmt.cyan("\u25E5")}${line}${fmt.cyan("\u25E4")}
2083
2338
  `
2084
2339
  );
2085
- return { prUrl: void 0 };
2340
+ }
2341
+ async openPullRequestPage(opts) {
2342
+ const parsed = extractAzureRepoInfoFromGit(opts.repoUrl);
2343
+ if (!parsed) {
2344
+ this.logger.info("pr.skipped", { reason: "remote_not_azure_devops_git" });
2345
+ return { prUrl: void 0 };
2346
+ }
2347
+ this.logger.info("pr.prompt.shown");
2348
+ const wantsPr = await confirm({
2349
+ message: "Do you want to open a Pull Request?",
2350
+ initialValue: true
2351
+ });
2352
+ if (!wantsPr) {
2353
+ this.logger.info("pr.declined");
2354
+ return { prUrl: void 0 };
2355
+ }
2356
+ const createPageUrl = buildPullRequestUrl(parsed, opts.sourceBranch, opts.targetBranch);
2357
+ try {
2358
+ await openUrlInBrowser(createPageUrl);
2359
+ } catch (e) {
2360
+ this.logger.warn("Could not open browser", e);
2361
+ }
2362
+ import_prompts2.log.message(
2363
+ `
2364
+ ${fmt.green("Opening Pull Request creation in your browser.")}
2365
+ ${fmt.cyan(createPageUrl)}
2366
+ `
2367
+ );
2368
+ return { prUrl: createPageUrl };
2086
2369
  }
2087
2370
  };
2088
2371
 
2089
2372
  // src/services/contribute/services/TmpRepoService.ts
2090
2373
  var import_node_os2 = require("os");
2091
- var import_node_path14 = __toESM(require("path"));
2092
- var import_fs_extra12 = __toESM(require("fs-extra"));
2374
+ var import_node_path17 = __toESM(require("path"));
2375
+ var import_fs_extra14 = __toESM(require("fs-extra"));
2093
2376
  var TmpRepoService = class {
2094
2377
  constructor(logger) {
2095
2378
  this.logger = logger;
2096
2379
  }
2097
2380
  async getTmpDir(target) {
2098
2381
  const slug = `${target.type}-${target.name}`.replace(/[^a-zA-Z0-9._-]+/g, "-");
2099
- return import_node_path14.default.join((0, import_node_os2.homedir)(), bloxFilePath, tempRepoName, slug);
2382
+ return import_node_path17.default.join((0, import_node_os2.homedir)(), bloxFilePath, tempRepoName, slug);
2100
2383
  }
2101
2384
  async prepare(opts) {
2102
2385
  const dir = await this.getTmpDir(opts.target);
@@ -2106,11 +2389,11 @@ var TmpRepoService = class {
2106
2389
  branch: opts.branch
2107
2390
  });
2108
2391
  this.logger.info("Prepare for tmp repo");
2109
- if (await import_fs_extra12.default.pathExists(dir)) {
2392
+ if (await import_fs_extra14.default.pathExists(dir)) {
2110
2393
  this.logger.debug(`${tempRepoName}.remove`, { dir });
2111
- await import_fs_extra12.default.remove(dir);
2394
+ await import_fs_extra14.default.remove(dir);
2112
2395
  }
2113
- await import_fs_extra12.default.ensureDir(import_node_path14.default.dirname(dir));
2396
+ await import_fs_extra14.default.ensureDir(import_node_path17.default.dirname(dir));
2114
2397
  await git.clone(opts.repoUrl, dir, opts.branch);
2115
2398
  return dir;
2116
2399
  }
@@ -2193,7 +2476,7 @@ var detach = command("detach").description("Migrate blox schema").option("--basi
2193
2476
  });
2194
2477
 
2195
2478
  // src/commands/init/index.ts
2196
- var import_fs_extra13 = __toESM(require("fs-extra"));
2479
+ var import_fs_extra15 = __toESM(require("fs-extra"));
2197
2480
  var init2 = command("init").description("Init new app").alias("i").option("-n, --name <name>", "App name").option("-t, --template <template>", "Template to use").option("--branch <name>", "branch name").action(async ({ name, template, branch }) => {
2198
2481
  await syncRegistries();
2199
2482
  try {
@@ -2232,10 +2515,10 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
2232
2515
  updateCheckpoint(def.name, { commit: commit2, branch }, name);
2233
2516
  await git.init(name);
2234
2517
  task.stop(`App initialized in ${name}`);
2235
- await runTask("Run init script", async () => runInitScript(name || ""));
2518
+ await runLifecycleHookWithTask(name || "", "init", "Run template init");
2236
2519
  } catch (e) {
2237
- if (name && import_fs_extra13.default.existsSync(name)) {
2238
- await import_fs_extra13.default.remove(name);
2520
+ if (name && import_fs_extra15.default.existsSync(name)) {
2521
+ await import_fs_extra15.default.remove(name);
2239
2522
  }
2240
2523
  error(e);
2241
2524
  }
@@ -2254,15 +2537,295 @@ var migrateSchema = command("migrate").description("Migrate blox schema").action
2254
2537
  }
2255
2538
  });
2256
2539
 
2540
+ // src/commands/remove/index.ts
2541
+ var import_node_path18 = __toESM(require("path"));
2542
+ var import_fs_extra16 = __toESM(require("fs-extra"));
2543
+ var blocksAbsolutePath = () => import_node_path18.default.resolve(process.cwd(), blocksDir);
2544
+ function listInstalledBlockRelPaths() {
2545
+ const root = blocksAbsolutePath();
2546
+ if (!import_fs_extra16.default.existsSync(root)) {
2547
+ return [];
2548
+ }
2549
+ const paths2 = [];
2550
+ for (const entry of import_fs_extra16.default.readdirSync(root, { withFileTypes: true })) {
2551
+ if (!entry.isDirectory()) {
2552
+ continue;
2553
+ }
2554
+ const abs = import_node_path18.default.join(root, entry.name);
2555
+ if (!isBlockDirectory(abs)) {
2556
+ continue;
2557
+ }
2558
+ paths2.push(import_node_path18.default.join(blocksDir, entry.name));
2559
+ }
2560
+ return paths2;
2561
+ }
2562
+ function getInstalledBlockSelectOptions() {
2563
+ return listInstalledBlockRelPaths().map((rel) => {
2564
+ const folder = import_node_path18.default.basename(rel);
2565
+ const def = getBlockDef(rel);
2566
+ const label = def?.name && def.name !== folder ? `${def.name} (${folder})` : folder;
2567
+ return { value: folder, label, hint: def?.name };
2568
+ });
2569
+ }
2570
+ function assertNoDependents(blockPathAbs, targetBlockName) {
2571
+ for (const rel of listInstalledBlockRelPaths()) {
2572
+ const abs = import_node_path18.default.resolve(process.cwd(), rel);
2573
+ if (abs === blockPathAbs) {
2574
+ continue;
2575
+ }
2576
+ const def = getBlockDef(rel);
2577
+ for (const dep of def.dependencies || []) {
2578
+ if (dep.name === targetBlockName) {
2579
+ throw new Error(
2580
+ `Cannot remove "${targetBlockName}": block "${def.name}" declares a dependency on it. Remove that dependency or the dependent block first.`
2581
+ );
2582
+ }
2583
+ }
2584
+ }
2585
+ }
2586
+ function assertUnderBlocksRoot(blockPathAbs) {
2587
+ const root = blocksAbsolutePath();
2588
+ const rel = import_node_path18.default.relative(root, blockPathAbs);
2589
+ if (!rel || rel.startsWith("..") || import_node_path18.default.isAbsolute(rel)) {
2590
+ throw new Error("Block path escapes the blocks directory");
2591
+ }
2592
+ }
2593
+ async function removeBlock(block, blocks, force = false) {
2594
+ const reg = blocks[block];
2595
+ const destination = reg ? reg.destination ?? block : block;
2596
+ const blockPathRel = import_node_path18.default.join(blocksDir, destination);
2597
+ const blockPathAbs = import_node_path18.default.resolve(process.cwd(), blockPathRel);
2598
+ assertUnderBlocksRoot(blockPathAbs);
2599
+ if (!import_fs_extra16.default.existsSync(blockPathAbs) || !isBlockDirectory(blockPathAbs)) {
2600
+ throw new Error(`Block is not installed at ${import_node_path18.default.relative(process.cwd(), blockPathAbs)}`);
2601
+ }
2602
+ const targetDef = getBlockDef(blockPathRel);
2603
+ if (!targetDef?.name) {
2604
+ throw new Error("Invalid block: missing name in .blox definition");
2605
+ }
2606
+ if (!force) {
2607
+ assertNoDependents(blockPathAbs, targetDef.name);
2608
+ }
2609
+ await runLifecycleHookWithTask(blockPathRel, "remove", "Run block remove");
2610
+ await runTask("Remove block files", async () => {
2611
+ assertUnderBlocksRoot(blockPathAbs);
2612
+ await import_fs_extra16.default.remove(blockPathAbs);
2613
+ });
2614
+ return true;
2615
+ }
2616
+ var remove = command("remove").description("Remove block from app").alias("rm").argument("[blocks...]", "Blocks to remove (registry key or installed folder name)").option("-f, --force", "Remove even if other blocks declare a dependency on this block").action(async (selectedBlocks, { force }) => {
2617
+ if (await git.hasUncommittedChanges()) {
2618
+ import_prompts2.log.warn(fmt.yellow("Make sure to commit any changes first"));
2619
+ return;
2620
+ }
2621
+ await migrateAll();
2622
+ await syncRegistries();
2623
+ try {
2624
+ const templateDef = getTemplateDef();
2625
+ const blocks = await getAvailableBlocks(templateDef);
2626
+ let blocksToRemove = Array.isArray(selectedBlocks) ? selectedBlocks : [];
2627
+ if (!blocksToRemove.length) {
2628
+ const options = getInstalledBlockSelectOptions();
2629
+ if (!options.length) {
2630
+ error("No installed blocks found under blocks/");
2631
+ }
2632
+ blocksToRemove = await multiselect({
2633
+ message: "Select blocks to remove",
2634
+ options
2635
+ });
2636
+ }
2637
+ if (!blocksToRemove.length) {
2638
+ error("No blocks selected");
2639
+ }
2640
+ if (force) {
2641
+ import_prompts2.log.warn(
2642
+ fmt.yellow(
2643
+ "--force: skipping dependency check; dependent blocks may be left in a broken state."
2644
+ )
2645
+ );
2646
+ }
2647
+ let removed = false;
2648
+ for (const blockName of blocksToRemove) {
2649
+ const blockRemoved = await removeBlock(blockName, blocks, force);
2650
+ removed = removed || blockRemoved;
2651
+ }
2652
+ if (removed) {
2653
+ await runLifecycleHookWithTask(".", "remove", "Run template remove");
2654
+ }
2655
+ if (!force) {
2656
+ await checkVersionsCompatibility();
2657
+ }
2658
+ } catch (e) {
2659
+ if (!isDebugMode()) {
2660
+ import_prompts2.log.warn("Error happened, Will rollback changes");
2661
+ await git.rollback();
2662
+ }
2663
+ error(e);
2664
+ }
2665
+ });
2666
+
2667
+ // src/commands/skills/index.ts
2668
+ var import_node_crypto = require("crypto");
2669
+ var import_node_os3 = __toESM(require("os"));
2670
+ var import_node_path20 = __toESM(require("path"));
2671
+ var import_cross_spawn2 = __toESM(require("cross-spawn"));
2672
+ var import_fs_extra18 = __toESM(require("fs-extra"));
2673
+
2674
+ // src/commands/skills/constants.ts
2675
+ var SKILLS_REPO_URL = "https://tfs.aas.com.sa/Medad/BLOX/_git/cli";
2676
+ var SKILLS_TEMP_ROOT_PREFIX = "blox-skills";
2677
+
2678
+ // src/commands/skills/utils/cliCompatibility.ts
2679
+ var import_node_path19 = __toESM(require("path"));
2680
+ var import_fs_extra17 = __toESM(require("fs-extra"));
2681
+ var import_semver = __toESM(require("semver"));
2682
+ var SKILLS_CLI_COMPATIBILITY_COMMANDS = ["add", "update"];
2683
+ function getSkillscommandIndex(args, subcommand) {
2684
+ for (let i = 0; i < args.length; i++) {
2685
+ if (args[i] !== subcommand) {
2686
+ continue;
2687
+ }
2688
+ if (args.slice(0, i).every((t) => t.startsWith("-"))) {
2689
+ return i;
2690
+ }
2691
+ }
2692
+ return -1;
2693
+ }
2694
+ function hasSkillscommand(args, subcommand) {
2695
+ return getSkillscommandIndex(args, subcommand) !== -1;
2696
+ }
2697
+ function needsCliCompatibilityCheck(args) {
2698
+ return SKILLS_CLI_COMPATIBILITY_COMMANDS.some((cmd) => hasSkillscommand(args, cmd));
2699
+ }
2700
+ function getAddCommandIndex(args) {
2701
+ return getSkillscommandIndex(args, "add");
2702
+ }
2703
+ async function loadSkillsData(cloneRoot) {
2704
+ const skillsDir = import_node_path19.default.join(cloneRoot, "skills");
2705
+ if (!await import_fs_extra17.default.pathExists(skillsDir)) {
2706
+ return [];
2707
+ }
2708
+ const entries = await import_fs_extra17.default.readdir(skillsDir, { withFileTypes: true });
2709
+ const manifests = await Promise.all(
2710
+ entries.filter((entry) => entry.isDirectory()).map(async (entry) => {
2711
+ const filePath = import_node_path19.default.join(skillsDir, entry.name, "skill.json");
2712
+ if (!await import_fs_extra17.default.pathExists(filePath)) {
2713
+ return null;
2714
+ }
2715
+ const raw = await import_fs_extra17.default.readJson(filePath);
2716
+ const range = raw.cliCompatibility?.trim();
2717
+ if (!range) {
2718
+ return null;
2719
+ }
2720
+ return {
2721
+ name: raw.name || entry.name,
2722
+ version: raw.version || "0.0.0",
2723
+ cliCompatibility: range
2724
+ };
2725
+ })
2726
+ );
2727
+ return manifests.filter(Boolean);
2728
+ }
2729
+ function getFirstIncompatibleSkill(skills2, cliVersion) {
2730
+ const normalized = import_semver.default.coerce(cliVersion)?.version ?? cliVersion;
2731
+ return skills2.find((skill) => {
2732
+ const range = skill.cliCompatibility;
2733
+ return import_semver.default.validRange(range) && !import_semver.default.satisfies(normalized, range, {
2734
+ includePrerelease: true
2735
+ });
2736
+ }) || null;
2737
+ }
2738
+ function warnIncompatibleSkill(skill, cliVersion) {
2739
+ const label = `${skill.name}@${skill.version}`;
2740
+ console.log("");
2741
+ console.log(
2742
+ fmt.yellow(`\u26A0\uFE0F Skill "${label}" may be incompatible with your CLI (${cliVersion})`)
2743
+ );
2744
+ console.log("");
2745
+ console.log(`${fmt.bold("Required:")} ${skill.cliCompatibility}`);
2746
+ console.log(`${fmt.bold("Current :")} ${cliVersion}`);
2747
+ console.log("");
2748
+ console.log(fmt.bold("You can:"));
2749
+ console.log(` ${fmt.cyan("\u2022")} Upgrade CLI \u2192 ${fmt.cyan("blox upgrade")}`);
2750
+ console.log("");
2751
+ }
2752
+
2753
+ // src/commands/skills/index.ts
2754
+ var skills = command("skills").description("Install, update, and manage BLOX CLI skills from internal repositories").helpOption(false).allowUnknownOption(true).action(async () => {
2755
+ try {
2756
+ const code = await runSkills();
2757
+ process.exit(code);
2758
+ } catch (e) {
2759
+ error(e, false);
2760
+ process.exit(1);
2761
+ }
2762
+ });
2763
+ async function runSkills() {
2764
+ const idx = process.argv.indexOf("skills");
2765
+ const args = idx === -1 ? [] : process.argv.slice(idx + 1);
2766
+ const tempDir = import_node_path20.default.join(import_node_os3.default.tmpdir(), `${SKILLS_TEMP_ROOT_PREFIX}-${(0, import_node_crypto.randomUUID)()}`);
2767
+ await import_fs_extra18.default.mkdir(tempDir);
2768
+ let exitCode = 1;
2769
+ try {
2770
+ await git.clone(SKILLS_REPO_URL, tempDir);
2771
+ if (needsCliCompatibilityCheck(args)) {
2772
+ const skills2 = await loadSkillsData(tempDir);
2773
+ const cliVersion = getBloxCliVersion();
2774
+ const uncompatibleSkill = getFirstIncompatibleSkill(skills2, cliVersion);
2775
+ if (uncompatibleSkill) {
2776
+ warnIncompatibleSkill(uncompatibleSkill, cliVersion);
2777
+ const proceed = await confirm({
2778
+ message: "Continue anyway? (No \u2014 exit and run blox upgrade first)",
2779
+ initialValue: false
2780
+ });
2781
+ if (!proceed) {
2782
+ return 1;
2783
+ }
2784
+ }
2785
+ }
2786
+ const finalArgs = injectRepoPathIfAdd(args, import_node_path20.default.resolve(tempDir));
2787
+ exitCode = await runSkillsCommand(finalArgs, process.cwd());
2788
+ } finally {
2789
+ try {
2790
+ await import_fs_extra18.default.remove(tempDir);
2791
+ } catch {
2792
+ debug(`Failed to cleanup temp dir: ${tempDir}`);
2793
+ }
2794
+ }
2795
+ return exitCode;
2796
+ }
2797
+ function injectRepoPathIfAdd(args, repoPath) {
2798
+ const addIndex = getAddCommandIndex(args);
2799
+ if (addIndex === -1) return args;
2800
+ const next = args[addIndex + 1];
2801
+ if (!next || next.startsWith("-")) {
2802
+ return [...args.slice(0, addIndex + 1), repoPath, ...args.slice(addIndex + 1)];
2803
+ }
2804
+ const updated = [...args];
2805
+ updated[addIndex + 1] = repoPath;
2806
+ return updated;
2807
+ }
2808
+ function runSkillsCommand(args, cwd) {
2809
+ debug(`npx skills ${args.join(" ")}`);
2810
+ return new Promise((resolve, reject) => {
2811
+ const child = (0, import_cross_spawn2.default)("npx", ["skills", ...args], {
2812
+ cwd,
2813
+ stdio: "inherit"
2814
+ });
2815
+ child.on("error", reject);
2816
+ child.on("close", (code) => resolve(code ?? 1));
2817
+ });
2818
+ }
2819
+
2257
2820
  // src/commands/update/index.ts
2258
- var import_prompts20 = require("@clack/prompts");
2821
+ var import_prompts23 = require("@clack/prompts");
2259
2822
 
2260
2823
  // src/commands/update/utils.ts
2261
- var import_node_path16 = __toESM(require("path"));
2824
+ var import_node_path22 = __toESM(require("path"));
2262
2825
 
2263
2826
  // src/services/updater.ts
2264
- var import_node_path15 = __toESM(require("path"));
2265
- var import_fs_extra14 = __toESM(require("fs-extra"));
2827
+ var import_node_path21 = __toESM(require("path"));
2828
+ var import_fs_extra19 = __toESM(require("fs-extra"));
2266
2829
  var import_klaw3 = __toESM(require("klaw"));
2267
2830
  async function updateFromRemote({
2268
2831
  name,
@@ -2308,9 +2871,9 @@ async function updateFromRemote({
2308
2871
  }
2309
2872
  const remoteIgnore = remoteBloxFile.definition?.ignore || [];
2310
2873
  ignore3.push(...remoteIgnore, bloxFilePath, `**/${bloxFilePath}`);
2311
- const gitIgnorePath = import_node_path15.default.join(dir, ".gitignore");
2312
- if (await import_fs_extra14.default.pathExists(gitIgnorePath)) {
2313
- const gitIgnoreContent = await import_fs_extra14.default.readFile(gitIgnorePath, "utf8");
2874
+ const gitIgnorePath = import_node_path21.default.join(dir, ".gitignore");
2875
+ if (await import_fs_extra19.default.pathExists(gitIgnorePath)) {
2876
+ const gitIgnoreContent = await import_fs_extra19.default.readFile(gitIgnorePath, "utf8");
2314
2877
  const gitIgnorePatterns = gitIgnoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
2315
2878
  ignore3.push(...gitIgnorePatterns);
2316
2879
  debug(`Added ${gitIgnorePatterns.length} patterns from .gitignore`);
@@ -2322,14 +2885,14 @@ async function updateFromRemote({
2322
2885
  if (hard) {
2323
2886
  const getAllFiles = async (d) => {
2324
2887
  const files = [];
2325
- if (await import_fs_extra14.default.pathExists(d)) {
2888
+ if (await import_fs_extra19.default.pathExists(d)) {
2326
2889
  for await (const file of (0, import_klaw3.default)(d)) {
2327
2890
  if (file.path.includes("/.git/") || file.path.endsWith("/.git") || file.path.includes("\\.git\\") || file.path.endsWith("\\.git"))
2328
2891
  continue;
2329
2892
  if (file.path.includes("/node_modules/") || file.path.includes("\\node_modules\\"))
2330
2893
  continue;
2331
2894
  if (file.stats.isFile()) {
2332
- files.push(import_node_path15.default.relative(d, file.path));
2895
+ files.push(import_node_path21.default.relative(d, file.path));
2333
2896
  }
2334
2897
  }
2335
2898
  }
@@ -2348,23 +2911,23 @@ async function updateFromRemote({
2348
2911
  for (const file of filesToProcess) {
2349
2912
  if (file === ".git" || file.startsWith(".git/") || file.startsWith(".git\\")) continue;
2350
2913
  if (ignoredMatcher.ignores(toIgnorePath(file))) continue;
2351
- const localPath = import_node_path15.default.join(dir, file);
2352
- const basePath = import_node_path15.default.join(baseDir, file);
2353
- const remotePath = import_node_path15.default.join(remoteDir, file);
2354
- const existsLocal = await import_fs_extra14.default.pathExists(localPath);
2355
- const existsBase = await import_fs_extra14.default.pathExists(basePath);
2356
- const existsRemote = await import_fs_extra14.default.pathExists(remotePath);
2357
- const ext = import_node_path15.default.extname(file);
2914
+ const localPath = import_node_path21.default.join(dir, file);
2915
+ const basePath = import_node_path21.default.join(baseDir, file);
2916
+ const remotePath = import_node_path21.default.join(remoteDir, file);
2917
+ const existsLocal = await import_fs_extra19.default.pathExists(localPath);
2918
+ const existsBase = await import_fs_extra19.default.pathExists(basePath);
2919
+ const existsRemote = await import_fs_extra19.default.pathExists(remotePath);
2920
+ const ext = import_node_path21.default.extname(file);
2358
2921
  const isBinary = isBinaryFile(ext);
2359
2922
  if (existsRemote) {
2360
- await import_fs_extra14.default.ensureDir(import_node_path15.default.dirname(localPath));
2923
+ await import_fs_extra19.default.ensureDir(import_node_path21.default.dirname(localPath));
2361
2924
  }
2362
2925
  if (hard) {
2363
2926
  if (existsRemote) {
2364
- await import_fs_extra14.default.copy(remotePath, localPath, { overwrite: true });
2927
+ await import_fs_extra19.default.copy(remotePath, localPath, { overwrite: true });
2365
2928
  debug(`Hard update: Overwrote ${file}`);
2366
2929
  } else if (existsLocal) {
2367
- await import_fs_extra14.default.remove(localPath);
2930
+ await import_fs_extra19.default.remove(localPath);
2368
2931
  debug(`Hard update: Removed ${file}`);
2369
2932
  }
2370
2933
  continue;
@@ -2373,29 +2936,29 @@ async function updateFromRemote({
2373
2936
  if (existsLocal) {
2374
2937
  if (isBinary) {
2375
2938
  debug(`Binary collision: ${file}, overwriting.`);
2376
- await import_fs_extra14.default.copy(remotePath, localPath, { overwrite: true });
2939
+ await import_fs_extra19.default.copy(remotePath, localPath, { overwrite: true });
2377
2940
  logWarningSection(`Overwrote binary file collision: ${file}`);
2378
2941
  } else {
2379
- const emptyBase = import_node_path15.default.join(baseDir, `${file}.empty`);
2380
- await import_fs_extra14.default.ensureFile(emptyBase);
2942
+ const emptyBase = import_node_path21.default.join(baseDir, `${file}.empty`);
2943
+ await import_fs_extra19.default.ensureFile(emptyBase);
2381
2944
  const result = await git.mergeFile(localPath, emptyBase, remotePath);
2382
2945
  if (!result) {
2383
2946
  hasConflicts2 = true;
2384
2947
  conflictFiles.push(file);
2385
2948
  }
2386
- await import_fs_extra14.default.remove(emptyBase);
2949
+ await import_fs_extra19.default.remove(emptyBase);
2387
2950
  }
2388
2951
  } else {
2389
- await import_fs_extra14.default.copy(remotePath, localPath);
2952
+ await import_fs_extra19.default.copy(remotePath, localPath);
2390
2953
  }
2391
2954
  continue;
2392
2955
  }
2393
2956
  if (existsBase && !existsRemote) {
2394
2957
  if (existsLocal) {
2395
- const localBuffer = await import_fs_extra14.default.readFile(localPath);
2396
- const baseBuffer = await import_fs_extra14.default.readFile(basePath);
2958
+ const localBuffer = await import_fs_extra19.default.readFile(localPath);
2959
+ const baseBuffer = await import_fs_extra19.default.readFile(basePath);
2397
2960
  if (localBuffer.equals(baseBuffer)) {
2398
- await import_fs_extra14.default.remove(localPath);
2961
+ await import_fs_extra19.default.remove(localPath);
2399
2962
  } else {
2400
2963
  logWarningSection(
2401
2964
  `File ${file} was deleted in remote but modified locally. Kept local version.`
@@ -2406,7 +2969,7 @@ async function updateFromRemote({
2406
2969
  }
2407
2970
  if (existsBase && existsRemote) {
2408
2971
  if (!existsLocal) {
2409
- await import_fs_extra14.default.copy(remotePath, localPath);
2972
+ await import_fs_extra19.default.copy(remotePath, localPath);
2410
2973
  logWarningSection(
2411
2974
  `File restored: ${file}`,
2412
2975
  `This file was deleted locally but updated in the remote block.
@@ -2415,7 +2978,7 @@ It has been recreated to apply upstream changes.`
2415
2978
  continue;
2416
2979
  }
2417
2980
  if (isBinary) {
2418
- await import_fs_extra14.default.copy(remotePath, localPath, { overwrite: true });
2981
+ await import_fs_extra19.default.copy(remotePath, localPath, { overwrite: true });
2419
2982
  logWarningSection(`Updated binary file: ${file} (overwritten)`);
2420
2983
  } else {
2421
2984
  const result = await git.mergeFile(localPath, basePath, remotePath);
@@ -2455,6 +3018,7 @@ async function updateApp({
2455
3018
  ignore: ignore3,
2456
3019
  hard = false
2457
3020
  }) {
3021
+ let updated = false;
2458
3022
  await runTask({ start: "Update App", end: "Updated App" }, async () => {
2459
3023
  const template = templates[templateDef.name];
2460
3024
  if (!template) {
@@ -2468,12 +3032,13 @@ async function updateApp({
2468
3032
  hard
2469
3033
  });
2470
3034
  if (!toAppCommit) return;
3035
+ updated = true;
2471
3036
  if (!templateDef.bases?.length) return;
2472
3037
  for (const block of usedBlocks) {
2473
3038
  const blockRegistryData = availableBlocks[block.name];
2474
3039
  if (!blockRegistryData) return;
2475
3040
  await git.updateRemote(block.name, blockRegistryData.source);
2476
- const blockPath = import_node_path16.default.join(blocksDir, block.name);
3041
+ const blockPath = import_node_path22.default.join(blocksDir, block.name);
2477
3042
  const currentBloxFile = getBloxFile(blockPath);
2478
3043
  const remoteBloxFile = (await migrateOnRemote(block.name, toAppCommit, blockPath)).output[".blox"];
2479
3044
  const blockFromCommit = currentBloxFile.checkpoints?.[block.name]?.commit;
@@ -2488,8 +3053,10 @@ async function updateApp({
2488
3053
  }
2489
3054
  }
2490
3055
  });
3056
+ return updated;
2491
3057
  }
2492
3058
  async function updateAppBases(templateDef, templates, ignore3, hard = false) {
3059
+ let updated = false;
2493
3060
  for (const base of templateDef.bases || []) {
2494
3061
  await runTask(
2495
3062
  { start: `Update App base: ${base.name}`, end: `Updated App base: ${base.name}` },
@@ -2499,27 +3066,40 @@ async function updateAppBases(templateDef, templates, ignore3, hard = false) {
2499
3066
  error("Selected template not available in registries");
2500
3067
  return;
2501
3068
  }
2502
- await updateFromRemote({ name: base.name, source: template.source, ignore: ignore3, hard });
3069
+ const toCommit = await updateFromRemote({
3070
+ name: base.name,
3071
+ source: template.source,
3072
+ ignore: ignore3,
3073
+ hard
3074
+ });
3075
+ if (toCommit) updated = true;
2503
3076
  }
2504
3077
  );
2505
3078
  }
3079
+ return updated;
2506
3080
  }
2507
3081
  async function updateBlock(block, blocks, ignore3, hard = false) {
2508
3082
  const blockRegistryData = blocks[block];
2509
- const blockPath = import_node_path16.default.join(blocksDir, block);
3083
+ const blockPath = import_node_path22.default.join(blocksDir, block);
3084
+ let updated = false;
2510
3085
  await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
2511
3086
  if (!blockRegistryData) {
2512
3087
  error(`Selected block: ${block} not available in registries`, false);
2513
3088
  return;
2514
3089
  }
2515
- await updateFromRemote({
3090
+ const toCommit = await updateFromRemote({
2516
3091
  name: block,
2517
3092
  source: blockRegistryData.source,
2518
3093
  dir: blockPath,
2519
3094
  ignore: ignore3,
2520
3095
  hard
2521
3096
  });
3097
+ if (toCommit) updated = true;
2522
3098
  });
3099
+ if (updated) {
3100
+ await runLifecycleHookWithTask(blockPath, "update", "Run block update");
3101
+ }
3102
+ return updated;
2523
3103
  }
2524
3104
  async function getCurrentCheckpoints() {
2525
3105
  const bloxFile = getBloxFile();
@@ -2561,7 +3141,7 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
2561
3141
  option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
2562
3142
  ).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) => {
2563
3143
  if (await git.hasUncommittedChanges()) {
2564
- import_prompts20.log.warn(fmt.yellow("Make sure to commit any changes first"));
3144
+ import_prompts23.log.warn(fmt.yellow("Make sure to commit any changes first"));
2565
3145
  return;
2566
3146
  }
2567
3147
  await migrateAll(true);
@@ -2584,8 +3164,9 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
2584
3164
  ignoresByName[repo].push(pattern);
2585
3165
  }
2586
3166
  try {
3167
+ let hasUpdate = false;
2587
3168
  if (["app", "all"].includes(args.scope)) {
2588
- await updateApp({
3169
+ const appUpdated = await updateApp({
2589
3170
  templateDef,
2590
3171
  templates,
2591
3172
  usedBlocks,
@@ -2593,23 +3174,26 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
2593
3174
  ignore: ignoresByName[templateDef.name],
2594
3175
  hard: args.hard
2595
3176
  });
3177
+ hasUpdate = hasUpdate || appUpdated;
2596
3178
  }
2597
3179
  if (["bases", "all"].includes(args.scope)) {
2598
- await updateAppBases(
3180
+ const basesUpdated = await updateAppBases(
2599
3181
  templateDef,
2600
3182
  templates,
2601
3183
  ignoresByName[templateDef.name],
2602
3184
  args.hard
2603
3185
  );
3186
+ hasUpdate = hasUpdate || basesUpdated;
2604
3187
  }
2605
3188
  if (args.scope === "all") {
2606
3189
  for (const block of usedBlocks) {
2607
- await updateBlock(
3190
+ const blockUpdated = await updateBlock(
2608
3191
  block.name,
2609
3192
  availableBlocks,
2610
3193
  ignoresByName[block.name],
2611
3194
  args.hard
2612
3195
  );
3196
+ hasUpdate = hasUpdate || blockUpdated;
2613
3197
  }
2614
3198
  }
2615
3199
  if (args.scope === "block") {
@@ -2627,19 +3211,23 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
2627
3211
  error("Selected block not used in app");
2628
3212
  return;
2629
3213
  }
2630
- await updateBlock(
3214
+ const blockUpdated = await updateBlock(
2631
3215
  blockDef.name,
2632
3216
  availableBlocks,
2633
3217
  ignoresByName[blockDef.name],
2634
3218
  args.hard
2635
3219
  );
3220
+ hasUpdate = hasUpdate || blockUpdated;
3221
+ }
3222
+ if (hasUpdate) {
3223
+ await runLifecycleHookWithTask(".", "update", "Run template update");
2636
3224
  }
2637
3225
  await checkVersionsCompatibility();
2638
3226
  const endCheckpoints = await getCurrentCheckpoints();
2639
3227
  await printChangeLog(startCheckpoints, endCheckpoints);
2640
3228
  } catch (e) {
2641
3229
  if (!isDebugMode()) {
2642
- import_prompts20.log.warn("Error happened, Will rollback changes");
3230
+ import_prompts23.log.warn("Error happened, Will rollback changes");
2643
3231
  await git.rollback();
2644
3232
  }
2645
3233
  error(e);
@@ -2659,10 +3247,22 @@ var upgrade = command("upgrade").description("Upgrade blox cli to latest version
2659
3247
  });
2660
3248
 
2661
3249
  // src/commands/index.ts
2662
- var commands = [init2, add2, update2, conf, upgrade, migrateSchema, detach, contribute];
3250
+ var commands = [
3251
+ init2,
3252
+ add2,
3253
+ remove,
3254
+ update2,
3255
+ conf,
3256
+ upgrade,
3257
+ migrateSchema,
3258
+ detach,
3259
+ contribute,
3260
+ skills
3261
+ ];
2663
3262
 
2664
3263
  // bin/run.ts
2665
3264
  async function main() {
3265
+ setBloxCliVersion(version);
2666
3266
  import_extra_typings2.program.name("blox").version(version);
2667
3267
  import_extra_typings2.program.option("-d, --debug", "work in debug mode");
2668
3268
  import_extra_typings2.program.option("-m, --minimal", "work in minimal mode");