masterrecord 1.1.4 → 1.1.6

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