@naseej/blox 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/run.ts CHANGED
@@ -3,9 +3,13 @@ import { cli } from '@/shared/command';
3
3
  import { version } from '../package.json';
4
4
  import { commands } from '../src';
5
5
 
6
- cli.name('blox').version(version);
7
- cli.option('-d, --debug', 'work in debug mode');
8
- cli.option('-m, --minimal', 'work in minimal mode');
6
+ async function main() {
7
+ cli.name('blox').version(version);
8
+ cli.option('-d, --debug', 'work in debug mode');
9
+ cli.option('-m, --minimal', 'work in minimal mode');
9
10
 
10
- commands.forEach((cmd) => cli.addCommand(cmd));
11
- cli.parse();
11
+ commands.forEach((cmd) => cli.addCommand(cmd));
12
+ cli.parse();
13
+ }
14
+
15
+ main();
package/dist/run.js CHANGED
@@ -31,15 +31,60 @@ var option = (flags, description) => {
31
31
  };
32
32
 
33
33
  // package.json
34
- var version = "0.2.0";
34
+ var version = "1.0.0";
35
35
 
36
36
  // src/commands/add/index.ts
37
- var import_fs_extra5 = __toESM(require("fs-extra"));
37
+ var import_fs_extra7 = __toESM(require("fs-extra"));
38
38
 
39
39
  // src/config/runtime.ts
40
40
  var isDebugMode = () => !!import_extra_typings2.program.opts()?.debug;
41
41
  var isMinimalMode = () => !!import_extra_typings2.program.opts()?.minimal;
42
42
 
43
+ // src/migrations/index.ts
44
+ var import_node_path4 = __toESM(require("path"));
45
+ var import_fs_extra3 = __toESM(require("fs-extra"));
46
+
47
+ // src/config/index.ts
48
+ var defaultConfig = {
49
+ registries: ["https://tfs.aas.com.sa/Medad/BLOX/_git/default-registry"]
50
+ };
51
+ var bloxFilePath = ".blox";
52
+ var blocksDir = "blocks";
53
+
54
+ // src/migrations/utils.ts
55
+ var import_node_path3 = __toESM(require("path"));
56
+ var import_fs_extra2 = __toESM(require("fs-extra"));
57
+
58
+ // src/migrations/list/v1.ts
59
+ var v1 = {
60
+ dependencies: {
61
+ packageJson: {
62
+ location: "package.json"
63
+ },
64
+ bloxFile: {
65
+ location: ".blox"
66
+ }
67
+ },
68
+ run: async ({ packageJson, bloxFile: oldBloxFile }) => {
69
+ const bloxFile = {
70
+ schemaVersion: 1,
71
+ definition: packageJson.blox,
72
+ checkpoints: {}
73
+ };
74
+ if (oldBloxFile.commit) {
75
+ bloxFile.checkpoints[bloxFile.definition.name] = { commit: oldBloxFile.commit };
76
+ }
77
+ Object.entries(oldBloxFile.bases || {}).forEach(([k, v]) => {
78
+ bloxFile.checkpoints[k] = v;
79
+ });
80
+ delete packageJson.blox;
81
+ return { bloxFile, packageJson };
82
+ }
83
+ };
84
+
85
+ // src/migrations/list/index.ts
86
+ var migrationsList = [v1];
87
+
43
88
  // src/services/git.ts
44
89
  var import_node_path2 = __toESM(require("path"));
45
90
  var import_fs_extra = __toESM(require("fs-extra"));
@@ -130,8 +175,8 @@ var clone = (repoUrl, options, shellOptions = {}) => {
130
175
  ...shellOptions
131
176
  });
132
177
  };
133
- var resetToCommit = async (commit, cwd = ".") => {
134
- await $("git", ["reset --hard", `${commit}`], { cwd });
178
+ var resetToCommit = async (commit2, cwd = ".") => {
179
+ await $("git", ["reset --hard", `${commit2}`], { cwd });
135
180
  };
136
181
  var updateRemote = async (name, source, shellOptions = {}) => {
137
182
  debug("updateRemote");
@@ -149,10 +194,10 @@ var updateRemote = async (name, source, shellOptions = {}) => {
149
194
  });
150
195
  await $("git", ["fetch", name], { ...defaultShellOptions, ...shellOptions });
151
196
  };
152
- var readJsonFromCommit = async (commit, file) => {
197
+ var readJsonFromCommit = async (commit2, file) => {
153
198
  try {
154
199
  let content = "";
155
- await $("git", ["show", `${commit}:${file}`], {
200
+ await $("git", ["show", `${commit2}:${file}`], {
156
201
  onStdout: (text2) => {
157
202
  content = text2;
158
203
  }
@@ -162,8 +207,8 @@ var readJsonFromCommit = async (commit, file) => {
162
207
  return {};
163
208
  }
164
209
  };
165
- var readJsonFromRemote = async (remote, file, commit) => {
166
- return readJsonFromCommit(commit || `${remote}/main`, file);
210
+ var readJsonFromRemote = async (remote, file, commit2) => {
211
+ return readJsonFromCommit(commit2 || `${remote}/main`, file);
167
212
  };
168
213
  var isCommitOlder = async (a, b) => {
169
214
  try {
@@ -179,19 +224,19 @@ var update = (shellOptions = {}) => {
179
224
  var getLatestCommitFromRemote = async (remote) => {
180
225
  return getLatestCommit(`${remote}/main`);
181
226
  };
182
- var getLatestCommitFromPath = async (path8) => {
183
- return getLatestCommit("HEAD", path8);
227
+ var getLatestCommitFromPath = async (path10) => {
228
+ return getLatestCommit("HEAD", path10);
184
229
  };
185
230
  var getLatestCommit = async (rev, cwd = ".") => {
186
231
  debug(`Get latest commit for rev: ${rev} and cwd: ${cwd}`);
187
- let commit = "";
232
+ let commit2 = "";
188
233
  await $("git", ["rev-parse", rev], {
189
234
  cwd,
190
235
  onStdout: (text2) => {
191
- commit = text2;
236
+ commit2 = text2;
192
237
  }
193
238
  });
194
- return commit.replace(/\n/g, "");
239
+ return commit2.replace(/\n/g, "");
195
240
  };
196
241
  var createPatch = async (fromCommit, toCommit, outputPath, ignore = []) => {
197
242
  return $("git", [
@@ -237,11 +282,25 @@ var add = async (toAdd) => {
237
282
  debug(`Git Add: ${toAdd}`);
238
283
  await $("git", ["add", toAdd]);
239
284
  };
285
+ var commit = async (msg) => {
286
+ debug(`Git commit: ${msg}`);
287
+ await $("git", ["commit", "-m", `"${msg}"`]);
288
+ };
240
289
  var rollback = async () => {
241
290
  debug("Rollback");
242
291
  await $("git", ["add", "."]);
243
292
  await $("git", ["reset", "--hard"]);
244
293
  };
294
+ var hasUncommittedChanges = async (cwd = ".") => {
295
+ let status = "";
296
+ await $("git", ["status", "--porcelain"], {
297
+ cwd,
298
+ onStdout: (text2) => {
299
+ status += text2;
300
+ }
301
+ });
302
+ return status.trim().length > 0;
303
+ };
245
304
  var git = {
246
305
  clone,
247
306
  update,
@@ -253,23 +312,145 @@ var git = {
253
312
  getChangesLog,
254
313
  applyPatch,
255
314
  updateRemote,
315
+ readJsonFromCommit,
256
316
  readJsonFromRemote,
257
317
  isCommitOlder,
258
318
  rollback,
259
319
  add,
260
- resetToCommit
320
+ resetToCommit,
321
+ commit,
322
+ hasUncommittedChanges
261
323
  };
262
324
 
325
+ // src/shared/prompts/index.ts
326
+ var import_prompts3 = require("@clack/prompts");
327
+ var checkIfCanceled = (value) => {
328
+ if ((0, import_prompts3.isCancel)(value)) {
329
+ (0, import_prompts3.cancel)();
330
+ process.exit(0);
331
+ }
332
+ };
333
+ var error = (error2, exit = true) => {
334
+ import_prompts3.log.error(
335
+ fmt.red(
336
+ typeof error2 === "string" ? error2 : error2?.shortMessage || error2?.message || JSON.stringify(error2)
337
+ )
338
+ );
339
+ exit && process.exit(-1);
340
+ };
341
+ var select = async (opts) => {
342
+ const value = await (0, import_prompts3.select)(opts);
343
+ checkIfCanceled(value);
344
+ return value;
345
+ };
346
+ var text = async (opts) => {
347
+ const value = await (0, import_prompts3.text)(opts);
348
+ checkIfCanceled(value);
349
+ return value;
350
+ };
351
+ var textList = async (opts) => {
352
+ opts.message = `${opts.message} ${fmt.gray('(separated with ",")')}`;
353
+ const value = await (0, import_prompts3.text)(opts);
354
+ checkIfCanceled(value);
355
+ opts.validate?.(value);
356
+ return value.split(",");
357
+ };
358
+
359
+ // src/migrations/utils.ts
360
+ function getApplicableMigrations(schemaVersion = 0) {
361
+ if (schemaVersion > migrationsList.length) {
362
+ error(
363
+ normalizeLogMessage(
364
+ `Used blox schema version: ${schemaVersion} is newer than cli version: ${migrationsList.length},
365
+ please update cli first or use older version`
366
+ )
367
+ );
368
+ return [];
369
+ }
370
+ return migrationsList.slice(schemaVersion);
371
+ }
372
+ async function migrate(name, { getPath = (f) => f, read, write }) {
373
+ let remoteBloxFile;
374
+ try {
375
+ remoteBloxFile = await read(getPath(".blox"));
376
+ } catch {
377
+ remoteBloxFile = {};
378
+ }
379
+ const migrations = getApplicableMigrations(remoteBloxFile.schemaVersion);
380
+ if (migrations.length) {
381
+ import_prompts2.log.warn(fmt.yellow(`Migrations found for ${name}, will migrate to latest schema`));
382
+ }
383
+ const currentRev = {
384
+ ".blox": remoteBloxFile
385
+ };
386
+ for (const migration of migrations) {
387
+ const deps = {};
388
+ for (const [name2, { location, defaultValue = {} }] of Object.entries(
389
+ migration.dependencies
390
+ )) {
391
+ try {
392
+ const filePath = getPath(location);
393
+ if (currentRev[filePath] !== void 0) {
394
+ deps[name2] = currentRev[filePath];
395
+ } else {
396
+ deps[name2] = await read(filePath);
397
+ }
398
+ } catch {
399
+ }
400
+ if (deps[name2] === void 0) {
401
+ deps[name2] = defaultValue;
402
+ }
403
+ }
404
+ const output = await migration.run(deps);
405
+ for (const [name2, value] of Object.entries(output || {})) {
406
+ const { location } = migration.dependencies[name2] || {};
407
+ location && (currentRev[location] = value);
408
+ }
409
+ }
410
+ if (write) {
411
+ for (const [location, value] of Object.entries(currentRev)) {
412
+ await write(getPath(location), JSON.stringify(value, null, 2));
413
+ }
414
+ }
415
+ return { output: currentRev, migrationsRan: migrations.length };
416
+ }
417
+ function migrateOnLocal(name, cwd = ".") {
418
+ return migrate(name, {
419
+ getPath: (file) => import_node_path3.default.join(cwd, file),
420
+ read: import_fs_extra2.default.readJson,
421
+ write: import_fs_extra2.default.writeFile
422
+ });
423
+ }
424
+ function migrateOnRemote(name, commit2) {
425
+ return migrate(name, {
426
+ read: (file) => git.readJsonFromCommit(commit2, file)
427
+ });
428
+ }
429
+
430
+ // src/migrations/index.ts
431
+ async function migrateAll(autoCommit) {
432
+ let migrationsRan = (await migrateOnLocal("app")).migrationsRan;
433
+ const blocks = import_fs_extra3.default.existsSync(blocksDir) ? import_fs_extra3.default.readdirSync(blocksDir) : [];
434
+ for (const block of blocks) {
435
+ migrationsRan += (await migrateOnLocal(block, import_node_path4.default.join(blocksDir, block))).migrationsRan;
436
+ }
437
+ if (autoCommit && migrationsRan) {
438
+ import_prompts2.log.warn(fmt.yellow(`Migrations done and will be commited`));
439
+ await git.add(".");
440
+ await git.commit("chore: migrate blox schema");
441
+ }
442
+ }
443
+
263
444
  // src/services/registry.ts
264
- var import_node_path4 = __toESM(require("path"));
265
- var import_fs_extra3 = __toESM(require("fs-extra"));
445
+ var import_node_path6 = __toESM(require("path"));
446
+ var import_fs_extra5 = __toESM(require("fs-extra"));
266
447
  var import_klaw = __toESM(require("klaw"));
267
448
  var import_merge = __toESM(require("lodash/merge"));
268
449
 
269
450
  // src/shared/spinner.ts
270
- var import_prompts3 = require("@clack/prompts");
451
+ var import_prompts5 = require("@clack/prompts");
271
452
  var spinner = () => {
272
- const s = (0, import_prompts3.spinner)();
453
+ const s = (0, import_prompts5.spinner)();
273
454
  const minimal = isMinimalMode() || isDebugMode();
274
455
  return {
275
456
  start: (msg) => {
@@ -298,49 +479,40 @@ async function runTask(message, task) {
298
479
  }
299
480
 
300
481
  // src/services/config.ts
301
- var import_node_path3 = __toESM(require("path"));
482
+ var import_node_path5 = __toESM(require("path"));
302
483
  var import_env_paths = __toESM(require("env-paths"));
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
484
+ var import_fs_extra4 = __toESM(require("fs-extra"));
313
485
  var appPaths = (0, import_env_paths.default)("blox", { suffix: "" });
314
- var configFilePath = import_node_path3.default.join(appPaths.config, "config.json");
486
+ var configFilePath = import_node_path5.default.join(appPaths.config, "config.json");
315
487
  var getLocalConfig = () => {
316
488
  try {
317
- return import_fs_extra2.default.readJSONSync(configFilePath);
489
+ return import_fs_extra4.default.readJSONSync(configFilePath);
318
490
  } catch {
319
491
  return defaultConfig;
320
492
  }
321
493
  };
322
494
  var updateLocalConfig = (config) => {
323
495
  debug("Update local config");
324
- import_fs_extra2.default.ensureFileSync(configFilePath);
496
+ import_fs_extra4.default.ensureFileSync(configFilePath);
325
497
  const current = getLocalConfig();
326
- import_fs_extra2.default.writeJsonSync(configFilePath, { ...current, ...config });
498
+ import_fs_extra4.default.writeJsonSync(configFilePath, { ...current, ...config });
327
499
  };
328
500
 
329
501
  // src/services/registry.ts
330
- var registriesDataPath = import_node_path4.default.join(appPaths.data, "registries");
502
+ var registriesDataPath = import_node_path6.default.join(appPaths.data, "registries");
331
503
  var syncRegistries = async () => {
332
504
  debug("Sync registries");
333
- import_fs_extra3.default.ensureDirSync(registriesDataPath);
505
+ import_fs_extra5.default.ensureDirSync(registriesDataPath);
334
506
  const config = getLocalConfig();
335
507
  return await runTask("Update registries", async () => {
336
508
  await Promise.all(
337
509
  config.registries.map(async (registry) => {
338
510
  debug(`update registry: ${registry}`);
339
511
  const repoName = registry.split("/").pop() || "";
340
- const repoDir = import_node_path4.default.join(registriesDataPath, repoName);
341
- if (!import_fs_extra3.default.existsSync(repoDir)) {
512
+ const repoDir = import_node_path6.default.join(registriesDataPath, repoName);
513
+ if (!import_fs_extra5.default.existsSync(repoDir)) {
342
514
  await git.clone(registry, "--depth 1", { cwd: registriesDataPath });
343
- } else if (import_fs_extra3.default.existsSync(import_node_path4.default.join(repoDir, ".git"))) {
515
+ } else if (import_fs_extra5.default.existsSync(import_node_path6.default.join(repoDir, ".git"))) {
344
516
  await git.update({ cwd: repoDir });
345
517
  } else {
346
518
  debug(`local registry`);
@@ -356,14 +528,20 @@ var getAvailableTemplates = async () => {
356
528
  filter: (item) => !item.includes(".git")
357
529
  })) {
358
530
  if (file.path.endsWith(".json")) {
359
- const data = import_fs_extra3.default.readJSONSync(file.path);
531
+ const data = import_fs_extra5.default.readJSONSync(file.path);
360
532
  Object.entries(data.templates || {}).forEach(([templateName, template]) => {
361
533
  if (!template.source) {
362
- template.source = `${data.baseUrl}/template-${templateName}`;
534
+ template.source = `/template-${templateName}`;
535
+ }
536
+ if (template.source.startsWith("/")) {
537
+ template.source = data.baseUrl + template.source;
363
538
  }
364
539
  Object.entries(template.blocks || {}).forEach(([blockName, block]) => {
365
540
  if (!block.source) {
366
- block.source = `${data.baseUrl}/block-${templateName}-${blockName}`;
541
+ block.source = `/block-${templateName}-${blockName}`;
542
+ }
543
+ if (block.source.startsWith("/")) {
544
+ block.source = data.baseUrl + block.source;
367
545
  }
368
546
  });
369
547
  if (templates[templateName]) {
@@ -390,69 +568,74 @@ var getAvailableBlocks = async (templateInfo) => {
390
568
  return blocks;
391
569
  };
392
570
  var getAvailableVersions = async (id) => {
393
- const registries = import_fs_extra3.default.readdirSync(registriesDataPath);
571
+ const registries = import_fs_extra5.default.readdirSync(registriesDataPath);
394
572
  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);
573
+ const versionsFile = import_node_path6.default.join(registriesDataPath, registry, "versions", `${id}.json`);
574
+ if (import_fs_extra5.default.existsSync(versionsFile)) {
575
+ return import_fs_extra5.default.readJSONSync(versionsFile);
398
576
  }
399
577
  }
400
578
  };
401
579
 
402
580
  // src/services/template.ts
403
- var import_node_path5 = __toESM(require("path"));
581
+ var import_node_path7 = __toESM(require("path"));
404
582
  var import_ejs = __toESM(require("ejs"));
405
- var import_fs_extra4 = __toESM(require("fs-extra"));
583
+ var import_fs_extra6 = __toESM(require("fs-extra"));
406
584
  var import_klaw2 = __toESM(require("klaw"));
407
585
  async function replacePlaceholders(dir, context) {
408
586
  debug("Replace placeholders");
409
587
  for await (const file of (0, import_klaw2.default)(dir)) {
410
588
  if (file.stats.isFile()) {
411
- const template = import_fs_extra4.default.readFileSync(file.path, "utf-8");
589
+ const template = import_fs_extra6.default.readFileSync(file.path, "utf-8");
412
590
  const rendered = import_ejs.default.render(template, context);
413
- import_fs_extra4.default.writeFileSync(file.path, rendered, "utf-8");
591
+ import_fs_extra6.default.writeFileSync(file.path, rendered, "utf-8");
414
592
  }
415
593
  }
416
594
  }
417
- function getPackage(cwd) {
418
- return import_fs_extra4.default.readJSONSync(import_node_path5.default.join(cwd, "package.json"));
419
- }
420
595
  function getTemplateDef(cwd = ".") {
421
596
  debug("Get template def");
422
- const def = getPackage(cwd).blox;
597
+ const def = getBloxFile(cwd).definition;
423
598
  debug(def);
424
599
  return def;
425
600
  }
426
601
  function getBlockDef(cwd = ".") {
427
602
  debug("Get block def");
428
- const def = getPackage(cwd).blox;
603
+ const def = getBloxFile(cwd).definition;
429
604
  def && debug(def);
430
605
  return def;
431
606
  }
432
- function getBasedOnInfo(cwd = ".") {
607
+ function getBloxFile(cwd = ".") {
433
608
  try {
434
- return import_fs_extra4.default.readJSONSync(import_node_path5.default.join(cwd, basedOnFile));
609
+ const file = import_fs_extra6.default.readJSONSync(import_node_path7.default.join(cwd, bloxFilePath));
610
+ if (!file.checkpoints) {
611
+ file.checkpoints = {};
612
+ }
613
+ return file;
435
614
  } catch {
436
615
  return {};
437
616
  }
438
617
  }
439
- function saveBasedOnInfo(info, cwd = ".") {
618
+ function saveBloxFile(info, cwd = ".") {
440
619
  debug("Save info");
441
- import_fs_extra4.default.writeFileSync(import_node_path5.default.join(cwd, basedOnFile), JSON.stringify(info, null, 2));
620
+ import_fs_extra6.default.writeFileSync(import_node_path7.default.join(cwd, bloxFilePath), JSON.stringify(info, null, 2));
442
621
  }
443
- function updateBasedOnInfo(updates, cwd = ".") {
444
- const info = getBasedOnInfo(cwd);
445
- saveBasedOnInfo({ ...info, ...updates }, cwd);
622
+ function updateCheckpoint(name, checkpoint, cwd = ".") {
623
+ const info = getBloxFile(cwd);
624
+ if (!info.checkpoints) {
625
+ info.checkpoints = {};
626
+ }
627
+ info.checkpoints[name] = checkpoint;
628
+ saveBloxFile(info, cwd);
446
629
  }
447
630
  function getUsedBlocks() {
448
631
  debug("Get used blocks");
449
632
  const blocks = [];
450
- if (import_fs_extra4.default.existsSync(blocksDir)) {
451
- import_fs_extra4.default.readdirSync(blocksDir, { withFileTypes: true }).forEach((file) => {
633
+ if (import_fs_extra6.default.existsSync(blocksDir)) {
634
+ import_fs_extra6.default.readdirSync(blocksDir, { withFileTypes: true }).forEach((file) => {
452
635
  if (!file.isDirectory()) {
453
636
  return;
454
637
  }
455
- const blockDef = getBlockDef(import_node_path5.default.join(blocksDir, file.name));
638
+ const blockDef = getBlockDef(import_node_path7.default.join(blocksDir, file.name));
456
639
  if (blockDef) {
457
640
  blocks.push(blockDef);
458
641
  }
@@ -473,11 +656,11 @@ function processTemplate(def) {
473
656
  return def;
474
657
  }
475
658
  function processBases(info) {
476
- if (!info || !info.bases) return {};
477
- Object.values(info.bases).forEach((base) => {
659
+ if (!info || !info.checkpoints) return {};
660
+ Object.values(info.checkpoints).forEach((base) => {
478
661
  if (!base.version) base.version = 0;
479
662
  });
480
- return info.bases;
663
+ return info.checkpoints;
481
664
  }
482
665
  function processBlocks(defs) {
483
666
  defs.forEach((def) => {
@@ -544,45 +727,11 @@ async function _checkVersionsCompatibility(template, usedBlocks, basesVersion) {
544
727
  async function checkVersionsCompatibility() {
545
728
  const template = processTemplate(getTemplateDef());
546
729
  const usedBlocks = processBlocks(getUsedBlocks());
547
- const basesVersion = processBases(getBasedOnInfo());
730
+ const basesVersion = processBases(getBloxFile());
548
731
  basesVersion[template.name] = { version: template.version, commit: "" };
549
732
  await _checkVersionsCompatibility(template, usedBlocks, basesVersion);
550
733
  }
551
734
 
552
- // src/shared/prompts/index.ts
553
- var import_prompts4 = require("@clack/prompts");
554
- var checkIfCanceled = (value) => {
555
- if ((0, import_prompts4.isCancel)(value)) {
556
- (0, import_prompts4.cancel)();
557
- process.exit(0);
558
- }
559
- };
560
- var error = (error2, exit = true) => {
561
- import_prompts4.log.error(
562
- fmt.red(
563
- typeof error2 === "string" ? error2 : error2?.shortMessage || error2?.message || JSON.stringify(error2)
564
- )
565
- );
566
- exit && process.exit(-1);
567
- };
568
- var select = async (opts) => {
569
- const value = await (0, import_prompts4.select)(opts);
570
- checkIfCanceled(value);
571
- return value;
572
- };
573
- var text = async (opts) => {
574
- const value = await (0, import_prompts4.text)(opts);
575
- checkIfCanceled(value);
576
- return value;
577
- };
578
- var textList = async (opts) => {
579
- opts.message = `${opts.message} ${fmt.gray('(separated with ",")')}`;
580
- const value = await (0, import_prompts4.text)(opts);
581
- checkIfCanceled(value);
582
- opts.validate?.(value);
583
- return value.split(",");
584
- };
585
-
586
735
  // src/services/versions/select.ts
587
736
  async function selectVersion(remote, fromCommit) {
588
737
  const versionsData = await getAvailableVersions(remote);
@@ -628,20 +777,21 @@ function runInitScript(cwd) {
628
777
  var addBlock = async (block, blocks) => {
629
778
  const blockPath = `blocks/${block}`;
630
779
  const blockRegistryData = blocks[block];
631
- if (!import_fs_extra5.default.existsSync(blockPath)) {
780
+ if (!import_fs_extra7.default.existsSync(blockPath)) {
632
781
  await runTask(
633
782
  { start: `Fetching block: ${block}`, end: `Added block: ${block}` },
634
783
  async () => {
635
784
  await git.clone(blockRegistryData?.source || "", blockPath);
636
- let commit = await selectVersion(block);
637
- if (commit) {
638
- await git.resetToCommit(commit, blockPath);
785
+ let commit2 = await selectVersion(block);
786
+ if (commit2) {
787
+ await git.resetToCommit(commit2, blockPath);
639
788
  } else {
640
- commit = await git.getLatestCommitFromPath(blockPath);
789
+ commit2 = await git.getLatestCommitFromPath(blockPath);
641
790
  }
642
791
  await git.unInit(blockPath);
643
792
  await replacePlaceholders(blockPath, {});
644
- saveBasedOnInfo({ commit }, blockPath);
793
+ await migrateAll();
794
+ updateCheckpoint(block, { commit: commit2 }, blockPath);
645
795
  }
646
796
  );
647
797
  await runTask("Run init script", async () => runInitScript(blockPath));
@@ -654,6 +804,7 @@ var addBlock = async (block, blocks) => {
654
804
  }
655
805
  };
656
806
  var add2 = command("add").description("Add block to app").alias("a").argument("[block]", "Block to be added").action(async (block) => {
807
+ await migrateAll();
657
808
  await syncRegistries();
658
809
  try {
659
810
  const templateDef = getTemplateDef();
@@ -706,6 +857,7 @@ var conf = command("conf").description("Set blox global config").alias("c").opti
706
857
  });
707
858
 
708
859
  // src/commands/init/index.ts
860
+ var import_fs_extra8 = __toESM(require("fs-extra"));
709
861
  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 }) => {
710
862
  await syncRegistries();
711
863
  try {
@@ -729,81 +881,88 @@ var init2 = command("init").description("Init new app").alias("i").option("-n, -
729
881
  const task = spinner();
730
882
  task.start(`Fetch template`);
731
883
  await git.clone(templates[template]?.source || "", name);
732
- let commit = await selectVersion(template);
733
- if (commit) {
734
- await git.resetToCommit(commit, name);
884
+ let commit2 = await selectVersion(template);
885
+ if (commit2) {
886
+ await git.resetToCommit(commit2, name);
735
887
  } else {
736
- commit = await git.getLatestCommitFromPath(name);
888
+ commit2 = await git.getLatestCommitFromPath(name);
737
889
  }
738
890
  await git.unInit(name);
891
+ await migrateAll();
739
892
  await replacePlaceholders(name, { app: { name } });
740
- updateBasedOnInfo({ commit }, name);
893
+ updateCheckpoint(name, { commit: commit2 }, name);
741
894
  await git.init(name);
742
895
  task.stop(`App initialized in ${name}`);
743
896
  await runTask("Run init script", async () => runInitScript(name || ""));
744
897
  } catch (e) {
898
+ name && import_fs_extra8.default.existsSync(name) && import_fs_extra8.default.rmdirSync(name);
899
+ error(e);
900
+ }
901
+ });
902
+
903
+ // src/commands/migrate/index.ts
904
+ var migrateSchema = command("migrate").description("Migrate blox schema").action(async () => {
905
+ try {
906
+ await migrateAll();
907
+ } catch (e) {
908
+ if (!isDebugMode()) {
909
+ import_prompts2.log.warn("Error happened, Will rollback changes");
910
+ await git.rollback();
911
+ }
745
912
  error(e);
746
913
  }
747
914
  });
748
915
 
749
916
  // src/commands/update/index.ts
750
- var import_prompts12 = require("@clack/prompts");
917
+ var import_prompts13 = require("@clack/prompts");
751
918
 
752
919
  // src/commands/update/utils.ts
753
- var import_node_path7 = __toESM(require("path"));
920
+ var import_node_path9 = __toESM(require("path"));
754
921
 
755
922
  // 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"));
923
+ var import_node_path8 = __toESM(require("path"));
924
+ var import_fs_extra9 = __toESM(require("fs-extra"));
759
925
  async function updateFromRemote(name, source = "", ignore = [], destPath = ".") {
760
926
  debug("Updating from remote");
761
927
  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
- }
928
+ const bloxFile = getBloxFile(destPath);
929
+ const fromCommit = bloxFile.checkpoints[name]?.commit;
769
930
  if (!fromCommit) {
770
931
  debug("Skip update, no fromCommit found");
771
932
  return;
772
933
  }
934
+ let toCommit = await selectVersion(name, fromCommit);
935
+ if (!toCommit) {
936
+ toCommit = await git.getLatestCommitFromRemote(name);
937
+ }
773
938
  debug({ fromCommit, toCommit });
774
939
  if (fromCommit == toCommit) {
775
940
  debug("No new version");
776
941
  return;
777
942
  }
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
- };
943
+ const remoteBloxFile = (await migrateOnRemote(name, toCommit)).output[".blox"];
944
+ for (const [baseName, baseInfo] of Object.entries(remoteBloxFile.checkpoints || {})) {
945
+ const baseFrom = bloxFile.checkpoints[baseName]?.commit;
787
946
  if (!baseFrom) {
788
- updateBase();
947
+ bloxFile.checkpoints[baseName] = baseInfo;
789
948
  continue;
790
949
  }
791
950
  const baseTo = baseInfo.commit;
792
951
  if (await git.isCommitOlder(baseFrom, baseTo)) {
793
- updateBase();
952
+ bloxFile.checkpoints[baseName] = baseInfo;
794
953
  } else {
795
954
  logWarningSection(
796
955
  `${baseName} is newer in project than template, make sure no breaking changes`
797
956
  );
798
957
  }
799
958
  }
800
- const patchFilePath = import_node_path6.default.join(destPath, "diff.patch");
959
+ const patchFilePath = import_node_path8.default.join(destPath, "diff.patch");
801
960
  ignore.push("./.blox");
802
961
  await git.createPatch(fromCommit, toCommit, patchFilePath, ignore);
803
962
  const changes = await git.getChangesLog(fromCommit, toCommit);
804
963
  const deletePatchFile = async () => {
805
964
  if (!isDebugMode()) {
806
- await import_fs_extra6.default.unlink(patchFilePath);
965
+ await import_fs_extra9.default.unlink(patchFilePath);
807
966
  }
808
967
  debug("make sure to delete the patch file after you're done with it.");
809
968
  };
@@ -814,7 +973,7 @@ async function updateFromRemote(name, source = "", ignore = [], destPath = ".")
814
973
  if (errorMessage.includes("error:")) {
815
974
  await deletePatchFile();
816
975
  console.log(`${e}`.replace("error:", fmt.red("error:")));
817
- error("Failed to apply changes.");
976
+ throw new Error("Failed to apply changes.");
818
977
  }
819
978
  }
820
979
  if (changes.trim() !== "") {
@@ -824,17 +983,13 @@ async function updateFromRemote(name, source = "", ignore = [], destPath = ".")
824
983
  );
825
984
  }
826
985
  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 };
986
+ bloxFile.checkpoints[name] = { commit: toCommit };
987
+ if (bloxFile.definition.name === name) {
988
+ bloxFile.definition = remoteBloxFile.definition;
834
989
  } else {
835
- basedOnInfo.commit = toCommit;
990
+ bloxFile.checkpoints[name].version = remoteBloxFile.definition.version;
836
991
  }
837
- saveBasedOnInfo(basedOnInfo, destPath);
992
+ saveBloxFile(bloxFile, destPath);
838
993
  }
839
994
 
840
995
  // src/commands/update/utils.ts
@@ -842,7 +997,7 @@ async function updateApp(templateInfo, templates) {
842
997
  await runTask({ start: "Update App", end: "Updated App" }, async () => {
843
998
  const template = templates[templateInfo.name];
844
999
  if (!template) {
845
- error("Selected template not available in registries");
1000
+ error(`Selected template: ${templateInfo.name} not available in registries`);
846
1001
  return;
847
1002
  }
848
1003
  await updateFromRemote(templateInfo.name, template.source, templateInfo.ignore);
@@ -865,10 +1020,10 @@ async function updateAppBases(templateInfo, templates) {
865
1020
  }
866
1021
  async function updateBlock(block, blocks) {
867
1022
  const blockDef = blocks[block];
868
- const blockPath = import_node_path7.default.join(blocksDir, block);
1023
+ const blockPath = import_node_path9.default.join(blocksDir, block);
869
1024
  await runTask({ start: `Update block: ${block}`, end: `Updated block: ${block}` }, async () => {
870
1025
  if (!blockDef) {
871
- error("Selected block not available in registries", false);
1026
+ error(`Selected block: ${block} not available in registries`, false);
872
1027
  return;
873
1028
  }
874
1029
  await updateFromRemote(block, blockDef.source, blockDef.ignore, blockPath);
@@ -879,6 +1034,11 @@ async function updateBlock(block, blocks) {
879
1034
  var update2 = command("update").description("Update app/block").alias("u").addOption(
880
1035
  option("-s, --scope <scope>", "Scope of update").default("all").choices(["app", "bases", "block", "all"])
881
1036
  ).option("-b, --block <name>", "Block to update, valid only with scope block").action(async (args) => {
1037
+ if (await git.hasUncommittedChanges()) {
1038
+ import_prompts13.log.warn("Make sure to commit any changes first");
1039
+ return;
1040
+ }
1041
+ await migrateAll(true);
882
1042
  await syncRegistries();
883
1043
  const templateDef = getTemplateDef();
884
1044
  const availableBlocks = await getAvailableBlocks(templateDef);
@@ -916,7 +1076,7 @@ var update2 = command("update").description("Update app/block").alias("u").addOp
916
1076
  await checkVersionsCompatibility();
917
1077
  } catch (e) {
918
1078
  if (!isDebugMode()) {
919
- import_prompts12.log.warn("Error happened, Will rollback changes");
1079
+ import_prompts13.log.warn("Error happened, Will rollback changes");
920
1080
  await git.rollback();
921
1081
  }
922
1082
  error(e);
@@ -934,11 +1094,14 @@ var upgrade = command("upgrade").description("Upgrade blox cli to latest version
934
1094
  });
935
1095
 
936
1096
  // src/commands/index.ts
937
- var commands = [init2, add2, update2, conf, upgrade];
1097
+ var commands = [init2, add2, update2, conf, upgrade, migrateSchema];
938
1098
 
939
1099
  // bin/run.ts
940
- import_extra_typings2.program.name("blox").version(version);
941
- import_extra_typings2.program.option("-d, --debug", "work in debug mode");
942
- import_extra_typings2.program.option("-m, --minimal", "work in minimal mode");
943
- commands.forEach((cmd) => import_extra_typings2.program.addCommand(cmd));
944
- import_extra_typings2.program.parse();
1100
+ async function main() {
1101
+ import_extra_typings2.program.name("blox").version(version);
1102
+ import_extra_typings2.program.option("-d, --debug", "work in debug mode");
1103
+ import_extra_typings2.program.option("-m, --minimal", "work in minimal mode");
1104
+ commands.forEach((cmd) => import_extra_typings2.program.addCommand(cmd));
1105
+ import_extra_typings2.program.parse();
1106
+ }
1107
+ main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naseej/blox",
3
- "version": "0.2.0",
3
+ "version": "1.0.0",
4
4
  "description": "blox cli",
5
5
  "bin": {
6
6
  "blox": "./bin/run"
package/readme.md CHANGED
@@ -50,6 +50,7 @@ Options:
50
50
  * [update](#update)
51
51
  * [conf](#conf)
52
52
  * [upgrade](#upgrade)
53
+ * [migrate](#migrate)
53
54
 
54
55
  #### init
55
56
 
@@ -126,6 +127,17 @@ blox upgrade
126
127
 
127
128
  Upgrade blox cli to latest version
128
129
  ```
130
+ #### migrate
131
+
132
+ ```sh
133
+ blox migrate --help
134
+ ```
135
+
136
+ ```
137
+ blox migrate
138
+
139
+ Migrate blox schema
140
+ ```
129
141
 
130
142
  ### Docs
131
143