masterrecord 1.1.5 → 1.1.7

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/Migrations/cli.js CHANGED
@@ -51,7 +51,6 @@ function __getMigrationTimestamp(file){
51
51
  const __MIGRATIONS_TABLE__ = '_masterrecord_migrations';
52
52
 
53
53
  async function __ensureMigrationsTable(ctx){
54
- const engine = ctx._SQLEngine;
55
54
  if (ctx.isSQLite) {
56
55
  await ctx._execute(`CREATE TABLE IF NOT EXISTS [${__MIGRATIONS_TABLE__}] (
57
56
  migration_name TEXT PRIMARY KEY,
@@ -127,7 +126,7 @@ async function __cleanupAndExit(contextInstance, exitCode = 0) {
127
126
  }
128
127
 
129
128
 
130
- const [,, ...args] = process.argv
129
+ const [,, ..._args] = process.argv
131
130
 
132
131
 
133
132
 
@@ -145,18 +144,18 @@ program.option('-V', 'output the version');
145
144
  .description('Enables the migration in your project by creating a configuration class called ContextSnapShot.json')
146
145
  .action(async function(contextFileName){
147
146
  try {
148
- var migration = new Migration();
147
+ const migration = new Migration();
149
148
  // location of folder where command is being executed..
150
- var executedLocation = process.cwd();
149
+ const executedLocation = process.cwd();
151
150
  // find context file from main folder location
152
- var contextFile = migration.findContextFile(executedLocation, contextFileName);
151
+ const contextFile = migration.findContextFile(executedLocation, contextFileName);
153
152
  if(!contextFile){
154
153
  console.error(`\n❌ Error - Cannot read or find Context file '${contextFileName}.js'`);
155
154
  console.error(`\nSearched in: ${executedLocation}`);
156
155
  console.error(`\nMake sure your Context file exists and is named correctly.`);
157
156
  process.exit(1);
158
157
  }
159
- var snap = {
158
+ const snap = {
160
159
  file : contextFile,
161
160
  executedLocation : executedLocation,
162
161
  contextEntities : [],
@@ -177,18 +176,18 @@ program.option('-V', 'output the version');
177
176
  .alias('ed')
178
177
  .description('Ensure the target database exists for the given context (MySQL)')
179
178
  .action(async function(contextFileName){
180
- var executedLocation = process.cwd();
179
+ const executedLocation = process.cwd();
181
180
  contextFileName = contextFileName.toLowerCase();
182
- var migration = new Migration();
183
- var contextInstance = null;
181
+ const _migration = new Migration();
182
+ let contextInstance = null;
184
183
  try{
185
- var files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
186
- var file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
184
+ const files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
185
+ const file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
187
186
  if(!file){
188
187
  console.log(`Error - Cannot read or find Context snapshot '${contextFileName}_contextSnapShot.json' in '${executedLocation}'.`);
189
188
  return;
190
189
  }
191
- var contextSnapshot;
190
+ let contextSnapshot;
192
191
  try{
193
192
  contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
194
193
  }catch(_){
@@ -204,16 +203,16 @@ program.option('-V', 'output the version');
204
203
  migBase = snapDir;
205
204
  }
206
205
  // Find latest migration file (so we can use its class which extends schema)
207
- var migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
206
+ let migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
208
207
  migrationFiles = (migrationFiles || []).map(f => path.resolve(migBase, f));
209
208
  if(!(migrationFiles && migrationFiles.length)){
210
209
  console.log("Error - Cannot read or find migration file");
211
210
  process.exit(1);
212
211
  }
213
- var mFiles = migrationFiles.slice().sort(function(a, b){
212
+ const mFiles = migrationFiles.slice().sort(function(a, b){
214
213
  return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
215
214
  });
216
- var mFile = mFiles[mFiles.length -1];
215
+ const mFile = mFiles[mFiles.length -1];
217
216
 
218
217
  let ContextCtor;
219
218
  try{
@@ -230,8 +229,8 @@ program.option('-V', 'output the version');
230
229
  }
231
230
 
232
231
  // Use the migration class (extends schema) so createdatabase is available
233
- var MigrationCtor = await __loadUserModule(mFile);
234
- var mig = new MigrationCtor(ContextCtor);
232
+ const MigrationCtor = await __loadUserModule(mFile);
233
+ const mig = new MigrationCtor(ContextCtor);
235
234
  contextInstance = mig._context || mig.context || null;
236
235
 
237
236
  if(typeof mig.createdatabase === 'function'){
@@ -283,18 +282,18 @@ program.option('-V', 'output the version');
283
282
  .command('add-migration <name> <contextFileName>')
284
283
  .alias('am')
285
284
  .action(async function(name, contextFileName){
286
- var executedLocation = process.cwd();
285
+ const executedLocation = process.cwd();
287
286
  contextFileName = contextFileName.toLowerCase();
288
- var migration = new Migration();
287
+ const migration = new Migration();
289
288
  try{
290
289
  // find context file from main folder location
291
- var files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
292
- var file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
290
+ const files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
291
+ const file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
293
292
  if(!file){
294
293
  console.log(`Error - Cannot read or find Context snapshot '${contextFileName}_contextSnapShot.json' in '${executedLocation}'. Run 'masterrecord enable-migrations ${contextFileName}'.`);
295
294
  return;
296
295
  }
297
- var contextSnapshot = null;
296
+ let contextSnapshot = null;
298
297
  try{
299
298
  contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
300
299
  }catch(_){
@@ -345,9 +344,9 @@ program.option('-V', 'output the version');
345
344
  }
346
345
  return;
347
346
  }
348
- var cleanEntities = migration.cleanEntities(contextInstance.__entities);
349
- var seedData = contextInstance.__contextSeedData || {};
350
- var seedConfig = contextInstance.__contextSeedConfig || {};
347
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
348
+ const seedData = contextInstance.__contextSeedData || {};
349
+ const seedConfig = contextInstance.__contextSeedConfig || {};
351
350
 
352
351
  // Skip if no changes between snapshot schema and current entities
353
352
  const has = migration.hasChanges(contextSnapshot.schema || [], cleanEntities || [], seedData);
@@ -356,12 +355,12 @@ program.option('-V', 'output the version');
356
355
  return;
357
356
  }
358
357
 
359
- var newEntity = migration.template(name, contextSnapshot.schema, cleanEntities, seedData, seedConfig, null);
358
+ const newEntity = migration.template(name, contextSnapshot.schema, cleanEntities, seedData, seedConfig, null);
360
359
  if(!fs.existsSync(migBase)){
361
360
  try{ fs.mkdirSync(migBase, { recursive: true }); }catch(_){ /* ignore */ }
362
361
  }
363
- var migrationDate = Date.now();
364
- var outputFile = `${migBase}/${migrationDate}_${name}_migration.js`
362
+ const migrationDate = Date.now();
363
+ const outputFile = `${migBase}/${migrationDate}_${name}_migration.js`
365
364
  fs.writeFile(outputFile, newEntity, 'utf8', function (err) {
366
365
  if (err) {
367
366
  console.log("--- Error running cammand, re-run command add-migration ---- ", err);
@@ -381,15 +380,15 @@ program.option('-V', 'output the version');
381
380
  .alias('ud')
382
381
  .description('Apply pending migrations to database - up method call')
383
382
  .action(async function(contextFileName){
384
- var executedLocation = process.cwd();
383
+ const executedLocation = process.cwd();
385
384
  contextFileName = contextFileName.toLowerCase();
386
- var migration = new Migration();
387
- var contextInstance = null;
385
+ const migration = new Migration();
386
+ let contextInstance = null;
388
387
  try{
389
388
  console.log(`\n🔍 Searching for context snapshot '${contextFileName}_contextSnapShot.json'...`);
390
389
  // find context snapshot (cwd-based glob)
391
- var files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
392
- var file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
390
+ const files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
391
+ const file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
393
392
 
394
393
  if(!file){
395
394
  console.error(`\n❌ Error - Cannot find Context snapshot file`);
@@ -401,7 +400,7 @@ program.option('-V', 'output the version');
401
400
 
402
401
  console.log(`✓ Found snapshot: ${file}`);
403
402
 
404
- var contextSnapshot;
403
+ let contextSnapshot;
405
404
  try{
406
405
  contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
407
406
  }catch(err){
@@ -421,7 +420,7 @@ program.option('-V', 'output the version');
421
420
  }
422
421
 
423
422
  console.log(`\n🔍 Searching for migration files in: ${migBase}`);
424
- var migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
423
+ let migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
425
424
  migrationFiles = (migrationFiles || []).map(f => path.resolve(migBase, f));
426
425
 
427
426
  if(!(migrationFiles && migrationFiles.length)){
@@ -435,13 +434,13 @@ program.option('-V', 'output the version');
435
434
  // Then run EVERY pending migration in order, not just the last one —
436
435
  // the old behavior silently skipped earlier pending migrations when a
437
436
  // user had stacked multiple add-migration calls before deploying.
438
- var mFiles = migrationFiles.slice().sort(function(a, b){
437
+ const mFiles = migrationFiles.slice().sort(function(a, b){
439
438
  return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
440
439
  });
441
440
  console.log(`✓ Found ${mFiles.length} migration file(s)`);
442
441
 
443
442
  console.log(`\n🔍 Loading Context file from: ${contextAbs}`);
444
- var ContextCtor;
443
+ let ContextCtor;
445
444
  try{
446
445
  ContextCtor = await __loadUserModule(contextAbs);
447
446
  }catch(err){
@@ -505,7 +504,7 @@ program.option('-V', 'output the version');
505
504
  }
506
505
 
507
506
  console.log(`\n🔍 Loading entities from context...`);
508
- var cleanEntities = migration.cleanEntities(contextInstance.__entities);
507
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
509
508
  console.log(`✓ Found ${cleanEntities.length} entity/entities`);
510
509
 
511
510
  if(cleanEntities.length === 0){
@@ -521,7 +520,7 @@ program.option('-V', 'output the version');
521
520
  // migration, so there's no historical per-migration tableObj.
522
521
  // Idempotent helpers (createTable checks tableExists; addColumn
523
522
  // no-ops on undefined `table.col`) make this safe in practice.
524
- var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
523
+ const tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
525
524
 
526
525
  // Bootstrap the migrations tracking table, then filter out any
527
526
  // migrations already applied so re-running update-database is a
@@ -565,7 +564,7 @@ program.option('-V', 'output the version');
565
564
  }
566
565
 
567
566
  console.log(`\n💾 Updating snapshot...`);
568
- var snap = {
567
+ const snap = {
569
568
  file : contextAbs,
570
569
  executedLocation : executedLocation,
571
570
  context : contextInstance,
@@ -607,18 +606,18 @@ program.option('-V', 'output the version');
607
606
  .alias('udd')
608
607
  .description('Run the latest migration down method for the given context')
609
608
  .action(async function(contextFileName){
610
- var executedLocation = process.cwd();
609
+ const executedLocation = process.cwd();
611
610
  contextFileName = contextFileName.toLowerCase();
612
- var migration = new Migration();
611
+ const migration = new Migration();
613
612
  var contextInstance = null;
614
613
  try{
615
- var files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
616
- var file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
614
+ const files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
615
+ const file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
617
616
  if(!file){
618
617
  console.log(`Error - Cannot read or find Context snapshot '${contextFileName}_contextSnapShot.json' in '${executedLocation}'.`);
619
618
  return;
620
619
  }
621
- var contextSnapshot;
620
+ let contextSnapshot;
622
621
  try{
623
622
  contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
624
623
  }catch(_){
@@ -628,7 +627,7 @@ program.option('-V', 'output the version');
628
627
  const snapDir = path.dirname(file);
629
628
  const contextAbs = path.resolve(snapDir, contextSnapshot.contextLocation || '');
630
629
  const migBase = path.resolve(snapDir, contextSnapshot.migrationFolder || '.');
631
- var migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
630
+ let migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
632
631
  migrationFiles = (migrationFiles || []).map(f => path.resolve(migBase, f));
633
632
  if(!(migrationFiles && migrationFiles.length)){
634
633
  console.log("Error - Cannot read or find migration file");
@@ -636,7 +635,7 @@ program.option('-V', 'output the version');
636
635
  }
637
636
  // Sort so we can find the latest APPLIED migration (not just the
638
637
  // latest on disk) using the tracking table.
639
- var mFiles = migrationFiles.slice().sort(function(a, b){
638
+ const mFiles = migrationFiles.slice().sort(function(a, b){
640
639
  return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
641
640
  });
642
641
 
@@ -674,8 +673,8 @@ program.option('-V', 'output the version');
674
673
  }
675
674
  return;
676
675
  }
677
- var cleanEntities = migration.cleanEntities(contextInstance.__entities);
678
- var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
676
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
677
+ const tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
679
678
 
680
679
  // Roll back the most recently APPLIED migration. Falls back to the
681
680
  // latest migration file on disk if the tracking table is missing or
@@ -696,8 +695,8 @@ program.option('-V', 'output the version');
696
695
  console.log(`⚠️ No applied-migration record found; falling back to latest file on disk: ${rollbackName}`);
697
696
  }
698
697
 
699
- var MigCtor = await __loadUserModule(rollbackFile);
700
- var migInstance = new MigCtor(ContextCtor);
698
+ const MigCtor = await __loadUserModule(rollbackFile);
699
+ const migInstance = new MigCtor(ContextCtor);
701
700
  if(typeof migInstance.down === 'function'){
702
701
  await migInstance.down(tableObj);
703
702
  await __removeMigrationApplied(contextInstance, rollbackName);
@@ -706,7 +705,7 @@ program.option('-V', 'output the version');
706
705
  }
707
706
 
708
707
  // Update snapshot
709
- var snap = {
708
+ const snap = {
710
709
  file : contextAbs,
711
710
  executedLocation : executedLocation,
712
711
  context : contextInstance,
@@ -731,19 +730,19 @@ program.option('-V', 'output the version');
731
730
  .alias('udr')
732
731
  .description('Apply pending migrations to database - up method call')
733
732
  .action(async function(contextFileName){
734
- var executedLocation = process.cwd();
733
+ const executedLocation = process.cwd();
735
734
  contextFileName = contextFileName.toLowerCase();
736
- var migration = new Migration();
735
+ const migration = new Migration();
737
736
  var contextInstance = null;
738
737
  try{
739
738
  // find context snapshot (cwd-based glob)
740
- var files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
741
- var file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
739
+ const files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
740
+ const file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
742
741
  if(!file){
743
742
  console.log(`Error - Cannot read or find Context snapshot '${contextFileName}_contextSnapShot.json' in '${executedLocation}'.`);
744
743
  return;
745
744
  }
746
- var contextSnapshot;
745
+ let contextSnapshot;
747
746
  try{
748
747
  contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
749
748
  }catch(_){
@@ -753,14 +752,14 @@ program.option('-V', 'output the version');
753
752
  const snapDir = path.dirname(file);
754
753
  const contextAbs = path.resolve(snapDir, contextSnapshot.contextLocation || '');
755
754
  const migBase = path.resolve(snapDir, contextSnapshot.migrationFolder || '.');
756
- var migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
755
+ let migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
757
756
  migrationFiles = (migrationFiles || []).map(f => path.resolve(migBase, f));
758
757
  if(!(migrationFiles && migrationFiles.length)){
759
758
  console.log("Error - Cannot read or find migration file");
760
759
  return;
761
760
  }
762
761
  // organize by time using filename timestamp or file mtime
763
- var mFiles = migrationFiles.slice().sort(function(a, b){
762
+ const mFiles = migrationFiles.slice().sort(function(a, b){
764
763
  return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
765
764
  });
766
765
  let ContextCtor;
@@ -793,12 +792,12 @@ program.option('-V', 'output the version');
793
792
  }
794
793
  return;
795
794
  }
796
- var cleanEntities = migration.cleanEntities(contextInstance.__entities);
795
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
797
796
  for (let i = 0; i < mFiles.length; i++) {
798
- var migFile = mFiles[i];
799
- var migrationProjectFile = await __loadUserModule(migFile);
800
- var newMigrationProjectInstance = new migrationProjectFile(ContextCtor);
801
- var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
797
+ const migFile = mFiles[i];
798
+ const migrationProjectFile = await __loadUserModule(migFile);
799
+ const newMigrationProjectInstance = new migrationProjectFile(ContextCtor);
800
+ const tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
802
801
  await newMigrationProjectInstance.up(tableObj);
803
802
  }
804
803
  const snap = {
@@ -826,27 +825,27 @@ program.option('-V', 'output the version');
826
825
  .alias('gm')
827
826
  .description('Get a list of migration file names using the context')
828
827
  .action(function(contextFileName){
829
- var executedLocation = process.cwd();
828
+ const executedLocation = process.cwd();
830
829
  contextFileName = contextFileName.toLowerCase();
831
- var files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
832
- var file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
830
+ const files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
831
+ const file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
833
832
  if(!file){
834
833
  console.log(`Error - Cannot read or find Context snapshot '${contextFileName}_contextSnapShot.json' in '${executedLocation}'.`);
835
834
  return;
836
835
  }
837
- var contextSnapshot;
836
+ let contextSnapshot;
838
837
  try{
839
838
  contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
840
839
  }catch(_){
841
840
  console.log(`Error - Cannot read context snapshot at '${file}'.`);
842
841
  return;
843
842
  }
844
- var migrationFiles = globSync(`**/*_migration.js`, { cwd: contextSnapshot.migrationFolder, dot: true, windowsPathsNoEscape: true });
843
+ const migrationFiles = globSync(`**/*_migration.js`, { cwd: contextSnapshot.migrationFolder, dot: true, windowsPathsNoEscape: true });
845
844
  if(!(migrationFiles && migrationFiles.length)){
846
845
  console.log("No migration files found.");
847
846
  return;
848
847
  }
849
- var sorted = migrationFiles.slice().sort((a,b) => __getMigrationTimestamp(path.resolve(contextSnapshot.migrationFolder, a)) - __getMigrationTimestamp(path.resolve(contextSnapshot.migrationFolder, b)));
848
+ const sorted = migrationFiles.slice().sort((a,b) => __getMigrationTimestamp(path.resolve(contextSnapshot.migrationFolder, a)) - __getMigrationTimestamp(path.resolve(contextSnapshot.migrationFolder, b)));
850
849
  // Print relative names for readability
851
850
  for(const f of sorted){
852
851
  console.log(path.basename(f));
@@ -860,31 +859,31 @@ program.option('-V', 'output the version');
860
859
  .description('Apply pending migrations to database - down method call')
861
860
  .action(async function(migrationFileName){
862
861
  // this will call all the down methods until it gets to the one your looking for. First it needs to validate that there is such a file.
863
- var executedLocation = process.cwd();
864
- var migration = new Migration();
862
+ const executedLocation = process.cwd();
863
+ const migration = new Migration();
865
864
  var contextInstance = null;
866
865
  try{
867
866
  // Accept either a bare filename or a path; normalize to basename
868
- var targetName = path.basename(migrationFileName);
867
+ const targetName = path.basename(migrationFileName);
869
868
 
870
869
  // Locate the target migration file anywhere under the current folder
871
- var targetMatches = globSync(`**/${targetName}`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true });
870
+ const targetMatches = globSync(`**/${targetName}`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true });
872
871
  if(!(targetMatches && targetMatches.length)){
873
872
  console.log(`Error - Cannot read or find migration file '${targetName}' in '${executedLocation}'.`);
874
873
  return;
875
874
  }
876
- var targetFilePath = path.resolve(executedLocation, targetMatches[0]);
877
- var migrationFolder = path.dirname(targetFilePath);
875
+ const targetFilePath = path.resolve(executedLocation, targetMatches[0]);
876
+ const migrationFolder = path.dirname(targetFilePath);
878
877
 
879
878
  // Find the context snapshot within the same migrations folder
880
- var snapshotMatches = globSync(`**/*_contextSnapShot.json`, { cwd: migrationFolder, dot: true, windowsPathsNoEscape: true });
881
- var snapshotFile = snapshotMatches && snapshotMatches[0] ? path.resolve(migrationFolder, snapshotMatches[0]) : null;
879
+ const snapshotMatches = globSync(`**/*_contextSnapShot.json`, { cwd: migrationFolder, dot: true, windowsPathsNoEscape: true });
880
+ const snapshotFile = snapshotMatches && snapshotMatches[0] ? path.resolve(migrationFolder, snapshotMatches[0]) : null;
882
881
  if(!snapshotFile){
883
882
  console.log("Error - Cannot read or find Context snapshot in migration folder.");
884
883
  return;
885
884
  }
886
885
 
887
- var contextSnapshot;
886
+ let contextSnapshot;
888
887
  try{
889
888
  contextSnapshot = JSON.parse(fs.readFileSync(snapshotFile, 'utf8'));
890
889
  }catch(_){
@@ -893,25 +892,30 @@ program.option('-V', 'output the version');
893
892
  }
894
893
 
895
894
  // Get all migration files in this folder
896
- var allMigrationFiles = globSync(`**/*_migration.js`, { cwd: migrationFolder, dot: true, windowsPathsNoEscape: true });
895
+ const allMigrationFiles = globSync(`**/*_migration.js`, { cwd: migrationFolder, dot: true, windowsPathsNoEscape: true });
897
896
  if(!(allMigrationFiles && allMigrationFiles.length)){
898
897
  console.log("Error - Cannot read or find migration file");
899
898
  return;
900
899
  }
901
900
 
902
901
  // Sort chronologically
903
- var sorted = allMigrationFiles.slice().sort(function(a, b){
902
+ const sorted = allMigrationFiles.slice().sort(function(a, b){
904
903
  return __getMigrationTimestamp(path.resolve(migrationFolder, a)) - __getMigrationTimestamp(path.resolve(migrationFolder, b));
905
904
  });
906
905
 
907
906
  // Find target index by basename match
908
- var targetIndex = sorted.findIndex(function(f){ return path.basename(f) === targetName; });
907
+ const targetIndex = sorted.findIndex(function(f){ return path.basename(f) === targetName; });
909
908
  if(targetIndex === -1){
910
909
  console.log(`Error - Target migration '${targetName}' not found.`);
911
910
  return;
912
911
  }
913
912
 
914
- // Prepare context and table object
913
+ // Prepare context and table object.
914
+ // Resolve the Context file path from the snapshot (relative to the
915
+ // snapshot's directory) — this was previously referenced as `contextAbs`
916
+ // without being defined in this handler, throwing ReferenceError on the
917
+ // first use below and breaking the rollback-to-target command.
918
+ const contextAbs = path.resolve(path.dirname(snapshotFile), contextSnapshot.contextLocation || '');
915
919
  let ContextCtor;
916
920
  try{
917
921
  ContextCtor = await __loadUserModule(contextAbs);
@@ -942,14 +946,14 @@ program.option('-V', 'output the version');
942
946
  }
943
947
  return;
944
948
  }
945
- var cleanEntities = migration.cleanEntities(contextInstance.__entities);
946
- var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
949
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
950
+ const tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
947
951
 
948
952
  // Roll back (down) all migrations newer than the target (i.e., strictly after targetIndex)
949
- for (var i = sorted.length - 1; i > targetIndex; i--) {
950
- var migFile = path.resolve(migrationFolder, sorted[i]);
951
- var MigCtor = await __loadUserModule(migFile);
952
- var migInstance = new MigCtor(ContextCtor);
953
+ for (let i = sorted.length - 1; i > targetIndex; i--) {
954
+ const migFile = path.resolve(migrationFolder, sorted[i]);
955
+ const MigCtor = await __loadUserModule(migFile);
956
+ const migInstance = new MigCtor(ContextCtor);
953
957
  if(typeof migInstance.down === 'function'){
954
958
  await migInstance.down(tableObj);
955
959
  } else {
@@ -958,7 +962,7 @@ program.option('-V', 'output the version');
958
962
  }
959
963
 
960
964
  // Update snapshot
961
- var snap = {
965
+ const snap = {
962
966
  file : contextAbs,
963
967
  executedLocation : executedLocation,
964
968
  context : contextInstance,
@@ -983,15 +987,15 @@ program.option('-V', 'output the version');
983
987
  .alias('ama')
984
988
  .description('Create a migration with the given name for all detected contexts')
985
989
  .action(async function(name){
986
- var executedLocation = process.cwd();
987
- var contextInstances = [];
990
+ const executedLocation = process.cwd();
991
+ const contextInstances = [];
988
992
  try{
989
- var snapshotFiles = globSync('**/*_contextSnapShot.json', { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
993
+ const snapshotFiles = globSync('**/*_contextSnapShot.json', { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
990
994
  if(!(snapshotFiles && snapshotFiles.length)){
991
995
  console.log('No context snapshots found. Run enable-migrations-all first.');
992
996
  return;
993
997
  }
994
- var created = 0;
998
+ let created = 0;
995
999
  for(const snapRel of snapshotFiles){
996
1000
  try{
997
1001
  const snapFile = path.resolve(executedLocation, snapRel);
@@ -1018,22 +1022,22 @@ program.option('-V', 'output the version');
1018
1022
  console.error(` Details: ${err.message}`);
1019
1023
  continue;
1020
1024
  }
1021
- var migration = new Migration();
1022
- var cleanEntities = migration.cleanEntities(contextInstance.__entities);
1023
- var seedData = contextInstance.__contextSeedData || {};
1024
- var seedConfig = contextInstance.__contextSeedConfig || {};
1025
+ const migration = new Migration();
1026
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
1027
+ const seedData = contextInstance.__contextSeedData || {};
1028
+ const seedConfig = contextInstance.__contextSeedConfig || {};
1025
1029
  // If no changes, skip with message
1026
1030
  const has = migration.hasChanges(cs.schema || [], cleanEntities || [], seedData);
1027
1031
  if(!has){
1028
1032
  console.log(`No changes detected for ${path.basename(contextAbs)}. Skipping.`);
1029
1033
  continue;
1030
1034
  }
1031
- var newEntity = migration.template(name, cs.schema, cleanEntities, seedData, seedConfig, null);
1035
+ const newEntity = migration.template(name, cs.schema, cleanEntities, seedData, seedConfig, null);
1032
1036
  if(!fs.existsSync(migBase)){
1033
1037
  try{ fs.mkdirSync(migBase, { recursive: true }); }catch(_){ /* ignore */ }
1034
1038
  }
1035
- var migrationDate = Date.now();
1036
- var outputFile = path.join(migBase, `${migrationDate}_${name}_migration.js`);
1039
+ const migrationDate = Date.now();
1040
+ const outputFile = path.join(migBase, `${migrationDate}_${name}_migration.js`);
1037
1041
  fs.writeFileSync(outputFile, newEntity, 'utf8');
1038
1042
  console.log(`Created migration '${path.basename(outputFile)}' for ${path.basename(contextAbs)}`);
1039
1043
  created++;
@@ -1068,17 +1072,17 @@ program.option('-V', 'output the version');
1068
1072
  .alias('uda')
1069
1073
  .description('Scan the project for *Context.js files and run update-database on each')
1070
1074
  .action(async function(){
1071
- var executedLocation = process.cwd();
1072
- var contextInstances = [];
1075
+ const executedLocation = process.cwd();
1076
+ const contextInstances = [];
1073
1077
  try{
1074
1078
  // Find all context snapshots and run update per snapshot (avoids unrelated framework contexts)
1075
- var snapshotFiles = globSync('**/*_contextSnapShot.json', { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
1079
+ const snapshotFiles = globSync('**/*_contextSnapShot.json', { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
1076
1080
  if(!(snapshotFiles && snapshotFiles.length)){
1077
1081
  console.log('No context snapshots found. Run enable-migrations for each context first.');
1078
1082
  return;
1079
1083
  }
1080
1084
  // Group snapshots by context name (case-insensitive) and pick best per group
1081
- var groups = {};
1085
+ const groups = {};
1082
1086
  for(const snapRel of snapshotFiles){
1083
1087
  const snapFile = path.resolve(executedLocation, snapRel);
1084
1088
  let cs;
@@ -1101,22 +1105,22 @@ program.option('-V', 'output the version');
1101
1105
  groups[ctxName].push({ snapFile, snapDir, cs, ctxName, migs, contextAbs, migBase });
1102
1106
  }
1103
1107
 
1104
- var migration = new Migration();
1105
- var ctxNames = Object.keys(groups);
1108
+ const migration = new Migration();
1109
+ const ctxNames = Object.keys(groups);
1106
1110
  for(const name of ctxNames){
1107
1111
  try{
1108
- var list = groups[name];
1112
+ const list = groups[name];
1109
1113
  // Prefer entries that actually have migration files
1110
- var withMigs = list.filter(e => e.migs && e.migs.length > 0);
1111
- var entry = withMigs.length ? withMigs[withMigs.length - 1] : list[0];
1114
+ const withMigs = list.filter(e => e.migs && e.migs.length > 0);
1115
+ const entry = withMigs.length ? withMigs[withMigs.length - 1] : list[0];
1112
1116
  if(!(entry.migs && entry.migs.length)){
1113
1117
  console.log(`Skipping ${entry.ctxName}: no migration files found.`);
1114
1118
  continue;
1115
1119
  }
1116
- var mFiles = entry.migs.slice().sort(function(a, b){
1120
+ const mFiles = entry.migs.slice().sort(function(a, b){
1117
1121
  return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
1118
1122
  });
1119
- var mFile = mFiles[mFiles.length - 1];
1123
+ const mFile = mFiles[mFiles.length - 1];
1120
1124
 
1121
1125
  var ContextCtor;
1122
1126
  try{
@@ -1135,12 +1139,12 @@ program.option('-V', 'output the version');
1135
1139
  console.error(` Details: ${err.message}`);
1136
1140
  continue;
1137
1141
  }
1138
- var migrationProjectFile = await __loadUserModule(mFile);
1139
- var newMigrationProjectInstance = new migrationProjectFile(ContextCtor);
1140
- var cleanEntities = migration.cleanEntities(contextInstance.__entities);
1141
- var tableObj = migration.buildUpObject(entry.cs.schema, cleanEntities);
1142
+ const migrationProjectFile = await __loadUserModule(mFile);
1143
+ const newMigrationProjectInstance = new migrationProjectFile(ContextCtor);
1144
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
1145
+ const tableObj = migration.buildUpObject(entry.cs.schema, cleanEntities);
1142
1146
  await newMigrationProjectInstance.up(tableObj);
1143
- var snap = {
1147
+ const snap = {
1144
1148
  file : entry.contextAbs,
1145
1149
  executedLocation : executedLocation,
1146
1150
  context : contextInstance,
@@ -1179,17 +1183,17 @@ program.option('-V', 'output the version');
1179
1183
  .alias('ema')
1180
1184
  .description('Enable migrations for all detected MasterRecord Context files')
1181
1185
  .action(function(){
1182
- var executedLocation = process.cwd();
1186
+ const executedLocation = process.cwd();
1183
1187
  try{
1184
1188
  // Find candidate Context files
1185
- var candidates = globSync('**/*Context.js', { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true }) || [];
1189
+ const candidates = globSync('**/*Context.js', { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true }) || [];
1186
1190
  if(!(candidates && candidates.length)){
1187
1191
  console.log('No Context files found.');
1188
1192
  return;
1189
1193
  }
1190
- var seen = new Set();
1191
- var enabled = 0;
1192
- var migration = new Migration();
1194
+ const seen = new Set();
1195
+ let enabled = 0;
1196
+ const migration = new Migration();
1193
1197
  for(const rel of candidates){
1194
1198
  try{
1195
1199
  const abs = path.resolve(executedLocation, rel);
@@ -1205,7 +1209,7 @@ program.option('-V', 'output the version');
1205
1209
  if(seen.has(key)){ continue; }
1206
1210
  seen.add(key);
1207
1211
  // Create snapshot relative to the context file directory
1208
- var snap = {
1212
+ const snap = {
1209
1213
  file : abs,
1210
1214
  executedLocation : executedLocation,
1211
1215
  contextEntities : [],