@naseej/blox 1.4.3 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/run.js +1380 -144
  2. package/package.json +24 -22
package/dist/run.js CHANGED
@@ -180,17 +180,17 @@ var checkForCliUpdate = async (currentVersion) => {
180
180
  };
181
181
 
182
182
  // package.json
183
- var version = "1.4.3";
183
+ var version = "1.5.0";
184
184
 
185
185
  // src/commands/add/index.ts
186
186
  var import_fs_extra9 = __toESM(require("fs-extra"));
187
187
 
188
188
  // src/migrations/index.ts
189
- var import_node_path6 = __toESM(require("path"));
189
+ var import_node_path7 = __toESM(require("path"));
190
190
  var import_fs_extra5 = __toESM(require("fs-extra"));
191
191
 
192
192
  // src/migrations/utils.ts
193
- var import_node_path5 = __toESM(require("path"));
193
+ var import_node_path6 = __toESM(require("path"));
194
194
  var import_fs_extra4 = __toESM(require("fs-extra"));
195
195
 
196
196
  // src/migrations/list/v1.ts
@@ -227,39 +227,43 @@ var v1 = {
227
227
  var migrationsList = [v1];
228
228
 
229
229
  // src/services/git.ts
230
- var import_node_path4 = __toESM(require("path"));
230
+ var import_node_os = __toESM(require("os"));
231
+ var import_node_path5 = __toESM(require("path"));
231
232
  var import_fs_extra3 = __toESM(require("fs-extra"));
232
233
 
233
- // src/services/path.ts
234
- var import_node_path3 = __toESM(require("path"));
235
- var normalizePath = (_path) => {
236
- return _path.split(import_node_path3.default.sep).join("/");
237
- };
238
-
239
234
  // src/services/shell.ts
240
235
  var import_node_child_process = require("child_process");
241
236
  var $ = async (bin, options = [], { cwd, onStdout } = {}) => {
242
237
  debug(`Command executed: "${bin} ${options.join(" ")}" with cwd = ${cwd}`);
243
238
  return new Promise(function(resolve, reject) {
244
239
  const child = (0, import_node_child_process.spawn)(bin, options, { cwd, shell: true, stdio: ["pipe", "pipe", "pipe"] });
245
- let error2 = "";
240
+ let stdout = "";
241
+ let stderr = "";
246
242
  child.stdout.on("data", (data) => {
243
+ const str = data.toString();
244
+ stdout += str;
247
245
  try {
248
- debug(data.toString());
249
- onStdout && onStdout(data.toString());
246
+ onStdout && onStdout(str);
250
247
  } catch (e) {
251
248
  reject(e);
252
249
  }
253
250
  });
254
251
  child.stderr.on("data", (data) => {
255
- error2 += data.toString();
252
+ stderr += data.toString();
256
253
  });
257
254
  child.on("close", function(code) {
258
- error2 && debug(error2);
259
255
  if (code) {
260
- reject(error2);
256
+ const combined = (stdout + "\n" + stderr).trim();
257
+ const msg = `Command "${bin} ${options.join(" ")}" failed (code ${code}).
258
+ ${combined}`;
259
+ const err = new Error(msg);
260
+ err.code = code;
261
+ err.stdout = stdout;
262
+ err.stderr = stderr;
263
+ err.combined = combined;
264
+ reject(err);
261
265
  } else {
262
- resolve(code);
266
+ resolve({ code, stdout, stderr });
263
267
  }
264
268
  });
265
269
  child.on("error", function(err) {
@@ -268,7 +272,156 @@ var $ = async (bin, options = [], { cwd, onStdout } = {}) => {
268
272
  });
269
273
  };
270
274
 
275
+ // src/shared/utils/buildGitExcludePathspecs.ts
276
+ var buildGitExcludePathspecs = (patterns) => {
277
+ const out = [];
278
+ for (const raw of patterns) {
279
+ let p = raw.trim();
280
+ if (!p) continue;
281
+ if (p.startsWith("#")) continue;
282
+ if (p.startsWith("!")) continue;
283
+ p = normalizeIgnorePath(p);
284
+ if (!p) continue;
285
+ const hadTrailingSlash = p.endsWith("/");
286
+ if (hadTrailingSlash) {
287
+ p = p.replace(/\/+$/, "");
288
+ }
289
+ const isDir = hadTrailingSlash || !hasGlobMagic(p) && looksLikeDirectory(p);
290
+ if (isDir && !hasGlobMagic(p)) {
291
+ p = `${p}/**`;
292
+ }
293
+ out.push(`:(exclude,glob)${p}`);
294
+ }
295
+ return out;
296
+ };
297
+ var normalizeIgnorePath = (input) => {
298
+ let p = input.trim();
299
+ if (!p) return "";
300
+ p = p.replace(/\\/g, "/");
301
+ if (p.startsWith("./")) {
302
+ p = p.slice(2);
303
+ }
304
+ if (p.startsWith("/")) {
305
+ p = p.slice(1);
306
+ }
307
+ p = p.replace(/\/+/g, "/");
308
+ return p;
309
+ };
310
+ var hasGlobMagic = (pattern) => {
311
+ return /[*?\[]/.test(pattern);
312
+ };
313
+ var looksLikeDirectory = (pattern) => {
314
+ if (pattern.endsWith("/")) return true;
315
+ const lastSegment = pattern.split("/").pop();
316
+ if (!lastSegment) return false;
317
+ return !lastSegment.includes(".");
318
+ };
319
+
320
+ // src/shared/utils/gitignoreMatcher.ts
321
+ var import_node_path3 = __toESM(require("path"));
322
+ var import_ignore = __toESM(require("ignore"));
323
+ var createGitignoreMatcher = (patterns) => {
324
+ const cleaned = patterns.map((p) => p.trim()).filter((p) => p && !p.startsWith("#"));
325
+ return (0, import_ignore.default)().add(cleaned);
326
+ };
327
+ var toIgnorePath = (repoRelativePath) => {
328
+ let p = repoRelativePath.split(import_node_path3.default.sep).join("/");
329
+ if (p.startsWith("./")) p = p.slice(2);
330
+ return p;
331
+ };
332
+
333
+ // src/shared/utils/isBinaryFile.ts
334
+ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
335
+ ".png",
336
+ ".jpg",
337
+ ".jpeg",
338
+ ".gif",
339
+ ".svg",
340
+ ".ico",
341
+ ".ttf",
342
+ ".woff",
343
+ ".woff2",
344
+ ".otf",
345
+ ".mp4",
346
+ ".mp3",
347
+ ".zip",
348
+ ".plist",
349
+ ".DS_Store",
350
+ ".bin"
351
+ ]);
352
+ function isBinaryFile(ext) {
353
+ return BINARY_EXTENSIONS.has(ext);
354
+ }
355
+
356
+ // src/services/path.ts
357
+ var import_node_path4 = __toESM(require("path"));
358
+ var normalizePath = (_path) => {
359
+ return _path.split(import_node_path4.default.sep).join("/");
360
+ };
361
+
271
362
  // src/services/git.ts
363
+ var remoteWorktrees = /* @__PURE__ */ new Map();
364
+ var getChangedFiles = async (fromCommit, toCommit, ignore3 = [], cwd = ".") => {
365
+ let output = "";
366
+ const args = [
367
+ "diff",
368
+ "--name-only",
369
+ "-z",
370
+ fromCommit,
371
+ toCommit,
372
+ "--",
373
+ ".",
374
+ ...buildGitExcludePathspecs(ignore3)
375
+ ];
376
+ await $("git", args, {
377
+ cwd,
378
+ onStdout: (text2) => {
379
+ output += text2;
380
+ }
381
+ });
382
+ return output.split("\0").filter(Boolean);
383
+ };
384
+ var getRemoteWorktree = async (remote, commit2) => {
385
+ const key = `${remote}:${commit2}`;
386
+ if (remoteWorktrees.has(key)) {
387
+ return remoteWorktrees.get(key);
388
+ }
389
+ const tmpDir = import_node_os.default.tmpdir();
390
+ const worktreeDir = import_node_path5.default.join(tmpDir, "blox-cli-worktrees", remote, commit2);
391
+ try {
392
+ await $("git", ["worktree", "prune"]);
393
+ } catch {
394
+ }
395
+ if (await import_fs_extra3.default.pathExists(worktreeDir)) {
396
+ try {
397
+ await $("git", ["worktree", "remove", "--force", worktreeDir]);
398
+ } catch {
399
+ await import_fs_extra3.default.remove(worktreeDir);
400
+ try {
401
+ await $("git", ["worktree", "prune"]);
402
+ } catch {
403
+ }
404
+ }
405
+ }
406
+ await $("git", ["worktree", "add", "--detach", "--force", worktreeDir, commit2]);
407
+ remoteWorktrees.set(key, worktreeDir);
408
+ return worktreeDir;
409
+ };
410
+ var cleanUpWorktrees = async () => {
411
+ debug("Cleaning up worktrees...");
412
+ for (const worktree of remoteWorktrees.values()) {
413
+ try {
414
+ await $("git", ["worktree", "remove", "--force", worktree]);
415
+ } catch (e) {
416
+ debug(`Failed to remove worktree ${worktree}: ${e}`);
417
+ }
418
+ }
419
+ try {
420
+ await $("git", ["worktree", "prune"]);
421
+ } catch {
422
+ }
423
+ remoteWorktrees.clear();
424
+ };
272
425
  var checkAuth = (message) => {
273
426
  if (message.includes("Username for")) {
274
427
  throw "Login to git first";
@@ -336,8 +489,8 @@ var update = (shellOptions = {}) => {
336
489
  var getLatestCommitFromRemote = async (remote, branch) => {
337
490
  return getLatestCommit(`${remote}/${branch}`);
338
491
  };
339
- var getLatestCommitFromPath = async (path12) => {
340
- return getLatestCommit("HEAD", path12);
492
+ var getLatestCommitFromPath = async (path17) => {
493
+ return getLatestCommit("HEAD", path17);
341
494
  };
342
495
  var getLatestCommit = async (rev, cwd = ".") => {
343
496
  debug(`Get latest commit for rev: ${rev} and cwd: ${cwd}`);
@@ -350,17 +503,6 @@ var getLatestCommit = async (rev, cwd = ".") => {
350
503
  });
351
504
  return commit2.replace(/\n/g, "");
352
505
  };
353
- var createPatch = async (fromCommit, toCommit, outputPath, ignore2 = []) => {
354
- return $("git", [
355
- "diff",
356
- fromCommit,
357
- toCommit,
358
- ">",
359
- outputPath,
360
- "--",
361
- ...ignore2.map((file) => `":(exclude)${file}"`)
362
- ]);
363
- };
364
506
  var getChangesLog = async (fromCommit, toCommit) => {
365
507
  let changes = "";
366
508
  await $("git", ["log", `${fromCommit}..${toCommit}`, '--pretty=format:"%B"'], {
@@ -370,18 +512,9 @@ var getChangesLog = async (fromCommit, toCommit) => {
370
512
  });
371
513
  return changes;
372
514
  };
373
- var applyPatch = (patch, cwd = ".") => {
374
- const args = ["apply", "-3", "--allow-empty"];
375
- if (cwd != ".") {
376
- args.push("--directory");
377
- args.push(normalizePath(cwd));
378
- }
379
- args.push(normalizePath(patch));
380
- return $("git", args);
381
- };
382
515
  var unInit = (cwd) => {
383
516
  debug("UnInit");
384
- return import_fs_extra3.default.remove(import_node_path4.default.join(cwd, ".git"));
517
+ return import_fs_extra3.default.remove(import_node_path5.default.join(cwd, ".git"));
385
518
  };
386
519
  var init = async (cwd) => {
387
520
  debug("Init");
@@ -390,18 +523,19 @@ var init = async (cwd) => {
390
523
  await $("git", ["commit", "-m", "init"], { cwd });
391
524
  await $("git", ["branch", "-m", defaultBranch], { cwd });
392
525
  };
393
- var add = async (toAdd) => {
526
+ var add = async (toAdd, cwd = ".") => {
394
527
  debug(`Git Add: ${toAdd}`);
395
- await $("git", ["add", toAdd]);
528
+ await $("git", ["add", toAdd], { cwd });
396
529
  };
397
- var commit = async (msg) => {
530
+ var commit = async (msg, cwd = ".") => {
398
531
  debug(`Git commit: ${msg}`);
399
- await $("git", ["commit", "-m", `"${msg}"`]);
532
+ await $("git", ["commit", "--no-verify", "-m", `"${msg}"`], { cwd });
400
533
  };
401
534
  var rollback = async () => {
402
535
  debug("Rollback");
403
536
  await $("git", ["add", "."]);
404
537
  await $("git", ["reset", "--hard"]);
538
+ await cleanUpWorktrees();
405
539
  };
406
540
  var hasUncommittedChanges = async (cwd = ".") => {
407
541
  let status = "";
@@ -413,6 +547,177 @@ var hasUncommittedChanges = async (cwd = ".") => {
413
547
  });
414
548
  return status.trim().length > 0;
415
549
  };
550
+ var hasStagedChanges = async (cwd = ".") => {
551
+ try {
552
+ await $("git", ["diff-index", "--cached", "--quiet", "HEAD"], { cwd });
553
+ return false;
554
+ } catch {
555
+ return true;
556
+ }
557
+ };
558
+ var checkout = async (branch, cwd = ".") => {
559
+ debug(`Git checkout: ${branch}`);
560
+ await $("git", ["checkout", branch], { cwd });
561
+ };
562
+ var merge = async (remoteBranch, options = {}) => {
563
+ debug(`Git merge: ${remoteBranch}`);
564
+ const args = ["merge", remoteBranch, "--no-edit"];
565
+ if (options.allowUnrelatedHistories) {
566
+ args.push("--allow-unrelated-histories");
567
+ }
568
+ await $("git", args);
569
+ };
570
+ var hasConflicts = async (cwd = ".") => {
571
+ let unmerged = "";
572
+ await $("git", ["ls-files", "--unmerged"], {
573
+ cwd,
574
+ onStdout: (text2) => {
575
+ unmerged += text2;
576
+ }
577
+ });
578
+ return unmerged.trim().length > 0;
579
+ };
580
+ var mergeFile = async (current, base, other) => {
581
+ try {
582
+ await $("git", ["merge-file", current, base, other]);
583
+ return true;
584
+ } catch {
585
+ return false;
586
+ }
587
+ };
588
+ var lsRemote = async (repoUrl, branch) => {
589
+ let out = "";
590
+ await $("git", ["ls-remote", repoUrl, `refs/heads/${branch}`], {
591
+ onStdout: (text2) => {
592
+ out += text2;
593
+ }
594
+ });
595
+ const line = out.trim().split("\n")[0];
596
+ if (!line) throw new Error(`No remote ref refs/heads/${branch} for ${repoUrl}`);
597
+ const hash = line.split(/\s+/)[0];
598
+ if (!hash) throw new Error(`Could not parse ls-remote output: ${line}`);
599
+ return hash.trim();
600
+ };
601
+ var listRemoteBranches = async (repoUrl) => {
602
+ let out = "";
603
+ await $("git", ["ls-remote", "--heads", repoUrl], {
604
+ onStdout: (text2) => {
605
+ out += text2;
606
+ }
607
+ });
608
+ return out.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => {
609
+ const parts = line.split(/\s+/);
610
+ const ref = parts[1] || "";
611
+ return ref.replace("refs/heads/", "");
612
+ }).filter((branch) => branch.length > 0 && branch !== "main" && branch !== "master");
613
+ };
614
+ var listBranches = async (cwd = ".") => {
615
+ let out = "";
616
+ await $("git", ["branch", "--list"], {
617
+ cwd,
618
+ onStdout: (text2) => {
619
+ out += text2;
620
+ }
621
+ });
622
+ return out.split("\n").map((l) => l.replace(/^\*?\s+/, "").trim()).filter(Boolean).filter((b) => !b.startsWith("("));
623
+ };
624
+ var createBranch = async (branch, from, cwd = ".") => {
625
+ if (from) {
626
+ await $("git", ["checkout", "-B", branch, from], { cwd });
627
+ } else {
628
+ await $("git", ["checkout", "-b", branch], { cwd });
629
+ }
630
+ };
631
+ var push = async (remote, branch, cwd = ".") => {
632
+ await $("git", ["push", "--progress", remote, `refs/heads/${branch}`], { cwd });
633
+ };
634
+ var checkoutFile = async (path17, ref, cwd = ".") => {
635
+ const args = ["checkout"];
636
+ if (ref) args.push(ref);
637
+ else args.push("HEAD");
638
+ args.push("--", path17);
639
+ await $("git", args, { cwd });
640
+ };
641
+ var pathExistsAsBlobInRev = async (rev, filePath, cwd = ".") => {
642
+ const p = normalizePath(filePath);
643
+ try {
644
+ await $("git", ["cat-file", "-e", `${rev}:${p}`], { cwd });
645
+ return true;
646
+ } catch {
647
+ return false;
648
+ }
649
+ };
650
+ var revertPathToHead = async (filePath, cwd = ".") => {
651
+ const p = normalizePath(filePath);
652
+ if (await pathExistsAsBlobInRev("HEAD", p, cwd)) {
653
+ await checkoutFile(p, "HEAD", cwd);
654
+ } else {
655
+ await $("git", ["rm", "-f", "--", p], { cwd });
656
+ }
657
+ };
658
+ var listCommits = async (limit, skip, cwd = ".") => {
659
+ let out = "";
660
+ await $(
661
+ "git",
662
+ ["log", '--pretty=format:"%H|%s"', "-n", String(limit), "--skip", String(skip), "HEAD"],
663
+ {
664
+ cwd,
665
+ onStdout: (text2) => {
666
+ out += text2;
667
+ }
668
+ }
669
+ );
670
+ const lines = out.split("\n").filter(Boolean);
671
+ return lines.map((line) => {
672
+ 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() };
676
+ });
677
+ };
678
+ var fetchCommit = async (fromRepo, commit2, cwd = ".") => {
679
+ await $("git", ["fetch", fromRepo, commit2], { cwd });
680
+ };
681
+ var cherryPick = async (commitHash, subtree, noCommit, cwd = ".") => {
682
+ const args = ["cherry-pick"];
683
+ if (noCommit) args.push("--no-commit");
684
+ if (subtree) args.push(`-Xsubtree=${subtree}`);
685
+ args.push(commitHash);
686
+ await $("git", args, { cwd });
687
+ };
688
+ var reset = async (path17, hard, cwd = ".") => {
689
+ const args = ["reset"];
690
+ if (hard) args.push("--hard");
691
+ if (path17) args.push(path17);
692
+ await $("git", args, { cwd });
693
+ };
694
+ var commitAll = async (message, cwd = ".") => {
695
+ await add(".", cwd);
696
+ await commit(message, cwd);
697
+ };
698
+ var getUnmergedFiles = async (cwd = ".") => {
699
+ let out = "";
700
+ await $("git", ["status", "--porcelain"], {
701
+ cwd,
702
+ onStdout: (text2) => {
703
+ out += text2;
704
+ }
705
+ });
706
+ return out.split("\n").filter((l) => /^(U.|.U|AA|DD)/.test(l)).map((l) => l.slice(3).trim());
707
+ };
708
+ var fetchRepo = async (cwd = ".") => {
709
+ await $("git", ["fetch", "--progress", "origin"], { cwd });
710
+ };
711
+ var getStagedFiles = async (cwd = ".") => {
712
+ let out = "";
713
+ await $("git", ["diff", "--cached", "--name-only"], {
714
+ cwd,
715
+ onStdout: (text2) => {
716
+ out += text2;
717
+ }
718
+ });
719
+ return out.split("\n").map((l) => l.trim()).filter(Boolean);
720
+ };
416
721
  var git = {
417
722
  clone,
418
723
  update,
@@ -420,9 +725,7 @@ var git = {
420
725
  init,
421
726
  getLatestCommitFromRemote,
422
727
  getLatestCommitFromPath,
423
- createPatch,
424
728
  getChangesLog,
425
- applyPatch,
426
729
  updateRemote,
427
730
  readJsonFromCommit,
428
731
  readJsonFromRemote,
@@ -431,7 +734,30 @@ var git = {
431
734
  add,
432
735
  resetToCommit,
433
736
  commit,
434
- hasUncommittedChanges
737
+ hasUncommittedChanges,
738
+ hasStagedChanges,
739
+ hasConflicts,
740
+ checkout,
741
+ merge,
742
+ getChangedFiles,
743
+ getRemoteWorktree,
744
+ cleanUpWorktrees,
745
+ mergeFile,
746
+ lsRemote,
747
+ listRemoteBranches,
748
+ listBranches,
749
+ createBranch,
750
+ push,
751
+ checkoutFile,
752
+ revertPathToHead,
753
+ listCommits,
754
+ fetchCommit,
755
+ cherryPick,
756
+ reset,
757
+ commitAll,
758
+ getUnmergedFiles,
759
+ fetchRepo,
760
+ getStagedFiles
435
761
  };
436
762
 
437
763
  // src/shared/prompts/index.ts
@@ -460,6 +786,16 @@ var text = async (opts) => {
460
786
  checkIfCanceled(value);
461
787
  return value;
462
788
  };
789
+ var confirm = async (opts) => {
790
+ const value = await (0, import_prompts3.confirm)(opts);
791
+ checkIfCanceled(value);
792
+ return value;
793
+ };
794
+ var multiselect = async (opts) => {
795
+ const value = await (0, import_prompts3.multiselect)(opts);
796
+ checkIfCanceled(value);
797
+ return value;
798
+ };
463
799
  var textList = async (opts) => {
464
800
  opts.message = `${opts.message} ${fmt.gray('(separated with ",")')}`;
465
801
  const value = await (0, import_prompts3.text)(opts);
@@ -533,7 +869,7 @@ async function migrate(name, { getPath = (f) => f, read, write }) {
533
869
  }
534
870
  function migrateOnLocal(name, cwd = ".") {
535
871
  return migrate(name, {
536
- getPath: (file) => import_node_path5.default.join(cwd, file),
872
+ getPath: (file) => import_node_path6.default.join(cwd, file),
537
873
  read: import_fs_extra4.default.readJson,
538
874
  write: import_fs_extra4.default.writeFile
539
875
  });
@@ -541,7 +877,7 @@ function migrateOnLocal(name, cwd = ".") {
541
877
  function migrateOnRemote(name, commit2, cwd) {
542
878
  return migrate(name, {
543
879
  read: (file) => git.readJsonFromCommit(commit2, file),
544
- getPath: cwd ? (file) => import_node_path5.default.join(cwd, file) : void 0
880
+ getPath: cwd ? (file) => import_node_path6.default.join(cwd, file) : void 0
545
881
  });
546
882
  }
547
883
 
@@ -550,7 +886,7 @@ async function migrateAll(autoCommit) {
550
886
  let filesChanged = (await migrateOnLocal("app")).filesChanged;
551
887
  const blocks = import_fs_extra5.default.existsSync(blocksDir) ? import_fs_extra5.default.readdirSync(blocksDir) : [];
552
888
  for (const block of blocks) {
553
- const res = await migrateOnLocal(block, import_node_path6.default.join(blocksDir, block));
889
+ const res = await migrateOnLocal(block, import_node_path7.default.join(blocksDir, block));
554
890
  filesChanged = filesChanged || res.filesChanged;
555
891
  }
556
892
  if (autoCommit && filesChanged && await git.hasUncommittedChanges()) {
@@ -561,17 +897,17 @@ async function migrateAll(autoCommit) {
561
897
  }
562
898
 
563
899
  // src/services/fs.ts
564
- var import_node_path7 = __toESM(require("path"));
900
+ var import_node_path8 = __toESM(require("path"));
565
901
  var import_fs_extra6 = __toESM(require("fs-extra"));
566
- var import_ignore = __toESM(require("ignore"));
902
+ var import_ignore2 = __toESM(require("ignore"));
567
903
  var import_klaw = __toESM(require("klaw"));
568
904
  var filterBlacklisted = (item) => {
569
905
  return !item.includes("node_modules") && !item.includes(".git");
570
906
  };
571
907
  var deletePattern = async (cwd, patterns = []) => {
572
- const ig = (0, import_ignore.default)().add(patterns);
908
+ const ig = (0, import_ignore2.default)().add(patterns);
573
909
  for await (const file of (0, import_klaw.default)(cwd, { filter: filterBlacklisted })) {
574
- const relativePath = import_node_path7.default.relative(cwd, file.path);
910
+ const relativePath = import_node_path8.default.relative(cwd, file.path);
575
911
  if (relativePath && ig.ignores(relativePath)) {
576
912
  if (!await import_fs_extra6.default.exists(file.path)) {
577
913
  continue;
@@ -583,7 +919,7 @@ var deletePattern = async (cwd, patterns = []) => {
583
919
  };
584
920
 
585
921
  // src/services/registry.ts
586
- var import_node_path8 = __toESM(require("path"));
922
+ var import_node_path9 = __toESM(require("path"));
587
923
  var import_fs_extra7 = __toESM(require("fs-extra"));
588
924
  var import_merge = __toESM(require("lodash/merge"));
589
925
 
@@ -619,7 +955,7 @@ async function runTask(message, task) {
619
955
  }
620
956
 
621
957
  // src/services/registry.ts
622
- var registriesDataPath = import_node_path8.default.join(appPaths.data, "registries");
958
+ var registriesDataPath = import_node_path9.default.join(appPaths.data, "registries");
623
959
  var upeToDate = false;
624
960
  var syncRegistries = async (branch) => {
625
961
  if (upeToDate) return;
@@ -632,10 +968,10 @@ var syncRegistries = async (branch) => {
632
968
  config.registries.map(async (registry) => {
633
969
  debug(`update registry: ${registry}`);
634
970
  const repoName = registry.split("/").pop() || "";
635
- const repoDir = import_node_path8.default.join(registriesDataPath, repoName);
971
+ const repoDir = import_node_path9.default.join(registriesDataPath, repoName);
636
972
  if (!import_fs_extra7.default.existsSync(repoDir)) {
637
973
  await git.clone(registry, "--depth 1", branch, { cwd: registriesDataPath });
638
- } else if (import_fs_extra7.default.existsSync(import_node_path8.default.join(repoDir, ".git"))) {
974
+ } else if (import_fs_extra7.default.existsSync(import_node_path9.default.join(repoDir, ".git"))) {
639
975
  await git.update({ cwd: repoDir });
640
976
  } else {
641
977
  debug(`local registry`);
@@ -649,7 +985,7 @@ var getAvailableTemplates = async () => {
649
985
  const templates = {};
650
986
  const registries = import_fs_extra7.default.readdirSync(registriesDataPath);
651
987
  for (const registry of registries) {
652
- const indexPath = import_node_path8.default.join(registriesDataPath, registry, "index.json");
988
+ const indexPath = import_node_path9.default.join(registriesDataPath, registry, "index.json");
653
989
  if (import_fs_extra7.default.existsSync(indexPath)) {
654
990
  const data = import_fs_extra7.default.readJSONSync(indexPath);
655
991
  Object.entries(data.templates || {}).forEach(([templateName, template]) => {
@@ -693,14 +1029,14 @@ var getAvailableBlocks = async (templateInfo) => {
693
1029
  var getAvailableVersions = async (source) => {
694
1030
  const registries = import_fs_extra7.default.readdirSync(registriesDataPath);
695
1031
  for (const registry of registries) {
696
- const registryPath = import_node_path8.default.join(registriesDataPath, registry);
697
- const indexPath = import_node_path8.default.join(registryPath, "index.json");
1032
+ const registryPath = import_node_path9.default.join(registriesDataPath, registry);
1033
+ const indexPath = import_node_path9.default.join(registryPath, "index.json");
698
1034
  if (!import_fs_extra7.default.existsSync(indexPath)) continue;
699
1035
  const registryData = import_fs_extra7.default.readJSONSync(indexPath);
700
- const versionDirPath = import_node_path8.default.join(registryPath, "versions");
1036
+ const versionDirPath = import_node_path9.default.join(registryPath, "versions");
701
1037
  const versionsFilePaths = [
702
- import_node_path8.default.join(versionDirPath, `${source.replace(`${registryData.baseUrl}/`, "")}.json`),
703
- import_node_path8.default.join(versionDirPath, `${encodeURIComponent(source)}.json`)
1038
+ import_node_path9.default.join(versionDirPath, `${source.replace(`${registryData.baseUrl}/`, "")}.json`),
1039
+ import_node_path9.default.join(versionDirPath, `${encodeURIComponent(source)}.json`)
704
1040
  ];
705
1041
  for (const versionsFile of versionsFilePaths) {
706
1042
  if (import_fs_extra7.default.existsSync(versionsFile)) {
@@ -711,34 +1047,16 @@ var getAvailableVersions = async (source) => {
711
1047
  };
712
1048
 
713
1049
  // src/services/template.ts
714
- var import_node_path9 = __toESM(require("path"));
1050
+ var import_node_path10 = __toESM(require("path"));
715
1051
  var import_ejs = __toESM(require("ejs"));
716
1052
  var import_fs_extra8 = __toESM(require("fs-extra"));
717
1053
  var import_klaw2 = __toESM(require("klaw"));
718
- var NON_RENDERABLE_FILES = [
719
- ".png",
720
- ".jpg",
721
- ".jpeg",
722
- ".gif",
723
- ".svg",
724
- ".ico",
725
- ".ttf",
726
- ".woff",
727
- ".woff2",
728
- ".otf",
729
- ".mp4",
730
- ".mp3",
731
- ".zip",
732
- ".plist",
733
- ".DS_Store",
734
- ".bin"
735
- ];
736
1054
  async function replacePlaceholders(dir, context) {
737
1055
  debug("Replace placeholders");
738
1056
  for await (const file of (0, import_klaw2.default)(dir)) {
739
1057
  if (!file.stats.isFile()) continue;
740
- const ext = import_node_path9.default.extname(file.path).toLowerCase();
741
- if (NON_RENDERABLE_FILES.includes(ext)) {
1058
+ const ext = import_node_path10.default.extname(file.path).toLowerCase();
1059
+ if (isBinaryFile(ext)) {
742
1060
  continue;
743
1061
  }
744
1062
  const templateContent = import_fs_extra8.default.readFileSync(file.path, "utf8");
@@ -768,7 +1086,7 @@ function getBlockDef(cwd = ".") {
768
1086
  }
769
1087
  function getBloxFile(cwd = ".") {
770
1088
  try {
771
- const file = import_fs_extra8.default.readJSONSync(import_node_path9.default.join(cwd, bloxFilePath));
1089
+ const file = import_fs_extra8.default.readJSONSync(import_node_path10.default.join(cwd, bloxFilePath));
772
1090
  if (!file.checkpoints) {
773
1091
  file.checkpoints = {};
774
1092
  }
@@ -779,7 +1097,7 @@ function getBloxFile(cwd = ".") {
779
1097
  }
780
1098
  function saveBloxFile(info, cwd = ".") {
781
1099
  debug("Save info");
782
- import_fs_extra8.default.writeFileSync(import_node_path9.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
1100
+ import_fs_extra8.default.writeFileSync(import_node_path10.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
783
1101
  }
784
1102
  function updateCheckpoint(name, checkpoint, cwd = ".") {
785
1103
  const info = getBloxFile(cwd);
@@ -800,7 +1118,7 @@ function getUsedBlocks() {
800
1118
  if (!file.isDirectory()) {
801
1119
  return;
802
1120
  }
803
- const blockDef = getBloxFile(import_node_path9.default.join(blocksDir, file.name));
1121
+ const blockDef = getBloxFile(import_node_path10.default.join(blocksDir, file.name));
804
1122
  if (blockDef && blockDef.definition) {
805
1123
  blocks.push(blockDef);
806
1124
  }
@@ -1035,6 +1353,805 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
1035
1353
  }
1036
1354
  });
1037
1355
 
1356
+ // src/services/contribute/constants/index.ts
1357
+ var UI_PAGE_SIZE = 15;
1358
+ var TARGET_SELECT_PAGE = {
1359
+ PREV: "__prev__",
1360
+ NEXT: "__next__",
1361
+ SEARCH_AGAIN: "__search__"
1362
+ };
1363
+ var COMMIT_TYPES = [
1364
+ { value: "fix", label: "fix: A bug fix (PATCH)" },
1365
+ { value: "feat", label: "feat: A new feature (MINOR)" },
1366
+ { value: "docs", label: "docs: Documentation only" },
1367
+ { value: "refactor", label: "refactor: Code change (no fix/feature)" },
1368
+ { value: "perf", label: "perf: Performance improvement" },
1369
+ { value: "test", label: "test: Adding/correcting tests" },
1370
+ { value: "build", label: "build: Build system / dependencies" },
1371
+ { value: "ci", label: "ci: CI configuration (GitLab/GitHub)" }
1372
+ ];
1373
+
1374
+ // src/services/contribute/types.ts
1375
+ var ContributionTargetType = /* @__PURE__ */ ((ContributionTargetType2) => {
1376
+ ContributionTargetType2["TEMPLATE"] = "template";
1377
+ ContributionTargetType2["BASE"] = "base";
1378
+ ContributionTargetType2["BLOCK"] = "block";
1379
+ return ContributionTargetType2;
1380
+ })(ContributionTargetType || {});
1381
+
1382
+ // src/services/contribute/utils/bloxCheckpoint.ts
1383
+ var import_node_path11 = __toESM(require("path"));
1384
+ function getCheckpointForTarget(cwd, target) {
1385
+ const bloxDir = getBloxDirForTarget(cwd, target);
1386
+ const blox = getBloxFile(bloxDir);
1387
+ const key = target.name;
1388
+ const cp = blox.checkpoints?.[key];
1389
+ return { commit: cp?.commit, branch: cp?.branch };
1390
+ }
1391
+ function getBloxDirForTarget(cwd, target) {
1392
+ if (target.type === "block" /* BLOCK */) {
1393
+ return import_node_path11.default.join(cwd, blocksDir, target.name);
1394
+ }
1395
+ return cwd;
1396
+ }
1397
+
1398
+ // src/services/contribute/utils/getRepoUrl.ts
1399
+ var getTargetRepoUrl = async (target) => {
1400
+ if (target.type === "template" /* TEMPLATE */ || target.type === "base" /* BASE */) {
1401
+ const templates = await getAvailableTemplates();
1402
+ const t = templates[target.name];
1403
+ if (!t?.source) {
1404
+ throw new Error(`No registry source found for template/base: ${target.name}`);
1405
+ }
1406
+ return t.source;
1407
+ }
1408
+ if (!target.templateName) {
1409
+ throw new Error(`Target missing templateName for block source resolution: ${target.name}`);
1410
+ }
1411
+ const templateDef = target.templateDef;
1412
+ if (!templateDef) {
1413
+ throw new Error(`Target missing templateDef for block source resolution: ${target.name}`);
1414
+ }
1415
+ const blocks = await getAvailableBlocks(templateDef);
1416
+ const blockSource = blocks?.[target.name]?.source;
1417
+ if (!blockSource) {
1418
+ throw new Error(`No registry source found for block: ${target.name}`);
1419
+ }
1420
+ return blockSource;
1421
+ };
1422
+
1423
+ // src/services/contribute/utils/sleep.ts
1424
+ async function sleep(ms2) {
1425
+ await new Promise((r) => setTimeout(r, ms2));
1426
+ }
1427
+
1428
+ // src/services/contribute/utils/slugifyTitle.ts
1429
+ function slugifyTitle(title) {
1430
+ const s = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1431
+ return (s || "contribution").slice(0, 80);
1432
+ }
1433
+
1434
+ // src/services/contribute/ContributionWorkflow.ts
1435
+ var MANUAL_BRANCH_OPTION = "__manual__";
1436
+ var ContributionWorkflow = class {
1437
+ constructor(ctx, logger, targetSelector, tmpRepo, commitSelector, commitApplier, pullRequest) {
1438
+ this.ctx = ctx;
1439
+ this.logger = logger;
1440
+ this.targetSelector = targetSelector;
1441
+ this.tmpRepo = tmpRepo;
1442
+ this.commitSelector = commitSelector;
1443
+ this.commitApplier = commitApplier;
1444
+ this.pullRequest = pullRequest;
1445
+ }
1446
+ async runFromFlags(flags) {
1447
+ await this.assertAppRepoClean();
1448
+ const target = await this.targetSelector.selectTargetInteractive();
1449
+ const mode = flags.existing ? "existing" : "new";
1450
+ const { title, description } = await this.promptNewContributionMeta(mode, flags);
1451
+ const commits = await this.resolveCommitsFromFlags(flags);
1452
+ const branch = await this.resolveContributionBranch({ mode, target, title });
1453
+ return this.run({
1454
+ target,
1455
+ mode,
1456
+ title,
1457
+ description,
1458
+ branch,
1459
+ commits
1460
+ });
1461
+ }
1462
+ async run(input) {
1463
+ const repoUrl = await getTargetRepoUrl(input.target);
1464
+ const checkpoint = getCheckpointForTarget(this.ctx.cwd, input.target);
1465
+ const remoteBranch = checkpoint.branch || defaultBranch;
1466
+ const remoteHead = await this.resolveRemoteHeadOrThrow(repoUrl, remoteBranch);
1467
+ this.ensureCheckpointValid(input, checkpoint, remoteHead);
1468
+ this.logger.debug("preflight.resolved", {
1469
+ repoUrl,
1470
+ remoteBranch,
1471
+ checkpoint: checkpoint.commit,
1472
+ remoteHead
1473
+ });
1474
+ this.assertCheckpointMatchesRemoteForNonTemplate(input, checkpoint, remoteHead);
1475
+ const tmpCwd = await this.tmpRepo.prepare({
1476
+ target: input.target,
1477
+ repoUrl,
1478
+ branch: remoteBranch
1479
+ });
1480
+ const branch = input.branch;
1481
+ if (!branch) {
1482
+ throw new Error("Internal error: branch not resolved.");
1483
+ }
1484
+ await this.checkoutBaseInTmp({
1485
+ tmpCwd,
1486
+ mode: input.mode,
1487
+ checkpointCommit: checkpoint.commit,
1488
+ branch,
1489
+ title: input.title
1490
+ });
1491
+ const { title, description } = this.deriveTitleAndDescription(input);
1492
+ await this.commitApplier.applyCommits({
1493
+ appRepoCwd: this.ctx.cwd,
1494
+ tmpRepoCwd: tmpCwd,
1495
+ commits: input.commits,
1496
+ target: input.target,
1497
+ title,
1498
+ description
1499
+ });
1500
+ await this.pushWithRetry(tmpCwd, "origin", branch);
1501
+ const pr = await this.pullRequest.printPullRequestInstructions({
1502
+ repoUrl,
1503
+ sourceBranch: branch,
1504
+ targetBranch: remoteBranch,
1505
+ title,
1506
+ description
1507
+ });
1508
+ this.logCompletion(pr.prUrl);
1509
+ return {
1510
+ branch,
1511
+ commits: input.commits,
1512
+ prUrl: pr.prUrl
1513
+ };
1514
+ }
1515
+ async assertAppRepoClean() {
1516
+ if (await git.hasUncommittedChanges(this.ctx.cwd)) {
1517
+ throw new Error(
1518
+ "Make sure to commit or stash any changes in the app repo before contributing."
1519
+ );
1520
+ }
1521
+ }
1522
+ async promptNewContributionMeta(mode, flags) {
1523
+ let title = flags.title;
1524
+ let description = flags.description;
1525
+ if (mode === "new") {
1526
+ if (!title) {
1527
+ title = await text({
1528
+ message: "Contribution title (conventional commit style recommended)",
1529
+ validate: (v) => v.trim() ? void 0 : "Title is required"
1530
+ });
1531
+ }
1532
+ if (description === void 0) {
1533
+ description = await text({ message: "Description (optional)", defaultValue: "" });
1534
+ }
1535
+ }
1536
+ return { title, description };
1537
+ }
1538
+ async resolveCommitsFromFlags(flags) {
1539
+ if (flags.commits) {
1540
+ const commits = flags.commits.split(",").map((c) => c.trim()).filter(Boolean);
1541
+ if (!commits.length) {
1542
+ throw new Error("No commit hashes parsed from --commits.");
1543
+ }
1544
+ return commits;
1545
+ }
1546
+ return this.commitSelector.selectCommitsInteractive({
1547
+ cwd: this.ctx.cwd
1548
+ });
1549
+ }
1550
+ async resolveContributionBranch(opts) {
1551
+ const { mode, target, title } = opts;
1552
+ if (mode === "new" && title) {
1553
+ const commitType = await select({
1554
+ message: "Select the commit type for this contribution:",
1555
+ options: COMMIT_TYPES
1556
+ });
1557
+ return `${commitType}/${slugifyTitle(title)}`;
1558
+ }
1559
+ if (mode === "existing") {
1560
+ import_prompts2.log.info("Fetching remote branches for the existing contribution...");
1561
+ const repoUrl = await getTargetRepoUrl(target);
1562
+ const remoteBranches = await git.listRemoteBranches(repoUrl);
1563
+ if (remoteBranches.length === 0) {
1564
+ throw new Error("No remote branches found to contribute to.");
1565
+ }
1566
+ const selectedBranch = await select({
1567
+ message: "Select the existing contribution branch:",
1568
+ options: [
1569
+ ...remoteBranches.map((b) => ({ label: b, value: b })),
1570
+ { label: "Type branch name manually...", value: MANUAL_BRANCH_OPTION }
1571
+ ]
1572
+ });
1573
+ if (selectedBranch === MANUAL_BRANCH_OPTION) {
1574
+ return await text({
1575
+ message: "Enter branch name:"
1576
+ });
1577
+ }
1578
+ return selectedBranch;
1579
+ }
1580
+ return void 0;
1581
+ }
1582
+ async resolveRemoteHeadOrThrow(repoUrl, remoteBranch) {
1583
+ try {
1584
+ return await git.lsRemote(repoUrl, remoteBranch);
1585
+ } catch (e) {
1586
+ throw new Error(
1587
+ `Failed to read remote ref for ${repoUrl} (branch ${remoteBranch}). ${e instanceof Error ? e.message : String(e)}`
1588
+ );
1589
+ }
1590
+ }
1591
+ ensureCheckpointValid(input, checkpoint, remoteHead) {
1592
+ if (input.target.type === "template" /* TEMPLATE */ && !checkpoint.commit) {
1593
+ checkpoint.commit = remoteHead;
1594
+ }
1595
+ if (!checkpoint.commit) {
1596
+ throw new Error(
1597
+ `Missing checkpoint commit for ${input.target.type}/${input.target.name} in .blox. Cannot contribute safely.`
1598
+ );
1599
+ }
1600
+ }
1601
+ assertCheckpointMatchesRemoteForNonTemplate(input, checkpoint, remoteHead) {
1602
+ if (input.target.type === "template" /* TEMPLATE */) {
1603
+ return;
1604
+ }
1605
+ if (checkpoint.commit !== remoteHead && !this.ctx.force) {
1606
+ 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.`;
1607
+ throw new Error(
1608
+ `${hint}
1609
+ Expected remote ${remoteHead}, local checkpoint ${checkpoint.commit}.`
1610
+ );
1611
+ }
1612
+ if (checkpoint.commit !== remoteHead && this.ctx.force) {
1613
+ this.logger.warn("preflight.overridden", {
1614
+ checkpoint: checkpoint.commit,
1615
+ remoteHead
1616
+ });
1617
+ }
1618
+ }
1619
+ async checkoutBaseInTmp(opts) {
1620
+ const { tmpCwd, mode, checkpointCommit, branch, title } = opts;
1621
+ if (mode === "new") {
1622
+ if (!title) {
1623
+ throw new Error("New contribution requires a title.");
1624
+ }
1625
+ await git.checkout(checkpointCommit, tmpCwd);
1626
+ this.logger.debug("branch.create", { branch, from: checkpointCommit });
1627
+ this.logger.info(`Create new branch ${branch} from ${checkpointCommit}`);
1628
+ await git.createBranch(branch, checkpointCommit, tmpCwd);
1629
+ return;
1630
+ }
1631
+ await git.checkout(branch, tmpCwd);
1632
+ }
1633
+ deriveTitleAndDescription(input) {
1634
+ const title = input.title || "contribution title";
1635
+ const description = input.description || "";
1636
+ return { title, description };
1637
+ }
1638
+ logCompletion(prUrl) {
1639
+ import_prompts2.log.success(
1640
+ fmt.green("Contribution flow completed.") + (prUrl ? `
1641
+ PR URL:
1642
+ ${prUrl}` : "\nPush completed. Create the PR using the instructions above.")
1643
+ );
1644
+ }
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
+ };
1666
+
1667
+ // src/services/contribute/config/index.ts
1668
+ var tempRepoName = "tmp";
1669
+ var alwaysSkipPatterns = [/\.blox$/];
1670
+
1671
+ // src/services/contribute/utils/getExcludedPrefixesForTarget.ts
1672
+ var import_node_path12 = __toESM(require("path"));
1673
+ var import_fs_extra10 = __toESM(require("fs-extra"));
1674
+ function getExcludedPrefixesForTarget(target, cwd) {
1675
+ if (target.type === "block" /* BLOCK */) {
1676
+ return [];
1677
+ }
1678
+ 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 });
1682
+ for (const entry of entries) {
1683
+ if (!entry.isDirectory()) continue;
1684
+ const blockBloxFile = import_node_path12.default.join(blocksPath, entry.name, bloxFilePath);
1685
+ if (import_fs_extra10.default.existsSync(blockBloxFile)) {
1686
+ excluded.push(normalizePath(`${blocksDir}/${entry.name}/`));
1687
+ }
1688
+ }
1689
+ }
1690
+ return excluded;
1691
+ }
1692
+
1693
+ // src/services/contribute/utils/getPathPrefixToStrip.ts
1694
+ function getPathPrefixToStrip(target) {
1695
+ if (target.type === "block" /* BLOCK */) {
1696
+ return normalizePath(`${blocksDir}/${target.name}/`);
1697
+ }
1698
+ return "";
1699
+ }
1700
+
1701
+ // src/services/contribute/utils/shouldExcludeFile.ts
1702
+ function shouldExcludeFile(file, excludedPrefixes) {
1703
+ const f = normalizePath(file);
1704
+ return excludedPrefixes.some((p) => f.startsWith(p));
1705
+ }
1706
+
1707
+ // src/services/contribute/services/CommitApplierService.ts
1708
+ var CommitApplierService = class {
1709
+ constructor(logger) {
1710
+ this.logger = logger;
1711
+ }
1712
+ async applyCommits(opts) {
1713
+ const subtreePath = getPathPrefixToStrip(opts.target).replace(/\/$/, "");
1714
+ const exclusion = getExcludedPrefixesForTarget(opts.target, opts.appRepoCwd);
1715
+ this.logger.debug("Prepare for apply commits", {
1716
+ appRepo: opts.appRepoCwd,
1717
+ tmpRepo: opts.tmpRepoCwd,
1718
+ subtree: subtreePath || "(root)",
1719
+ exclusion
1720
+ });
1721
+ this.logger.info("Prepare for apply commits");
1722
+ for (const commit2 of opts.commits) {
1723
+ await this.applySingleCommit(opts, subtreePath, exclusion, commit2);
1724
+ }
1725
+ }
1726
+ async applySingleCommit(opts, subtreePath, exclusion, commit2) {
1727
+ this.logger.debug("apply.commit.start", { commit: commit2.slice(0, 7) });
1728
+ this.logger.info(`Apply commit ${commit2.slice(0, 7)} start`);
1729
+ try {
1730
+ await git.fetchCommit(opts.appRepoCwd, commit2, opts.tmpRepoCwd);
1731
+ try {
1732
+ await git.cherryPick("FETCH_HEAD", subtreePath || void 0, true, opts.tmpRepoCwd);
1733
+ } catch (e) {
1734
+ this.logger.debug("apply.commit.conflicts_initial", {
1735
+ commit: commit2.slice(0, 7),
1736
+ message: e instanceof Error ? e.message : String(e)
1737
+ });
1738
+ }
1739
+ await this.revertExcludedStagedFiles(opts.tmpRepoCwd, commit2, exclusion);
1740
+ const remainingConflicts = await git.getUnmergedFiles(opts.tmpRepoCwd);
1741
+ if (remainingConflicts.length) {
1742
+ this.logger.error("apply.commit.conflicts", {
1743
+ commit: commit2.slice(0, 7),
1744
+ files: remainingConflicts
1745
+ });
1746
+ await this.waitUntilUserResolvesConflicts(opts.tmpRepoCwd, commit2);
1747
+ }
1748
+ await this.commitStagedIfAny(opts, commit2);
1749
+ } catch (e) {
1750
+ const msg = `Failed to apply commit ${commit2.slice(0, 7)}.
1751
+ Resolve manually in the temp repo:
1752
+ cd ${opts.tmpRepoCwd}
1753
+ git status
1754
+ `;
1755
+ throw new Error(`${msg}
1756
+ ${e instanceof Error ? e.message : String(e)}`);
1757
+ }
1758
+ }
1759
+ async revertExcludedStagedFiles(tmpRepoCwd, commit2, exclusion) {
1760
+ const stagedFiles = await git.getStagedFiles(tmpRepoCwd);
1761
+ const unmergedFiles = await git.getUnmergedFiles(tmpRepoCwd);
1762
+ const allTouchedFiles = [.../* @__PURE__ */ new Set([...stagedFiles, ...unmergedFiles])];
1763
+ for (const file of allTouchedFiles) {
1764
+ const isAlwaysSkipped = alwaysSkipPatterns.some((p) => p.test(file));
1765
+ 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
+ });
1772
+ await git.revertPathToHead(file, tmpRepoCwd);
1773
+ }
1774
+ }
1775
+ }
1776
+ async waitUntilUserResolvesConflicts(tmpRepoCwd, commit2) {
1777
+ let remainingConflicts = await git.getUnmergedFiles(tmpRepoCwd);
1778
+ while (remainingConflicts.length) {
1779
+ console.log(`
1780
+ ${fmt.red(fmt.bold("!! CONFLICTS DETECTED !!"))}`);
1781
+ console.log(
1782
+ fmt.yellow(`Commit ${commit2.slice(0, 7)} has conflicts in the following files:`)
1783
+ );
1784
+ remainingConflicts.forEach((f) => console.log(fmt.red(` - ${f}`)));
1785
+ console.log(`
1786
+ ${fmt.cyan("Instructions:")}`);
1787
+ console.log(fmt.white(" 1. Open a new terminal and go to:"));
1788
+ console.log(fmt.green(` cd "${tmpRepoCwd}"`));
1789
+ console.log(fmt.white(" 2. Resolve the conflicts manually."));
1790
+ console.log(fmt.white(" 3. Stage your changes with: ") + fmt.green("git add ."));
1791
+ console.log("\n");
1792
+ await text({
1793
+ message: "Press Enter once you have resolved and staged all changes to continue..."
1794
+ });
1795
+ remainingConflicts = await git.getUnmergedFiles(tmpRepoCwd);
1796
+ if (remainingConflicts.length) {
1797
+ console.log(
1798
+ `
1799
+ ${fmt.red("Still detected conflicts in: " + remainingConflicts.join(", "))}`
1800
+ );
1801
+ console.log(fmt.yellow("Please make sure to 'git add' your resolved files."));
1802
+ }
1803
+ }
1804
+ }
1805
+ async commitStagedIfAny(opts, commit2) {
1806
+ if (await git.hasStagedChanges(opts.tmpRepoCwd)) {
1807
+ let commitMsg = `${opts.title}${opts.commits.length > 1 ? ` (cherry-pick: ${commit2.slice(0, 7)})` : ""}`;
1808
+ if (opts.description) {
1809
+ commitMsg += `
1810
+
1811
+ ${opts.description}`;
1812
+ }
1813
+ await git.commitAll(commitMsg, opts.tmpRepoCwd);
1814
+ this.logger.debug("apply.commit.success", { commit: commit2.slice(0, 7) });
1815
+ this.logger.info("Apply commit success");
1816
+ return;
1817
+ }
1818
+ this.logger.debug("apply.commit.skip_empty", {
1819
+ commit: commit2.slice(0, 7),
1820
+ message: "No changes left for this target after filtering."
1821
+ });
1822
+ this.logger.info(
1823
+ "Apply commit skip empty : No changes left for this target after filtering."
1824
+ );
1825
+ }
1826
+ };
1827
+
1828
+ // src/services/contribute/services/CommitSelectorService.ts
1829
+ var CommitSelectorService = class {
1830
+ constructor(logger) {
1831
+ this.logger = logger;
1832
+ }
1833
+ async selectCommitsInteractive(opts) {
1834
+ const selected = [];
1835
+ let page = 0;
1836
+ let hasMore = true;
1837
+ while (hasMore) {
1838
+ const commits = await git.listCommits(UI_PAGE_SIZE, page * UI_PAGE_SIZE, opts.cwd);
1839
+ if (!commits.length) {
1840
+ if (page === 0) {
1841
+ throw new Error("No commits found in app repository.");
1842
+ }
1843
+ break;
1844
+ }
1845
+ const value = await multiselect({
1846
+ message: `Select commits ${fmt.gray(`(page ${page + 1})`)}`,
1847
+ options: commits.map((c) => ({
1848
+ value: c.hash,
1849
+ label: `${c.hash.slice(0, 7)} ${c.subject}`
1850
+ })),
1851
+ required: false
1852
+ });
1853
+ for (const h of value) {
1854
+ if (!selected.includes(h)) {
1855
+ selected.push(h);
1856
+ }
1857
+ }
1858
+ hasMore = commits.length === UI_PAGE_SIZE;
1859
+ if (!hasMore) {
1860
+ break;
1861
+ }
1862
+ const loadMore = await confirm({
1863
+ message: "Load next page of commits?",
1864
+ initialValue: false
1865
+ });
1866
+ if (!loadMore) {
1867
+ break;
1868
+ }
1869
+ page += 1;
1870
+ }
1871
+ if (!selected.length) {
1872
+ throw new Error("No commits selected.");
1873
+ }
1874
+ this.logger.debug("commits.selected", { count: selected.length });
1875
+ this.logger.info(`${selected.length} Commits selected`);
1876
+ return selected;
1877
+ }
1878
+ };
1879
+
1880
+ // src/services/contribute/utils/discoverContributionTargets.ts
1881
+ var import_node_path13 = __toESM(require("path"));
1882
+ var import_fs_extra11 = __toESM(require("fs-extra"));
1883
+ var readBloxFileIfExists = (cwd) => {
1884
+ const p = import_node_path13.default.join(cwd, bloxFilePath);
1885
+ if (!import_fs_extra11.default.existsSync(p)) return;
1886
+ try {
1887
+ return import_fs_extra11.default.readJSONSync(p);
1888
+ } catch {
1889
+ return;
1890
+ }
1891
+ };
1892
+ var discoverContributionTargets = (cwd) => {
1893
+ const targets = [];
1894
+ const rootBlox = readBloxFileIfExists(cwd);
1895
+ const appTemplateName = rootBlox?.definition?.name;
1896
+ const appTemplateDef = rootBlox?.definition;
1897
+ if (rootBlox?.definition?.name) {
1898
+ targets.push({
1899
+ type: "template" /* TEMPLATE */,
1900
+ name: rootBlox.definition.name,
1901
+ templateName: rootBlox.definition.name,
1902
+ templateDef: appTemplateDef,
1903
+ label: `template/${rootBlox.definition.name}`
1904
+ });
1905
+ for (const base of rootBlox.definition.bases || []) {
1906
+ targets.push({
1907
+ type: "base" /* BASE */,
1908
+ name: base.name,
1909
+ templateDef: appTemplateDef,
1910
+ label: `base/${base.name}`,
1911
+ hint: base.version !== void 0 ? `version: ${JSON.stringify(base.version)}` : void 0
1912
+ });
1913
+ }
1914
+ }
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 });
1918
+ for (const entry of entries) {
1919
+ if (!entry.isDirectory()) continue;
1920
+ const blockName = entry.name;
1921
+ const blockBlox = readBloxFileIfExists(import_node_path13.default.join(blocksPath, blockName));
1922
+ if (!blockBlox?.definition?.name) continue;
1923
+ const def = blockBlox.definition;
1924
+ const templateName = def.templates?.[0]?.name || appTemplateName;
1925
+ targets.push({
1926
+ type: "block" /* BLOCK */,
1927
+ name: blockName,
1928
+ templateName,
1929
+ templateDef: appTemplateDef,
1930
+ label: `block/${blockName}`,
1931
+ hint: blockBlox.definition.version !== void 0 ? `v${blockBlox.definition.version}` : void 0
1932
+ });
1933
+ }
1934
+ }
1935
+ return targets;
1936
+ };
1937
+
1938
+ // src/services/contribute/utils/parseContributionTargetType.ts
1939
+ var parseContributionTargetType = (segment) => {
1940
+ if (segment === "template" /* TEMPLATE */ || segment === "base" /* BASE */ || segment === "block" /* BLOCK */) {
1941
+ return segment;
1942
+ }
1943
+ return;
1944
+ };
1945
+
1946
+ // src/services/contribute/services/ContributionTargetSelector.ts
1947
+ var ContributionTargetSelector = class {
1948
+ constructor(opts, logger) {
1949
+ this.opts = opts;
1950
+ this.logger = logger;
1951
+ }
1952
+ async selectTargetInteractive() {
1953
+ const all = discoverContributionTargets(this.opts.cwd);
1954
+ if (!all.length) {
1955
+ throw new Error(
1956
+ "No contribution targets found (missing root `.blox` and/or `blocks/*/.blox`)."
1957
+ );
1958
+ }
1959
+ let query = "";
1960
+ for (; ; ) {
1961
+ query = await text({
1962
+ message: `Search targets ${fmt.gray("(empty for all)")}`,
1963
+ placeholder: "auth, template, base, ...",
1964
+ defaultValue: query
1965
+ });
1966
+ const filtered = filterTargetsByQuery(all, query);
1967
+ if (!filtered.length) {
1968
+ this.logger.warn(`No matches for search: "${query}"`);
1969
+ const again = await confirm({ message: "Search again?" });
1970
+ if (again) continue;
1971
+ throw new Error("Aborted: no target selected.");
1972
+ }
1973
+ const pageSize = UI_PAGE_SIZE;
1974
+ let page = 0;
1975
+ const maxPage = Math.max(0, Math.ceil(filtered.length / pageSize) - 1);
1976
+ while (true) {
1977
+ const start = page * pageSize;
1978
+ const slice = filtered.slice(start, start + pageSize);
1979
+ const value = await select({
1980
+ message: `Select contribution target ${fmt.gray(
1981
+ `(page ${page + 1}/${maxPage + 1})`
1982
+ )}`,
1983
+ options: buildTargetPageSelectOptions(slice, page, maxPage)
1984
+ });
1985
+ if (value === TARGET_SELECT_PAGE.PREV) {
1986
+ page = Math.max(0, page - 1);
1987
+ continue;
1988
+ }
1989
+ if (value === TARGET_SELECT_PAGE.NEXT) {
1990
+ page = Math.min(maxPage, page + 1);
1991
+ continue;
1992
+ }
1993
+ if (value === TARGET_SELECT_PAGE.SEARCH_AGAIN) {
1994
+ break;
1995
+ }
1996
+ const [typeRaw, name, templateNameRaw] = value.split(":");
1997
+ const type = typeRaw ? parseContributionTargetType(typeRaw) : void 0;
1998
+ if (!type || !name) {
1999
+ throw new Error(`Invalid selection: ${value}`);
2000
+ }
2001
+ const found = all.find((t) => t.type === type && t.name === name);
2002
+ return {
2003
+ type,
2004
+ name,
2005
+ templateName: templateNameRaw || void 0,
2006
+ templateDef: found?.templateDef
2007
+ };
2008
+ }
2009
+ }
2010
+ }
2011
+ };
2012
+ function filterTargetsByQuery(all, query) {
2013
+ const q = query.trim().toLowerCase();
2014
+ if (!q) {
2015
+ return all;
2016
+ }
2017
+ return all.filter((t) => `${t.type}/${t.name}`.toLowerCase().includes(q));
2018
+ }
2019
+ function buildTargetPageSelectOptions(slice, page, maxPage) {
2020
+ return [
2021
+ ...slice.map((t) => ({
2022
+ value: `${t.type}:${t.name}:${t.templateName || ""}`,
2023
+ label: t.label,
2024
+ hint: t.hint
2025
+ })),
2026
+ ...page > 0 ? [{ value: TARGET_SELECT_PAGE.PREV, label: "\u25C0 prev page" }] : [],
2027
+ ...page < maxPage ? [{ value: TARGET_SELECT_PAGE.NEXT, label: "next page \u25B6" }] : [],
2028
+ { value: TARGET_SELECT_PAGE.SEARCH_AGAIN, label: "search again" }
2029
+ ];
2030
+ }
2031
+
2032
+ // src/services/contribute/services/LoggerService.ts
2033
+ var LoggerService = class {
2034
+ constructor() {
2035
+ }
2036
+ formatData(data) {
2037
+ if (data === void 0) return "";
2038
+ const pretty = JSON.stringify(data, null, 2);
2039
+ return `
2040
+ ${fmt.gray(
2041
+ pretty.split("\n").map((line) => ` ${line}`).join("\n")
2042
+ )}`;
2043
+ }
2044
+ debug(message, data) {
2045
+ if (!isDebugMode()) return;
2046
+ import_prompts2.log.info(`${fmt.magenta("DEBUG")} ${message}${this.formatData(data)}`);
2047
+ }
2048
+ info(message, data) {
2049
+ import_prompts2.log.info(`${fmt.cyan("INFO")} ${message}${this.formatData(data)}`);
2050
+ }
2051
+ warn(message, data) {
2052
+ import_prompts2.log.warn(`${fmt.yellow("WARN")} ${message}${this.formatData(data)}`);
2053
+ }
2054
+ error(message, data) {
2055
+ import_prompts2.log.error(`${fmt.red("ERROR")} ${fmt.bold(message)}${this.formatData(data)}`);
2056
+ }
2057
+ };
2058
+
2059
+ // src/services/contribute/services/PullRequestService.ts
2060
+ var PullRequestService = class {
2061
+ constructor(logger) {
2062
+ this.logger = logger;
2063
+ }
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. ");
2068
+ const line = "\u2501".repeat(60);
2069
+ import_prompts2.log.message(
2070
+ `
2071
+ ${fmt.cyan("\u25E2")}${line}${fmt.cyan("\u25E3")}
2072
+ ${header}
2073
+ ${subHeader}
2074
+
2075
+ ${fmt.bold("Target:")} ${fmt.green(opts.targetBranch)}
2076
+ ${fmt.bold("Source:")} ${fmt.yellow(opts.sourceBranch)}
2077
+ ${fmt.bold("URL:")} ${fmt.blue(opts.repoUrl)}
2078
+ ${fmt.bold("Title:")} ${opts.title}
2079
+ ` + (opts.description ? `
2080
+ ${fmt.gray("Description:")}
2081
+ ${opts.description}
2082
+ ` : "") + `${fmt.cyan("\u25E5")}${line}${fmt.cyan("\u25E4")}
2083
+ `
2084
+ );
2085
+ return { prUrl: void 0 };
2086
+ }
2087
+ };
2088
+
2089
+ // src/services/contribute/services/TmpRepoService.ts
2090
+ var import_node_os2 = require("os");
2091
+ var import_node_path14 = __toESM(require("path"));
2092
+ var import_fs_extra12 = __toESM(require("fs-extra"));
2093
+ var TmpRepoService = class {
2094
+ constructor(logger) {
2095
+ this.logger = logger;
2096
+ }
2097
+ async getTmpDir(target) {
2098
+ 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);
2100
+ }
2101
+ async prepare(opts) {
2102
+ const dir = await this.getTmpDir(opts.target);
2103
+ this.logger.debug(`${tempRepoName}.prepare`, {
2104
+ dir,
2105
+ repoUrl: opts.repoUrl,
2106
+ branch: opts.branch
2107
+ });
2108
+ this.logger.info("Prepare for tmp repo");
2109
+ if (await import_fs_extra12.default.pathExists(dir)) {
2110
+ this.logger.debug(`${tempRepoName}.remove`, { dir });
2111
+ await import_fs_extra12.default.remove(dir);
2112
+ }
2113
+ await import_fs_extra12.default.ensureDir(import_node_path14.default.dirname(dir));
2114
+ await git.clone(opts.repoUrl, dir, opts.branch);
2115
+ return dir;
2116
+ }
2117
+ };
2118
+
2119
+ // src/services/contribute/index.ts
2120
+ async function buildContributionWorkflow(opts) {
2121
+ const logger = new LoggerService();
2122
+ const targetSelector = new ContributionTargetSelector({ cwd: opts.cwd }, logger);
2123
+ const tmpRepo = new TmpRepoService(logger);
2124
+ const commitSelector = new CommitSelectorService(logger);
2125
+ const commitApplier = new CommitApplierService(logger);
2126
+ const pullRequest = new PullRequestService(logger);
2127
+ return new ContributionWorkflow(
2128
+ { cwd: opts.cwd, force: opts.force },
2129
+ logger,
2130
+ targetSelector,
2131
+ tmpRepo,
2132
+ commitSelector,
2133
+ commitApplier,
2134
+ pullRequest
2135
+ );
2136
+ }
2137
+
2138
+ // src/commands/contribute/index.ts
2139
+ 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(
2140
+ option("--type <type>", "target type").choices(Object.values(ContributionTargetType))
2141
+ ).option("--name <name>", "target name").action(async (flags) => {
2142
+ try {
2143
+ await migrateAll(true);
2144
+ await syncRegistries();
2145
+ const workflow = await buildContributionWorkflow({
2146
+ cwd: process.cwd(),
2147
+ force: !!flags.force
2148
+ });
2149
+ await workflow.runFromFlags(flags);
2150
+ } catch (e) {
2151
+ error(e);
2152
+ }
2153
+ });
2154
+
1038
2155
  // src/commands/detach/index.ts
1039
2156
  var detach = command("detach").description("Migrate blox schema").option("--basic", "run detach only").action(async ({ basic }) => {
1040
2157
  try {
@@ -1076,7 +2193,7 @@ var detach = command("detach").description("Migrate blox schema").option("--basi
1076
2193
  });
1077
2194
 
1078
2195
  // src/commands/init/index.ts
1079
- var import_fs_extra10 = __toESM(require("fs-extra"));
2196
+ var import_fs_extra13 = __toESM(require("fs-extra"));
1080
2197
  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 }) => {
1081
2198
  await syncRegistries();
1082
2199
  try {
@@ -1117,8 +2234,8 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
1117
2234
  task.stop(`App initialized in ${name}`);
1118
2235
  await runTask("Run init script", async () => runInitScript(name || ""));
1119
2236
  } catch (e) {
1120
- if (name && import_fs_extra10.default.existsSync(name)) {
1121
- await import_fs_extra10.default.remove(name);
2237
+ if (name && import_fs_extra13.default.existsSync(name)) {
2238
+ await import_fs_extra13.default.remove(name);
1122
2239
  }
1123
2240
  error(e);
1124
2241
  }
@@ -1138,15 +2255,22 @@ var migrateSchema = command("migrate").description("Migrate blox schema").action
1138
2255
  });
1139
2256
 
1140
2257
  // src/commands/update/index.ts
1141
- var import_prompts15 = require("@clack/prompts");
2258
+ var import_prompts20 = require("@clack/prompts");
1142
2259
 
1143
2260
  // src/commands/update/utils.ts
1144
- var import_node_path11 = __toESM(require("path"));
2261
+ var import_node_path16 = __toESM(require("path"));
1145
2262
 
1146
2263
  // src/services/updater.ts
1147
- var import_node_path10 = __toESM(require("path"));
1148
- var import_fs_extra11 = __toESM(require("fs-extra"));
1149
- async function updateFromRemote({ name, source = "", ignore: ignore2 = [], dir = "." }) {
2264
+ var import_node_path15 = __toESM(require("path"));
2265
+ var import_fs_extra14 = __toESM(require("fs-extra"));
2266
+ var import_klaw3 = __toESM(require("klaw"));
2267
+ async function updateFromRemote({
2268
+ name,
2269
+ source = "",
2270
+ ignore: ignore3 = [],
2271
+ dir = ".",
2272
+ hard = false
2273
+ }) {
1150
2274
  debug("Updating from remote");
1151
2275
  await git.updateRemote(name, source);
1152
2276
  const bloxFile = getBloxFile(dir);
@@ -1166,7 +2290,7 @@ async function updateFromRemote({ name, source = "", ignore: ignore2 = [], dir =
1166
2290
  debug("No new version");
1167
2291
  return;
1168
2292
  }
1169
- const remoteBloxFile = (await migrateOnRemote(name, toCommit)).output[".blox"];
2293
+ const remoteBloxFile = (await migrateOnRemote(name, toCommit)).output[bloxFilePath];
1170
2294
  for (const [baseName, baseInfo] of Object.entries(remoteBloxFile.checkpoints || {})) {
1171
2295
  const baseFrom = bloxFile.checkpoints[baseName]?.commit;
1172
2296
  if (!baseFrom) {
@@ -1182,45 +2306,136 @@ async function updateFromRemote({ name, source = "", ignore: ignore2 = [], dir =
1182
2306
  );
1183
2307
  }
1184
2308
  }
1185
- const patchFilePath = import_node_path10.default.join(dir, "diff.patch");
1186
2309
  const remoteIgnore = remoteBloxFile.definition?.ignore || [];
1187
- ignore2.push(...remoteIgnore, ".blox", "**/.blox");
1188
- await git.createPatch(fromCommit, toCommit, patchFilePath, ignore2);
1189
- const deletePatchFile = async () => {
1190
- if (!isDebugMode()) {
1191
- await import_fs_extra11.default.unlink(patchFilePath);
2310
+ 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");
2314
+ const gitIgnorePatterns = gitIgnoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
2315
+ ignore3.push(...gitIgnorePatterns);
2316
+ debug(`Added ${gitIgnorePatterns.length} patterns from .gitignore`);
2317
+ }
2318
+ debug("Preparing update worktrees...");
2319
+ const baseDir = await git.getRemoteWorktree(name, fromCommit);
2320
+ const remoteDir = await git.getRemoteWorktree(name, toCommit);
2321
+ let filesToProcess = [];
2322
+ if (hard) {
2323
+ const getAllFiles = async (d) => {
2324
+ const files = [];
2325
+ if (await import_fs_extra14.default.pathExists(d)) {
2326
+ for await (const file of (0, import_klaw3.default)(d)) {
2327
+ if (file.path.includes("/.git/") || file.path.endsWith("/.git") || file.path.includes("\\.git\\") || file.path.endsWith("\\.git"))
2328
+ continue;
2329
+ if (file.path.includes("/node_modules/") || file.path.includes("\\node_modules\\"))
2330
+ continue;
2331
+ if (file.stats.isFile()) {
2332
+ files.push(import_node_path15.default.relative(d, file.path));
2333
+ }
2334
+ }
2335
+ }
2336
+ return files;
2337
+ };
2338
+ const remoteFiles = await getAllFiles(remoteDir);
2339
+ const localFiles = await getAllFiles(dir);
2340
+ const allFiles = /* @__PURE__ */ new Set([...remoteFiles, ...localFiles]);
2341
+ filesToProcess = Array.from(allFiles);
2342
+ } else {
2343
+ filesToProcess = await git.getChangedFiles(fromCommit, toCommit, ignore3);
2344
+ }
2345
+ const ignoredMatcher = createGitignoreMatcher(ignore3);
2346
+ let hasConflicts2 = false;
2347
+ const conflictFiles = [];
2348
+ for (const file of filesToProcess) {
2349
+ if (file === ".git" || file.startsWith(".git/") || file.startsWith(".git\\")) continue;
2350
+ 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);
2358
+ const isBinary = isBinaryFile(ext);
2359
+ if (existsRemote) {
2360
+ await import_fs_extra14.default.ensureDir(import_node_path15.default.dirname(localPath));
1192
2361
  }
1193
- debug("make sure to delete the patch file after you're done with it.");
1194
- };
1195
- let hasMergeConflicts = false;
1196
- try {
1197
- await git.applyPatch(patchFilePath, dir);
1198
- } catch (e) {
1199
- const errorMessage = `${e}`;
1200
- if (errorMessage.includes("error:")) {
1201
- await deletePatchFile();
1202
- console.log(errorMessage.replace("error:", fmt.red("error:")));
1203
- if (errorMessage.includes("does not exist in index")) {
2362
+ if (hard) {
2363
+ if (existsRemote) {
2364
+ await import_fs_extra14.default.copy(remotePath, localPath, { overwrite: true });
2365
+ debug(`Hard update: Overwrote ${file}`);
2366
+ } else if (existsLocal) {
2367
+ await import_fs_extra14.default.remove(localPath);
2368
+ debug(`Hard update: Removed ${file}`);
2369
+ }
2370
+ continue;
2371
+ }
2372
+ if (!existsBase && existsRemote) {
2373
+ if (existsLocal) {
2374
+ if (isBinary) {
2375
+ debug(`Binary collision: ${file}, overwriting.`);
2376
+ await import_fs_extra14.default.copy(remotePath, localPath, { overwrite: true });
2377
+ logWarningSection(`Overwrote binary file collision: ${file}`);
2378
+ } else {
2379
+ const emptyBase = import_node_path15.default.join(baseDir, `${file}.empty`);
2380
+ await import_fs_extra14.default.ensureFile(emptyBase);
2381
+ const result = await git.mergeFile(localPath, emptyBase, remotePath);
2382
+ if (!result) {
2383
+ hasConflicts2 = true;
2384
+ conflictFiles.push(file);
2385
+ }
2386
+ await import_fs_extra14.default.remove(emptyBase);
2387
+ }
2388
+ } else {
2389
+ await import_fs_extra14.default.copy(remotePath, localPath);
2390
+ }
2391
+ continue;
2392
+ }
2393
+ if (existsBase && !existsRemote) {
2394
+ if (existsLocal) {
2395
+ const localBuffer = await import_fs_extra14.default.readFile(localPath);
2396
+ const baseBuffer = await import_fs_extra14.default.readFile(basePath);
2397
+ if (localBuffer.equals(baseBuffer)) {
2398
+ await import_fs_extra14.default.remove(localPath);
2399
+ } else {
2400
+ logWarningSection(
2401
+ `File ${file} was deleted in remote but modified locally. Kept local version.`
2402
+ );
2403
+ }
2404
+ }
2405
+ continue;
2406
+ }
2407
+ if (existsBase && existsRemote) {
2408
+ if (!existsLocal) {
2409
+ await import_fs_extra14.default.copy(remotePath, localPath);
1204
2410
  logWarningSection(
1205
- "Some files has changes in remote but were deleted, \n if you want to skip them pass this arg to update command:",
1206
- fmt.cyan(
1207
- `--ignore ${[
1208
- ...errorMessage.matchAll(/error: (.*): does not exist in index/g)
1209
- ].map((m) => `"${name}:${m[1]}"`).join(",")}`
1210
- )
2411
+ `File restored: ${file}`,
2412
+ `This file was deleted locally but updated in the remote block.
2413
+ It has been recreated to apply upstream changes.`
1211
2414
  );
2415
+ continue;
2416
+ }
2417
+ if (isBinary) {
2418
+ await import_fs_extra14.default.copy(remotePath, localPath, { overwrite: true });
2419
+ logWarningSection(`Updated binary file: ${file} (overwritten)`);
2420
+ } else {
2421
+ const result = await git.mergeFile(localPath, basePath, remotePath);
2422
+ if (!result) {
2423
+ hasConflicts2 = true;
2424
+ conflictFiles.push(file);
2425
+ }
1212
2426
  }
1213
- throw new Error("Failed to apply changes.");
1214
2427
  }
1215
- hasMergeConflicts = errorMessage.includes("with conflicts");
1216
2428
  }
1217
- if (hasMergeConflicts) {
2429
+ if (hasConflicts2) {
2430
+ logWarningSection(
2431
+ "Conflicts detected in the following files:",
2432
+ conflictFiles.map((f) => fmt.red(f)).join("\n")
2433
+ );
1218
2434
  await select({
1219
- message: "Please resolve conflicts press enter",
1220
- options: [{ value: true, label: "continue" }]
2435
+ message: "Please resolve conflicts manually (look for <<<<<<< HEAD) and press enter to continue",
2436
+ options: [{ value: true, label: "Resolved" }]
1221
2437
  });
1222
2438
  }
1223
- await deletePatchFile();
1224
2439
  bloxFile.checkpoints[name] = { commit: toCommit };
1225
2440
  if (bloxFile.definition.name === name) {
1226
2441
  bloxFile.definition = remoteBloxFile.definition;
@@ -1237,7 +2452,8 @@ async function updateApp({
1237
2452
  templates,
1238
2453
  usedBlocks,
1239
2454
  availableBlocks,
1240
- ignore: ignore2
2455
+ ignore: ignore3,
2456
+ hard = false
1241
2457
  }) {
1242
2458
  await runTask({ start: "Update App", end: "Updated App" }, async () => {
1243
2459
  const template = templates[templateDef.name];
@@ -1248,7 +2464,8 @@ async function updateApp({
1248
2464
  const toAppCommit = await updateFromRemote({
1249
2465
  name: templateDef.name,
1250
2466
  source: template.source,
1251
- ignore: ignore2
2467
+ ignore: ignore3,
2468
+ hard
1252
2469
  });
1253
2470
  if (!toAppCommit) return;
1254
2471
  if (!templateDef.bases?.length) return;
@@ -1256,7 +2473,7 @@ async function updateApp({
1256
2473
  const blockRegistryData = availableBlocks[block.name];
1257
2474
  if (!blockRegistryData) return;
1258
2475
  await git.updateRemote(block.name, blockRegistryData.source);
1259
- const blockPath = import_node_path11.default.join(blocksDir, block.name);
2476
+ const blockPath = import_node_path16.default.join(blocksDir, block.name);
1260
2477
  const currentBloxFile = getBloxFile(blockPath);
1261
2478
  const remoteBloxFile = (await migrateOnRemote(block.name, toAppCommit, blockPath)).output[".blox"];
1262
2479
  const blockFromCommit = currentBloxFile.checkpoints?.[block.name]?.commit;
@@ -1272,7 +2489,7 @@ async function updateApp({
1272
2489
  }
1273
2490
  });
1274
2491
  }
1275
- async function updateAppBases(templateDef, templates, ignore2) {
2492
+ async function updateAppBases(templateDef, templates, ignore3, hard = false) {
1276
2493
  for (const base of templateDef.bases || []) {
1277
2494
  await runTask(
1278
2495
  { start: `Update App base: ${base.name}`, end: `Updated App base: ${base.name}` },
@@ -1282,14 +2499,14 @@ async function updateAppBases(templateDef, templates, ignore2) {
1282
2499
  error("Selected template not available in registries");
1283
2500
  return;
1284
2501
  }
1285
- await updateFromRemote({ name: base.name, source: template.source, ignore: ignore2 });
2502
+ await updateFromRemote({ name: base.name, source: template.source, ignore: ignore3, hard });
1286
2503
  }
1287
2504
  );
1288
2505
  }
1289
2506
  }
1290
- async function updateBlock(block, blocks, ignore2) {
2507
+ async function updateBlock(block, blocks, ignore3, hard = false) {
1291
2508
  const blockRegistryData = blocks[block];
1292
- const blockPath = import_node_path11.default.join(blocksDir, block);
2509
+ const blockPath = import_node_path16.default.join(blocksDir, block);
1293
2510
  await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
1294
2511
  if (!blockRegistryData) {
1295
2512
  error(`Selected block: ${block} not available in registries`, false);
@@ -1299,7 +2516,8 @@ async function updateBlock(block, blocks, ignore2) {
1299
2516
  name: block,
1300
2517
  source: blockRegistryData.source,
1301
2518
  dir: blockPath,
1302
- ignore: ignore2
2519
+ ignore: ignore3,
2520
+ hard
1303
2521
  });
1304
2522
  });
1305
2523
  }
@@ -1341,9 +2559,9 @@ ${fmt.gray("-".repeat(82))}
1341
2559
  // src/commands/update/index.ts
1342
2560
  var update2 = command("update").description("Update app/block").alias("u").addOption(
1343
2561
  option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
1344
- ).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").action(async (args) => {
2562
+ ).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) => {
1345
2563
  if (await git.hasUncommittedChanges()) {
1346
- import_prompts15.log.warn(fmt.yellow("Make sure to commit any changes first"));
2564
+ import_prompts20.log.warn(fmt.yellow("Make sure to commit any changes first"));
1347
2565
  return;
1348
2566
  }
1349
2567
  await migrateAll(true);
@@ -1354,8 +2572,8 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
1354
2572
  const templates = await getAvailableTemplates();
1355
2573
  const usedBlocks = getUsedBlocksDef();
1356
2574
  const ignoresByName = {};
1357
- for (const ignore2 of args.ignore || []) {
1358
- const [repo, pattern] = ignore2.split(":");
2575
+ for (const ignore3 of args.ignore || []) {
2576
+ const [repo, pattern] = ignore3.split(":");
1359
2577
  if (!repo || !pattern) {
1360
2578
  error("Invalid ignore pattern");
1361
2579
  return;
@@ -1372,15 +2590,26 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
1372
2590
  templates,
1373
2591
  usedBlocks,
1374
2592
  availableBlocks,
1375
- ignore: ignoresByName[templateDef.name]
2593
+ ignore: ignoresByName[templateDef.name],
2594
+ hard: args.hard
1376
2595
  });
1377
2596
  }
1378
2597
  if (["bases", "all"].includes(args.scope)) {
1379
- await updateAppBases(templateDef, templates, ignoresByName[templateDef.name]);
2598
+ await updateAppBases(
2599
+ templateDef,
2600
+ templates,
2601
+ ignoresByName[templateDef.name],
2602
+ args.hard
2603
+ );
1380
2604
  }
1381
2605
  if (args.scope === "all") {
1382
2606
  for (const block of usedBlocks) {
1383
- await updateBlock(block.name, availableBlocks, ignoresByName[block.name]);
2607
+ await updateBlock(
2608
+ block.name,
2609
+ availableBlocks,
2610
+ ignoresByName[block.name],
2611
+ args.hard
2612
+ );
1384
2613
  }
1385
2614
  }
1386
2615
  if (args.scope === "block") {
@@ -1398,17 +2627,24 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
1398
2627
  error("Selected block not used in app");
1399
2628
  return;
1400
2629
  }
1401
- await updateBlock(blockDef.name, availableBlocks, ignoresByName[blockDef.name]);
2630
+ await updateBlock(
2631
+ blockDef.name,
2632
+ availableBlocks,
2633
+ ignoresByName[blockDef.name],
2634
+ args.hard
2635
+ );
1402
2636
  }
1403
2637
  await checkVersionsCompatibility();
1404
2638
  const endCheckpoints = await getCurrentCheckpoints();
1405
2639
  await printChangeLog(startCheckpoints, endCheckpoints);
1406
2640
  } catch (e) {
1407
2641
  if (!isDebugMode()) {
1408
- import_prompts15.log.warn("Error happened, Will rollback changes");
2642
+ import_prompts20.log.warn("Error happened, Will rollback changes");
1409
2643
  await git.rollback();
1410
2644
  }
1411
2645
  error(e);
2646
+ } finally {
2647
+ await git.cleanUpWorktrees();
1412
2648
  }
1413
2649
  });
1414
2650
 
@@ -1423,7 +2659,7 @@ var upgrade = command("upgrade").description("Upgrade blox cli to latest version
1423
2659
  });
1424
2660
 
1425
2661
  // src/commands/index.ts
1426
- var commands = [init2, add2, update2, conf, upgrade, migrateSchema, detach];
2662
+ var commands = [init2, add2, update2, conf, upgrade, migrateSchema, detach, contribute];
1427
2663
 
1428
2664
  // bin/run.ts
1429
2665
  async function main() {