@naseej/blox 0.1.29 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/run.js +417 -285
  2. package/package.json +2 -1
  3. package/readme.md +1 -19
package/dist/run.js CHANGED
@@ -31,47 +31,18 @@ var option = (flags, description) => {
31
31
  };
32
32
 
33
33
  // package.json
34
- var version = "0.1.29";
34
+ var version = "0.2.0";
35
35
 
36
36
  // src/commands/add/index.ts
37
- var import_fs_extra7 = __toESM(require("fs-extra"));
38
-
39
- // src/commands/update/utils.ts
40
- var import_node_path7 = __toESM(require("path"));
41
-
42
- // src/config/index.ts
43
- var defaultConfig = {
44
- syncFrequency: "1d",
45
- registries: ["https://tfs.aas.com.sa/Medad/BLOX/_git/default-registry"]
46
- };
47
- var basedOnFile = ".blox";
48
- var blocksDir = "blocks";
49
-
50
- // src/services/registry.ts
51
- var import_node_path4 = __toESM(require("path"));
52
- var import_dayjs = __toESM(require("dayjs"));
53
- var import_fs_extra4 = __toESM(require("fs-extra"));
54
- var import_klaw = __toESM(require("klaw"));
55
- var import_merge = __toESM(require("lodash/merge"));
56
- var import_ms = __toESM(require("ms"));
37
+ var import_fs_extra5 = __toESM(require("fs-extra"));
57
38
 
58
39
  // src/config/runtime.ts
59
40
  var isDebugMode = () => !!import_extra_typings2.program.opts()?.debug;
60
41
  var isMinimalMode = () => !!import_extra_typings2.program.opts()?.minimal;
61
42
 
62
- // src/services/fs.ts
63
- var import_fs_extra = __toESM(require("fs-extra"));
64
- var readJsonFile = (path8, defaultValue = {}) => {
65
- try {
66
- return import_fs_extra.default.readJSONSync(path8);
67
- } catch {
68
- return defaultValue;
69
- }
70
- };
71
-
72
43
  // src/services/git.ts
73
44
  var import_node_path2 = __toESM(require("path"));
74
- var import_fs_extra2 = __toESM(require("fs-extra"));
45
+ var import_fs_extra = __toESM(require("fs-extra"));
75
46
 
76
47
  // src/services/path.ts
77
48
  var import_node_path = __toESM(require("path"));
@@ -109,6 +80,9 @@ var logWarningSection = (title, content) => {
109
80
  content && console2.log(content);
110
81
  console2.log(line + "\n");
111
82
  };
83
+ var normalizeLogMessage = (content) => {
84
+ return content.split("\n").map((l) => l.trim()).filter(Boolean).join("\n");
85
+ };
112
86
 
113
87
  // src/services/shell.ts
114
88
  var $ = async (bin, options = [], { cwd, onStdout } = {}) => {
@@ -156,6 +130,9 @@ var clone = (repoUrl, options, shellOptions = {}) => {
156
130
  ...shellOptions
157
131
  });
158
132
  };
133
+ var resetToCommit = async (commit, cwd = ".") => {
134
+ await $("git", ["reset --hard", `${commit}`], { cwd });
135
+ };
159
136
  var updateRemote = async (name, source, shellOptions = {}) => {
160
137
  debug("updateRemote");
161
138
  debug({ name, source });
@@ -172,10 +149,10 @@ var updateRemote = async (name, source, shellOptions = {}) => {
172
149
  });
173
150
  await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
174
151
  };
175
- var readJsonFromRemote = async (remote, file) => {
152
+ var readJsonFromCommit = async (commit, file) => {
176
153
  try {
177
154
  let content = "";
178
- await $("git", ["show", `${remote}/main:${file}`], {
155
+ await $("git", ["show", `${commit}:${file}`], {
179
156
  onStdout: (text2) => {
180
157
  content = text2;
181
158
  }
@@ -185,6 +162,9 @@ var readJsonFromRemote = async (remote, file) => {
185
162
  return {};
186
163
  }
187
164
  };
165
+ var readJsonFromRemote = async (remote, file, commit) => {
166
+ return readJsonFromCommit(commit || `${remote}/main`, file);
167
+ };
188
168
  var isCommitOlder = async (a, b) => {
189
169
  try {
190
170
  await $("git", ["merge-base --is-ancestor", a, b]);
@@ -220,6 +200,7 @@ var createPatch = async (fromCommit, toCommit, outputPath, ignore = []) => {
220
200
  toCommit,
221
201
  ">",
222
202
  outputPath,
203
+ "--",
223
204
  ...ignore.map((file) => `':!${file}'`)
224
205
  ]);
225
206
  };
@@ -243,7 +224,7 @@ var applyPatch = (patch, cwd = ".") => {
243
224
  };
244
225
  var unInit = (cwd) => {
245
226
  debug("UnInit");
246
- return import_fs_extra2.default.remove(import_node_path2.default.join(cwd, ".git"));
227
+ return import_fs_extra.default.remove(import_node_path2.default.join(cwd, ".git"));
247
228
  };
248
229
  var init = async (cwd) => {
249
230
  debug("Init");
@@ -252,6 +233,15 @@ var init = async (cwd) => {
252
233
  await $("git", ["commit", "-m", "init"], { cwd });
253
234
  await $("git", ["branch", "-m", "main"], { cwd });
254
235
  };
236
+ var add = async (toAdd) => {
237
+ debug(`Git Add: ${toAdd}`);
238
+ await $("git", ["add", toAdd]);
239
+ };
240
+ var rollback = async () => {
241
+ debug("Rollback");
242
+ await $("git", ["add", "."]);
243
+ await $("git", ["reset", "--hard"]);
244
+ };
255
245
  var git = {
256
246
  clone,
257
247
  update,
@@ -264,9 +254,18 @@ var git = {
264
254
  applyPatch,
265
255
  updateRemote,
266
256
  readJsonFromRemote,
267
- isCommitOlder
257
+ isCommitOlder,
258
+ rollback,
259
+ add,
260
+ resetToCommit
268
261
  };
269
262
 
263
+ // src/services/registry.ts
264
+ var import_node_path4 = __toESM(require("path"));
265
+ var import_fs_extra3 = __toESM(require("fs-extra"));
266
+ var import_klaw = __toESM(require("klaw"));
267
+ var import_merge = __toESM(require("lodash/merge"));
268
+
270
269
  // src/shared/spinner.ts
271
270
  var import_prompts3 = require("@clack/prompts");
272
271
  var spinner = () => {
@@ -276,8 +275,8 @@ var spinner = () => {
276
275
  start: (msg) => {
277
276
  minimal ? import_prompts2.log.step(`${msg || "start"}...`) : s.start(msg);
278
277
  },
279
- stop: (msg, code) => {
280
- minimal ? code ? import_prompts2.log.error(msg || "error") : import_prompts2.log.step(msg || "success") : s.stop(msg, code);
278
+ stop: (msg = "error", code) => {
279
+ minimal ? code ? import_prompts2.log.error(msg) : import_prompts2.log.step(msg || "success") : s.stop(code ? fmt.red(msg) : fmt.green(msg), code);
281
280
  },
282
281
  message: (msg) => {
283
282
  minimal ? import_prompts2.log.message(msg) : s.message(msg);
@@ -293,7 +292,7 @@ async function runTask(message, task) {
293
292
  await (typeof task === "function" ? task() : task);
294
293
  taskSpinner.stop(endMessage);
295
294
  } catch (e) {
296
- taskSpinner.stop(`Failed: ${endMessage}`, 1);
295
+ taskSpinner.stop(`Failed: ${startMessage}`, 1);
297
296
  throw e;
298
297
  }
299
298
  }
@@ -301,62 +300,54 @@ async function runTask(message, task) {
301
300
  // src/services/config.ts
302
301
  var import_node_path3 = __toESM(require("path"));
303
302
  var import_env_paths = __toESM(require("env-paths"));
304
- var import_fs_extra3 = __toESM(require("fs-extra"));
303
+ var import_fs_extra2 = __toESM(require("fs-extra"));
304
+
305
+ // src/config/index.ts
306
+ var defaultConfig = {
307
+ registries: ["https://tfs.aas.com.sa/Medad/BLOX/_git/default-registry"]
308
+ };
309
+ var basedOnFile = ".blox";
310
+ var blocksDir = "blocks";
311
+
312
+ // src/services/config.ts
305
313
  var appPaths = (0, import_env_paths.default)("blox", { suffix: "" });
306
314
  var configFilePath = import_node_path3.default.join(appPaths.config, "config.json");
307
315
  var getLocalConfig = () => {
308
316
  try {
309
- return import_fs_extra3.default.readJSONSync(configFilePath);
317
+ return import_fs_extra2.default.readJSONSync(configFilePath);
310
318
  } catch {
311
319
  return defaultConfig;
312
320
  }
313
321
  };
314
322
  var updateLocalConfig = (config) => {
315
323
  debug("Update local config");
316
- import_fs_extra3.default.ensureFileSync(configFilePath);
324
+ import_fs_extra2.default.ensureFileSync(configFilePath);
317
325
  const current = getLocalConfig();
318
- import_fs_extra3.default.writeJsonSync(configFilePath, { ...current, ...config });
326
+ import_fs_extra2.default.writeJsonSync(configFilePath, { ...current, ...config });
319
327
  };
320
328
 
321
329
  // src/services/registry.ts
322
330
  var registriesDataPath = import_node_path4.default.join(appPaths.data, "registries");
323
- var registriesStatPath = import_node_path4.default.join(registriesDataPath, "stats.json");
324
- var syncRegistries = async (force, logProgress = true) => {
331
+ var syncRegistries = async () => {
325
332
  debug("Sync registries");
326
- logProgress = logProgress || isDebugMode();
327
- import_fs_extra4.default.ensureDirSync(registriesDataPath);
333
+ import_fs_extra3.default.ensureDirSync(registriesDataPath);
328
334
  const config = getLocalConfig();
329
- const registriesStat = readJsonFile(registriesStatPath);
330
- return Promise.all(
331
- config.registries.map(async (registry) => {
332
- const task = spinner();
333
- try {
335
+ return await runTask("Update registries", async () => {
336
+ await Promise.all(
337
+ config.registries.map(async (registry) => {
338
+ debug(`update registry: ${registry}`);
334
339
  const repoName = registry.split("/").pop() || "";
335
- logProgress && task.start(`Updating registry: ${registry}`);
336
340
  const repoDir = import_node_path4.default.join(registriesDataPath, repoName);
337
- if (!registriesStat[repoName]) {
338
- registriesStat[repoName] = {};
339
- }
340
- const now = (0, import_dayjs.default)();
341
- const lastUpdated = registriesStat[repoName].lastUpdated;
342
- const shouldUpdate = !lastUpdated || now.isAfter((0, import_dayjs.default)(lastUpdated).add((0, import_ms.default)(config.syncFrequency)));
343
- if (!import_fs_extra4.default.existsSync(repoDir)) {
341
+ if (!import_fs_extra3.default.existsSync(repoDir)) {
344
342
  await git.clone(registry, "--depth 1", { cwd: registriesDataPath });
345
- registriesStat[repoName].lastUpdated = now.format();
346
- } else if (force || shouldUpdate) {
343
+ } else if (import_fs_extra3.default.existsSync(import_node_path4.default.join(repoDir, ".git"))) {
347
344
  await git.update({ cwd: repoDir });
348
- registriesStat[repoName].lastUpdated = now.format();
349
345
  } else {
350
- logProgress && import_prompts2.log.step(`Have recent version`);
346
+ debug(`local registry`);
351
347
  }
352
- import_fs_extra4.default.writeJSONSync(registriesStatPath, registriesStat);
353
- logProgress && task.stop(`Updated registry: ${registry}`);
354
- } catch (e) {
355
- task.stop(`Updating registry: ${registry} failed`, 1);
356
- throw e;
357
- }
358
- })
359
- );
348
+ })
349
+ );
350
+ });
360
351
  };
361
352
  var getAvailableTemplates = async () => {
362
353
  debug("Get available templates");
@@ -365,25 +356,25 @@ var getAvailableTemplates = async () => {
365
356
  filter: (item) => !item.includes(".git")
366
357
  })) {
367
358
  if (file.path.endsWith(".json")) {
368
- const data = import_fs_extra4.default.readJSONSync(file.path);
369
- Object.keys(data.templates || {}).forEach((templ) => {
370
- const source = data.templates[templ]?.source || `${data.baseUrl}/template-${templ}`;
371
- const template = { ...data.templates[templ], source };
372
- if (templates[templ]?.source === source) {
373
- templates[templ] = (0, import_merge.default)(templates[templ], template);
374
- } else {
375
- templates[templ] = template;
359
+ const data = import_fs_extra3.default.readJSONSync(file.path);
360
+ Object.entries(data.templates || {}).forEach(([templateName, template]) => {
361
+ if (!template.source) {
362
+ template.source = `${data.baseUrl}/template-${templateName}`;
376
363
  }
377
- Object.keys(templates[templ].blocks || {}).forEach((blockName) => {
378
- const block = templates[templ]?.blocks?.[blockName];
379
- if (block && !block.source) {
380
- block.source = `${data.baseUrl}/block-${templ}-${blockName}`;
364
+ Object.entries(template.blocks || {}).forEach(([blockName, block]) => {
365
+ if (!block.source) {
366
+ block.source = `${data.baseUrl}/block-${templateName}-${blockName}`;
381
367
  }
382
368
  });
369
+ if (templates[templateName]) {
370
+ templates[templateName] = (0, import_merge.default)(templates[templateName], template);
371
+ } else {
372
+ templates[templateName] = template;
373
+ }
383
374
  });
384
375
  }
385
376
  }
386
- debug(templates);
377
+ debug({ templates });
387
378
  return templates;
388
379
  };
389
380
  var getAvailableBlocks = async (templateInfo) => {
@@ -395,44 +386,59 @@ var getAvailableBlocks = async (templateInfo) => {
395
386
  const baseTemplate = templates[base.name];
396
387
  Object.entries(baseTemplate?.blocks || {}).forEach(([k, v]) => blocks[k] = v);
397
388
  }
398
- debug(blocks);
389
+ debug({ blocks });
399
390
  return blocks;
400
391
  };
392
+ var getAvailableVersions = async (id) => {
393
+ const registries = import_fs_extra3.default.readdirSync(registriesDataPath);
394
+ for (const registry of registries) {
395
+ const versionsFile = import_node_path4.default.join(registriesDataPath, registry, "versions", `${id}.json`);
396
+ if (import_fs_extra3.default.existsSync(versionsFile)) {
397
+ return import_fs_extra3.default.readJSONSync(versionsFile);
398
+ }
399
+ }
400
+ };
401
401
 
402
402
  // src/services/template.ts
403
403
  var import_node_path5 = __toESM(require("path"));
404
404
  var import_ejs = __toESM(require("ejs"));
405
- var import_fs_extra5 = __toESM(require("fs-extra"));
405
+ var import_fs_extra4 = __toESM(require("fs-extra"));
406
406
  var import_klaw2 = __toESM(require("klaw"));
407
407
  async function replacePlaceholders(dir, context) {
408
408
  debug("Replace placeholders");
409
409
  for await (const file of (0, import_klaw2.default)(dir)) {
410
410
  if (file.stats.isFile()) {
411
- const template = import_fs_extra5.default.readFileSync(file.path, "utf-8");
411
+ const template = import_fs_extra4.default.readFileSync(file.path, "utf-8");
412
412
  const rendered = import_ejs.default.render(template, context);
413
- import_fs_extra5.default.writeFileSync(file.path, rendered, "utf-8");
413
+ import_fs_extra4.default.writeFileSync(file.path, rendered, "utf-8");
414
414
  }
415
415
  }
416
416
  }
417
417
  function getPackage(cwd) {
418
- return import_fs_extra5.default.readJSONSync(import_node_path5.default.join(cwd, "package.json"));
418
+ return import_fs_extra4.default.readJSONSync(import_node_path5.default.join(cwd, "package.json"));
419
+ }
420
+ function getTemplateDef(cwd = ".") {
421
+ debug("Get template def");
422
+ const def = getPackage(cwd).blox;
423
+ debug(def);
424
+ return def;
419
425
  }
420
- function getTemplateInfo(cwd = ".") {
421
- debug("Get template info");
422
- const templateInfo = getPackage(cwd).blox;
423
- debug(templateInfo);
424
- return templateInfo;
426
+ function getBlockDef(cwd = ".") {
427
+ debug("Get block def");
428
+ const def = getPackage(cwd).blox;
429
+ def && debug(def);
430
+ return def;
425
431
  }
426
432
  function getBasedOnInfo(cwd = ".") {
427
433
  try {
428
- return import_fs_extra5.default.readJSONSync(import_node_path5.default.join(cwd, basedOnFile));
434
+ return import_fs_extra4.default.readJSONSync(import_node_path5.default.join(cwd, basedOnFile));
429
435
  } catch {
430
436
  return {};
431
437
  }
432
438
  }
433
439
  function saveBasedOnInfo(info, cwd = ".") {
434
440
  debug("Save info");
435
- import_fs_extra5.default.writeFileSync(import_node_path5.default.join(cwd, basedOnFile), JSON.stringify(info, null, 2));
441
+ import_fs_extra4.default.writeFileSync(import_node_path5.default.join(cwd, basedOnFile), JSON.stringify(info, null, 2));
436
442
  }
437
443
  function updateBasedOnInfo(updates, cwd = ".") {
438
444
  const info = getBasedOnInfo(cwd);
@@ -441,14 +447,14 @@ function updateBasedOnInfo(updates, cwd = ".") {
441
447
  function getUsedBlocks() {
442
448
  debug("Get used blocks");
443
449
  const blocks = [];
444
- if (import_fs_extra5.default.existsSync(blocksDir)) {
445
- import_fs_extra5.default.readdirSync(blocksDir, { withFileTypes: true }).forEach((file) => {
450
+ if (import_fs_extra4.default.existsSync(blocksDir)) {
451
+ import_fs_extra4.default.readdirSync(blocksDir, { withFileTypes: true }).forEach((file) => {
446
452
  if (!file.isDirectory()) {
447
453
  return;
448
454
  }
449
- const templateInfo = getTemplateInfo(import_node_path5.default.join(blocksDir, file.name));
450
- if (templateInfo) {
451
- blocks.push(templateInfo);
455
+ const blockDef = getBlockDef(import_node_path5.default.join(blocksDir, file.name));
456
+ if (blockDef) {
457
+ blocks.push(blockDef);
452
458
  }
453
459
  });
454
460
  }
@@ -456,10 +462,92 @@ function getUsedBlocks() {
456
462
  return blocks;
457
463
  }
458
464
 
459
- // src/services/updater.ts
460
- var import_node_path6 = __toESM(require("path"));
461
- var import_fs_extra6 = __toESM(require("fs-extra"));
462
- var import_merge2 = __toESM(require("lodash/merge"));
465
+ // src/services/versions/checkCompatibility.ts
466
+ function processDependencyVersion(dep) {
467
+ if (!dep.version) dep.version = 0;
468
+ return dep;
469
+ }
470
+ function processTemplate(def) {
471
+ if (!def.version) def.version = 0;
472
+ Object.values(def.bases || {}).forEach(processDependencyVersion);
473
+ return def;
474
+ }
475
+ function processBases(info) {
476
+ if (!info || !info.bases) return {};
477
+ Object.values(info.bases).forEach((base) => {
478
+ if (!base.version) base.version = 0;
479
+ });
480
+ return info.bases;
481
+ }
482
+ function processBlocks(defs) {
483
+ defs.forEach((def) => {
484
+ if (!def.version) def.version = 0;
485
+ def.dependencies?.forEach(processDependencyVersion);
486
+ def.templates?.forEach(processDependencyVersion);
487
+ });
488
+ return defs;
489
+ }
490
+ function ensureVersionOverlap(version2 = 0, range = 0, mismatchMessage) {
491
+ if (typeof range === "number") {
492
+ range = [range, range];
493
+ }
494
+ const match = version2 >= range[0] && version2 <= range[1];
495
+ if (!match) {
496
+ const requiredVersionText = range[0] === range[1] ? `${range[0]}` : `min: ${range[0]}, max: ${range[1]}`;
497
+ throw new Error(
498
+ normalizeLogMessage(`
499
+ ${mismatchMessage}
500
+ current version: ${version2}
501
+ required version: ${requiredVersionText}
502
+ `)
503
+ );
504
+ }
505
+ }
506
+ async function _checkVersionsCompatibility(template, usedBlocks, basesVersion) {
507
+ for (const templateBaseDep of template.bases || []) {
508
+ const currentVersion = basesVersion[templateBaseDep.name]?.version;
509
+ ensureVersionOverlap(
510
+ currentVersion,
511
+ templateBaseDep.version,
512
+ `Template "${template.name}" version: ${template.version} is not compatible with base "${templateBaseDep.name}"`
513
+ );
514
+ }
515
+ for (const block of usedBlocks) {
516
+ for (const blockTemplateDep of block.templates || []) {
517
+ const currentTemplate = basesVersion[blockTemplateDep.name];
518
+ if (!currentTemplate) {
519
+ throw new Error(
520
+ `Block "${block.name}" version: ${block.version} depends on missing template "${blockTemplateDep.name}" `
521
+ );
522
+ }
523
+ ensureVersionOverlap(
524
+ currentTemplate?.version,
525
+ blockTemplateDep.version,
526
+ `Block "${block.name}" version: ${block.version} is not compatible with template "${blockTemplateDep.name}" `
527
+ );
528
+ }
529
+ for (const blockDep of block.dependencies || []) {
530
+ const blockDepDef = usedBlocks.find((b) => b.name === blockDep.name);
531
+ if (!blockDepDef) {
532
+ throw new Error(
533
+ `Block "${block.name}" version: ${block.version} depends on missing block "${blockDep.name}" `
534
+ );
535
+ }
536
+ ensureVersionOverlap(
537
+ blockDepDef?.version,
538
+ blockDep.version,
539
+ `Block "${block.name}" version: ${block.version} is not compatible with block "${blockDep.name}" `
540
+ );
541
+ }
542
+ }
543
+ }
544
+ async function checkVersionsCompatibility() {
545
+ const template = processTemplate(getTemplateDef());
546
+ const usedBlocks = processBlocks(getUsedBlocks());
547
+ const basesVersion = processBases(getBasedOnInfo());
548
+ basesVersion[template.name] = { version: template.version, commit: "" };
549
+ await _checkVersionsCompatibility(template, usedBlocks, basesVersion);
550
+ }
463
551
 
464
552
  // src/shared/prompts/index.ts
465
553
  var import_prompts4 = require("@clack/prompts");
@@ -471,7 +559,9 @@ var checkIfCanceled = (value) => {
471
559
  };
472
560
  var error = (error2, exit = true) => {
473
561
  import_prompts4.log.error(
474
- typeof error2 === "string" ? error2 : error2?.shortMessage || error2?.message || JSON.stringify(error2)
562
+ fmt.red(
563
+ typeof error2 === "string" ? error2 : error2?.shortMessage || error2?.message || JSON.stringify(error2)
564
+ )
475
565
  );
476
566
  exit && process.exit(-1);
477
567
  };
@@ -493,139 +583,42 @@ var textList = async (opts) => {
493
583
  return value.split(",");
494
584
  };
495
585
 
496
- // src/services/updater.ts
497
- async function updateFromRemote(name, source = "", ignore = [], destPath = ".") {
498
- debug("Updating from remote");
499
- const basedOnInfo = getBasedOnInfo(destPath);
500
- const remoteBloxFile = await git.readJsonFromRemote(name, ".blox");
501
- for (const [baseName, baseInfo] of Object.entries(remoteBloxFile.bases || {})) {
502
- const baseFrom = basedOnInfo.bases?.[baseName]?.commit;
503
- const updateBase = () => {
504
- if (!basedOnInfo.bases) {
505
- basedOnInfo.bases = {};
506
- }
507
- basedOnInfo.bases = (0, import_merge2.default)(basedOnInfo.bases, { [baseName]: baseInfo });
508
- };
509
- if (!baseFrom) {
510
- updateBase();
586
+ // src/services/versions/select.ts
587
+ async function selectVersion(remote, fromCommit) {
588
+ const versionsData = await getAvailableVersions(remote);
589
+ if (!versionsData) return;
590
+ const versions = [];
591
+ for (const [v, { lastCommit }] of Object.entries(versionsData)) {
592
+ if (!fromCommit) {
593
+ versions.push(v);
511
594
  continue;
512
595
  }
513
- const baseTo = baseInfo.commit;
514
- if (await git.isCommitOlder(baseFrom, baseTo)) {
515
- updateBase();
516
- } else {
517
- logWarningSection(
518
- `${baseName} is newer in project than template, make sure no breaking changes`
519
- );
596
+ if (fromCommit === lastCommit) continue;
597
+ if (!lastCommit || await git.isCommitOlder(fromCommit, lastCommit)) {
598
+ versions.push(v);
520
599
  }
521
600
  }
522
- const fromBasedCommit = basedOnInfo.bases?.[name]?.commit;
523
- const fromCommit = fromBasedCommit || basedOnInfo.commit;
524
- if (!fromCommit) {
525
- debug("Skip update, no fromCommit found");
526
- return;
527
- }
528
- await git.updateRemote(name, source);
529
- const toCommit = await git.getLatestCommitFromRemote(name);
530
- debug({ fromCommit, toCommit });
531
- if (fromCommit == toCommit) {
532
- debug("No new version");
601
+ if (!versions.length) {
602
+ debug("No versions found, will download latest commit");
533
603
  return;
534
604
  }
535
- const patchFilePath = import_node_path6.default.join(destPath, "diff.patch");
536
- ignore.push("./.blox");
537
- await git.createPatch(fromCommit, toCommit, patchFilePath, ignore);
538
- const changes = await git.getChangesLog(fromCommit, toCommit);
539
- const deletePatchFile = async () => {
540
- if (!isDebugMode()) {
541
- await import_fs_extra6.default.unlink(patchFilePath);
542
- }
543
- debug("make sure to delete the patch file after you're done with it.");
544
- };
545
- try {
546
- await git.applyPatch(patchFilePath, destPath);
547
- } catch (e) {
548
- const errorMessage = `${e}`;
549
- if (errorMessage.includes("error:")) {
550
- await deletePatchFile();
551
- console.log(`${e}`.replace("error:", fmt.red("error:")));
552
- error("Failed to apply changes.");
553
- }
554
- }
555
- if (changes.trim() !== "") {
556
- logWarningSection(
557
- "These is the changes from last update, make sure to review for breaking changes",
558
- changes.replace(/BREAKING CHANGE/gi, fmt.red("BREAKING CHANGE"))
559
- );
560
- }
561
- await deletePatchFile();
562
- if (fromBasedCommit) {
563
- if (!basedOnInfo.bases) {
564
- basedOnInfo.bases = {};
565
- }
566
- if (!basedOnInfo.bases[name]) {
567
- basedOnInfo.bases[name] = { commit: toCommit };
568
- } else {
569
- basedOnInfo.bases[name].commit = toCommit;
570
- }
571
- } else {
572
- basedOnInfo.commit = toCommit;
573
- }
574
- saveBasedOnInfo(basedOnInfo, destPath);
575
- }
576
-
577
- // src/commands/update/utils.ts
578
- async function updateAPP(templateInfo) {
579
- const templates = await getAvailableTemplates();
580
- await runTask({ start: "Update App", end: "Updated App" }, async () => {
581
- const template = templates[templateInfo.name];
582
- if (!template) {
583
- error("Selected template not available, try to sync registries");
584
- return;
585
- }
586
- await updateFromRemote(templateInfo.name, template.source, templateInfo.ignore);
587
- });
588
- for (const base of templateInfo.bases || []) {
589
- await runTask(
590
- { start: `Update App base: ${base.name}`, end: `Updated App base: ${base.name}` },
591
- async () => {
592
- const template = templates[base.name];
593
- if (!template) {
594
- error("Selected template not available, try to sync registries");
595
- return;
596
- }
597
- await updateFromRemote(base.name, template.source, []);
598
- }
599
- );
600
- }
601
- }
602
- var updatedBlocks = /* @__PURE__ */ new Set();
603
- async function updateBlock(block, blocks) {
604
- if (updatedBlocks.has(block)) {
605
- debug(`${block} already updated`);
606
- return;
605
+ if (versions.length === 1) {
606
+ return versionsData[versions[0] || ""]?.lastCommit;
607
607
  }
608
- const blockDef = blocks[block];
609
- const blockPath = import_node_path7.default.join(blocksDir, block);
610
- await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
611
- if (!blockDef) {
612
- error("Selected block not available, try to sync registries", false);
613
- return;
614
- }
615
- await updateFromRemote(block, blockDef.source, blockDef.ignore, blockPath);
616
- updatedBlocks.add(block);
608
+ const version2 = await select({
609
+ message: "Select version to be used",
610
+ options: versions.map((v) => ({
611
+ value: v,
612
+ label: v
613
+ }))
617
614
  });
618
- const blockInfo = getTemplateInfo(blockPath);
619
- for (const dep of blockInfo?.dependencies || []) {
620
- debug(`${block} has dependency on ${dep.name}, will be updated`);
621
- await updateBlock(dep.name, blocks);
622
- }
615
+ return versionsData[version2]?.lastCommit;
623
616
  }
624
617
 
625
618
  // src/commands/init/utils/index.ts
626
619
  function runInitScript(cwd) {
627
620
  debug(`Run init script in: ${cwd}`);
628
- const info = getTemplateInfo(cwd);
621
+ const info = getTemplateDef(cwd);
629
622
  if (info.init) {
630
623
  return $(info.init, [], { cwd });
631
624
  }
@@ -634,13 +627,18 @@ function runInitScript(cwd) {
634
627
  // src/commands/add/index.ts
635
628
  var addBlock = async (block, blocks) => {
636
629
  const blockPath = `blocks/${block}`;
637
- const blockDef = blocks[block];
638
- if (!import_fs_extra7.default.existsSync(blockPath)) {
630
+ const blockRegistryData = blocks[block];
631
+ if (!import_fs_extra5.default.existsSync(blockPath)) {
639
632
  await runTask(
640
633
  { start: `Fetching block: ${block}`, end: `Added block: ${block}` },
641
634
  async () => {
642
- await git.clone(blockDef?.source || "", blockPath);
643
- const commit = await git.getLatestCommitFromPath(blockPath);
635
+ await git.clone(blockRegistryData?.source || "", blockPath);
636
+ let commit = await selectVersion(block);
637
+ if (commit) {
638
+ await git.resetToCommit(commit, blockPath);
639
+ } else {
640
+ commit = await git.getLatestCommitFromPath(blockPath);
641
+ }
644
642
  await git.unInit(blockPath);
645
643
  await replacePlaceholders(blockPath, {});
646
644
  saveBasedOnInfo({ commit }, blockPath);
@@ -648,19 +646,18 @@ var addBlock = async (block, blocks) => {
648
646
  );
649
647
  await runTask("Run init script", async () => runInitScript(blockPath));
650
648
  } else {
651
- debug(`${block} already exists, will be updated`);
652
- await updateBlock(block, blocks);
649
+ debug(`${block} already exists`);
653
650
  }
654
- const blockInfo = getTemplateInfo(blockPath);
655
- for (const dep of blockInfo?.dependencies || []) {
651
+ const blockDef = getBlockDef(blockPath);
652
+ for (const dep of blockDef?.dependencies || []) {
656
653
  await addBlock(dep.name, blocks);
657
654
  }
658
655
  };
659
- var add = command("add").description("Add block to app").alias("a").argument("[block]", "Block to be added").action(async (block) => {
660
- await syncRegistries(false, false);
656
+ var add2 = command("add").description("Add block to app").alias("a").argument("[block]", "Block to be added").action(async (block) => {
657
+ await syncRegistries();
661
658
  try {
662
- const templateInfo = getTemplateInfo();
663
- const blocks = await getAvailableBlocks(templateInfo);
659
+ const templateDef = getTemplateDef();
660
+ const blocks = await getAvailableBlocks(templateDef);
664
661
  if (!block) {
665
662
  block = await select({
666
663
  message: "Select template to be used",
@@ -672,10 +669,15 @@ var add = command("add").description("Add block to app").alias("a").argument("[b
672
669
  });
673
670
  }
674
671
  if (!blocks[block]) {
675
- error("Selected block not available, try to sync registries");
672
+ error("Selected block not available in registries");
676
673
  }
677
674
  await addBlock(block, blocks);
675
+ await checkVersionsCompatibility();
678
676
  } catch (e) {
677
+ if (!isDebugMode()) {
678
+ import_prompts2.log.warn("Error happened, Will rollback changes");
679
+ await git.rollback();
680
+ }
679
681
  error(e);
680
682
  }
681
683
  });
@@ -688,14 +690,7 @@ var ensureRequired = (name) => (value) => {
688
690
  };
689
691
 
690
692
  // src/commands/conf/index.ts
691
- var conf = command("conf").description("Set blox global config").alias("c").option("-r, --registries <registries...>", "Remote registries urls").option("-f, --sync-frequency <duration>", "Remote registries sync frequency").action(async ({ registries, syncFrequency }) => {
692
- if (!syncFrequency) {
693
- syncFrequency = await text({
694
- message: "Sync frequency",
695
- placeholder: "(1m, 1h,1d,...etc)",
696
- defaultValue: defaultConfig.syncFrequency
697
- });
698
- }
693
+ var conf = command("conf").description("Set blox global config").alias("c").option("-r, --registries <registries...>", "Remote registries urls").action(async ({ registries }) => {
699
694
  if (!registries?.length) {
700
695
  registries = await textList({
701
696
  message: "Registries urls",
@@ -703,7 +698,7 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
703
698
  });
704
699
  }
705
700
  try {
706
- updateLocalConfig({ registries, syncFrequency });
701
+ updateLocalConfig({ registries });
707
702
  import_prompts2.log.success("local config updated successfully.");
708
703
  } catch (e) {
709
704
  error(e);
@@ -712,7 +707,7 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
712
707
 
713
708
  // src/commands/init/index.ts
714
709
  var init2 = command("init").description("Init new app").alias("i").option("-n, --name <name>", "App name").option("-t, --template <template>", "Template to use").action(async ({ name, template }) => {
715
- await syncRegistries(false, false);
710
+ await syncRegistries();
716
711
  try {
717
712
  if (!name) {
718
713
  name = await text({ message: "Select app name" });
@@ -729,12 +724,17 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
729
724
  });
730
725
  }
731
726
  if (!templates[template]) {
732
- error("Selected template not available, try to sync registries");
727
+ error("Selected template not available in registries");
733
728
  }
734
729
  const task = spinner();
735
730
  task.start(`Fetch template`);
736
731
  await git.clone(templates[template]?.source || "", name);
737
- const commit = await git.getLatestCommitFromPath(name);
732
+ let commit = await selectVersion(template);
733
+ if (commit) {
734
+ await git.resetToCommit(commit, name);
735
+ } else {
736
+ commit = await git.getLatestCommitFromPath(name);
737
+ }
738
738
  await git.unInit(name);
739
739
  await replacePlaceholders(name, { app: { name } });
740
740
  updateBasedOnInfo({ commit }, name);
@@ -746,48 +746,180 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
746
746
  }
747
747
  });
748
748
 
749
- // src/commands/sync/index.ts
750
- var sync = command("sync").description("Sync local registry with remote updates").alias("s").option("-f, --force", "Force registry update").action(async ({ force = false }) => {
749
+ // src/commands/update/index.ts
750
+ var import_prompts12 = require("@clack/prompts");
751
+
752
+ // src/commands/update/utils.ts
753
+ var import_node_path7 = __toESM(require("path"));
754
+
755
+ // src/services/updater.ts
756
+ var import_node_path6 = __toESM(require("path"));
757
+ var import_fs_extra6 = __toESM(require("fs-extra"));
758
+ var import_merge2 = __toESM(require("lodash/merge"));
759
+ async function updateFromRemote(name, source = "", ignore = [], destPath = ".") {
760
+ debug("Updating from remote");
761
+ await git.updateRemote(name, source);
762
+ const basedOnInfo = getBasedOnInfo(destPath);
763
+ const baseFromCommit = basedOnInfo.bases?.[name]?.commit;
764
+ const fromCommit = baseFromCommit || basedOnInfo.commit;
765
+ let toCommit = await selectVersion(name, fromCommit);
766
+ if (!toCommit) {
767
+ toCommit = await git.getLatestCommitFromRemote(name);
768
+ }
769
+ if (!fromCommit) {
770
+ debug("Skip update, no fromCommit found");
771
+ return;
772
+ }
773
+ debug({ fromCommit, toCommit });
774
+ if (fromCommit == toCommit) {
775
+ debug("No new version");
776
+ return;
777
+ }
778
+ const remoteBloxFile = await git.readJsonFromRemote(toCommit, ".blox");
779
+ for (const [baseName, baseInfo] of Object.entries(remoteBloxFile.bases || {})) {
780
+ const baseFrom = basedOnInfo.bases?.[baseName]?.commit;
781
+ const updateBase = () => {
782
+ if (!basedOnInfo.bases) {
783
+ basedOnInfo.bases = {};
784
+ }
785
+ basedOnInfo.bases = (0, import_merge2.default)(basedOnInfo.bases, { [baseName]: baseInfo });
786
+ };
787
+ if (!baseFrom) {
788
+ updateBase();
789
+ continue;
790
+ }
791
+ const baseTo = baseInfo.commit;
792
+ if (await git.isCommitOlder(baseFrom, baseTo)) {
793
+ updateBase();
794
+ } else {
795
+ logWarningSection(
796
+ `${baseName} is newer in project than template, make sure no breaking changes`
797
+ );
798
+ }
799
+ }
800
+ const patchFilePath = import_node_path6.default.join(destPath, "diff.patch");
801
+ ignore.push("./.blox");
802
+ await git.createPatch(fromCommit, toCommit, patchFilePath, ignore);
803
+ const changes = await git.getChangesLog(fromCommit, toCommit);
804
+ const deletePatchFile = async () => {
805
+ if (!isDebugMode()) {
806
+ await import_fs_extra6.default.unlink(patchFilePath);
807
+ }
808
+ debug("make sure to delete the patch file after you're done with it.");
809
+ };
751
810
  try {
752
- await syncRegistries(force);
753
- import_prompts2.log.success("Local registries synced successfully.");
811
+ await git.applyPatch(patchFilePath, destPath);
754
812
  } catch (e) {
755
- error(e);
813
+ const errorMessage = `${e}`;
814
+ if (errorMessage.includes("error:")) {
815
+ await deletePatchFile();
816
+ console.log(`${e}`.replace("error:", fmt.red("error:")));
817
+ error("Failed to apply changes.");
818
+ }
756
819
  }
757
- });
820
+ if (changes.trim() !== "") {
821
+ logWarningSection(
822
+ "These is the changes from last update, make sure to review for breaking changes",
823
+ changes.replace(/BREAKING CHANGE/gi, fmt.red("BREAKING CHANGE"))
824
+ );
825
+ }
826
+ await deletePatchFile();
827
+ if (baseFromCommit) {
828
+ if (!basedOnInfo.bases) {
829
+ basedOnInfo.bases = {};
830
+ }
831
+ const remotePackageJson = await git.readJsonFromRemote(name, "package.json");
832
+ const version2 = remotePackageJson.blox?.version;
833
+ basedOnInfo.bases[name] = { commit: toCommit, version: version2 };
834
+ } else {
835
+ basedOnInfo.commit = toCommit;
836
+ }
837
+ saveBasedOnInfo(basedOnInfo, destPath);
838
+ }
839
+
840
+ // src/commands/update/utils.ts
841
+ async function updateApp(templateInfo, templates) {
842
+ await runTask({ start: "Update App", end: "Updated App" }, async () => {
843
+ const template = templates[templateInfo.name];
844
+ if (!template) {
845
+ error("Selected template not available in registries");
846
+ return;
847
+ }
848
+ await updateFromRemote(templateInfo.name, template.source, templateInfo.ignore);
849
+ });
850
+ }
851
+ async function updateAppBases(templateInfo, templates) {
852
+ for (const base of templateInfo.bases || []) {
853
+ await runTask(
854
+ { start: `Update App base: ${base.name}`, end: `Updated App base: ${base.name}` },
855
+ async () => {
856
+ const template = templates[base.name];
857
+ if (!template) {
858
+ error("Selected template not available in registries");
859
+ return;
860
+ }
861
+ await updateFromRemote(base.name, template.source, []);
862
+ }
863
+ );
864
+ }
865
+ }
866
+ async function updateBlock(block, blocks) {
867
+ const blockDef = blocks[block];
868
+ const blockPath = import_node_path7.default.join(blocksDir, block);
869
+ await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
870
+ if (!blockDef) {
871
+ error("Selected block not available in registries", false);
872
+ return;
873
+ }
874
+ await updateFromRemote(block, blockDef.source, blockDef.ignore, blockPath);
875
+ });
876
+ }
758
877
 
759
878
  // src/commands/update/index.ts
760
879
  var update2 = command("update").description("Update app/block").alias("u").addOption(
761
- option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "block", "all"])
762
- ).option("-b, --block <name>", "Block to update, valid only with scope block").option("-i, --interactive", "Select version in interactive mode").action(async (args) => {
763
- const templateInfo = getTemplateInfo();
764
- if (["all", "app"].includes(args.scope)) {
765
- await updateAPP(templateInfo);
766
- }
767
- if (args.scope === "app") return;
768
- const availableBlocks = await getAvailableBlocks(templateInfo);
880
+ option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
881
+ ).option("-b, --block <name>", "Block to update, valid only with scope block").action(async (args) => {
882
+ await syncRegistries();
883
+ const templateDef = getTemplateDef();
884
+ const availableBlocks = await getAvailableBlocks(templateDef);
885
+ const templates = await getAvailableTemplates();
769
886
  const usedBlocks = getUsedBlocks();
770
- if (args.scope === "all") {
771
- for (const block of usedBlocks) {
772
- await updateBlock(block.name, availableBlocks);
887
+ try {
888
+ if (["app", "all"].includes(args.scope)) {
889
+ await updateApp(templateDef, templates);
773
890
  }
774
- }
775
- if (args.scope === "block") {
776
- if (!args.block) {
777
- args.block = await select({
778
- message: "Select block to be updated",
779
- options: usedBlocks.map((block2) => ({
780
- value: block2.name,
781
- label: block2.name
782
- }))
783
- });
891
+ if (["bases", "all"].includes(args.scope)) {
892
+ await updateAppBases(templateDef, templates);
784
893
  }
785
- const block = usedBlocks.find((block2) => block2.name === args.block);
786
- if (!block) {
787
- error("Selected block not used in app");
788
- return;
894
+ if (args.scope === "all") {
895
+ for (const block of usedBlocks) {
896
+ await updateBlock(block.name, availableBlocks);
897
+ }
898
+ }
899
+ if (args.scope === "block") {
900
+ if (!args.block) {
901
+ args.block = await select({
902
+ message: "Select block to be updated",
903
+ options: usedBlocks.map((block) => ({
904
+ value: block.name,
905
+ label: block.name
906
+ }))
907
+ });
908
+ }
909
+ const blockDef = usedBlocks.find((block) => block.name === args.block);
910
+ if (!blockDef) {
911
+ error("Selected block not used in app");
912
+ return;
913
+ }
914
+ await updateBlock(blockDef.name, availableBlocks);
789
915
  }
790
- await updateBlock(block.name, availableBlocks);
916
+ await checkVersionsCompatibility();
917
+ } catch (e) {
918
+ if (!isDebugMode()) {
919
+ import_prompts12.log.warn("Error happened, Will rollback changes");
920
+ await git.rollback();
921
+ }
922
+ error(e);
791
923
  }
792
924
  });
793
925
 
@@ -802,7 +934,7 @@ var upgrade = command("upgrade").description("Upgrade blox cli to latest version
802
934
  });
803
935
 
804
936
  // src/commands/index.ts
805
- var commands = [init2, add, update2, sync, conf, upgrade];
937
+ var commands = [init2, add2, update2, conf, upgrade];
806
938
 
807
939
  // bin/run.ts
808
940
  import_extra_typings2.program.name("blox").version(version);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naseej/blox",
3
- "version": "0.1.29",
3
+ "version": "0.2.0",
4
4
  "description": "blox cli",
5
5
  "bin": {
6
6
  "blox": "./bin/run"
@@ -44,6 +44,7 @@
44
44
  "@types/lodash": "4.17.20",
45
45
  "eslint": "^8.57.0",
46
46
  "vitest": "2.1.8",
47
+ "vite-tsconfig-paths": "^5.1.4",
47
48
  "prettier": "^3.2.5",
48
49
  "tsx": "4.19.2",
49
50
  "tsup": "^8.0.2",
package/readme.md CHANGED
@@ -32,7 +32,6 @@ Commands:
32
32
  blox init Init new app [alias: i]
33
33
  blox add Add block to app [alias: a]
34
34
  blox update Update app/block [alias: u]
35
- blox sync Sync local registry with remote updates [alias: s]
36
35
  blox conf Set blox global config [alias: c]
37
36
 
38
37
  Options:
@@ -49,7 +48,6 @@ Options:
49
48
  * [init](#init)
50
49
  * [add](#add)
51
50
  * [update](#update)
52
- * [sync](#sync)
53
51
  * [conf](#conf)
54
52
  * [upgrade](#upgrade)
55
53
 
@@ -96,28 +94,12 @@ blox update
96
94
  Update app/block
97
95
 
98
96
  Options:
99
- -i, --interactive Select version in interactive mode [boolean] [default: "false"]
100
- -s, --scope Scope of update [choices: "app", "block", "all"] [default: "all"]
97
+ -s, --scope Scope of update [choices: "app", "bases", "block", "all"] [default: "all"]
101
98
  -b, --block Block to update, valid only with scope block
102
99
  ```
103
100
 
104
101
  * Note: you may need to resolve merge conflicts if found
105
102
 
106
- #### sync
107
-
108
- ```sh
109
- blox sync --help
110
- ```
111
-
112
- ```
113
- blox sync
114
-
115
- Sync local registry with remote updates
116
-
117
- Options:
118
- -f, --force Force update [boolean] [default: "false"]
119
- ```
120
-
121
103
  #### conf
122
104
 
123
105
  ```sh