@naseej/blox 0.1.28 → 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 +418 -282
  2. package/package.json +2 -1
  3. package/readme.md +1 -19
package/dist/run.js CHANGED
@@ -31,46 +31,18 @@ var option = (flags, description) => {
31
31
  };
32
32
 
33
33
  // package.json
34
- var version = "0.1.28";
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_ms = __toESM(require("ms"));
37
+ var import_fs_extra5 = __toESM(require("fs-extra"));
56
38
 
57
39
  // src/config/runtime.ts
58
40
  var isDebugMode = () => !!import_extra_typings2.program.opts()?.debug;
59
41
  var isMinimalMode = () => !!import_extra_typings2.program.opts()?.minimal;
60
42
 
61
- // src/services/fs.ts
62
- var import_fs_extra = __toESM(require("fs-extra"));
63
- var readJsonFile = (path8, defaultValue = {}) => {
64
- try {
65
- return import_fs_extra.default.readJSONSync(path8);
66
- } catch {
67
- return defaultValue;
68
- }
69
- };
70
-
71
43
  // src/services/git.ts
72
44
  var import_node_path2 = __toESM(require("path"));
73
- var import_fs_extra2 = __toESM(require("fs-extra"));
45
+ var import_fs_extra = __toESM(require("fs-extra"));
74
46
 
75
47
  // src/services/path.ts
76
48
  var import_node_path = __toESM(require("path"));
@@ -108,6 +80,9 @@ var logWarningSection = (title, content) => {
108
80
  content && console2.log(content);
109
81
  console2.log(line + "\n");
110
82
  };
83
+ var normalizeLogMessage = (content) => {
84
+ return content.split("\n").map((l) => l.trim()).filter(Boolean).join("\n");
85
+ };
111
86
 
112
87
  // src/services/shell.ts
113
88
  var $ = async (bin, options = [], { cwd, onStdout } = {}) => {
@@ -155,6 +130,9 @@ var clone = (repoUrl, options, shellOptions = {}) => {
155
130
  ...shellOptions
156
131
  });
157
132
  };
133
+ var resetToCommit = async (commit, cwd = ".") => {
134
+ await $("git", ["reset --hard", `${commit}`], { cwd });
135
+ };
158
136
  var updateRemote = async (name, source, shellOptions = {}) => {
159
137
  debug("updateRemote");
160
138
  debug({ name, source });
@@ -171,10 +149,10 @@ var updateRemote = async (name, source, shellOptions = {}) => {
171
149
  });
172
150
  await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
173
151
  };
174
- var readJsonFromRemote = async (remote, file) => {
152
+ var readJsonFromCommit = async (commit, file) => {
175
153
  try {
176
154
  let content = "";
177
- await $("git", ["show", `${remote}/main:${file}`], {
155
+ await $("git", ["show", `${commit}:${file}`], {
178
156
  onStdout: (text2) => {
179
157
  content = text2;
180
158
  }
@@ -184,6 +162,9 @@ var readJsonFromRemote = async (remote, file) => {
184
162
  return {};
185
163
  }
186
164
  };
165
+ var readJsonFromRemote = async (remote, file, commit) => {
166
+ return readJsonFromCommit(commit || `${remote}/main`, file);
167
+ };
187
168
  var isCommitOlder = async (a, b) => {
188
169
  try {
189
170
  await $("git", ["merge-base --is-ancestor", a, b]);
@@ -219,6 +200,7 @@ var createPatch = async (fromCommit, toCommit, outputPath, ignore = []) => {
219
200
  toCommit,
220
201
  ">",
221
202
  outputPath,
203
+ "--",
222
204
  ...ignore.map((file) => `':!${file}'`)
223
205
  ]);
224
206
  };
@@ -242,7 +224,7 @@ var applyPatch = (patch, cwd = ".") => {
242
224
  };
243
225
  var unInit = (cwd) => {
244
226
  debug("UnInit");
245
- 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"));
246
228
  };
247
229
  var init = async (cwd) => {
248
230
  debug("Init");
@@ -251,6 +233,15 @@ var init = async (cwd) => {
251
233
  await $("git", ["commit", "-m", "init"], { cwd });
252
234
  await $("git", ["branch", "-m", "main"], { cwd });
253
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
+ };
254
245
  var git = {
255
246
  clone,
256
247
  update,
@@ -263,9 +254,18 @@ var git = {
263
254
  applyPatch,
264
255
  updateRemote,
265
256
  readJsonFromRemote,
266
- isCommitOlder
257
+ isCommitOlder,
258
+ rollback,
259
+ add,
260
+ resetToCommit
267
261
  };
268
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
+
269
269
  // src/shared/spinner.ts
270
270
  var import_prompts3 = require("@clack/prompts");
271
271
  var spinner = () => {
@@ -275,8 +275,8 @@ var spinner = () => {
275
275
  start: (msg) => {
276
276
  minimal ? import_prompts2.log.step(`${msg || "start"}...`) : s.start(msg);
277
277
  },
278
- stop: (msg, code) => {
279
- 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);
280
280
  },
281
281
  message: (msg) => {
282
282
  minimal ? import_prompts2.log.message(msg) : s.message(msg);
@@ -292,7 +292,7 @@ async function runTask(message, task) {
292
292
  await (typeof task === "function" ? task() : task);
293
293
  taskSpinner.stop(endMessage);
294
294
  } catch (e) {
295
- taskSpinner.stop(`Failed: ${endMessage}`, 1);
295
+ taskSpinner.stop(`Failed: ${startMessage}`, 1);
296
296
  throw e;
297
297
  }
298
298
  }
@@ -300,62 +300,54 @@ async function runTask(message, task) {
300
300
  // src/services/config.ts
301
301
  var import_node_path3 = __toESM(require("path"));
302
302
  var import_env_paths = __toESM(require("env-paths"));
303
- 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
304
313
  var appPaths = (0, import_env_paths.default)("blox", { suffix: "" });
305
314
  var configFilePath = import_node_path3.default.join(appPaths.config, "config.json");
306
315
  var getLocalConfig = () => {
307
316
  try {
308
- return import_fs_extra3.default.readJSONSync(configFilePath);
317
+ return import_fs_extra2.default.readJSONSync(configFilePath);
309
318
  } catch {
310
319
  return defaultConfig;
311
320
  }
312
321
  };
313
322
  var updateLocalConfig = (config) => {
314
323
  debug("Update local config");
315
- import_fs_extra3.default.ensureFileSync(configFilePath);
324
+ import_fs_extra2.default.ensureFileSync(configFilePath);
316
325
  const current = getLocalConfig();
317
- import_fs_extra3.default.writeJsonSync(configFilePath, { ...current, ...config });
326
+ import_fs_extra2.default.writeJsonSync(configFilePath, { ...current, ...config });
318
327
  };
319
328
 
320
329
  // src/services/registry.ts
321
330
  var registriesDataPath = import_node_path4.default.join(appPaths.data, "registries");
322
- var registriesStatPath = import_node_path4.default.join(registriesDataPath, "stats.json");
323
- var syncRegistries = async (force, logProgress = true) => {
331
+ var syncRegistries = async () => {
324
332
  debug("Sync registries");
325
- logProgress = logProgress || isDebugMode();
326
- import_fs_extra4.default.ensureDirSync(registriesDataPath);
333
+ import_fs_extra3.default.ensureDirSync(registriesDataPath);
327
334
  const config = getLocalConfig();
328
- const registriesStat = readJsonFile(registriesStatPath);
329
- return Promise.all(
330
- config.registries.map(async (registry) => {
331
- const task = spinner();
332
- try {
335
+ return await runTask("Update registries", async () => {
336
+ await Promise.all(
337
+ config.registries.map(async (registry) => {
338
+ debug(`update registry: ${registry}`);
333
339
  const repoName = registry.split("/").pop() || "";
334
- logProgress && task.start(`Updating registry: ${registry}`);
335
340
  const repoDir = import_node_path4.default.join(registriesDataPath, repoName);
336
- if (!registriesStat[repoName]) {
337
- registriesStat[repoName] = {};
338
- }
339
- const now = (0, import_dayjs.default)();
340
- const lastUpdated = registriesStat[repoName].lastUpdated;
341
- const shouldUpdate = !lastUpdated || now.isAfter((0, import_dayjs.default)(lastUpdated).add((0, import_ms.default)(config.syncFrequency)));
342
- if (!import_fs_extra4.default.existsSync(repoDir)) {
341
+ if (!import_fs_extra3.default.existsSync(repoDir)) {
343
342
  await git.clone(registry, "--depth 1", { cwd: registriesDataPath });
344
- registriesStat[repoName].lastUpdated = now.format();
345
- } else if (force || shouldUpdate) {
343
+ } else if (import_fs_extra3.default.existsSync(import_node_path4.default.join(repoDir, ".git"))) {
346
344
  await git.update({ cwd: repoDir });
347
- registriesStat[repoName].lastUpdated = now.format();
348
345
  } else {
349
- logProgress && import_prompts2.log.step(`Have recent version`);
346
+ debug(`local registry`);
350
347
  }
351
- import_fs_extra4.default.writeJSONSync(registriesStatPath, registriesStat);
352
- logProgress && task.stop(`Updated registry: ${registry}`);
353
- } catch (e) {
354
- task.stop(`Updating registry: ${registry} failed`, 1);
355
- throw e;
356
- }
357
- })
358
- );
348
+ })
349
+ );
350
+ });
359
351
  };
360
352
  var getAvailableTemplates = async () => {
361
353
  debug("Get available templates");
@@ -364,22 +356,25 @@ var getAvailableTemplates = async () => {
364
356
  filter: (item) => !item.includes(".git")
365
357
  })) {
366
358
  if (file.path.endsWith(".json")) {
367
- const data = import_fs_extra4.default.readJSONSync(file.path);
368
- Object.keys(data.templates || {}).forEach((templ) => {
369
- templates[templ] = {
370
- ...data.templates[templ],
371
- source: data.templates[templ]?.source || `${data.baseUrl}/template-${templ}`
372
- };
373
- Object.keys(templates[templ].blocks || {}).forEach((blockName) => {
374
- const block = templates[templ]?.blocks?.[blockName];
375
- if (block && !block.source) {
376
- block.source = `${data.baseUrl}/block-${templ}-${blockName}`;
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}`;
363
+ }
364
+ Object.entries(template.blocks || {}).forEach(([blockName, block]) => {
365
+ if (!block.source) {
366
+ block.source = `${data.baseUrl}/block-${templateName}-${blockName}`;
377
367
  }
378
368
  });
369
+ if (templates[templateName]) {
370
+ templates[templateName] = (0, import_merge.default)(templates[templateName], template);
371
+ } else {
372
+ templates[templateName] = template;
373
+ }
379
374
  });
380
375
  }
381
376
  }
382
- debug(templates);
377
+ debug({ templates });
383
378
  return templates;
384
379
  };
385
380
  var getAvailableBlocks = async (templateInfo) => {
@@ -391,44 +386,59 @@ var getAvailableBlocks = async (templateInfo) => {
391
386
  const baseTemplate = templates[base.name];
392
387
  Object.entries(baseTemplate?.blocks || {}).forEach(([k, v]) => blocks[k] = v);
393
388
  }
394
- debug(blocks);
389
+ debug({ blocks });
395
390
  return blocks;
396
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
+ };
397
401
 
398
402
  // src/services/template.ts
399
403
  var import_node_path5 = __toESM(require("path"));
400
404
  var import_ejs = __toESM(require("ejs"));
401
- var import_fs_extra5 = __toESM(require("fs-extra"));
405
+ var import_fs_extra4 = __toESM(require("fs-extra"));
402
406
  var import_klaw2 = __toESM(require("klaw"));
403
407
  async function replacePlaceholders(dir, context) {
404
408
  debug("Replace placeholders");
405
409
  for await (const file of (0, import_klaw2.default)(dir)) {
406
410
  if (file.stats.isFile()) {
407
- const template = import_fs_extra5.default.readFileSync(file.path, "utf-8");
411
+ const template = import_fs_extra4.default.readFileSync(file.path, "utf-8");
408
412
  const rendered = import_ejs.default.render(template, context);
409
- import_fs_extra5.default.writeFileSync(file.path, rendered, "utf-8");
413
+ import_fs_extra4.default.writeFileSync(file.path, rendered, "utf-8");
410
414
  }
411
415
  }
412
416
  }
413
417
  function getPackage(cwd) {
414
- 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;
415
425
  }
416
- function getTemplateInfo(cwd = ".") {
417
- debug("Get template info");
418
- const templateInfo = getPackage(cwd).blox;
419
- debug(templateInfo);
420
- return templateInfo;
426
+ function getBlockDef(cwd = ".") {
427
+ debug("Get block def");
428
+ const def = getPackage(cwd).blox;
429
+ def && debug(def);
430
+ return def;
421
431
  }
422
432
  function getBasedOnInfo(cwd = ".") {
423
433
  try {
424
- 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));
425
435
  } catch {
426
436
  return {};
427
437
  }
428
438
  }
429
439
  function saveBasedOnInfo(info, cwd = ".") {
430
440
  debug("Save info");
431
- 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));
432
442
  }
433
443
  function updateBasedOnInfo(updates, cwd = ".") {
434
444
  const info = getBasedOnInfo(cwd);
@@ -437,14 +447,14 @@ function updateBasedOnInfo(updates, cwd = ".") {
437
447
  function getUsedBlocks() {
438
448
  debug("Get used blocks");
439
449
  const blocks = [];
440
- if (import_fs_extra5.default.existsSync(blocksDir)) {
441
- 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) => {
442
452
  if (!file.isDirectory()) {
443
453
  return;
444
454
  }
445
- const templateInfo = getTemplateInfo(import_node_path5.default.join(blocksDir, file.name));
446
- if (templateInfo) {
447
- blocks.push(templateInfo);
455
+ const blockDef = getBlockDef(import_node_path5.default.join(blocksDir, file.name));
456
+ if (blockDef) {
457
+ blocks.push(blockDef);
448
458
  }
449
459
  });
450
460
  }
@@ -452,10 +462,92 @@ function getUsedBlocks() {
452
462
  return blocks;
453
463
  }
454
464
 
455
- // src/services/updater.ts
456
- var import_node_path6 = __toESM(require("path"));
457
- var import_fs_extra6 = __toESM(require("fs-extra"));
458
- var import_merge = __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
+ }
459
551
 
460
552
  // src/shared/prompts/index.ts
461
553
  var import_prompts4 = require("@clack/prompts");
@@ -467,7 +559,9 @@ var checkIfCanceled = (value) => {
467
559
  };
468
560
  var error = (error2, exit = true) => {
469
561
  import_prompts4.log.error(
470
- 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
+ )
471
565
  );
472
566
  exit && process.exit(-1);
473
567
  };
@@ -489,139 +583,42 @@ var textList = async (opts) => {
489
583
  return value.split(",");
490
584
  };
491
585
 
492
- // src/services/updater.ts
493
- async function updateFromRemote(name, source = "", ignore = [], destPath = ".") {
494
- debug("Updating from remote");
495
- const basedOnInfo = getBasedOnInfo(destPath);
496
- const remoteBloxFile = await git.readJsonFromRemote(name, ".blox");
497
- for (const [baseName, baseInfo] of Object.entries(remoteBloxFile.bases || {})) {
498
- const baseFrom = basedOnInfo.bases?.[baseName]?.commit;
499
- const updateBase = () => {
500
- if (!basedOnInfo.bases) {
501
- basedOnInfo.bases = {};
502
- }
503
- basedOnInfo.bases = (0, import_merge.default)(basedOnInfo.bases, { [baseName]: baseInfo });
504
- };
505
- if (!baseFrom) {
506
- 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);
507
594
  continue;
508
595
  }
509
- const baseTo = baseInfo.commit;
510
- if (await git.isCommitOlder(baseFrom, baseTo)) {
511
- updateBase();
512
- } else {
513
- logWarningSection(
514
- `${baseName} is newer in project than template, make sure no breaking changes`
515
- );
596
+ if (fromCommit === lastCommit) continue;
597
+ if (!lastCommit || await git.isCommitOlder(fromCommit, lastCommit)) {
598
+ versions.push(v);
516
599
  }
517
600
  }
518
- const fromBasedCommit = basedOnInfo.bases?.[name]?.commit;
519
- const fromCommit = fromBasedCommit || basedOnInfo.commit;
520
- if (!fromCommit) {
521
- debug("Skip update, no fromCommit found");
522
- return;
523
- }
524
- await git.updateRemote(name, source);
525
- const toCommit = await git.getLatestCommitFromRemote(name);
526
- debug({ fromCommit, toCommit });
527
- if (fromCommit == toCommit) {
528
- debug("No new version");
601
+ if (!versions.length) {
602
+ debug("No versions found, will download latest commit");
529
603
  return;
530
604
  }
531
- const patchFilePath = import_node_path6.default.join(destPath, "diff.patch");
532
- ignore.push("./.blox");
533
- await git.createPatch(fromCommit, toCommit, patchFilePath, ignore);
534
- const changes = await git.getChangesLog(fromCommit, toCommit);
535
- const deletePatchFile = async () => {
536
- if (!isDebugMode()) {
537
- await import_fs_extra6.default.unlink(patchFilePath);
538
- }
539
- debug("make sure to delete the patch file after you're done with it.");
540
- };
541
- try {
542
- await git.applyPatch(patchFilePath, destPath);
543
- } catch (e) {
544
- const errorMessage = `${e}`;
545
- if (errorMessage.includes("error:")) {
546
- await deletePatchFile();
547
- console.log(`${e}`.replace("error:", fmt.red("error:")));
548
- error("Failed to apply changes.");
549
- }
550
- }
551
- if (changes.trim() !== "") {
552
- logWarningSection(
553
- "These is the changes from last update, make sure to review for breaking changes",
554
- changes.replace(/BREAKING CHANGE/gi, fmt.red("BREAKING CHANGE"))
555
- );
556
- }
557
- await deletePatchFile();
558
- if (fromBasedCommit) {
559
- if (!basedOnInfo.bases) {
560
- basedOnInfo.bases = {};
561
- }
562
- if (!basedOnInfo.bases[name]) {
563
- basedOnInfo.bases[name] = { commit: toCommit };
564
- } else {
565
- basedOnInfo.bases[name].commit = toCommit;
566
- }
567
- } else {
568
- basedOnInfo.commit = toCommit;
569
- }
570
- saveBasedOnInfo(basedOnInfo, destPath);
571
- }
572
-
573
- // src/commands/update/utils.ts
574
- async function updateAPP(templateInfo) {
575
- const templates = await getAvailableTemplates();
576
- await runTask({ start: "Update App", end: "Updated App" }, async () => {
577
- const template = templates[templateInfo.name];
578
- if (!template) {
579
- error("Selected template not available, try to sync registries");
580
- return;
581
- }
582
- await updateFromRemote(templateInfo.name, template.source, templateInfo.ignore);
583
- });
584
- for (const base of templateInfo.bases || []) {
585
- await runTask(
586
- { start: `Update App base: ${base.name}`, end: `Updated App base: ${base.name}` },
587
- async () => {
588
- const template = templates[base.name];
589
- if (!template) {
590
- error("Selected template not available, try to sync registries");
591
- return;
592
- }
593
- await updateFromRemote(base.name, template.source, []);
594
- }
595
- );
596
- }
597
- }
598
- var updatedBlocks = /* @__PURE__ */ new Set();
599
- async function updateBlock(block, blocks) {
600
- if (updatedBlocks.has(block)) {
601
- debug(`${block} already updated`);
602
- return;
605
+ if (versions.length === 1) {
606
+ return versionsData[versions[0] || ""]?.lastCommit;
603
607
  }
604
- const blockDef = blocks[block];
605
- const blockPath = import_node_path7.default.join(blocksDir, block);
606
- await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
607
- if (!blockDef) {
608
- error("Selected block not available, try to sync registries", false);
609
- return;
610
- }
611
- await updateFromRemote(block, blockDef.source, blockDef.ignore, blockPath);
612
- 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
+ }))
613
614
  });
614
- const blockInfo = getTemplateInfo(blockPath);
615
- for (const dep of blockInfo?.dependencies || []) {
616
- debug(`${block} has dependency on ${dep.name}, will be updated`);
617
- await updateBlock(dep.name, blocks);
618
- }
615
+ return versionsData[version2]?.lastCommit;
619
616
  }
620
617
 
621
618
  // src/commands/init/utils/index.ts
622
619
  function runInitScript(cwd) {
623
620
  debug(`Run init script in: ${cwd}`);
624
- const info = getTemplateInfo(cwd);
621
+ const info = getTemplateDef(cwd);
625
622
  if (info.init) {
626
623
  return $(info.init, [], { cwd });
627
624
  }
@@ -630,13 +627,18 @@ function runInitScript(cwd) {
630
627
  // src/commands/add/index.ts
631
628
  var addBlock = async (block, blocks) => {
632
629
  const blockPath = `blocks/${block}`;
633
- const blockDef = blocks[block];
634
- if (!import_fs_extra7.default.existsSync(blockPath)) {
630
+ const blockRegistryData = blocks[block];
631
+ if (!import_fs_extra5.default.existsSync(blockPath)) {
635
632
  await runTask(
636
633
  { start: `Fetching block: ${block}`, end: `Added block: ${block}` },
637
634
  async () => {
638
- await git.clone(blockDef?.source || "", blockPath);
639
- 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
+ }
640
642
  await git.unInit(blockPath);
641
643
  await replacePlaceholders(blockPath, {});
642
644
  saveBasedOnInfo({ commit }, blockPath);
@@ -644,19 +646,18 @@ var addBlock = async (block, blocks) => {
644
646
  );
645
647
  await runTask("Run init script", async () => runInitScript(blockPath));
646
648
  } else {
647
- debug(`${block} already exists, will be updated`);
648
- await updateBlock(block, blocks);
649
+ debug(`${block} already exists`);
649
650
  }
650
- const blockInfo = getTemplateInfo(blockPath);
651
- for (const dep of blockInfo?.dependencies || []) {
651
+ const blockDef = getBlockDef(blockPath);
652
+ for (const dep of blockDef?.dependencies || []) {
652
653
  await addBlock(dep.name, blocks);
653
654
  }
654
655
  };
655
- var add = command("add").description("Add block to app").alias("a").argument("[block]", "Block to be added").action(async (block) => {
656
- 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();
657
658
  try {
658
- const templateInfo = getTemplateInfo();
659
- const blocks = await getAvailableBlocks(templateInfo);
659
+ const templateDef = getTemplateDef();
660
+ const blocks = await getAvailableBlocks(templateDef);
660
661
  if (!block) {
661
662
  block = await select({
662
663
  message: "Select template to be used",
@@ -668,10 +669,15 @@ var add = command("add").description("Add block to app").alias("a").argument("[b
668
669
  });
669
670
  }
670
671
  if (!blocks[block]) {
671
- error("Selected block not available, try to sync registries");
672
+ error("Selected block not available in registries");
672
673
  }
673
674
  await addBlock(block, blocks);
675
+ await checkVersionsCompatibility();
674
676
  } catch (e) {
677
+ if (!isDebugMode()) {
678
+ import_prompts2.log.warn("Error happened, Will rollback changes");
679
+ await git.rollback();
680
+ }
675
681
  error(e);
676
682
  }
677
683
  });
@@ -684,14 +690,7 @@ var ensureRequired = (name) => (value) => {
684
690
  };
685
691
 
686
692
  // src/commands/conf/index.ts
687
- 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 }) => {
688
- if (!syncFrequency) {
689
- syncFrequency = await text({
690
- message: "Sync frequency",
691
- placeholder: "(1m, 1h,1d,...etc)",
692
- defaultValue: defaultConfig.syncFrequency
693
- });
694
- }
693
+ var conf = command("conf").description("Set blox global config").alias("c").option("-r, --registries <registries...>", "Remote registries urls").action(async ({ registries }) => {
695
694
  if (!registries?.length) {
696
695
  registries = await textList({
697
696
  message: "Registries urls",
@@ -699,7 +698,7 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
699
698
  });
700
699
  }
701
700
  try {
702
- updateLocalConfig({ registries, syncFrequency });
701
+ updateLocalConfig({ registries });
703
702
  import_prompts2.log.success("local config updated successfully.");
704
703
  } catch (e) {
705
704
  error(e);
@@ -708,7 +707,7 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
708
707
 
709
708
  // src/commands/init/index.ts
710
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 }) => {
711
- await syncRegistries(false, false);
710
+ await syncRegistries();
712
711
  try {
713
712
  if (!name) {
714
713
  name = await text({ message: "Select app name" });
@@ -725,12 +724,17 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
725
724
  });
726
725
  }
727
726
  if (!templates[template]) {
728
- error("Selected template not available, try to sync registries");
727
+ error("Selected template not available in registries");
729
728
  }
730
729
  const task = spinner();
731
730
  task.start(`Fetch template`);
732
731
  await git.clone(templates[template]?.source || "", name);
733
- 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
+ }
734
738
  await git.unInit(name);
735
739
  await replacePlaceholders(name, { app: { name } });
736
740
  updateBasedOnInfo({ commit }, name);
@@ -742,48 +746,180 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
742
746
  }
743
747
  });
744
748
 
745
- // src/commands/sync/index.ts
746
- 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
+ };
747
810
  try {
748
- await syncRegistries(force);
749
- import_prompts2.log.success("Local registries synced successfully.");
811
+ await git.applyPatch(patchFilePath, destPath);
750
812
  } catch (e) {
751
- 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
+ }
752
819
  }
753
- });
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
+ }
754
877
 
755
878
  // src/commands/update/index.ts
756
879
  var update2 = command("update").description("Update app/block").alias("u").addOption(
757
- option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "block", "all"])
758
- ).option("-b, --block <name>", "Block to update, valid only with scope block").option("-i, --interactive", "Select version in interactive mode").action(async (args) => {
759
- const templateInfo = getTemplateInfo();
760
- if (["all", "app"].includes(args.scope)) {
761
- await updateAPP(templateInfo);
762
- }
763
- if (args.scope === "app") return;
764
- 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();
765
886
  const usedBlocks = getUsedBlocks();
766
- if (args.scope === "all") {
767
- for (const block of usedBlocks) {
768
- await updateBlock(block.name, availableBlocks);
887
+ try {
888
+ if (["app", "all"].includes(args.scope)) {
889
+ await updateApp(templateDef, templates);
769
890
  }
770
- }
771
- if (args.scope === "block") {
772
- if (!args.block) {
773
- args.block = await select({
774
- message: "Select block to be updated",
775
- options: usedBlocks.map((block2) => ({
776
- value: block2.name,
777
- label: block2.name
778
- }))
779
- });
891
+ if (["bases", "all"].includes(args.scope)) {
892
+ await updateAppBases(templateDef, templates);
780
893
  }
781
- const block = usedBlocks.find((block2) => block2.name === args.block);
782
- if (!block) {
783
- error("Selected block not used in app");
784
- 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);
785
915
  }
786
- 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);
787
923
  }
788
924
  });
789
925
 
@@ -798,7 +934,7 @@ var upgrade = command("upgrade").description("Upgrade blox cli to latest version
798
934
  });
799
935
 
800
936
  // src/commands/index.ts
801
- var commands = [init2, add, update2, sync, conf, upgrade];
937
+ var commands = [init2, add2, update2, conf, upgrade];
802
938
 
803
939
  // bin/run.ts
804
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.28",
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