@rpcbase/migrations 0.10.0 → 0.12.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/dist/history.d.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  import { Db } from 'mongodb';
2
- import { MigrationHistoryRecord } from './types';
2
+ import { CompiledMigration, CompiledMigrationRegistry, MigrationDatabaseTarget, MigrationHistoryRecord, MigrationScope } from './types';
3
3
  export declare const MIGRATIONS_COLLECTION = "rbmigrations";
4
4
  export declare const readMigrationHistory: (db: Db) => Promise<MigrationHistoryRecord[]>;
5
+ export declare const isKnownMigrationHistoryChecksum: (migration: CompiledMigration, checksum: string) => boolean;
6
+ export declare const validateMigrationHistoryRecord: (migration: CompiledMigration, record: MigrationHistoryRecord, targetScope: MigrationScope) => string[];
7
+ export declare const normalizeLegacyMigrationHistory: (registry: CompiledMigrationRegistry, target: MigrationDatabaseTarget, options: {
8
+ assertOwned(): Promise<void>;
9
+ signal?: AbortSignal;
10
+ }) => Promise<number>;
5
11
  //# sourceMappingURL=history.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"history.d.ts","sourceRoot":"","sources":["../src/history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAA;AAEjC,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAGrD,eAAO,MAAM,qBAAqB,iBAAiB,CAAA;AAEnD,eAAO,MAAM,oBAAoB,GAAU,IAAI,EAAE,KAAG,OAAO,CAAC,sBAAsB,EAAE,CAItE,CAAA"}
1
+ {"version":3,"file":"history.d.ts","sourceRoot":"","sources":["../src/history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAU,MAAM,SAAS,CAAA;AAGzC,OAAO,KAAK,EACV,iBAAiB,EACjB,yBAAyB,EACzB,uBAAuB,EACvB,sBAAsB,EACtB,cAAc,EACf,MAAM,SAAS,CAAA;AAGhB,eAAO,MAAM,qBAAqB,iBAAiB,CAAA;AAEnD,eAAO,MAAM,oBAAoB,GAAU,IAAI,EAAE,KAAG,OAAO,CAAC,sBAAsB,EAAE,CAItE,CAAA;AAEd,eAAO,MAAM,+BAA+B,GAC1C,WAAW,iBAAiB,EAC5B,UAAU,MAAM,KACf,OAAiG,CAAA;AAEpG,eAAO,MAAM,8BAA8B,GACzC,WAAW,iBAAiB,EAC5B,QAAQ,sBAAsB,EAC9B,aAAa,cAAc,KAC1B,MAAM,EAwBR,CAAA;AAiBD,eAAO,MAAM,+BAA+B,GAC1C,UAAU,yBAAyB,EACnC,QAAQ,uBAAuB,EAC/B,SAAS;IACP,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB,KACA,OAAO,CAAC,MAAM,CA+BhB,CAAA"}
package/dist/index.js CHANGED
@@ -281,30 +281,50 @@ var defineMigrationSource = (source) => {
281
281
  ids.add(migration.id);
282
282
  previousId = migration.id;
283
283
  }
284
+ for (const id of [...Object.keys(source.checksums ?? {}), ...Object.keys(source.legacyHistoryChecksums ?? {})]) if (!ids.has(id)) throw new Error(`Migration source ${name} declares a checksum for unknown migration ${id}`);
285
+ for (const [id, checksums] of Object.entries(source.legacyHistoryChecksums ?? {})) if (!Array.isArray(checksums)) throw new Error(`Migration ${name}:${id} has invalid legacy history checksums`);
284
286
  return Object.freeze({
285
287
  ...source,
286
288
  name,
287
289
  migrations: Object.freeze([...source.migrations]),
288
290
  resourceSnapshots: Object.freeze([...source.resourceSnapshots ?? []]),
289
- checksums: Object.freeze({ ...source.checksums ?? {} })
291
+ checksums: Object.freeze({ ...source.checksums ?? {} }),
292
+ legacyHistoryChecksums: Object.freeze(Object.fromEntries(Object.entries(source.legacyHistoryChecksums ?? {}).map(([id, checksums]) => [id, Object.freeze([...checksums])])))
290
293
  });
291
294
  };
292
295
  var resolveDependencyId = (source, dependency) => dependency.includes(":") ? dependency : `${source}:${dependency}`;
296
+ var historyChecksum = (migration, source, codeChecksum) => canonicalChecksum({
297
+ id: migration.id,
298
+ source,
299
+ scope: migration.scope,
300
+ phase: migration.phase,
301
+ dependsOn: migration.dependsOn ?? [],
302
+ resources: migration.resources ?? null,
303
+ codeChecksum
304
+ });
305
+ var computeLegacyMigrationHistoryChecksum = (migration, source) => historyChecksum(migration, source, canonicalChecksum(migration.up.toString()));
293
306
  var migrationChecksum = (migration, source) => {
294
- const injectedChecksum = migration.__rpcbaseIntegrity ?? source.checksums?.[migration.id];
295
- if (injectedChecksum !== void 0 && (typeof injectedChecksum !== "string" || !/^[a-f0-9]{64}$/.test(injectedChecksum))) throw new Error(`Migration ${source.name}:${migration.id} has an invalid source checksum`);
296
- const codeChecksum = injectedChecksum ?? canonicalChecksum(migration.up.toString());
307
+ const injectedChecksum = migration.__rpcbaseIntegrity;
308
+ const declaredChecksum = source.checksums?.[migration.id];
309
+ for (const checksum of [injectedChecksum, declaredChecksum]) {
310
+ if (checksum === void 0) continue;
311
+ if (typeof checksum !== "string" || !/^[a-f0-9]{64}$/.test(checksum)) throw new Error(`Migration ${source.name}:${migration.id} has an invalid source checksum`);
312
+ }
313
+ if (injectedChecksum !== void 0 && declaredChecksum !== void 0 && injectedChecksum !== declaredChecksum) throw new Error(`Migration ${source.name}:${migration.id} differs from its declared source checksum`);
314
+ const sourceIntegrity = typeof injectedChecksum === "string" ? injectedChecksum : declaredChecksum;
315
+ const checksum = sourceIntegrity ? historyChecksum(migration, source.name, sourceIntegrity) : computeLegacyMigrationHistoryChecksum(migration, source.name);
316
+ const legacyHistoryChecksums = source.legacyHistoryChecksums?.[migration.id] ?? [];
317
+ const uniqueLegacyHistoryChecksums = /* @__PURE__ */ new Set();
318
+ for (const legacyChecksum of legacyHistoryChecksums) {
319
+ if (typeof legacyChecksum !== "string" || !/^[a-f0-9]{64}$/.test(legacyChecksum)) throw new Error(`Migration ${source.name}:${migration.id} has an invalid legacy history checksum`);
320
+ if (legacyChecksum === checksum || uniqueLegacyHistoryChecksums.has(legacyChecksum)) throw new Error(`Migration ${source.name}:${migration.id} has a duplicate legacy history checksum`);
321
+ uniqueLegacyHistoryChecksums.add(legacyChecksum);
322
+ }
297
323
  return {
298
- checksum: canonicalChecksum({
299
- id: migration.id,
300
- source: source.name,
301
- scope: migration.scope,
302
- phase: migration.phase,
303
- dependsOn: migration.dependsOn ?? [],
304
- resources: migration.resources ?? null,
305
- codeChecksum
306
- }),
307
- sealed: Boolean(injectedChecksum)
324
+ checksum,
325
+ ...sourceIntegrity ? { sourceIntegrity } : {},
326
+ legacyHistoryChecksums: Object.freeze([...uniqueLegacyHistoryChecksums]),
327
+ sealed: Boolean(sourceIntegrity)
308
328
  };
309
329
  };
310
330
  var sortMigrations = (migrations) => {
@@ -362,7 +382,7 @@ var compileMigrationRegistry = (inputSources, options = {}) => {
362
382
  if (!snapshots.has(migration.resources.after)) throw new Error(`Missing after resource snapshot for ${source.name}:${migration.id}`);
363
383
  }
364
384
  const integrity = migrationChecksum(migration, source);
365
- if (options.requireSealed && !integrity.sealed) throw new Error(`Migration ${source.name}:${migration.id} has no build-injected checksum`);
385
+ if (options.requireSealed && !integrity.sealed) throw new Error(`Migration ${source.name}:${migration.id} has no sealed source checksum`);
366
386
  const compiled = Object.freeze({
367
387
  ...migration,
368
388
  qualifiedId: `${source.name}:${migration.id}`,
@@ -371,6 +391,8 @@ var compileMigrationRegistry = (inputSources, options = {}) => {
371
391
  sourcePriority: priority,
372
392
  dependsOn: Object.freeze((migration.dependsOn ?? []).map((id) => resolveDependencyId(source.name, id))),
373
393
  checksum: integrity.checksum,
394
+ ...integrity.sourceIntegrity ? { sourceIntegrity: integrity.sourceIntegrity } : {},
395
+ legacyHistoryChecksums: integrity.legacyHistoryChecksums,
374
396
  sealed: integrity.sealed
375
397
  });
376
398
  migrations.push(compiled);
@@ -706,7 +728,7 @@ var wait = async (milliseconds, signal) => {
706
728
  signal.throwIfAborted();
707
729
  };
708
730
  var createMigrationHelpers = (db, signal, options = {}) => {
709
- const searchTimeoutMs = options.searchTimeoutMs ?? 10 * 6e4;
731
+ const searchTimeoutMs = options.searchTimeoutMs ?? 6e5;
710
732
  const searchPollIntervalMs = options.searchPollIntervalMs ?? 1e3;
711
733
  const ensureCollection = async (name, collectionOptions = {}) => {
712
734
  signal.throwIfAborted();
@@ -889,6 +911,54 @@ var readMigrationHistory = async (db) => db.collection(MIGRATIONS_COLLECTION).fi
889
911
  source: 1,
890
912
  sourcePosition: 1
891
913
  }).toArray();
914
+ var isKnownMigrationHistoryChecksum = (migration, checksum) => checksum === migration.checksum || migration.legacyHistoryChecksums.includes(checksum);
915
+ var validateMigrationHistoryRecord = (migration, record, targetScope) => {
916
+ const errors = [];
917
+ if (!isKnownMigrationHistoryChecksum(migration, record.checksum)) errors.push(`${migration.qualifiedId}: checksum differs`);
918
+ if (record.source !== migration.source) errors.push(`${migration.qualifiedId}: source differs`);
919
+ if (record.sourcePosition !== migration.sourcePosition) errors.push(`${migration.qualifiedId}: source position differs`);
920
+ if (record.scope !== migration.scope) errors.push(`${migration.qualifiedId}: scope differs`);
921
+ if (migration.scope !== targetScope) errors.push(`${migration.qualifiedId}: migration history is stored in a ${targetScope} database`);
922
+ if (record.phase !== migration.phase) errors.push(`${migration.qualifiedId}: phase differs`);
923
+ if (![
924
+ "running",
925
+ "applied",
926
+ "failed"
927
+ ].includes(record.status)) errors.push(`${migration.qualifiedId}: history status is invalid`);
928
+ const expectedBeforeHash = migration.resources?.before ?? void 0;
929
+ const expectedAfterHash = migration.resources?.after;
930
+ if (record.resourcesBeforeHash !== expectedBeforeHash) errors.push(`${migration.qualifiedId}: resource before checksum differs`);
931
+ if (record.resourcesAfterHash !== expectedAfterHash) errors.push(`${migration.qualifiedId}: resource after checksum differs`);
932
+ return errors;
933
+ };
934
+ var checksumNormalizationFilter = (migration, record) => ({
935
+ _id: migration.qualifiedId,
936
+ checksum: record.checksum,
937
+ source: migration.source,
938
+ sourcePosition: migration.sourcePosition,
939
+ scope: migration.scope,
940
+ phase: migration.phase,
941
+ status: record.status,
942
+ resourcesBeforeHash: migration.resources?.before ?? { $exists: false },
943
+ resourcesAfterHash: migration.resources?.after ?? { $exists: false }
944
+ });
945
+ var normalizeLegacyMigrationHistory = async (registry, target, options) => {
946
+ const history = await readMigrationHistory(target.db);
947
+ const collection = target.db.collection(MIGRATIONS_COLLECTION);
948
+ let normalized = 0;
949
+ for (const record of history) {
950
+ options.signal?.throwIfAborted();
951
+ const migration = registry.migrationsById.get(record._id);
952
+ if (!migration || record.checksum === migration.checksum || !migration.legacyHistoryChecksums.includes(record.checksum) || validateMigrationHistoryRecord(migration, record, target.scope).length > 0) continue;
953
+ await options.assertOwned();
954
+ if ((await collection.updateOne(checksumNormalizationFilter(migration, record), { $set: { checksum: migration.checksum } }, { writeConcern: { w: "majority" } })).matchedCount === 1) {
955
+ normalized += 1;
956
+ continue;
957
+ }
958
+ if ((await collection.findOne({ _id: migration.qualifiedId }))?.checksum !== migration.checksum) throw new MigrationIntegrityError(`${migration.qualifiedId}: history state changed while normalizing its legacy checksum`);
959
+ }
960
+ return normalized;
961
+ };
892
962
  //#endregion
893
963
  //#region src/databaseProvider.ts
894
964
  var normalizeAppName = (value) => {
@@ -907,7 +977,7 @@ var createMigrationDatabaseProvider = (options) => {
907
977
  const appName = normalizeAppName(options.appName);
908
978
  const globalDbName = `${appName}-global-db`;
909
979
  const tenantCollection = options.tenantCollection?.trim() || "rbtenants";
910
- const initializingTenantStaleAfterMs = options.initializingTenantStaleAfterMs ?? 5 * 6e4;
980
+ const initializingTenantStaleAfterMs = options.initializingTenantStaleAfterMs ?? 3e5;
911
981
  if (!Number.isFinite(initializingTenantStaleAfterMs) || initializingTenantStaleAfterMs < 0) throw new Error("initializingTenantStaleAfterMs must be a non-negative finite number");
912
982
  const staleInitializingFilter = () => ({
913
983
  provisioningStatus: "initializing",
@@ -965,25 +1035,6 @@ var toPlanItem = (migration) => ({
965
1035
  dependsOn: migration.dependsOn
966
1036
  });
967
1037
  var historyById = (history) => new Map(history.map((record) => [record._id, record]));
968
- var validateKnownRecord = (migration, record, targetScope) => {
969
- const errors = [];
970
- if (record.checksum !== migration.checksum) errors.push(`${migration.qualifiedId}: checksum differs`);
971
- if (record.source !== migration.source) errors.push(`${migration.qualifiedId}: source differs`);
972
- if (record.sourcePosition !== migration.sourcePosition) errors.push(`${migration.qualifiedId}: source position differs`);
973
- if (record.scope !== migration.scope) errors.push(`${migration.qualifiedId}: scope differs`);
974
- if (migration.scope !== targetScope) errors.push(`${migration.qualifiedId}: migration history is stored in a ${targetScope} database`);
975
- if (record.phase !== migration.phase) errors.push(`${migration.qualifiedId}: phase differs`);
976
- if (![
977
- "running",
978
- "applied",
979
- "failed"
980
- ].includes(record.status)) errors.push(`${migration.qualifiedId}: history status is invalid`);
981
- const expectedBeforeHash = migration.resources?.before ?? void 0;
982
- const expectedAfterHash = migration.resources?.after;
983
- if (record.resourcesBeforeHash !== expectedBeforeHash) errors.push(`${migration.qualifiedId}: resource before checksum differs`);
984
- if (record.resourcesAfterHash !== expectedAfterHash) errors.push(`${migration.qualifiedId}: resource after checksum differs`);
985
- return errors;
986
- };
987
1038
  var validateSourcePrefixes = (registry, scope, records) => {
988
1039
  const errors = [];
989
1040
  for (const source of registry.sources) {
@@ -1023,7 +1074,7 @@ var planMigrationTarget = async (registry, target, options = {}) => {
1023
1074
  for (const record of history) {
1024
1075
  const migration = registry.migrationsById.get(record._id);
1025
1076
  if (migration) {
1026
- integrityErrors.push(...validateKnownRecord(migration, record, target.scope));
1077
+ integrityErrors.push(...validateMigrationHistoryRecord(migration, record, target.scope));
1027
1078
  continue;
1028
1079
  }
1029
1080
  unknown.push(record._id);
@@ -1454,6 +1505,12 @@ var runMigrations = async (registry, provider, options = {}) => {
1454
1505
  tenantId: options.tenantId,
1455
1506
  signal
1456
1507
  });
1508
+ await runWithConcurrency(targets, concurrency, async (target) => {
1509
+ await normalizeLegacyMigrationHistory(registry, target, {
1510
+ assertOwned: lock.assertOwned,
1511
+ signal
1512
+ });
1513
+ });
1457
1514
  const globalTarget = targets.find((target) => target.scope === "global");
1458
1515
  if (!globalTarget) throw new Error("Migration provider did not return a global database");
1459
1516
  let globalApplied = /* @__PURE__ */ new Set();
@@ -1692,6 +1749,6 @@ var testSingleMigration = async (options) => {
1692
1749
  }
1693
1750
  };
1694
1751
  //#endregion
1695
- export { MIGRATIONS_COLLECTION, MIGRATION_LOCKS_COLLECTION, MigrationIntegrityError, MigrationLockLostError, MigrationLockUnavailableError, acquireMigrationLock, assertMigrationsCurrent, canonicalChecksum, canonicalStringify, collectMigrationTargets, compileMigrationRegistry, computeMigrationIntegrity, createMigrationDatabaseProvider, createMigrationHelpers, createMigrationIntegrityPlugin, defineMigration, defineMigrationSource, defineMongoResources, diffMongoResources, filterMongoResources, getExpectedResources, getMigrationDatabaseName, initializeTenantMigrations, inspectMongoResources, mergeMongoResources, planMigrationTarget, planMigrations, readMigrationHistory, reconcileRuntimeIndexOptions, runMigrations, sha256, testMigrationRegistry, testSingleMigration };
1752
+ export { MIGRATIONS_COLLECTION, MIGRATION_LOCKS_COLLECTION, MigrationIntegrityError, MigrationLockLostError, MigrationLockUnavailableError, acquireMigrationLock, assertMigrationsCurrent, canonicalChecksum, canonicalStringify, collectMigrationTargets, compileMigrationRegistry, computeLegacyMigrationHistoryChecksum, computeMigrationIntegrity, createMigrationDatabaseProvider, createMigrationHelpers, createMigrationIntegrityPlugin, defineMigration, defineMigrationSource, defineMongoResources, diffMongoResources, filterMongoResources, getExpectedResources, getMigrationDatabaseName, initializeTenantMigrations, inspectMongoResources, isKnownMigrationHistoryChecksum, mergeMongoResources, normalizeLegacyMigrationHistory, planMigrationTarget, planMigrations, readMigrationHistory, reconcileRuntimeIndexOptions, runMigrations, sha256, testMigrationRegistry, testSingleMigration, validateMigrationHistoryRecord };
1696
1753
 
1697
1754
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["createHash","BSON","normalizeSerializedValue","value","Array","isArray","map","Object","fromEntries","entries","Record","filter","item","undefined","sort","left","right","localeCompare","key","normalizeValue","EJSON","serialize","relaxed","canonicalStringify","JSON","stringify","sha256","Uint8Array","update","digest","canonicalChecksum","Document","canonicalChecksum","canonicalStringify","MigrationScope","MongoCollectionResource","MongoCollectionResourceInput","MongoCollectionValidatorResource","MongoCollectionValidatorResourceInput","MongoIndexResource","MongoIndexResourceInput","MongoResources","MongoResourcesInput","MongoSearchIndexResource","MongoSearchIndexResourceInput","scopes","Set","runtimeIndexOptions","assertName","value","label","normalized","trim","Error","includes","assertScope","scope","has","String","copyDocument","undefined","structuredClone","collectionIdentity","resource","name","indexIdentity","collection","validatorIdentity","uniqueResources","resources","T","identity","seen","Map","key","canonical","previous","get","set","normalizeCollection","options","normalizeIndex","Object","keys","length","optionNames","unsupportedRuntimeOption","runtimeOptions","find","overlappingRuntimeOption","normalizeSearchIndex","definition","normalizeValidator","validator","validationLevel","validationAction","sortByIdentity","sort","left","right","localeCompare","checksumInput","Omit","collections","map","indexes","entries","searchIndexes","collectionValidators","defineMongoResources","input","freeze","checksum","filterMongoResources","filter","mergeMongoResources","resourceSets","validators","merge","target","comparisonValue","values","canonicalStringify","MongoCollectionResource","MongoCollectionValidatorResource","MongoIndexResource","MongoResourceChange","MongoResources","MongoResourcesDiff","MongoSearchIndexResource","collectionIdentity","resource","scope","name","indexIdentity","collection","validatorIdentity","indexComparisonValue","key","Object","entries","runtimeOptions","keys","sort","diffSet","before","T","after","identity","comparisonValue","beforeById","Map","map","afterById","ids","Set","flatMap","id","previous","get","next","kind","diffMongoResources","collections","indexes","searchIndexes","collectionValidators","changes","changed","length","requiresContract","some","change","canonicalChecksum","defineMongoResources","filterMongoResources","mergeMongoResources","CompiledMigration","CompiledMigrationRegistry","CompiledMigrationSource","DefineMigrationRegistryOptions","MigrationDefinition","MigrationScope","MigrationSource","MongoResources","migrationIdPattern","sourceNamePattern","scopeRank","Record","global","tenant","filesystem","scopes","Object","keys","bootstrapIntegrity","operation","protocolVersion","revision","hasResources","resources","collections","length","indexes","searchIndexes","collectionValidators","bootstrapId","scope","runResourceBootstrap","helpers","Error","index","after","options","unique","sparseFilter","sparse","$or","key","map","field","$exists","undefined","partialFilter","partialFilterExpression","filter","$and","duplicates","findDuplicateKeys","collection","collation","name","JSON","stringify","reconcileResources","createResourceBootstraps","source","baseline","flatMap","id","migrations","some","migration","freeze","phase","const","before","checksum","up","__rpcbaseIntegrity","assertMigration","test","defineMigration","TCheckpoint","dependsOn","defineMigrationSource","trim","previousId","ids","Set","has","add","resourceSnapshots","checksums","resolveDependencyId","dependency","includes","migrationChecksum","sealed","injectedChecksum","codeChecksum","toString","Boolean","sortMigrations","byId","Map","qualifiedId","visiting","visited","ordered","visit","dependencyId","get","sourcePosition","delete","push","sort","left","right","scopeDifference","sourceDifference","sourcePriority","compileMigrationRegistry","inputSources","sourceNames","compiledSources","priority","inputSource","entries","snapshots","ReturnType","snapshot","normalized","set","currentResources","migrationDefinitions","sourceMigrations","integrity","requireSealed","compiled","previousChecksum","previousResources","item","transition","beforeResources","currentForScope","previousSnapshot","migrationsById","sources","Document","ignoredIndexOptions","Set","falseDefaultOptions","collationDefaults","Map","isDocument","value","Boolean","Array","isArray","hasDirection","key","direction","Object","values","some","normalizeCollation","fromEntries","entries","filter","name","option","get","normalizeWeights","weight","Number","normalizeIndexOptions","options","normalized","undefined","has","collation","weights","keys","length","default_language","language_override","textIndexVersion","normalizeIndexKey","declaredKey","hasTextRepresentation","actualTextFields","actualTextFieldSet","declaredTextFields","map","orderedTextFields","includes","sort","flatMap","field","NormalizedIndexDefinition","normalizeIndexDefinition","Db","Document","canonicalStringify","normalizeIndexDefinition","MongoResourceDivergence","MongoResources","selectKeys","document","expected","Object","fromEntries","keys","map","key","normalizeValidatorDefinition","validator","undefined","validationLevel","validationAction","same","left","right","message","collection","resource","detail","InspectMongoResourcesOptions","signal","AbortSignal","requireSearchReady","inspectMongoResources","db","resources","options","Promise","divergences","throwIfAborted","collectionNames","Set","collections","name","indexes","searchIndexes","collectionValidators","listedCollections","size","listCollections","$in","nameOnly","toArray","collectionsByName","Map","actual","get","push","code","scope","expectedOptions","actualOptions","indexesByCollection","has","listIndexes","set","find","index","actualDefinition","expectedDefinition","runtimeOptions","runtimeOptionNames","fixedOptions","indexOptions","entries","filter","runtimeOnly","expectedValidator","actualValidator","searchIndexesByCollection","Error","listSearchIndexes","error","String","latestDefinition","definition","status","queryable","Db","Document","canonicalStringify","normalizeIndexDefinition","MigrationHelpers","MongoResources","namespaceExists","error","value","code","codeName","namespaceMissing","indexMissing","same","left","right","wait","milliseconds","signal","AbortSignal","Promise","throwIfAborted","resolve","reject","timer","setTimeout","removeEventListener","onAbort","clearTimeout","reason","addEventListener","once","CreateMigrationHelpersOptions","searchTimeoutMs","searchPollIntervalMs","createMigrationHelpers","db","options","ensureCollection","name","collectionOptions","existing","listCollections","nameOnly","hasNext","createCollection","dropCollectionIfExists","dropCollection","ensureIndex","collectionName","key","indexOptions","collection","indexes","listIndexes","toArray","find","index","actualDefinition","expectedDefinition","Error","createIndex","dropIndexIfExists","dropIndex","findDuplicateKeys","duplicateOptions","id","Object","keys","map","path","pipeline","filter","push","$match","$group","_id","count","$sum","$gt","$limit","limit","documents","aggregate","collation","document","Number","waitForSearchIndex","deadline","Date","now","listSearchIndexes","status","queryable","ensureSearchIndex","definition","createSearchIndex","latestDefinition","updateSearchIndex","dropSearchIndexIfExists","length","dropSearchIndex","setCollectionValidator","validator","validatorOptions","command","collMod","helpers","reconcileResources","resources","collections","collectionValidators","validationLevel","validationAction","runtimeOptions","searchIndexes","reconcileRuntimeIndexOptions","actual","candidate","runtimeOptionNames","Set","fixedOptions","fromEntries","entries","has","differs","some","Db","MigrationHistoryRecord","MIGRATIONS_COLLECTION","readMigrationHistory","db","Promise","collection","find","sort","source","sourcePosition","toArray","Db","MongoClient","MigrationDatabaseProvider","normalizeAppName","value","appName","trim","Error","test","normalizeTenantId","tenantId","CreateMigrationDatabaseProviderOptions","client","tenantCollection","initializingTenantStaleAfterMs","filesystemRequired","signal","AbortSignal","Promise","createMigrationDatabaseProvider","options","globalDbName","Number","isFinite","staleInitializingFilter","provisioningStatus","$or","provisioningStartedAt","$exists","$lte","Date","now","global","db","tenantIds","throwIfAborted","documents","collection","find","projection","sort","toArray","Set","flatMap","document","tenantExists","normalized","tenant","findOne","_id","Boolean","activateRecoveredTenant","result","updateOne","$set","provisionedAt","$unset","provisioningError","matchedCount","filesystem","getMigrationDatabaseName","databaseName","filterMongoResources","mergeMongoResources","inspectMongoResources","readMigrationHistory","CompiledMigration","CompiledMigrationRegistry","MigrationDatabasePlan","MigrationDatabaseProvider","MigrationDatabaseTarget","MigrationHistoryRecord","MigrationPlan","MigrationPlanItem","MigrationPlanOptions","MigrationScope","MongoResources","neverAbortedSignal","AbortController","signal","toPlanItem","migration","id","qualifiedId","checksum","source","scope","phase","dependsOn","historyById","history","Map","map","record","_id","validateKnownRecord","targetScope","errors","push","sourcePosition","const","includes","status","expectedBeforeHash","resources","before","undefined","expectedAfterHash","after","resourcesBeforeHash","resourcesAfterHash","validateSourcePrefixes","registry","records","ReadonlyMap","sources","gap","migrations","filter","item","applied","get","getExpectedResources","snapshots","snapshot","resourceSnapshots","Error","name","planMigrationTarget","target","options","Pick","Promise","throwIfAborted","db","relevant","integrityErrors","unknown","migrationsById","allowedNewerMigration","allowNewerApplied","pending","has","running","failed","expectedResources","resourceDivergences","length","requireSearchReady","database","databaseName","tenantId","collectMigrationTargets","provider","global","targets","tenantIds","tenantExists","tenant","filesystem","required","filesystemRequired","planMigrations","databases","protocolVersion","registryChecksum","hasPending","some","hasErrors","divergence","code","randomUUID","Db","Document","MigrationLockLostError","MigrationLockUnavailableError","MIGRATION_LOCKS_COLLECTION","MigrationLockDocument","_id","owner","runId","fence","expiresAt","Date","MigrationLock","signal","AbortSignal","assertOwned","Promise","release","AcquireMigrationLockOptions","lockId","leaseMs","heartbeatMs","isDuplicateKey","error","Boolean","code","acquireMigrationLock","db","options","trim","Error","collection","document","updateOne","$setOnInsert","upsert","writeConcern","w","findOneAndUpdate","$expr","$or","$lte","$ifNull","$eq","$set","$add","acquiredAt","heartbeatAt","$dateAdd","startDate","unit","amount","returnDocument","abortController","AbortController","state","heartbeatTimer","ReturnType","setTimeout","heartbeatPromise","lose","reason","cause","undefined","clearTimeout","abort","owned","findOne","$gt","projection","heartbeat","result","modifiedCount","scheduleHeartbeat","catch","finally","unref","releasedAt","$unset","Collection","MigrationIntegrityError","MigrationLockLostError","createMigrationHelpers","reconcileRuntimeIndexOptions","MIGRATIONS_COLLECTION","readMigrationHistory","inspectMongoResources","acquireMigrationLock","MigrationLock","filterMongoResources","collectMigrationTargets","getExpectedResources","planMigrationTarget","planMigrations","CompiledMigration","CompiledMigrationRegistry","MigrationCheckpoint","MigrationDatabasePlan","MigrationDatabaseProvider","MigrationDatabaseTarget","MigrationHistoryRecord","MigrationPlan","MigrationScope","MongoResources","RunMigrationsOptions","errorMessage","error","message","Error","String","slice","combineSignals","signals","Array","AbortSignal","active","filter","signal","Boolean","length","AbortController","any","assertPlanCanRun","plan","retrying","running","failed","errors","integrityErrors","resourceDivergences","divergence","code","map","database","join","recordForMigration","migration","lock","attempt","release","_id","qualifiedId","checksum","source","sourcePosition","scope","phase","status","resources","before","resourcesBeforeHash","resourcesAfterHash","after","runId","fence","startedAt","Date","heartbeatAt","startMigration","collection","Promise","assertOwned","existing","findOne","record","insertOne","writeConcern","w","_recordId","recordUpdates","result","findOneAndUpdate","$in","$set","checkpoint","undefined","$unset","appliedAt","durationMs","returnDocument","createCheckpoint","T","value","update","next","clear","updateOne","matchedCount","save","markFailed","markApplied","getTime","getExpectedTransitionSnapshot","snapshots","ReadonlyMap","snapshot","get","applyMigration","registry","target","throwIfAborted","db","sources","find","item","name","resourceTransition","resourceSnapshots","up","tenantId","helpers","history","hypothetical","const","expected","divergences","requireSearchReady","catch","sourcePredecessorsApplied","applied","ReadonlySet","migrations","candidate","every","has","runTarget","options","earlierScopeDependencyApplied","dependency","Set","some","expectedResources","migrationsToRun","dependenciesReady","dependencyId","dependsOn","migrationsById","ready","add","runWithConcurrency","values","concurrency","action","nextIndex","failure","workers","from","Math","min","index","all","runMigrations","provider","Number","isInteger","globalDb","global","lockId","leaseMs","heartbeatMs","targets","globalTarget","globalApplied","initializeTenant","globalPlan","pending","tenantApplied","Map","tenantTargets","set","filesystemTargets","appliedForTenant","activatedRecoveredTenant","activateRecoveredTenant","keys","tenantPlans","databases","current","initializeTenantMigrations","Omit","MigrationIntegrityError","planMigrations","CompiledMigrationRegistry","MigrationDatabaseProvider","MigrationPlan","MigrationPlanOptions","assertMigrationsCurrent","registry","provider","options","Promise","plan","errors","database","databases","pending","length","push","running","failed","integrityErrors","map","error","resourceDivergences","filter","divergence","code","message","join","existsSync","readFileSync","dirname","extname","isAbsolute","resolve","ImportType","initSync","parse","canonicalChecksum","sha256","relativeImportPattern","migrationCallPattern","incompleteCollectionMigrationPattern","typeOnlyImportPattern","resolveLocalImport","importer","specifier","base","candidates","resolved","find","candidate","Error","collectIntegrityFiles","entry","rootDir","files","Map","visiting","Set","filePath","has","startsWith","add","source","imports","imported","t","Dynamic","DynamicSourcePhase","DynamicDeferPhase","ImportMeta","declaration","slice","ss","se","test","n","delete","set","ComputeMigrationIntegrityOptions","computeMigrationIntegrity","options","entryPath","entries","map","path","length","checksum","sort","left","right","localeCompare","MigrationIntegrityPluginOptions","createMigrationIntegrityPlugin","name","enforce","const","transform","code","id","cleanId","split","integrity","transformed","replace","match","JSON","stringify","randomUUID","Db","MongoClient","assertMigrationsCurrent","createMigrationDatabaseProvider","createMigrationHelpers","MIGRATIONS_COLLECTION","compileMigrationRegistry","defineMigration","defineMigrationSource","runMigrations","CompiledMigrationRegistry","MigrationContext","MigrationDefinition","MigrationHistoryRecord","MigrationScope","testAppNamePattern","testTenantIdPattern","createTestAppName","replaceAll","slice","assertTestAppName","appName","test","Error","databaseNames","tenantId","TestMigrationRegistryOptions","client","registry","signal","AbortSignal","TestMigrationRegistryResult","checkpointRecoveryAttempt","testMigrationRegistry","options","Promise","recoveryAppName","databases","provider","filesystemRequired","globalDb","global","collection","insertOne","provisioningStatus","concurrency","recoveryMigration","id","scope","phase","up","checkpoint","value","save","recoveryRegistry","name","migrations","recoveryProvider","then","error","message","recoveryDb","history","findOne","_id","status","attempt","all","map","databaseName","startsWith","db","dropDatabase","TestSingleMigrationOptions","migration","TCheckpoint","prepare","verify","testSingleMigration","controller","AbortController","any","checkpointValue","context","clear","undefined","helpers","abort"],"sources":["../src/canonical.ts","../src/resources.ts","../src/diffResources.ts","../src/registry.ts","../src/indexDefinition.ts","../src/inspectResources.ts","../src/helpers.ts","../src/errors.ts","../src/history.ts","../src/databaseProvider.ts","../src/planner.ts","../src/lock.ts","../src/runner.ts","../src/assertCurrent.ts","../src/integrity.ts","../src/testHarness.ts"],"sourcesContent":["import { createHash } from \"node:crypto\"\n\nimport { BSON } from \"mongodb\"\n\n\nconst normalizeSerializedValue = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalizeSerializedValue)\n\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .filter(([, item]) => item !== undefined)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, item]) => [key, normalizeSerializedValue(item)]),\n )\n }\n\n return value\n}\n\nconst normalizeValue = (value: unknown): unknown =>\n normalizeSerializedValue(BSON.EJSON.serialize(value, { relaxed: false }))\n\nexport const canonicalStringify = (value: unknown): string => JSON.stringify(normalizeValue(value))\n\nexport const sha256 = (value: string | Uint8Array): string =>\n createHash(\"sha256\").update(value).digest(\"hex\")\n\nexport const canonicalChecksum = (value: unknown): string => sha256(canonicalStringify(value))\n","import type { Document } from \"mongodb\"\n\nimport { canonicalChecksum, canonicalStringify } from \"./canonical\"\nimport type {\n MigrationScope,\n MongoCollectionResource,\n MongoCollectionResourceInput,\n MongoCollectionValidatorResource,\n MongoCollectionValidatorResourceInput,\n MongoIndexResource,\n MongoIndexResourceInput,\n MongoResources,\n MongoResourcesInput,\n MongoSearchIndexResource,\n MongoSearchIndexResourceInput,\n} from \"./types\"\n\n\nconst scopes = new Set<MigrationScope>([\"global\", \"tenant\", \"filesystem\"])\nconst runtimeIndexOptions = new Set([\"expireAfterSeconds\"])\n\nconst assertName = (value: string, label: string): string => {\n const normalized = value.trim()\n if (!normalized) throw new Error(`${label} is required`)\n if (normalized.includes(\"\\0\")) throw new Error(`${label} cannot contain a null byte`)\n return normalized\n}\n\nconst assertScope = (scope: MigrationScope): void => {\n if (!scopes.has(scope)) throw new Error(`Invalid migration scope: ${String(scope)}`)\n}\n\nconst copyDocument = (value: Document | undefined): Document | undefined => {\n if (!value) return undefined\n return structuredClone(value)\n}\n\nconst collectionIdentity = (resource: MongoCollectionResource): string =>\n `${resource.scope}:${resource.name}`\n\nconst indexIdentity = (resource: MongoIndexResource | MongoSearchIndexResource): string =>\n `${resource.scope}:${resource.collection}:${resource.name}`\n\nconst validatorIdentity = (resource: MongoCollectionValidatorResource): string =>\n `${resource.scope}:${resource.collection}`\n\nconst uniqueResources = <T>(resources: readonly T[], identity: (resource: T) => string, label: string): readonly T[] => {\n const seen = new Map<string, string>()\n\n for (const resource of resources) {\n const key = identity(resource)\n const canonical = canonicalStringify(resource)\n const previous = seen.get(key)\n if (previous && previous !== canonical) throw new Error(`Conflicting ${label} resource: ${key}`)\n if (previous) throw new Error(`Duplicate ${label} resource: ${key}`)\n seen.set(key, canonical)\n }\n\n return resources\n}\n\nconst normalizeCollection = (resource: MongoCollectionResourceInput): MongoCollectionResource => {\n assertScope(resource.scope)\n return {\n scope: resource.scope,\n name: assertName(resource.name, \"Collection name\"),\n ...(resource.options ? { options: copyDocument(resource.options) } : {}),\n }\n}\n\nconst normalizeIndex = (resource: MongoIndexResourceInput): MongoIndexResource => {\n assertScope(resource.scope)\n if (Object.keys(resource.key).length === 0) throw new Error(\"Index key cannot be empty\")\n const optionNames = new Set(Object.keys(resource.options ?? {}))\n const unsupportedRuntimeOption = Object.keys(resource.runtimeOptions ?? {})\n .find((name) => !runtimeIndexOptions.has(name))\n if (unsupportedRuntimeOption) {\n throw new Error(`Unsupported runtime-managed index option: ${unsupportedRuntimeOption}`)\n }\n const overlappingRuntimeOption = Object.keys(resource.runtimeOptions ?? {})\n .find((name) => optionNames.has(name))\n if (overlappingRuntimeOption) {\n throw new Error(`Index option ${overlappingRuntimeOption} cannot be both fixed and runtime-managed`)\n }\n return {\n scope: resource.scope,\n collection: assertName(resource.collection, \"Index collection\"),\n name: assertName(resource.name, \"Index name\"),\n key: structuredClone(resource.key),\n ...(resource.options ? { options: copyDocument(resource.options) } : {}),\n ...(resource.runtimeOptions ? { runtimeOptions: copyDocument(resource.runtimeOptions) } : {}),\n }\n}\n\nconst normalizeSearchIndex = (resource: MongoSearchIndexResourceInput): MongoSearchIndexResource => {\n assertScope(resource.scope)\n return {\n scope: resource.scope,\n collection: assertName(resource.collection, \"Search index collection\"),\n name: assertName(resource.name, \"Search index name\"),\n definition: structuredClone(resource.definition),\n }\n}\n\nconst normalizeValidator = (\n resource: MongoCollectionValidatorResourceInput,\n): MongoCollectionValidatorResource => {\n assertScope(resource.scope)\n return {\n scope: resource.scope,\n collection: assertName(resource.collection, \"Validator collection\"),\n validator: structuredClone(resource.validator),\n ...(resource.validationLevel ? { validationLevel: resource.validationLevel } : {}),\n ...(resource.validationAction ? { validationAction: resource.validationAction } : {}),\n }\n}\n\nconst sortByIdentity = <T>(resources: readonly T[], identity: (resource: T) => string): readonly T[] =>\n [...resources].sort((left, right) => identity(left).localeCompare(identity(right)))\n\nconst checksumInput = (resources: Omit<MongoResources, \"checksum\">) => ({\n collections: resources.collections.map((resource) => ({\n ...resource,\n options: resource.options ?? {},\n })),\n indexes: resources.indexes.map((resource) => ({\n ...resource,\n key: Object.entries(resource.key),\n options: resource.options ?? {},\n ...(resource.runtimeOptions\n ? { runtimeOptions: Object.keys(resource.runtimeOptions).sort() }\n : {}),\n })),\n searchIndexes: resources.searchIndexes,\n collectionValidators: resources.collectionValidators,\n})\n\nexport const defineMongoResources = (input: MongoResourcesInput = {}): MongoResources => {\n const collections = sortByIdentity(\n uniqueResources((input.collections ?? []).map(normalizeCollection), collectionIdentity, \"collection\"),\n collectionIdentity,\n )\n const indexes = sortByIdentity(\n uniqueResources((input.indexes ?? []).map(normalizeIndex), indexIdentity, \"index\"),\n indexIdentity,\n )\n const searchIndexes = sortByIdentity(\n uniqueResources((input.searchIndexes ?? []).map(normalizeSearchIndex), indexIdentity, \"Search index\"),\n indexIdentity,\n )\n const collectionValidators = sortByIdentity(\n uniqueResources(\n (input.collectionValidators ?? []).map(normalizeValidator),\n validatorIdentity,\n \"collection validator\",\n ),\n validatorIdentity,\n )\n const resources = { collections, indexes, searchIndexes, collectionValidators }\n\n return Object.freeze({\n checksum: canonicalChecksum(checksumInput(resources)),\n ...resources,\n })\n}\n\nexport const filterMongoResources = (resources: MongoResources, scope: MigrationScope): MongoResources =>\n defineMongoResources({\n collections: resources.collections.filter((resource) => resource.scope === scope),\n indexes: resources.indexes.filter((resource) => resource.scope === scope),\n searchIndexes: resources.searchIndexes.filter((resource) => resource.scope === scope),\n collectionValidators: resources.collectionValidators.filter((resource) => resource.scope === scope),\n })\n\nexport const mergeMongoResources = (resourceSets: readonly MongoResources[]): MongoResources => {\n const collections = new Map<string, MongoCollectionResource>()\n const indexes = new Map<string, MongoIndexResource>()\n const searchIndexes = new Map<string, MongoSearchIndexResource>()\n const validators = new Map<string, MongoCollectionValidatorResource>()\n\n const merge = <T>(\n target: Map<string, T>,\n resource: T,\n identity: (value: T) => string,\n label: string,\n comparisonValue: (value: T) => unknown = (value) => value,\n ) => {\n const key = identity(resource)\n const previous = target.get(key)\n if (previous\n && canonicalStringify(comparisonValue(previous)) !== canonicalStringify(comparisonValue(resource))) {\n throw new Error(`Conflicting ${label} resource across migration sources: ${key}`)\n }\n target.set(key, resource)\n }\n\n for (const resources of resourceSets) {\n for (const resource of resources.collections) merge(collections, resource, collectionIdentity, \"collection\")\n for (const resource of resources.indexes) {\n merge(indexes, resource, indexIdentity, \"index\", (value) => ({\n ...value,\n key: Object.entries(value.key),\n }))\n }\n for (const resource of resources.searchIndexes) merge(searchIndexes, resource, indexIdentity, \"Search index\")\n for (const resource of resources.collectionValidators) {\n merge(validators, resource, validatorIdentity, \"collection validator\")\n }\n }\n\n return defineMongoResources({\n collections: [...collections.values()],\n indexes: [...indexes.values()],\n searchIndexes: [...searchIndexes.values()],\n collectionValidators: [...validators.values()],\n })\n}\n","import { canonicalStringify } from \"./canonical\"\nimport type {\n MongoCollectionResource,\n MongoCollectionValidatorResource,\n MongoIndexResource,\n MongoResourceChange,\n MongoResources,\n MongoResourcesDiff,\n MongoSearchIndexResource,\n} from \"./types\"\n\n\nconst collectionIdentity = (resource: MongoCollectionResource): string =>\n `${resource.scope}:${resource.name}`\n\nconst indexIdentity = (resource: MongoIndexResource | MongoSearchIndexResource): string =>\n `${resource.scope}:${resource.collection}:${resource.name}`\n\nconst validatorIdentity = (resource: MongoCollectionValidatorResource): string =>\n `${resource.scope}:${resource.collection}`\n\nconst indexComparisonValue = (resource: MongoIndexResource) => ({\n ...resource,\n key: Object.entries(resource.key),\n runtimeOptions: Object.keys(resource.runtimeOptions ?? {}).sort(),\n})\n\nconst diffSet = <T>(\n before: readonly T[],\n after: readonly T[],\n identity: (resource: T) => string,\n comparisonValue: (resource: T) => unknown = (resource) => resource,\n): readonly MongoResourceChange<T>[] => {\n const beforeById = new Map(before.map((resource) => [identity(resource), resource]))\n const afterById = new Map(after.map((resource) => [identity(resource), resource]))\n const ids = [...new Set([...beforeById.keys(), ...afterById.keys()])].sort()\n\n return ids.flatMap((id): MongoResourceChange<T>[] => {\n const previous = beforeById.get(id)\n const next = afterById.get(id)\n if (!previous && next) return [{ kind: \"added\", after: next }]\n if (previous && !next) return [{ kind: \"removed\", before: previous }]\n if (previous && next\n && canonicalStringify(comparisonValue(previous)) !== canonicalStringify(comparisonValue(next))) {\n return [{ kind: \"changed\", before: previous, after: next }]\n }\n return []\n })\n}\n\nexport const diffMongoResources = (\n before: MongoResources,\n after: MongoResources,\n): MongoResourcesDiff => {\n const collections = diffSet(before.collections, after.collections, collectionIdentity)\n const indexes = diffSet(before.indexes, after.indexes, indexIdentity, indexComparisonValue)\n const searchIndexes = diffSet(before.searchIndexes, after.searchIndexes, indexIdentity)\n const collectionValidators = diffSet(\n before.collectionValidators,\n after.collectionValidators,\n validatorIdentity,\n )\n const changes = [...collections, ...indexes, ...searchIndexes, ...collectionValidators]\n\n return {\n collections,\n indexes,\n searchIndexes,\n collectionValidators,\n changed: changes.length > 0,\n requiresContract: changes.some((change) => change.kind !== \"added\"),\n }\n}\n","import { canonicalChecksum } from \"./canonical\"\nimport { defineMongoResources, filterMongoResources, mergeMongoResources } from \"./resources\"\nimport type {\n CompiledMigration,\n CompiledMigrationRegistry,\n CompiledMigrationSource,\n DefineMigrationRegistryOptions,\n MigrationDefinition,\n MigrationScope,\n MigrationSource,\n MongoResources,\n} from \"./types\"\n\n\nconst migrationIdPattern = /^\\d{8}(?:\\d{6})?-[a-z0-9]+(?:-[a-z0-9]+)*$/\nconst sourceNamePattern = /^(?:@[a-z0-9][a-z0-9._-]*\\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/\nconst scopeRank: Record<MigrationScope, number> = { global: 0, tenant: 1, filesystem: 2 }\nconst scopes = Object.keys(scopeRank) as MigrationScope[]\nconst bootstrapIntegrity = canonicalChecksum({\n operation: \"bootstrap-mongo-resources\",\n protocolVersion: 2,\n revision: 1,\n})\n\nconst hasResources = (resources: MongoResources): boolean => (\n resources.collections.length > 0\n || resources.indexes.length > 0\n || resources.searchIndexes.length > 0\n || resources.collectionValidators.length > 0\n)\n\nconst bootstrapId = (scope: MigrationScope): string => `00000000-bootstrap-${scope}`\n\nconst runResourceBootstrap: MigrationDefinition[\"up\"] = async ({ helpers, resources }) => {\n if (!resources) throw new Error(\"Missing bootstrap resource snapshot\")\n for (const index of resources.after.indexes) {\n if (index.options?.unique !== true) continue\n const sparseFilter = index.options.sparse === true\n ? { $or: Object.keys(index.key).map((field) => ({ [field]: { $exists: true } })) }\n : undefined\n const partialFilter = index.options.partialFilterExpression\n const filter = sparseFilter && partialFilter\n ? { $and: [partialFilter, sparseFilter] }\n : partialFilter ?? sparseFilter\n const duplicates = await helpers.findDuplicateKeys(index.collection, index.key, {\n ...(filter ? { filter } : {}),\n ...(index.options.collation ? { collation: index.options.collation } : {}),\n })\n if (duplicates.length > 0) {\n throw new Error(\n `Cannot create unique index ${index.collection}.${index.name}: duplicate keys found: ${JSON.stringify(duplicates)}`,\n )\n }\n }\n await helpers.reconcileResources(resources.after)\n}\n\nconst createResourceBootstraps = (\n source: MigrationSource,\n baseline: MongoResources,\n): readonly MigrationDefinition[] => scopes.flatMap((scope) => {\n if (!hasResources(filterMongoResources(baseline, scope))) return []\n const id = bootstrapId(scope)\n if (source.migrations.some((migration) => migration.id === id)) {\n throw new Error(`Migration id ${id} is reserved for the ${source.name} resource bootstrap`)\n }\n return [Object.freeze({\n id,\n scope,\n phase: \"expand\" as const,\n resources: Object.freeze({ before: null, after: baseline.checksum }),\n up: runResourceBootstrap,\n __rpcbaseIntegrity: bootstrapIntegrity,\n })]\n})\n\nconst assertMigration = (migration: MigrationDefinition): void => {\n if (!migrationIdPattern.test(migration.id)) {\n throw new Error(`Invalid migration id \"${migration.id}\"`)\n }\n if (!(migration.scope in scopeRank)) throw new Error(`Invalid migration scope for ${migration.id}`)\n if (migration.phase !== \"expand\" && migration.phase !== \"contract\") {\n throw new Error(`Invalid migration phase for ${migration.id}`)\n }\n if (typeof migration.up !== \"function\") throw new Error(`Migration ${migration.id} is missing up()`)\n if (migration.resources && migration.resources.before === migration.resources.after) {\n throw new Error(`Migration ${migration.id} has an unchanged resource transition`)\n }\n}\n\nexport const defineMigration = <TCheckpoint = unknown>(\n migration: MigrationDefinition<TCheckpoint>,\n): MigrationDefinition<TCheckpoint> => {\n assertMigration(migration as MigrationDefinition)\n return Object.freeze({\n ...migration,\n dependsOn: Object.freeze([...(migration.dependsOn ?? [])]),\n ...(migration.resources ? { resources: Object.freeze({ ...migration.resources }) } : {}),\n })\n}\n\nexport const defineMigrationSource = (source: MigrationSource): MigrationSource => {\n const name = source.name.trim()\n if (!sourceNamePattern.test(name)) throw new Error(`Invalid migration source name \"${source.name}\"`)\n if ((source.baseline === undefined) !== (source.resources === undefined)) {\n throw new Error(`Migration source ${name} must declare baseline and resources together`)\n }\n\n let previousId: string | null = null\n const ids = new Set<string>()\n for (const migration of source.migrations) {\n assertMigration(migration)\n if (ids.has(migration.id)) throw new Error(`Duplicate migration id in ${name}: ${migration.id}`)\n if (previousId && migration.id <= previousId) {\n throw new Error(`Migration ids in ${name} must be strictly increasing: ${previousId}, ${migration.id}`)\n }\n ids.add(migration.id)\n previousId = migration.id\n }\n\n return Object.freeze({\n ...source,\n name,\n migrations: Object.freeze([...source.migrations]),\n resourceSnapshots: Object.freeze([...(source.resourceSnapshots ?? [])]),\n checksums: Object.freeze({ ...(source.checksums ?? {}) }),\n })\n}\n\nconst resolveDependencyId = (source: string, dependency: string): string =>\n dependency.includes(\":\") ? dependency : `${source}:${dependency}`\n\nconst migrationChecksum = (\n migration: MigrationDefinition,\n source: MigrationSource,\n): { checksum: string; sealed: boolean } => {\n const injectedChecksum = (\n migration as MigrationDefinition & { __rpcbaseIntegrity?: unknown }\n ).__rpcbaseIntegrity ?? source.checksums?.[migration.id]\n if (injectedChecksum !== undefined\n && (typeof injectedChecksum !== \"string\" || !/^[a-f0-9]{64}$/.test(injectedChecksum))) {\n throw new Error(`Migration ${source.name}:${migration.id} has an invalid source checksum`)\n }\n const codeChecksum = injectedChecksum ?? canonicalChecksum(migration.up.toString())\n return {\n checksum: canonicalChecksum({\n id: migration.id,\n source: source.name,\n scope: migration.scope,\n phase: migration.phase,\n dependsOn: migration.dependsOn ?? [],\n resources: migration.resources ?? null,\n codeChecksum,\n }),\n sealed: Boolean(injectedChecksum),\n }\n}\n\nconst sortMigrations = (migrations: readonly CompiledMigration[]): readonly CompiledMigration[] => {\n const byId = new Map(migrations.map((migration) => [migration.qualifiedId, migration]))\n const visiting = new Set<string>()\n const visited = new Set<string>()\n const ordered: CompiledMigration[] = []\n\n const visit = (migration: CompiledMigration) => {\n if (visited.has(migration.qualifiedId)) return\n if (visiting.has(migration.qualifiedId)) {\n throw new Error(`Cyclic migration dependency involving ${migration.qualifiedId}`)\n }\n\n visiting.add(migration.qualifiedId)\n for (const dependencyId of migration.dependsOn) {\n const dependency = byId.get(dependencyId)\n if (!dependency) throw new Error(`Unknown dependency ${dependencyId} for ${migration.qualifiedId}`)\n if (scopeRank[dependency.scope] > scopeRank[migration.scope]) {\n throw new Error(`${migration.qualifiedId} cannot depend on later scope migration ${dependencyId}`)\n }\n if (dependency.source === migration.source\n && dependency.scope === migration.scope\n && dependency.sourcePosition > migration.sourcePosition) {\n throw new Error(`${migration.qualifiedId} cannot depend on a later migration in its source: ${dependencyId}`)\n }\n visit(dependency)\n }\n visiting.delete(migration.qualifiedId)\n visited.add(migration.qualifiedId)\n ordered.push(migration)\n }\n\n for (const migration of [...migrations].sort((left, right) => {\n const scopeDifference = scopeRank[left.scope] - scopeRank[right.scope]\n if (scopeDifference !== 0) return scopeDifference\n const sourceDifference = left.sourcePriority - right.sourcePriority\n if (sourceDifference !== 0) return sourceDifference\n return left.sourcePosition - right.sourcePosition\n })) visit(migration)\n\n return Object.freeze(ordered)\n}\n\nexport const compileMigrationRegistry = (\n inputSources: readonly MigrationSource[],\n options: DefineMigrationRegistryOptions = {},\n): CompiledMigrationRegistry => {\n const sourceNames = new Set<string>()\n const migrations: CompiledMigration[] = []\n const compiledSources: CompiledMigrationSource[] = []\n\n for (const [priority, inputSource] of inputSources.entries()) {\n const source = defineMigrationSource(inputSource)\n if (sourceNames.has(source.name)) throw new Error(`Duplicate migration source: ${source.name}`)\n sourceNames.add(source.name)\n\n const snapshots = new Map<string, ReturnType<typeof defineMongoResources>>()\n for (const snapshot of [\n ...(source.baseline ? [source.baseline] : []),\n ...(source.resourceSnapshots ?? []),\n ...(source.resources ? [source.resources] : []),\n ]) {\n const normalized = defineMongoResources(snapshot)\n if (normalized.checksum !== snapshot.checksum) {\n throw new Error(`Invalid resource snapshot checksum in ${source.name}: ${snapshot.checksum}`)\n }\n snapshots.set(normalized.checksum, normalized)\n }\n\n const baseline = source.baseline ? snapshots.get(source.baseline.checksum) : undefined\n const currentResources = source.resources ? snapshots.get(source.resources.checksum) : undefined\n const migrationDefinitions = [\n ...(baseline ? createResourceBootstraps(source, baseline) : []),\n ...source.migrations,\n ]\n const sourceMigrations = migrationDefinitions.map((migration, sourcePosition) => {\n if (migration.resources) {\n if (migration.resources.before && !snapshots.has(migration.resources.before)) {\n throw new Error(`Missing before resource snapshot for ${source.name}:${migration.id}`)\n }\n if (!snapshots.has(migration.resources.after)) {\n throw new Error(`Missing after resource snapshot for ${source.name}:${migration.id}`)\n }\n }\n\n const integrity = migrationChecksum(migration, source)\n if (options.requireSealed && !integrity.sealed) {\n throw new Error(`Migration ${source.name}:${migration.id} has no build-injected checksum`)\n }\n const compiled: CompiledMigration = Object.freeze({\n ...migration,\n qualifiedId: `${source.name}:${migration.id}`,\n source: source.name,\n sourcePosition,\n sourcePriority: priority,\n dependsOn: Object.freeze((migration.dependsOn ?? []).map((id) => resolveDependencyId(source.name, id))),\n checksum: integrity.checksum,\n sealed: integrity.sealed,\n })\n migrations.push(compiled)\n return compiled\n })\n\n for (const scope of scopes) {\n let previousChecksum: string | null = null\n let previousResources = defineMongoResources()\n for (const migration of sourceMigrations.filter((item) => item.scope === scope && item.resources)) {\n const transition = migration.resources\n if (!transition) continue\n const beforeResources = transition.before\n ? snapshots.get(transition.before)\n : defineMongoResources()\n if (!beforeResources\n || filterMongoResources(beforeResources, scope).checksum\n !== filterMongoResources(previousResources, scope).checksum) {\n throw new Error(\n `Non-contiguous resource transition for ${migration.qualifiedId}: expected ${previousChecksum ?? \"null\"}`,\n )\n }\n previousChecksum = transition.after\n previousResources = snapshots.get(previousChecksum) ?? defineMongoResources()\n }\n\n const currentForScope = currentResources\n ? filterMongoResources(currentResources, scope)\n : defineMongoResources()\n if (hasResources(currentForScope) || previousChecksum) {\n if (!previousChecksum) throw new Error(`Source ${source.name} has unmanaged ${scope} resources without a migration`)\n const previousSnapshot = snapshots.get(previousChecksum)\n if (!previousSnapshot\n || filterMongoResources(previousSnapshot, scope).checksum !== currentForScope.checksum) {\n throw new Error(`Latest ${scope} resource transition for ${source.name} does not match current resources`)\n }\n }\n }\n\n compiledSources.push(Object.freeze({\n ...source,\n ...(baseline ? { baseline } : {}),\n ...(currentResources ? { resources: currentResources } : {}),\n priority,\n migrations: Object.freeze(sourceMigrations),\n resourceSnapshots: snapshots,\n }))\n }\n\n const ordered = sortMigrations(migrations)\n const migrationsById = new Map<string, CompiledMigration>()\n for (const migration of ordered) {\n if (migrationsById.has(migration.qualifiedId)) throw new Error(`Duplicate migration: ${migration.qualifiedId}`)\n migrationsById.set(migration.qualifiedId, migration)\n }\n\n mergeMongoResources(compiledSources.flatMap((source) => source.resources ? [source.resources] : []))\n\n return Object.freeze({\n protocolVersion: 2,\n sources: Object.freeze(compiledSources),\n migrations: ordered,\n migrationsById,\n checksum: canonicalChecksum(ordered.map((migration) => ({\n id: migration.qualifiedId,\n checksum: migration.checksum,\n }))),\n })\n}\n","import type { Document } from \"mongodb\"\n\n\nconst ignoredIndexOptions = new Set([\"background\", \"key\", \"name\", \"ns\", \"v\"])\nconst falseDefaultOptions = new Set([\"hidden\", \"sparse\", \"unique\"])\nconst collationDefaults = new Map<string, unknown>([\n [\"alternate\", \"non-ignorable\"],\n [\"backwards\", false],\n [\"caseFirst\", \"off\"],\n [\"caseLevel\", false],\n [\"maxVariable\", \"punct\"],\n [\"normalization\", false],\n [\"numericOrdering\", false],\n [\"strength\", 3],\n])\n\nconst isDocument = (value: unknown): value is Document =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst hasDirection = (key: Document, direction: unknown): boolean =>\n Object.values(key).some((value) => value === direction)\n\nconst normalizeCollation = (value: unknown): unknown => {\n if (!isDocument(value)) return value\n return Object.fromEntries(\n Object.entries(value).filter(([name, option]) => (\n name !== \"version\" && collationDefaults.get(name) !== option\n )),\n )\n}\n\nconst normalizeWeights = (value: unknown): unknown => {\n if (!isDocument(value)) return value\n return Object.fromEntries(\n Object.entries(value).filter(([, weight]) => Number(weight) !== 1),\n )\n}\n\nconst normalizeIndexOptions = (options: Document, key: Document): Document => {\n const normalized = Object.fromEntries(\n Object.entries(options).filter(([name, value]) => (\n value !== undefined\n && !ignoredIndexOptions.has(name)\n && !(falseDefaultOptions.has(name) && value === false)\n )),\n )\n if (normalized.collation !== undefined) {\n normalized.collation = normalizeCollation(normalized.collation)\n }\n if (normalized.weights !== undefined) {\n normalized.weights = normalizeWeights(normalized.weights)\n if (isDocument(normalized.weights) && Object.keys(normalized.weights).length === 0) {\n delete normalized.weights\n }\n }\n if (hasDirection(key, \"text\")) {\n if (normalized.default_language === \"english\") delete normalized.default_language\n if (normalized.language_override === \"language\") delete normalized.language_override\n if (Number(normalized.textIndexVersion) === 3) delete normalized.textIndexVersion\n }\n if (hasDirection(key, \"2dsphere\") && Number(normalized[\"2dsphereIndexVersion\"]) === 3) {\n delete normalized[\"2dsphereIndexVersion\"]\n }\n return normalized\n}\n\nconst normalizeIndexKey = (\n key: Document,\n options: Document,\n declaredKey: Document,\n): readonly [string, unknown][] => {\n const entries = Object.entries(key)\n const hasTextRepresentation = entries.some(([name, direction]) => name === \"_fts\" && direction === \"text\")\n && entries.some(([name, direction]) => name === \"_ftsx\" && direction === 1)\n if (!hasTextRepresentation || !isDocument(options.weights)) return entries\n\n const actualTextFields = Object.keys(options.weights)\n const actualTextFieldSet = new Set(actualTextFields)\n const declaredTextFields = Object.entries(declaredKey)\n .filter(([, direction]) => direction === \"text\")\n .map(([name]) => name)\n const orderedTextFields = [\n ...declaredTextFields.filter((name) => actualTextFieldSet.has(name)),\n ...actualTextFields.filter((name) => !declaredTextFields.includes(name)).sort(),\n ]\n\n return entries.flatMap(([name, direction]): [string, unknown][] => {\n if (name === \"_fts\" && direction === \"text\") {\n return orderedTextFields.map((field) => [field, \"text\"])\n }\n if (name === \"_ftsx\" && direction === 1) return []\n return [[name, direction]]\n })\n}\n\nexport type NormalizedIndexDefinition = {\n key: readonly [string, unknown][]\n options: Document\n}\n\nexport const normalizeIndexDefinition = (\n key: Document,\n options: Document = {},\n declaredKey: Document = key,\n): NormalizedIndexDefinition => ({\n key: normalizeIndexKey(key, options, declaredKey),\n options: normalizeIndexOptions(options, key),\n})\n","import type { Db, Document } from \"mongodb\"\n\nimport { canonicalStringify } from \"./canonical\"\nimport { normalizeIndexDefinition } from \"./indexDefinition\"\nimport type {\n MongoResourceDivergence,\n MongoResources,\n} from \"./types\"\n\n\nconst selectKeys = (document: Document | undefined, expected: Document | undefined): Document => {\n if (!expected) return {}\n return Object.fromEntries(\n Object.keys(expected).map((key) => [key, document?.[key]]),\n )\n}\n\nconst normalizeValidatorDefinition = (document: Document | undefined): Document => ({\n ...(document?.validator !== undefined ? { validator: document.validator } : {}),\n ...(document?.validationLevel !== undefined && document.validationLevel !== \"strict\"\n ? { validationLevel: document.validationLevel }\n : {}),\n ...(document?.validationAction !== undefined && document.validationAction !== \"error\"\n ? { validationAction: document.validationAction }\n : {}),\n})\n\nconst same = (left: unknown, right: unknown): boolean =>\n canonicalStringify(left) === canonicalStringify(right)\n\nconst message = (collection: string, resource: string | undefined, detail: string): string =>\n `${collection}${resource ? `.${resource}` : \"\"}: ${detail}`\n\nexport type InspectMongoResourcesOptions = {\n signal?: AbortSignal\n requireSearchReady?: boolean\n}\n\nexport const inspectMongoResources = async (\n db: Db,\n resources: MongoResources,\n options: InspectMongoResourcesOptions = {},\n): Promise<MongoResourceDivergence[]> => {\n const divergences: MongoResourceDivergence[] = []\n const signal = options.signal\n signal?.throwIfAborted()\n\n const collectionNames = new Set([\n ...resources.collections.map((resource) => resource.name),\n ...resources.indexes.map((resource) => resource.collection),\n ...resources.searchIndexes.map((resource) => resource.collection),\n ...resources.collectionValidators.map((resource) => resource.collection),\n ])\n const listedCollections = collectionNames.size > 0\n ? await db.listCollections({ name: { $in: [...collectionNames] } }, { nameOnly: false }).toArray()\n : []\n const collectionsByName = new Map(listedCollections.map((collection) => [collection.name, collection]))\n\n for (const expected of resources.collections) {\n const actual = collectionsByName.get(expected.name)\n if (!actual) {\n divergences.push({\n code: \"missing_collection\",\n scope: expected.scope,\n collection: expected.name,\n message: message(expected.name, undefined, \"managed collection is missing\"),\n })\n continue\n }\n\n const expectedOptions = expected.options ?? {}\n const actualOptions = selectKeys(actual.options, expectedOptions)\n if (!same(actualOptions, expectedOptions)) {\n divergences.push({\n code: \"collection_options_mismatch\",\n scope: expected.scope,\n collection: expected.name,\n expected: expectedOptions,\n actual: actualOptions,\n message: message(expected.name, undefined, \"collection options differ\"),\n })\n }\n }\n\n const indexesByCollection = new Map<string, Document[]>()\n for (const expected of resources.indexes) {\n if (!collectionsByName.has(expected.collection)) {\n divergences.push({\n code: \"missing_index\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n message: message(expected.collection, expected.name, \"index collection is missing\"),\n })\n continue\n }\n\n let indexes = indexesByCollection.get(expected.collection)\n if (!indexes) {\n indexes = await db.collection(expected.collection).listIndexes().toArray()\n indexesByCollection.set(expected.collection, indexes)\n }\n const actual = indexes.find((index) => index.name === expected.name)\n if (!actual) {\n divergences.push({\n code: \"missing_index\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n message: message(expected.collection, expected.name, \"managed index is missing\"),\n })\n continue\n }\n const actualDefinition = normalizeIndexDefinition(actual.key ?? {}, actual, expected.key)\n const expectedDefinition = normalizeIndexDefinition(expected.key, {\n ...(expected.options ?? {}),\n ...(expected.runtimeOptions ?? {}),\n })\n if (!same(actualDefinition.key, expectedDefinition.key)) {\n divergences.push({\n code: \"index_key_mismatch\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n expected: expected.key,\n actual: Object.fromEntries(actualDefinition.key),\n message: message(expected.collection, expected.name, \"index keys differ\"),\n })\n }\n const expectedOptions = expectedDefinition.options\n const actualOptions = actualDefinition.options\n if (!same(actualOptions, expectedOptions)) {\n const runtimeOptionNames = new Set(Object.keys(expected.runtimeOptions ?? {}))\n const fixedOptions = (indexOptions: Document) => Object.fromEntries(\n Object.entries(indexOptions).filter(([name]) => !runtimeOptionNames.has(name)),\n )\n const runtimeOnly = runtimeOptionNames.size > 0\n && same(fixedOptions(actualOptions), fixedOptions(expectedOptions))\n divergences.push({\n code: runtimeOnly ? \"runtime_index_options_mismatch\" : \"index_options_mismatch\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n expected: expectedOptions,\n actual: actualOptions,\n message: message(expected.collection, expected.name, \"index options differ\"),\n })\n }\n }\n\n for (const expected of resources.collectionValidators) {\n const collection = collectionsByName.get(expected.collection)\n const actual = collection?.options as Document | undefined\n const expectedValidator = normalizeValidatorDefinition({\n validator: expected.validator,\n ...(expected.validationLevel ? { validationLevel: expected.validationLevel } : {}),\n ...(expected.validationAction ? { validationAction: expected.validationAction } : {}),\n })\n const actualValidator = normalizeValidatorDefinition(actual)\n if (!collection || !same(actualValidator, expectedValidator)) {\n divergences.push({\n code: \"collection_validator_mismatch\",\n scope: expected.scope,\n collection: expected.collection,\n expected: expectedValidator,\n actual: collection ? actualValidator : undefined,\n message: message(expected.collection, undefined, \"collection validator differs\"),\n })\n }\n }\n\n const searchIndexesByCollection = new Map<string, Document[] | Error>()\n for (const expected of resources.searchIndexes) {\n let indexes = searchIndexesByCollection.get(expected.collection)\n if (!indexes) {\n try {\n indexes = await db.collection(expected.collection).listSearchIndexes().toArray()\n } catch (error) {\n indexes = error instanceof Error ? error : new Error(String(error))\n }\n searchIndexesByCollection.set(expected.collection, indexes)\n }\n if (indexes instanceof Error) {\n divergences.push({\n code: \"search_unavailable\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n actual: indexes.message,\n message: message(expected.collection, expected.name, \"MongoDB Search inspection is unavailable\"),\n })\n continue\n }\n const actual = indexes.find((index) => index.name === expected.name)\n if (!actual) {\n divergences.push({\n code: \"missing_search_index\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n message: message(expected.collection, expected.name, \"managed Search index is missing\"),\n })\n continue\n }\n if (!same(actual.latestDefinition, expected.definition)) {\n divergences.push({\n code: \"search_index_definition_mismatch\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n expected: expected.definition,\n actual: actual.latestDefinition,\n message: message(expected.collection, expected.name, \"Search index definition differs\"),\n })\n }\n if (options.requireSearchReady && (actual.status !== \"READY\" || actual.queryable !== true)) {\n divergences.push({\n code: \"search_index_not_ready\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n expected: { status: \"READY\", queryable: true },\n actual: { status: actual.status, queryable: actual.queryable },\n message: message(expected.collection, expected.name, \"Search index is not ready and queryable\"),\n })\n }\n }\n\n signal?.throwIfAborted()\n return divergences\n}\n","import type { Db, Document } from \"mongodb\"\n\nimport { canonicalStringify } from \"./canonical\"\nimport { normalizeIndexDefinition } from \"./indexDefinition\"\nimport type { MigrationHelpers, MongoResources } from \"./types\"\n\n\nconst namespaceExists = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const value = error as { code?: unknown; codeName?: unknown }\n return value.code === 48 || value.codeName === \"NamespaceExists\"\n}\n\nconst namespaceMissing = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const value = error as { code?: unknown; codeName?: unknown }\n return value.code === 26 || value.codeName === \"NamespaceNotFound\"\n}\n\nconst indexMissing = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const value = error as { code?: unknown; codeName?: unknown }\n return value.code === 27 || value.codeName === \"IndexNotFound\"\n}\n\nconst same = (left: unknown, right: unknown): boolean =>\n canonicalStringify(left) === canonicalStringify(right)\n\nconst wait = async (milliseconds: number, signal: AbortSignal): Promise<void> => {\n signal.throwIfAborted()\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort)\n resolve()\n }, milliseconds)\n const onAbort = () => {\n clearTimeout(timer)\n reject(signal.reason)\n }\n signal.addEventListener(\"abort\", onAbort, { once: true })\n })\n signal.throwIfAborted()\n}\n\nexport type CreateMigrationHelpersOptions = {\n searchTimeoutMs?: number\n searchPollIntervalMs?: number\n}\n\nexport const createMigrationHelpers = (\n db: Db,\n signal: AbortSignal,\n options: CreateMigrationHelpersOptions = {},\n): MigrationHelpers => {\n const searchTimeoutMs = options.searchTimeoutMs ?? 10 * 60_000\n const searchPollIntervalMs = options.searchPollIntervalMs ?? 1_000\n\n const ensureCollection: MigrationHelpers[\"ensureCollection\"] = async (name, collectionOptions = {}) => {\n signal.throwIfAborted()\n const existing = await db.listCollections({ name }, { nameOnly: true }).hasNext()\n if (existing) return\n try {\n await db.createCollection(name, collectionOptions)\n } catch (error) {\n if (!namespaceExists(error)) throw error\n }\n }\n\n const dropCollectionIfExists: MigrationHelpers[\"dropCollectionIfExists\"] = async (name) => {\n signal.throwIfAborted()\n try {\n await db.dropCollection(name)\n } catch (error) {\n if (!namespaceMissing(error)) throw error\n }\n }\n\n const ensureIndex: MigrationHelpers[\"ensureIndex\"] = async (collectionName, key, indexOptions) => {\n signal.throwIfAborted()\n await ensureCollection(collectionName)\n const collection = db.collection(collectionName)\n const indexes = await collection.listIndexes().toArray()\n const existing = indexes.find((index) => index.name === indexOptions.name)\n if (existing) {\n const actualDefinition = normalizeIndexDefinition(existing.key ?? {}, existing, key)\n const expectedDefinition = normalizeIndexDefinition(key, indexOptions)\n if (!same(actualDefinition, expectedDefinition)) {\n throw new Error(`Index ${collectionName}.${indexOptions.name} exists with a different definition`)\n }\n return\n }\n await collection.createIndex(key, indexOptions)\n }\n\n const dropIndexIfExists: MigrationHelpers[\"dropIndexIfExists\"] = async (collectionName, name) => {\n signal.throwIfAborted()\n try {\n await db.collection(collectionName).dropIndex(name)\n } catch (error) {\n if (!namespaceMissing(error) && !indexMissing(error)) throw error\n }\n }\n\n const findDuplicateKeys: MigrationHelpers[\"findDuplicateKeys\"] = async (collectionName, key, duplicateOptions = {}) => {\n signal.throwIfAborted()\n const id = Object.keys(key).map((path) => `$${path}`)\n const pipeline: Document[] = []\n if (duplicateOptions.filter) pipeline.push({ $match: duplicateOptions.filter })\n pipeline.push(\n { $group: { _id: id, count: { $sum: 1 } } },\n { $match: { count: { $gt: 1 } } },\n { $limit: duplicateOptions.limit ?? 20 },\n )\n const documents = await db.collection(collectionName).aggregate(\n pipeline,\n duplicateOptions.collation ? { collation: duplicateOptions.collation } : {},\n ).toArray()\n return documents.map((document) => ({ key: document._id, count: Number(document.count) }))\n }\n\n const waitForSearchIndex = async (collectionName: string, name: string): Promise<void> => {\n const deadline = Date.now() + searchTimeoutMs\n while (Date.now() < deadline) {\n signal.throwIfAborted()\n const indexes = await db.collection(collectionName).listSearchIndexes(name).toArray() as Document[]\n const index = indexes[0]\n if (index?.status === \"READY\" && index.queryable === true) return\n if (index?.status === \"FAILED\") throw new Error(`Search index ${collectionName}.${name} failed to build`)\n await wait(searchPollIntervalMs, signal)\n }\n throw new Error(`Timed out waiting for Search index ${collectionName}.${name}`)\n }\n\n const ensureSearchIndex: MigrationHelpers[\"ensureSearchIndex\"] = async (collectionName, name, definition) => {\n signal.throwIfAborted()\n await ensureCollection(collectionName)\n const collection = db.collection(collectionName)\n const indexes = await collection.listSearchIndexes(name).toArray() as Document[]\n const existing = indexes[0]\n if (!existing) {\n await collection.createSearchIndex({ name, definition })\n } else if (!same(existing.latestDefinition, definition)) {\n await collection.updateSearchIndex(name, definition)\n }\n await waitForSearchIndex(collectionName, name)\n }\n\n const dropSearchIndexIfExists: MigrationHelpers[\"dropSearchIndexIfExists\"] = async (collectionName, name) => {\n signal.throwIfAborted()\n const collection = db.collection(collectionName)\n const indexes = await collection.listSearchIndexes(name).toArray()\n if (indexes.length === 0) return\n await collection.dropSearchIndex(name)\n const deadline = Date.now() + searchTimeoutMs\n while (Date.now() < deadline) {\n signal.throwIfAborted()\n if ((await collection.listSearchIndexes(name).toArray()).length === 0) return\n await wait(searchPollIntervalMs, signal)\n }\n throw new Error(`Timed out deleting Search index ${collectionName}.${name}`)\n }\n\n const setCollectionValidator: MigrationHelpers[\"setCollectionValidator\"] = async (\n collection,\n validator,\n validatorOptions = {},\n ) => {\n signal.throwIfAborted()\n await ensureCollection(collection)\n await db.command({ collMod: collection, validator, ...validatorOptions })\n }\n\n const helpers: MigrationHelpers = {\n ensureCollection,\n dropCollectionIfExists,\n ensureIndex,\n dropIndexIfExists,\n findDuplicateKeys,\n ensureSearchIndex,\n dropSearchIndexIfExists,\n setCollectionValidator,\n reconcileResources: async (resources: MongoResources) => {\n for (const collection of resources.collections) {\n await ensureCollection(collection.name, collection.options)\n }\n for (const validator of resources.collectionValidators) {\n await setCollectionValidator(validator.collection, validator.validator, {\n ...(validator.validationLevel ? { validationLevel: validator.validationLevel } : {}),\n ...(validator.validationAction ? { validationAction: validator.validationAction } : {}),\n })\n }\n for (const index of resources.indexes) {\n await ensureIndex(index.collection, index.key, {\n name: index.name,\n ...(index.options ?? {}),\n ...(index.runtimeOptions ?? {}),\n })\n }\n for (const index of resources.searchIndexes) {\n await ensureSearchIndex(index.collection, index.name, index.definition)\n }\n },\n }\n\n return helpers\n}\n\nexport const reconcileRuntimeIndexOptions = async (\n db: Db,\n resources: MongoResources,\n signal: AbortSignal,\n): Promise<void> => {\n for (const index of resources.indexes) {\n const runtimeOptions = index.runtimeOptions ?? {}\n if (Object.keys(runtimeOptions).length === 0) continue\n signal.throwIfAborted()\n let indexes: Document[]\n try {\n indexes = await db.collection(index.collection).listIndexes().toArray()\n } catch (error) {\n if (namespaceMissing(error)) continue\n throw error\n }\n const actual = indexes.find((candidate) => candidate.name === index.name)\n if (!actual) continue\n const actualDefinition = normalizeIndexDefinition(actual.key ?? {}, actual, index.key)\n const expectedDefinition = normalizeIndexDefinition(index.key, {\n ...(index.options ?? {}),\n ...runtimeOptions,\n })\n const runtimeOptionNames = new Set(Object.keys(runtimeOptions))\n const fixedOptions = (options: Document) => Object.fromEntries(\n Object.entries(options).filter(([name]) => !runtimeOptionNames.has(name)),\n )\n if (!same(actualDefinition.key, expectedDefinition.key)\n || !same(fixedOptions(actualDefinition.options), fixedOptions(expectedDefinition.options))) {\n continue\n }\n const differs = Object.keys(runtimeOptions).some((name) => (\n !same(actualDefinition.options[name], expectedDefinition.options[name])\n ))\n if (!differs) continue\n await db.command({\n collMod: index.collection,\n index: { name: index.name, ...runtimeOptions },\n })\n }\n}\n","export class MigrationIntegrityError extends Error {\n readonly code = \"RB_MIGRATION_INTEGRITY\"\n\n constructor(message: string) {\n super(message)\n this.name = \"MigrationIntegrityError\"\n }\n}\n\nexport class MigrationLockUnavailableError extends Error {\n readonly code = \"RB_MIGRATION_LOCK_UNAVAILABLE\"\n\n constructor(message: string) {\n super(message)\n this.name = \"MigrationLockUnavailableError\"\n }\n}\n\nexport class MigrationLockLostError extends Error {\n readonly code = \"RB_MIGRATION_LOCK_LOST\"\n\n constructor(message: string) {\n super(message)\n this.name = \"MigrationLockLostError\"\n }\n}\n","import type { Db } from \"mongodb\"\n\nimport type { MigrationHistoryRecord } from \"./types\"\n\n\nexport const MIGRATIONS_COLLECTION = \"rbmigrations\"\n\nexport const readMigrationHistory = async (db: Db): Promise<MigrationHistoryRecord[]> =>\n db.collection<MigrationHistoryRecord>(MIGRATIONS_COLLECTION)\n .find({})\n .sort({ source: 1, sourcePosition: 1 })\n .toArray()\n","import type { Db, MongoClient } from \"mongodb\"\n\nimport type { MigrationDatabaseProvider } from \"./types\"\n\n\nconst normalizeAppName = (value: string): string => {\n const appName = value.trim()\n if (!appName) throw new Error(\"Missing appName\")\n if (/[/\\\\.\"$*<>:|?]/.test(appName)) throw new Error(`Invalid appName: ${appName}`)\n return appName\n}\n\nconst normalizeTenantId = (value: string): string => {\n const tenantId = value.trim()\n if (!tenantId) throw new Error(\"Missing tenantId\")\n if (/[/\\\\.\"$*<>:|?]/.test(tenantId)) throw new Error(`Invalid tenantId: ${tenantId}`)\n return tenantId\n}\n\nexport type CreateMigrationDatabaseProviderOptions = {\n client: MongoClient\n appName: string\n tenantCollection?: string\n initializingTenantStaleAfterMs?: number\n filesystemRequired?: (tenantId: string, signal: AbortSignal) => boolean | Promise<boolean>\n}\n\nexport const createMigrationDatabaseProvider = (\n options: CreateMigrationDatabaseProviderOptions,\n): MigrationDatabaseProvider => {\n const appName = normalizeAppName(options.appName)\n const globalDbName = `${appName}-global-db`\n const tenantCollection = options.tenantCollection?.trim() || \"rbtenants\"\n const initializingTenantStaleAfterMs = options.initializingTenantStaleAfterMs ?? 5 * 60_000\n if (!Number.isFinite(initializingTenantStaleAfterMs) || initializingTenantStaleAfterMs < 0) {\n throw new Error(\"initializingTenantStaleAfterMs must be a non-negative finite number\")\n }\n\n const staleInitializingFilter = () => ({\n provisioningStatus: \"initializing\",\n $or: [\n { provisioningStartedAt: { $exists: false } },\n { provisioningStartedAt: { $lte: new Date(Date.now() - initializingTenantStaleAfterMs) } },\n ],\n })\n\n return {\n global: () => options.client.db(globalDbName),\n tenantIds: async (signal) => {\n signal.throwIfAborted()\n const documents = await options.client.db(globalDbName)\n .collection<{ tenantId?: unknown; provisioningStatus?: unknown }>(tenantCollection)\n .find({\n $or: [\n { provisioningStatus: { $exists: false } },\n { provisioningStatus: \"active\" },\n staleInitializingFilter(),\n ],\n }, { projection: { tenantId: 1 } })\n .sort({ tenantId: 1 })\n .toArray()\n signal.throwIfAborted()\n return [...new Set(documents.flatMap((document) => (\n typeof document.tenantId === \"string\" && document.tenantId.trim()\n ? [normalizeTenantId(document.tenantId)]\n : []\n )))]\n },\n tenantExists: async (tenantId, signal) => {\n signal.throwIfAborted()\n const normalized = normalizeTenantId(tenantId)\n const tenant = await options.client.db(globalDbName)\n .collection(tenantCollection)\n .findOne({ tenantId: normalized }, { projection: { _id: 1 } })\n signal.throwIfAborted()\n return Boolean(tenant)\n },\n tenant: (tenantId) => options.client.db(`${appName}-${normalizeTenantId(tenantId)}-db`),\n activateRecoveredTenant: async (tenantId, signal) => {\n signal.throwIfAborted()\n const result = await options.client.db(globalDbName)\n .collection(tenantCollection)\n .updateOne(\n { tenantId: normalizeTenantId(tenantId), ...staleInitializingFilter() },\n {\n $set: { provisioningStatus: \"active\", provisionedAt: new Date() },\n $unset: { provisioningError: \"\" },\n },\n )\n signal.throwIfAborted()\n return result.matchedCount === 1\n },\n filesystemRequired: options.filesystemRequired ?? (() => false),\n filesystem: (tenantId) => options.client.db(`${appName}-${normalizeTenantId(tenantId)}-filesystem-db`),\n }\n}\n\nexport const getMigrationDatabaseName = (db: Db): string => db.databaseName\n","import { filterMongoResources, mergeMongoResources } from \"./resources\"\nimport { inspectMongoResources } from \"./inspectResources\"\nimport { readMigrationHistory } from \"./history\"\nimport type {\n CompiledMigration,\n CompiledMigrationRegistry,\n MigrationDatabasePlan,\n MigrationDatabaseProvider,\n MigrationDatabaseTarget,\n MigrationHistoryRecord,\n MigrationPlan,\n MigrationPlanItem,\n MigrationPlanOptions,\n MigrationScope,\n MongoResources,\n} from \"./types\"\n\n\nconst neverAbortedSignal = new AbortController().signal\n\nconst toPlanItem = (migration: CompiledMigration): MigrationPlanItem => ({\n id: migration.qualifiedId,\n checksum: migration.checksum,\n source: migration.source,\n scope: migration.scope,\n phase: migration.phase,\n dependsOn: migration.dependsOn,\n})\n\nconst historyById = (history: readonly MigrationHistoryRecord[]): Map<string, MigrationHistoryRecord> =>\n new Map(history.map((record) => [record._id, record]))\n\nconst validateKnownRecord = (\n migration: CompiledMigration,\n record: MigrationHistoryRecord,\n targetScope: MigrationScope,\n): string[] => {\n const errors: string[] = []\n if (record.checksum !== migration.checksum) errors.push(`${migration.qualifiedId}: checksum differs`)\n if (record.source !== migration.source) errors.push(`${migration.qualifiedId}: source differs`)\n if (record.sourcePosition !== migration.sourcePosition) errors.push(`${migration.qualifiedId}: source position differs`)\n if (record.scope !== migration.scope) errors.push(`${migration.qualifiedId}: scope differs`)\n if (migration.scope !== targetScope) {\n errors.push(`${migration.qualifiedId}: migration history is stored in a ${targetScope} database`)\n }\n if (record.phase !== migration.phase) errors.push(`${migration.qualifiedId}: phase differs`)\n if (!([\"running\", \"applied\", \"failed\"] as const).includes(record.status)) {\n errors.push(`${migration.qualifiedId}: history status is invalid`)\n }\n const expectedBeforeHash = migration.resources?.before ?? undefined\n const expectedAfterHash = migration.resources?.after\n if (record.resourcesBeforeHash !== expectedBeforeHash) {\n errors.push(`${migration.qualifiedId}: resource before checksum differs`)\n }\n if (record.resourcesAfterHash !== expectedAfterHash) {\n errors.push(`${migration.qualifiedId}: resource after checksum differs`)\n }\n return errors\n}\n\nconst validateSourcePrefixes = (\n registry: CompiledMigrationRegistry,\n scope: MigrationScope,\n records: ReadonlyMap<string, MigrationHistoryRecord>,\n): string[] => {\n const errors: string[] = []\n for (const source of registry.sources) {\n let gap: CompiledMigration | null = null\n for (const migration of source.migrations.filter((item) => item.scope === scope)) {\n const applied = records.get(migration.qualifiedId)?.status === \"applied\"\n if (!applied && !gap) gap = migration\n if (applied && gap) {\n errors.push(`${migration.qualifiedId}: applied after missing migration ${gap.qualifiedId}`)\n }\n }\n }\n return errors\n}\n\nexport const getExpectedResources = (\n registry: CompiledMigrationRegistry,\n scope: MigrationScope,\n history: readonly MigrationHistoryRecord[],\n): MongoResources => {\n const records = historyById(history)\n const snapshots: MongoResources[] = []\n\n for (const source of registry.sources) {\n let checksum: string | null = null\n for (const migration of source.migrations) {\n if (migration.scope !== scope || !migration.resources) continue\n if (records.get(migration.qualifiedId)?.status === \"applied\") checksum = migration.resources.after\n }\n if (!checksum) continue\n const snapshot = source.resourceSnapshots.get(checksum)\n if (!snapshot) throw new Error(`Missing resource snapshot ${checksum} for ${source.name}`)\n snapshots.push(filterMongoResources(snapshot, scope))\n }\n\n return mergeMongoResources(snapshots)\n}\n\nexport const planMigrationTarget = async (\n registry: CompiledMigrationRegistry,\n target: MigrationDatabaseTarget,\n options: Pick<MigrationPlanOptions, \"allowNewerApplied\" | \"signal\"> = {},\n): Promise<MigrationDatabasePlan> => {\n const signal = options.signal ?? neverAbortedSignal\n signal.throwIfAborted()\n const history = await readMigrationHistory(target.db)\n const records = historyById(history)\n const relevant = registry.migrations.filter((migration) => migration.scope === target.scope)\n const integrityErrors: string[] = []\n const unknown: string[] = []\n\n for (const record of history) {\n const migration = registry.migrationsById.get(record._id)\n if (migration) {\n integrityErrors.push(...validateKnownRecord(migration, record, target.scope))\n continue\n }\n\n unknown.push(record._id)\n const allowedNewerMigration = options.allowNewerApplied\n && record.status === \"applied\"\n && record.scope === target.scope\n if (!allowedNewerMigration) integrityErrors.push(`${record._id}: applied migration is absent from the registry`)\n }\n\n integrityErrors.push(...validateSourcePrefixes(registry, target.scope, records))\n\n const applied = relevant\n .filter((migration) => records.get(migration.qualifiedId)?.status === \"applied\")\n .map((migration) => migration.qualifiedId)\n const pending = relevant\n .filter((migration) => !records.has(migration.qualifiedId))\n .map(toPlanItem)\n const running = relevant\n .filter((migration) => records.get(migration.qualifiedId)?.status === \"running\")\n .map((migration) => migration.qualifiedId)\n const failed = relevant\n .filter((migration) => records.get(migration.qualifiedId)?.status === \"failed\")\n .map((migration) => migration.qualifiedId)\n const expectedResources = getExpectedResources(registry, target.scope, history)\n const resourceDivergences = options.allowNewerApplied && unknown.length > 0\n ? []\n : await inspectMongoResources(target.db, expectedResources, {\n signal,\n requireSearchReady: true,\n })\n\n return {\n database: target.db.databaseName,\n scope: target.scope,\n ...(target.tenantId ? { tenantId: target.tenantId } : {}),\n applied,\n pending,\n running,\n failed,\n unknown,\n integrityErrors,\n resourceDivergences,\n }\n}\n\nexport const collectMigrationTargets = async (\n provider: MigrationDatabaseProvider,\n options: Pick<MigrationPlanOptions, \"tenantId\" | \"signal\"> = {},\n): Promise<MigrationDatabaseTarget[]> => {\n const signal = options.signal ?? neverAbortedSignal\n const global = await provider.global()\n const targets: MigrationDatabaseTarget[] = [{ db: global, scope: \"global\" }]\n let tenantIds: string[]\n if (options.tenantId) {\n if (provider.tenantExists && !await provider.tenantExists(options.tenantId, signal)) {\n throw new Error(`Unknown tenant: ${options.tenantId}`)\n }\n tenantIds = [options.tenantId]\n } else {\n tenantIds = [...await provider.tenantIds(signal)]\n }\n\n for (const tenantId of tenantIds) {\n targets.push({ db: await provider.tenant(tenantId), scope: \"tenant\", tenantId })\n }\n if (provider.filesystem) {\n for (const tenantId of tenantIds) {\n const required = await provider.filesystemRequired?.(tenantId, signal) ?? false\n if (required) targets.push({ db: await provider.filesystem(tenantId), scope: \"filesystem\", tenantId })\n }\n }\n return targets\n}\n\nexport const planMigrations = async (\n registry: CompiledMigrationRegistry,\n provider: MigrationDatabaseProvider,\n options: MigrationPlanOptions = {},\n): Promise<MigrationPlan> => {\n const targets = await collectMigrationTargets(provider, options)\n const databases: MigrationDatabasePlan[] = []\n for (const target of targets) databases.push(await planMigrationTarget(registry, target, options))\n return {\n protocolVersion: 2,\n registryChecksum: registry.checksum,\n databases,\n hasPending: databases.some((database) => (\n database.pending.length > 0 || database.running.length > 0 || database.failed.length > 0\n )),\n hasErrors: databases.some((database) => (\n database.integrityErrors.length > 0\n || (\n database.running.length === 0\n && database.failed.length === 0\n && database.resourceDivergences.some((divergence) => (\n divergence.code !== \"runtime_index_options_mismatch\"\n ))\n )\n )),\n }\n}\n","import { randomUUID } from \"node:crypto\"\n\nimport type { Db, Document } from \"mongodb\"\n\nimport { MigrationLockLostError, MigrationLockUnavailableError } from \"./errors\"\n\n\nexport const MIGRATION_LOCKS_COLLECTION = \"rbmigrationlocks\"\n\ntype MigrationLockDocument = Document & {\n _id: string\n owner: string\n runId: string\n fence: number\n expiresAt: Date\n}\n\nexport type MigrationLock = {\n owner: string\n runId: string\n fence: number\n signal: AbortSignal\n assertOwned(): Promise<void>\n release(): Promise<void>\n}\n\nexport type AcquireMigrationLockOptions = {\n lockId?: string\n owner?: string\n runId?: string\n leaseMs?: number\n heartbeatMs?: number\n}\n\nconst isDuplicateKey = (error: unknown): boolean =>\n Boolean(error && typeof error === \"object\" && \"code\" in error && (error as { code?: unknown }).code === 11000)\n\nexport const acquireMigrationLock = async (\n db: Db,\n options: AcquireMigrationLockOptions = {},\n): Promise<MigrationLock> => {\n const lockId = options.lockId?.trim() || \"default\"\n const owner = options.owner?.trim() || randomUUID()\n const runId = options.runId?.trim() || randomUUID()\n const leaseMs = options.leaseMs ?? 120_000\n const heartbeatMs = options.heartbeatMs ?? 30_000\n if (leaseMs <= 0) throw new Error(\"Migration lock lease must be positive\")\n if (heartbeatMs <= 0 || heartbeatMs >= leaseMs) {\n throw new Error(\"Migration lock heartbeat must be positive and shorter than the lease\")\n }\n\n const collection = db.collection<MigrationLockDocument>(MIGRATION_LOCKS_COLLECTION)\n let document: MigrationLockDocument | null\n try {\n await collection.updateOne(\n { _id: lockId },\n {\n $setOnInsert: {\n owner: \"\",\n runId: \"\",\n fence: 0,\n expiresAt: new Date(0),\n },\n },\n { upsert: true, writeConcern: { w: \"majority\" } },\n )\n document = await collection.findOneAndUpdate(\n {\n _id: lockId,\n $expr: {\n $or: [\n { $lte: [{ $ifNull: [\"$expiresAt\", new Date(0)] }, \"$$NOW\"] },\n { $eq: [\"$owner\", owner] },\n ],\n },\n },\n [\n {\n $set: {\n owner,\n runId,\n fence: { $add: [{ $ifNull: [\"$fence\", 0] }, 1] },\n acquiredAt: \"$$NOW\",\n heartbeatAt: \"$$NOW\",\n expiresAt: { $dateAdd: { startDate: \"$$NOW\", unit: \"millisecond\", amount: leaseMs } },\n },\n },\n ],\n { returnDocument: \"after\", writeConcern: { w: \"majority\" } },\n )\n } catch (error) {\n if (isDuplicateKey(error)) {\n throw new MigrationLockUnavailableError(`Migration lock ${lockId} is held by another runner`)\n }\n throw error\n }\n if (!document || document.owner !== owner || document.runId !== runId) {\n throw new MigrationLockUnavailableError(`Migration lock ${lockId} could not be acquired`)\n }\n\n const fence = document.fence\n const abortController = new AbortController()\n let state: \"active\" | \"lost\" | \"released\" = \"active\"\n let heartbeatTimer: ReturnType<typeof setTimeout> | undefined\n let heartbeatPromise: Promise<void> | null = null\n\n const lose = (reason: string, cause?: unknown): MigrationLockLostError => {\n const error = new MigrationLockLostError(`Migration lock ${lockId} was lost: ${reason}`)\n if (cause !== undefined) error.cause = cause\n if (state === \"active\") {\n state = \"lost\"\n if (heartbeatTimer) clearTimeout(heartbeatTimer)\n abortController.abort(error)\n }\n return error\n }\n\n const assertOwned = async (): Promise<void> => {\n if (state === \"lost\") throw abortController.signal.reason\n if (state !== \"active\") throw new MigrationLockLostError(`Migration lock ${lockId} is no longer active`)\n const owned = await collection.findOne({\n _id: lockId,\n owner,\n runId,\n fence,\n $expr: { $gt: [\"$expiresAt\", \"$$NOW\"] },\n }, { projection: { _id: 1 } })\n if (!owned) throw lose(\"ownership or lease expiry could not be confirmed\")\n }\n\n const heartbeat = async (): Promise<void> => {\n if (state !== \"active\") return\n const result = await collection.updateOne(\n {\n _id: lockId,\n owner,\n runId,\n fence,\n $expr: { $gt: [\"$expiresAt\", \"$$NOW\"] },\n },\n [{\n $set: {\n heartbeatAt: \"$$NOW\",\n expiresAt: { $dateAdd: { startDate: \"$$NOW\", unit: \"millisecond\", amount: leaseMs } },\n },\n }],\n { writeConcern: { w: \"majority\" } },\n )\n if (result.modifiedCount !== 1) throw lose(\"heartbeat was rejected\")\n }\n\n const scheduleHeartbeat = () => {\n if (state !== \"active\") return\n heartbeatTimer = setTimeout(() => {\n heartbeatPromise = heartbeat()\n .catch((error) => {\n if (state === \"active\") lose(\"heartbeat failed\", error)\n })\n .finally(() => {\n heartbeatPromise = null\n scheduleHeartbeat()\n })\n }, heartbeatMs)\n heartbeatTimer.unref?.()\n }\n\n const release = async (): Promise<void> => {\n if (state === \"released\") return\n if (heartbeatTimer) clearTimeout(heartbeatTimer)\n if (heartbeatPromise) await heartbeatPromise.catch(() => undefined)\n if (state === \"lost\") return\n state = \"released\"\n await collection.updateOne(\n { _id: lockId, owner, runId, fence },\n {\n $set: { expiresAt: new Date(0), releasedAt: new Date() },\n $unset: { owner: \"\", runId: \"\" },\n },\n { writeConcern: { w: \"majority\" } },\n )\n }\n\n scheduleHeartbeat()\n return { owner, runId, fence, signal: abortController.signal, assertOwned, release }\n}\n","import type { Collection } from \"mongodb\"\n\nimport { MigrationIntegrityError, MigrationLockLostError } from \"./errors\"\nimport { createMigrationHelpers, reconcileRuntimeIndexOptions } from \"./helpers\"\nimport { MIGRATIONS_COLLECTION, readMigrationHistory } from \"./history\"\nimport { inspectMongoResources } from \"./inspectResources\"\nimport { acquireMigrationLock, type MigrationLock } from \"./lock\"\nimport { filterMongoResources } from \"./resources\"\nimport {\n collectMigrationTargets,\n getExpectedResources,\n planMigrationTarget,\n planMigrations,\n} from \"./planner\"\nimport type {\n CompiledMigration,\n CompiledMigrationRegistry,\n MigrationCheckpoint,\n MigrationDatabasePlan,\n MigrationDatabaseProvider,\n MigrationDatabaseTarget,\n MigrationHistoryRecord,\n MigrationPlan,\n MigrationScope,\n MongoResources,\n RunMigrationsOptions,\n} from \"./types\"\n\n\nconst errorMessage = (error: unknown): string => {\n const message = error instanceof Error ? error.message : String(error)\n return message.slice(0, 8_000)\n}\n\nconst combineSignals = (...signals: Array<AbortSignal | undefined>): AbortSignal => {\n const active = signals.filter((signal): signal is AbortSignal => Boolean(signal))\n if (active.length === 0) return new AbortController().signal\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n\nconst assertPlanCanRun = (plan: MigrationDatabasePlan): void => {\n const retrying = plan.running.length > 0 || plan.failed.length > 0\n const errors = [\n ...plan.integrityErrors,\n ...(retrying ? [] : plan.resourceDivergences\n .filter((divergence) => divergence.code !== \"runtime_index_options_mismatch\")\n .map((divergence) => divergence.message)),\n ]\n if (errors.length > 0) {\n throw new MigrationIntegrityError(`${plan.database}: ${errors.join(\"; \")}`)\n }\n}\n\nconst recordForMigration = (\n migration: CompiledMigration,\n lock: MigrationLock,\n attempt: number,\n release: string | undefined,\n): MigrationHistoryRecord => ({\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n source: migration.source,\n sourcePosition: migration.sourcePosition,\n scope: migration.scope,\n phase: migration.phase,\n status: \"running\",\n attempt,\n ...(migration.resources?.before ? { resourcesBeforeHash: migration.resources.before } : {}),\n ...(migration.resources ? { resourcesAfterHash: migration.resources.after } : {}),\n ...(release ? { release } : {}),\n runId: lock.runId,\n fence: lock.fence,\n startedAt: new Date(),\n heartbeatAt: new Date(),\n})\n\nconst startMigration = async (\n collection: Collection<MigrationHistoryRecord>,\n migration: CompiledMigration,\n lock: MigrationLock,\n release: string | undefined,\n): Promise<MigrationHistoryRecord> => {\n await lock.assertOwned()\n const existing = await collection.findOne({ _id: migration.qualifiedId })\n if (existing?.status === \"applied\") return existing\n if (existing && existing.checksum !== migration.checksum) {\n throw new MigrationIntegrityError(`${migration.qualifiedId}: checksum differs`)\n }\n\n const record = recordForMigration(migration, lock, (existing?.attempt ?? 0) + 1, release)\n if (!existing) {\n await collection.insertOne(record, { writeConcern: { w: \"majority\" } })\n return record\n }\n\n const { _id: _recordId, ...recordUpdates } = record\n const result = await collection.findOneAndUpdate(\n {\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n status: { $in: [\"running\", \"failed\"] },\n },\n {\n $set: {\n ...recordUpdates,\n ...(existing.checkpoint !== undefined ? { checkpoint: existing.checkpoint } : {}),\n },\n $unset: { error: \"\", appliedAt: \"\", durationMs: \"\" },\n },\n { returnDocument: \"after\", writeConcern: { w: \"majority\" } },\n )\n if (!result) throw new MigrationIntegrityError(`${migration.qualifiedId}: history state changed while starting`)\n return result\n}\n\nconst createCheckpoint = <T>(\n collection: Collection<MigrationHistoryRecord>,\n migration: CompiledMigration,\n record: MigrationHistoryRecord,\n lock: MigrationLock,\n): MigrationCheckpoint<T> => {\n let value = record.checkpoint as T | undefined\n const update = async (next: T | undefined, clear: boolean): Promise<void> => {\n await lock.assertOwned()\n const result = await collection.updateOne(\n {\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n status: \"running\",\n runId: lock.runId,\n fence: lock.fence,\n },\n clear\n ? { $unset: { checkpoint: \"\" }, $set: { heartbeatAt: new Date() } }\n : { $set: { checkpoint: next, heartbeatAt: new Date() } },\n { writeConcern: { w: \"majority\" } },\n )\n if (result.matchedCount !== 1) {\n throw new MigrationLockLostError(`${migration.qualifiedId}: checkpoint ownership was lost`)\n }\n value = next\n }\n\n return {\n get value() {\n return value\n },\n save: async (next) => update(next, false),\n clear: async () => update(undefined, true),\n }\n}\n\nconst markFailed = async (\n collection: Collection<MigrationHistoryRecord>,\n migration: CompiledMigration,\n lock: MigrationLock,\n error: unknown,\n): Promise<void> => {\n await collection.updateOne(\n {\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n status: \"running\",\n runId: lock.runId,\n fence: lock.fence,\n },\n { $set: { status: \"failed\", error: errorMessage(error), heartbeatAt: new Date() } },\n { writeConcern: { w: \"majority\" } },\n )\n}\n\nconst markApplied = async (\n collection: Collection<MigrationHistoryRecord>,\n migration: CompiledMigration,\n record: MigrationHistoryRecord,\n lock: MigrationLock,\n): Promise<void> => {\n await lock.assertOwned()\n const appliedAt = new Date()\n const result = await collection.updateOne(\n {\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n status: \"running\",\n runId: lock.runId,\n fence: lock.fence,\n },\n {\n $set: {\n status: \"applied\",\n appliedAt,\n heartbeatAt: appliedAt,\n durationMs: appliedAt.getTime() - record.startedAt.getTime(),\n },\n $unset: { error: \"\" },\n },\n { writeConcern: { w: \"majority\" } },\n )\n if (result.matchedCount !== 1) throw new MigrationLockLostError(`${migration.qualifiedId}: apply ownership was lost`)\n}\n\nconst getExpectedTransitionSnapshot = (\n snapshots: ReadonlyMap<string, MongoResources>,\n checksum: string,\n scope: MigrationScope,\n): MongoResources => {\n const snapshot = snapshots.get(checksum)\n if (!snapshot) throw new MigrationIntegrityError(`Missing resource snapshot ${checksum}`)\n return filterMongoResources(snapshot, scope)\n}\n\nconst applyMigration = async (\n registry: CompiledMigrationRegistry,\n target: MigrationDatabaseTarget,\n migration: CompiledMigration,\n lock: MigrationLock,\n signal: AbortSignal,\n release: string | undefined,\n): Promise<void> => {\n signal.throwIfAborted()\n const collection = target.db.collection<MigrationHistoryRecord>(MIGRATIONS_COLLECTION)\n const record = await startMigration(collection, migration, lock, release)\n if (record.status === \"applied\") return\n const checkpoint = createCheckpoint(collection, migration, record, lock)\n const source = registry.sources.find((item) => item.name === migration.source)\n const resourceTransition = migration.resources && source\n ? {\n ...(migration.resources.before\n ? { before: getExpectedTransitionSnapshot(source.resourceSnapshots, migration.resources.before, target.scope) }\n : {}),\n after: getExpectedTransitionSnapshot(source.resourceSnapshots, migration.resources.after, target.scope),\n }\n : undefined\n\n try {\n await migration.up({\n db: target.db,\n ...(target.tenantId ? { tenantId: target.tenantId } : {}),\n checkpoint,\n signal,\n helpers: createMigrationHelpers(target.db, signal),\n ...(resourceTransition ? { resources: resourceTransition } : {}),\n })\n signal.throwIfAborted()\n\n if (migration.resources) {\n const history = await readMigrationHistory(target.db)\n const hypothetical = history.map((item) => item._id === migration.qualifiedId\n ? { ...item, status: \"applied\" as const }\n : item)\n const expected = getExpectedResources(registry, target.scope, hypothetical)\n const divergences = await inspectMongoResources(target.db, expected, {\n signal,\n requireSearchReady: true,\n })\n if (divergences.length > 0) {\n throw new MigrationIntegrityError(divergences.map((divergence) => divergence.message).join(\"; \"))\n }\n }\n\n await markApplied(collection, migration, record, lock)\n } catch (error) {\n await markFailed(collection, migration, lock, error).catch(() => undefined)\n throw error\n }\n}\n\nconst sourcePredecessorsApplied = (\n registry: CompiledMigrationRegistry,\n migration: CompiledMigration,\n applied: ReadonlySet<string>,\n): boolean => registry.sources\n .find((source) => source.name === migration.source)\n ?.migrations\n .filter((candidate) => candidate.scope === migration.scope && candidate.sourcePosition < migration.sourcePosition)\n .every((candidate) => applied.has(candidate.qualifiedId)) ?? false\n\nconst runTarget = async (\n registry: CompiledMigrationRegistry,\n target: MigrationDatabaseTarget,\n lock: MigrationLock,\n signal: AbortSignal,\n options: RunMigrationsOptions,\n earlierScopeDependencyApplied: (dependency: CompiledMigration) => Promise<boolean>,\n): Promise<Set<string>> => {\n let plan = await planMigrationTarget(registry, target, { signal })\n assertPlanCanRun(plan)\n if (plan.resourceDivergences.some((divergence) => divergence.code === \"runtime_index_options_mismatch\")) {\n const history = await readMigrationHistory(target.db)\n const expectedResources = getExpectedResources(registry, target.scope, history)\n await reconcileRuntimeIndexOptions(target.db, expectedResources, signal)\n plan = await planMigrationTarget(registry, target, { signal })\n assertPlanCanRun(plan)\n }\n const applied = new Set(plan.applied)\n\n const migrationsToRun = registry.migrations.filter((migration) => (\n migration.scope === target.scope && !applied.has(migration.qualifiedId)\n ))\n for (const migration of migrationsToRun) {\n if (!sourcePredecessorsApplied(registry, migration, applied)) continue\n let dependenciesReady = true\n for (const dependencyId of migration.dependsOn) {\n const dependency = registry.migrationsById.get(dependencyId)\n if (!dependency) throw new MigrationIntegrityError(`Unknown dependency ${dependencyId}`)\n const ready = dependency.scope === target.scope\n ? applied.has(dependencyId)\n : await earlierScopeDependencyApplied(dependency)\n if (!ready) {\n dependenciesReady = false\n break\n }\n }\n if (!dependenciesReady) continue\n await applyMigration(registry, target, migration, lock, signal, options.release)\n applied.add(migration.qualifiedId)\n }\n return applied\n}\n\nconst runWithConcurrency = async <T>(\n values: readonly T[],\n concurrency: number,\n action: (value: T) => Promise<void>,\n): Promise<void> => {\n let nextIndex = 0\n let failed = false\n let failure: unknown\n const workers = Array.from({ length: Math.min(concurrency, values.length) }, async () => {\n while (nextIndex < values.length && !failed) {\n const index = nextIndex\n nextIndex += 1\n try {\n await action(values[index])\n } catch (error) {\n if (!failed) failure = error\n failed = true\n }\n }\n })\n await Promise.all(workers)\n if (failed) throw failure\n}\n\nexport const runMigrations = async (\n registry: CompiledMigrationRegistry,\n provider: MigrationDatabaseProvider,\n options: RunMigrationsOptions = {},\n): Promise<MigrationPlan> => {\n const concurrency = options.concurrency ?? 4\n if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(\"Migration concurrency must be a positive integer\")\n const globalDb = await provider.global()\n const lock = await acquireMigrationLock(globalDb, {\n lockId: options.lockId,\n leaseMs: options.leaseMs,\n heartbeatMs: options.heartbeatMs,\n })\n const signal = combineSignals(options.signal, lock.signal)\n\n try {\n const targets = await collectMigrationTargets(provider, { tenantId: options.tenantId, signal })\n const globalTarget = targets.find((target) => target.scope === \"global\")\n if (!globalTarget) throw new Error(\"Migration provider did not return a global database\")\n let globalApplied = new Set<string>()\n if (options.initializeTenant) {\n const globalPlan = await planMigrationTarget(registry, globalTarget, { signal })\n assertPlanCanRun(globalPlan)\n if (globalPlan.pending.length > 0 || globalPlan.running.length > 0 || globalPlan.failed.length > 0) {\n throw new MigrationIntegrityError(\"Global migrations must be current before initializing a tenant\")\n }\n globalApplied = new Set(globalPlan.applied)\n } else {\n globalApplied = await runTarget(\n registry,\n globalTarget,\n lock,\n signal,\n options,\n async () => false,\n )\n }\n\n const tenantApplied = new Map<string, Set<string>>()\n const tenantTargets = targets.filter((target) => target.scope === \"tenant\")\n await runWithConcurrency(tenantTargets, concurrency, async (target) => {\n const applied = await runTarget(registry, target, lock, signal, options, async (dependency) => (\n dependency.scope === \"global\" && globalApplied.has(dependency.qualifiedId)\n ))\n if (target.tenantId) tenantApplied.set(target.tenantId, applied)\n })\n\n const filesystemTargets = targets.filter((target) => target.scope === \"filesystem\")\n await runWithConcurrency(filesystemTargets, concurrency, async (target) => {\n const appliedForTenant = target.tenantId ? tenantApplied.get(target.tenantId) : undefined\n await runTarget(registry, target, lock, signal, options, async (dependency) => {\n if (dependency.scope === \"global\") return globalApplied.has(dependency.qualifiedId)\n if (dependency.scope === \"tenant\") return appliedForTenant?.has(dependency.qualifiedId) ?? false\n return false\n })\n })\n\n const plan = await planMigrations(registry, provider, { tenantId: options.tenantId, signal })\n let activatedRecoveredTenant = false\n if (!options.initializeTenant && provider.activateRecoveredTenant) {\n for (const tenantId of tenantApplied.keys()) {\n const tenantPlans = plan.databases.filter((database) => database.tenantId === tenantId)\n const current = tenantPlans.length > 0 && tenantPlans.every((database) => (\n database.pending.length === 0\n && database.running.length === 0\n && database.failed.length === 0\n && database.integrityErrors.length === 0\n && database.resourceDivergences.length === 0\n ))\n if (!current) continue\n if (await provider.activateRecoveredTenant(tenantId, signal)) {\n activatedRecoveredTenant = true\n }\n }\n }\n\n return activatedRecoveredTenant\n ? await planMigrations(registry, provider, { tenantId: options.tenantId, signal })\n : plan\n } finally {\n await lock.release()\n }\n}\n\nexport const initializeTenantMigrations = async (\n registry: CompiledMigrationRegistry,\n provider: MigrationDatabaseProvider,\n tenantId: string,\n options: Omit<RunMigrationsOptions, \"tenantId\" | \"initializeTenant\"> = {},\n): Promise<MigrationPlan> => await runMigrations(registry, provider, {\n ...options,\n tenantId,\n initializeTenant: true,\n})\n","import { MigrationIntegrityError } from \"./errors\"\nimport { planMigrations } from \"./planner\"\nimport type {\n CompiledMigrationRegistry,\n MigrationDatabaseProvider,\n MigrationPlan,\n MigrationPlanOptions,\n} from \"./types\"\n\n\nexport const assertMigrationsCurrent = async (\n registry: CompiledMigrationRegistry,\n provider: MigrationDatabaseProvider,\n options: MigrationPlanOptions = {},\n): Promise<MigrationPlan> => {\n const plan = await planMigrations(registry, provider, options)\n const errors: string[] = []\n for (const database of plan.databases) {\n if (database.pending.length > 0) errors.push(`${database.database}: ${database.pending.length} migration(s) pending`)\n if (database.running.length > 0) errors.push(`${database.database}: migration running`)\n if (database.failed.length > 0) errors.push(`${database.database}: migration failed`)\n errors.push(...database.integrityErrors.map((error) => `${database.database}: ${error}`))\n errors.push(...database.resourceDivergences\n .filter((divergence) => divergence.code !== \"runtime_index_options_mismatch\")\n .map((divergence) => `${database.database}: ${divergence.message}`))\n }\n if (errors.length > 0) throw new MigrationIntegrityError(errors.join(\"; \"))\n return plan\n}\n","import { existsSync, readFileSync } from \"node:fs\"\nimport { dirname, extname, isAbsolute, resolve } from \"node:path\"\n\nimport { ImportType, initSync, parse } from \"es-module-lexer\"\n\nimport { canonicalChecksum, sha256 } from \"./canonical\"\n\n\nconst relativeImportPattern = /^(?:\\.\\.?\\/)/\nconst migrationCallPattern = /defineMigration(?:<[^>]+>)?\\s*\\(\\s*\\{/\nconst incompleteCollectionMigrationPattern = /Implement the collection option migration for/\nconst typeOnlyImportPattern = /^import\\s+type\\b/\n\ninitSync()\n\nconst resolveLocalImport = (importer: string, specifier: string): string => {\n const base = resolve(dirname(importer), specifier)\n const candidates = extname(base)\n ? [base]\n : [\n `${base}.ts`,\n `${base}.tsx`,\n `${base}.js`,\n `${base}.mjs`,\n resolve(base, \"index.ts\"),\n resolve(base, \"index.tsx\"),\n resolve(base, \"index.js\"),\n ]\n const resolved = candidates.find((candidate) => existsSync(candidate))\n if (!resolved) throw new Error(`Cannot resolve migration import ${specifier} from ${importer}`)\n return resolved\n}\n\nconst collectIntegrityFiles = (\n entry: string,\n rootDir: string,\n files: Map<string, string>,\n visiting: Set<string>,\n): void => {\n const filePath = resolve(entry)\n if (visiting.has(filePath) || files.has(filePath)) return\n if (!filePath.startsWith(`${rootDir}/`) && filePath !== rootDir) {\n throw new Error(`Migration dependency escapes integrity root: ${filePath}`)\n }\n visiting.add(filePath)\n const source = readFileSync(filePath, \"utf8\")\n const [imports] = parse(source, filePath)\n\n for (const imported of imports) {\n if (imported.t === ImportType.Dynamic\n || imported.t === ImportType.DynamicSourcePhase\n || imported.t === ImportType.DynamicDeferPhase) {\n throw new Error(`Dynamic imports are not allowed in migrations: ${filePath}`)\n }\n if (imported.t === ImportType.ImportMeta) continue\n const declaration = source.slice(imported.ss, imported.se)\n if (typeOnlyImportPattern.test(declaration)) continue\n const specifier = imported.n\n if (!specifier) throw new Error(`Cannot resolve migration import in ${filePath}`)\n if (specifier === \"@rpcbase/migrations\") continue\n if (!relativeImportPattern.test(specifier)) {\n throw new Error(`Mutable runtime import \"${specifier}\" is not allowed in migration ${filePath}`)\n }\n collectIntegrityFiles(resolveLocalImport(filePath, specifier), rootDir, files, visiting)\n }\n\n visiting.delete(filePath)\n files.set(filePath, source)\n}\n\nexport type ComputeMigrationIntegrityOptions = {\n rootDir?: string\n}\n\nexport const computeMigrationIntegrity = (\n entry: string,\n options: ComputeMigrationIntegrityOptions = {},\n): string => {\n const entryPath = resolve(entry)\n const rootDir = resolve(options.rootDir ?? dirname(entryPath))\n const files = new Map<string, string>()\n collectIntegrityFiles(entryPath, rootDir, files, new Set())\n return canonicalChecksum(\n [...files.entries()]\n .map(([filePath, source]) => ({ path: filePath.slice(rootDir.length), checksum: sha256(source) }))\n .sort((left, right) => left.path.localeCompare(right.path)),\n )\n}\n\nexport type MigrationIntegrityPluginOptions = {\n rootDir?: string\n}\n\nexport const createMigrationIntegrityPlugin = (options: MigrationIntegrityPluginOptions = {}) => ({\n name: \"rpcbase-migration-integrity\",\n enforce: \"pre\" as const,\n transform(code: string, id: string) {\n const cleanId = id.split(\"?\", 1)[0]\n if (!isAbsolute(cleanId) || !migrationCallPattern.test(code)) return null\n if (incompleteCollectionMigrationPattern.test(code)) {\n throw new Error(`Incomplete collection option migration: ${cleanId}`)\n }\n const rootDir = resolve(options.rootDir ?? dirname(cleanId))\n const integrity = computeMigrationIntegrity(cleanId, { rootDir })\n const transformed = code.replace(\n migrationCallPattern,\n (match) => `${match}\\n __rpcbaseIntegrity: ${JSON.stringify(integrity)},`,\n )\n return { code: transformed, map: null }\n },\n})\n","import { randomUUID } from \"node:crypto\"\n\nimport type { Db, MongoClient } from \"mongodb\"\n\nimport { assertMigrationsCurrent } from \"./assertCurrent\"\nimport { createMigrationDatabaseProvider } from \"./databaseProvider\"\nimport { createMigrationHelpers } from \"./helpers\"\nimport { MIGRATIONS_COLLECTION } from \"./history\"\nimport { compileMigrationRegistry, defineMigration, defineMigrationSource } from \"./registry\"\nimport { runMigrations } from \"./runner\"\nimport type {\n CompiledMigrationRegistry,\n MigrationContext,\n MigrationDefinition,\n MigrationHistoryRecord,\n MigrationScope,\n} from \"./types\"\n\n\nconst testAppNamePattern = /^rbmtest-[a-f0-9]{24}$/\nconst testTenantIdPattern = /^[a-z0-9][a-z0-9_-]{0,15}$/\n\nconst createTestAppName = (): string => `rbmtest-${randomUUID().replaceAll(\"-\", \"\").slice(0, 24)}`\n\nconst assertTestAppName = (appName: string): void => {\n if (!testAppNamePattern.test(appName)) {\n throw new Error(`Refusing to use unsafe migrations test app name: ${appName}`)\n }\n}\n\nconst databaseNames = (appName: string, tenantId: string): string[] => [\n `${appName}-global-db`,\n `${appName}-${tenantId}-db`,\n `${appName}-${tenantId}-filesystem-db`,\n]\n\nexport type TestMigrationRegistryOptions = {\n client: MongoClient\n registry: CompiledMigrationRegistry\n appName?: string\n tenantId?: string\n signal?: AbortSignal\n}\n\nexport type TestMigrationRegistryResult = {\n appName: string\n tenantId: string\n checkpointRecoveryAttempt: number\n}\n\nexport const testMigrationRegistry = async (\n options: TestMigrationRegistryOptions,\n): Promise<TestMigrationRegistryResult> => {\n const appName = options.appName ?? createTestAppName()\n const recoveryAppName = createTestAppName()\n const tenantId = options.tenantId ?? \"tenant\"\n assertTestAppName(appName)\n assertTestAppName(recoveryAppName)\n if (!testTenantIdPattern.test(tenantId)) {\n throw new Error(`Refusing to use unsafe migrations test tenant id: ${tenantId}`)\n }\n const databases = [\n ...databaseNames(appName, tenantId),\n ...databaseNames(recoveryAppName, tenantId),\n ]\n\n try {\n const provider = createMigrationDatabaseProvider({\n client: options.client,\n appName,\n filesystemRequired: () => true,\n })\n const globalDb = await provider.global()\n await globalDb.collection(\"rbtenants\").insertOne({\n tenantId,\n provisioningStatus: \"active\",\n })\n await runMigrations(options.registry, provider, {\n concurrency: 1,\n signal: options.signal,\n })\n await assertMigrationsCurrent(options.registry, provider, { signal: options.signal })\n\n const recoveryMigration = defineMigration<number>({\n id: \"20000101000000-checkpoint-recovery\",\n scope: \"global\",\n phase: \"expand\",\n async up({ checkpoint }) {\n if (checkpoint.value === 1) return\n await checkpoint.save(1)\n throw new Error(\"simulated migration interruption\")\n },\n })\n const recoveryRegistry = compileMigrationRegistry([defineMigrationSource({\n name: \"rbmtest\",\n migrations: [recoveryMigration],\n })])\n const recoveryProvider = createMigrationDatabaseProvider({\n client: options.client,\n appName: recoveryAppName,\n })\n await runMigrations(recoveryRegistry, recoveryProvider, {\n signal: options.signal,\n }).then(\n () => { throw new Error(\"Checkpoint recovery probe did not interrupt\") },\n (error) => {\n if (!(error instanceof Error) || error.message !== \"simulated migration interruption\") throw error\n },\n )\n await runMigrations(recoveryRegistry, recoveryProvider, { signal: options.signal })\n await assertMigrationsCurrent(recoveryRegistry, recoveryProvider, { signal: options.signal })\n const recoveryDb = await recoveryProvider.global()\n const history = await recoveryDb\n .collection<MigrationHistoryRecord>(MIGRATIONS_COLLECTION)\n .findOne({ _id: \"rbmtest:20000101000000-checkpoint-recovery\" })\n if (!history || history.status !== \"applied\" || history.checkpoint !== 1 || history.attempt !== 2) {\n throw new Error(\"Checkpoint recovery probe did not resume from its saved checkpoint\")\n }\n\n return { appName, tenantId, checkpointRecoveryAttempt: history.attempt }\n } finally {\n await Promise.all(databases.map(async (databaseName) => {\n if (!databaseName.startsWith(`${appName}-`) && !databaseName.startsWith(`${recoveryAppName}-`)) {\n throw new Error(`Refusing to clean unsafe migrations test database: ${databaseName}`)\n }\n await options.client.db(databaseName).dropDatabase()\n }))\n }\n}\n\nexport type TestSingleMigrationOptions<TCheckpoint = unknown> = {\n client: MongoClient\n migration: MigrationDefinition<TCheckpoint>\n scope?: MigrationScope\n tenantId?: string\n prepare(db: Db): Promise<void>\n verify(db: Db): Promise<void>\n checkpoint?: TCheckpoint\n signal?: AbortSignal\n}\n\nexport const testSingleMigration = async <TCheckpoint = unknown>(\n options: TestSingleMigrationOptions<TCheckpoint>,\n): Promise<void> => {\n const appName = createTestAppName()\n assertTestAppName(appName)\n const tenantId = options.tenantId ?? \"tenant\"\n const scope = options.scope ?? options.migration.scope\n if (scope !== \"global\" && !testTenantIdPattern.test(tenantId)) {\n throw new Error(`Refusing to use unsafe migrations test tenant id: ${tenantId}`)\n }\n const databaseName = scope === \"global\"\n ? `${appName}-global-db`\n : scope === \"filesystem\"\n ? `${appName}-${tenantId}-filesystem-db`\n : `${appName}-${tenantId}-db`\n const db = options.client.db(databaseName)\n const controller = new AbortController()\n const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal\n try {\n await options.prepare(db)\n let checkpointValue = options.checkpoint\n const context: MigrationContext<TCheckpoint> = {\n db,\n ...(scope === \"global\" ? {} : { tenantId }),\n checkpoint: {\n get value() {\n return checkpointValue\n },\n save: async (value) => { checkpointValue = value },\n clear: async () => { checkpointValue = undefined },\n },\n signal,\n helpers: createMigrationHelpers(db, signal),\n }\n await options.migration.up(context)\n await options.verify(db)\n } finally {\n controller.abort()\n await db.dropDatabase()\n }\n}\n"],"mappings":";;;;;;AAKA,IAAME,4BAA4BC,UAA4B;CAC5D,IAAIC,MAAMC,QAAQF,KAAK,GAAG,OAAOA,MAAMG,IAAIJ,wBAAwB;CAEnE,IAAIC,SAAS,OAAOA,UAAU,UAC5B,OAAOI,OAAOC,YACZD,OAAOE,QAAQN,KAAgC,CAAC,CAC7CQ,QAAQ,GAAGC,UAAUA,SAASC,KAAAA,CAAS,CAAC,CACxCC,MAAM,CAACC,OAAO,CAACC,WAAWD,KAAKE,cAAcD,KAAK,CAAC,CAAC,CACpDV,KAAK,CAACY,KAAKN,UAAU,CAACM,KAAKhB,yBAAyBU,IAAI,CAAC,CAAC,CAC/D;CAGF,OAAOT;AACT;AAEA,IAAMgB,kBAAkBhB,UACtBD,yBAAyBD,KAAKmB,MAAMC,UAAUlB,OAAO,EAAEmB,SAAS,MAAM,CAAC,CAAC;AAE1E,IAAaC,sBAAsBpB,UAA2BqB,KAAKC,UAAUN,eAAehB,KAAK,CAAC;AAElG,IAAauB,UAAUvB,UACrBH,WAAW,QAAQ,CAAC,CAAC4B,OAAOzB,KAAK,CAAC,CAAC0B,OAAO,KAAK;AAEjD,IAAaC,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ts","../src/diffResources.ts","../src/registry.ts","../src/indexDefinition.ts","../src/inspectResources.ts","../src/helpers.ts","../src/errors.ts","../src/history.ts","../src/databaseProvider.ts","../src/planner.ts","../src/lock.ts","../src/runner.ts","../src/assertCurrent.ts","../src/integrity.ts","../src/testHarness.ts"],"sourcesContent":["import { createHash } from \"node:crypto\"\n\nimport { BSON } from \"mongodb\"\n\n\nconst normalizeSerializedValue = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalizeSerializedValue)\n\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .filter(([, item]) => item !== undefined)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, item]) => [key, normalizeSerializedValue(item)]),\n )\n }\n\n return value\n}\n\nconst normalizeValue = (value: unknown): unknown =>\n normalizeSerializedValue(BSON.EJSON.serialize(value, { relaxed: false }))\n\nexport const canonicalStringify = (value: unknown): string => JSON.stringify(normalizeValue(value))\n\nexport const sha256 = (value: string | Uint8Array): string =>\n createHash(\"sha256\").update(value).digest(\"hex\")\n\nexport const canonicalChecksum = (value: unknown): string => sha256(canonicalStringify(value))\n","import type { Document } from \"mongodb\"\n\nimport { canonicalChecksum, canonicalStringify } from \"./canonical\"\nimport type {\n MigrationScope,\n MongoCollectionResource,\n MongoCollectionResourceInput,\n MongoCollectionValidatorResource,\n MongoCollectionValidatorResourceInput,\n MongoIndexResource,\n MongoIndexResourceInput,\n MongoResources,\n MongoResourcesInput,\n MongoSearchIndexResource,\n MongoSearchIndexResourceInput,\n} from \"./types\"\n\n\nconst scopes = new Set<MigrationScope>([\"global\", \"tenant\", \"filesystem\"])\nconst runtimeIndexOptions = new Set([\"expireAfterSeconds\"])\n\nconst assertName = (value: string, label: string): string => {\n const normalized = value.trim()\n if (!normalized) throw new Error(`${label} is required`)\n if (normalized.includes(\"\\0\")) throw new Error(`${label} cannot contain a null byte`)\n return normalized\n}\n\nconst assertScope = (scope: MigrationScope): void => {\n if (!scopes.has(scope)) throw new Error(`Invalid migration scope: ${String(scope)}`)\n}\n\nconst copyDocument = (value: Document | undefined): Document | undefined => {\n if (!value) return undefined\n return structuredClone(value)\n}\n\nconst collectionIdentity = (resource: MongoCollectionResource): string =>\n `${resource.scope}:${resource.name}`\n\nconst indexIdentity = (resource: MongoIndexResource | MongoSearchIndexResource): string =>\n `${resource.scope}:${resource.collection}:${resource.name}`\n\nconst validatorIdentity = (resource: MongoCollectionValidatorResource): string =>\n `${resource.scope}:${resource.collection}`\n\nconst uniqueResources = <T>(resources: readonly T[], identity: (resource: T) => string, label: string): readonly T[] => {\n const seen = new Map<string, string>()\n\n for (const resource of resources) {\n const key = identity(resource)\n const canonical = canonicalStringify(resource)\n const previous = seen.get(key)\n if (previous && previous !== canonical) throw new Error(`Conflicting ${label} resource: ${key}`)\n if (previous) throw new Error(`Duplicate ${label} resource: ${key}`)\n seen.set(key, canonical)\n }\n\n return resources\n}\n\nconst normalizeCollection = (resource: MongoCollectionResourceInput): MongoCollectionResource => {\n assertScope(resource.scope)\n return {\n scope: resource.scope,\n name: assertName(resource.name, \"Collection name\"),\n ...(resource.options ? { options: copyDocument(resource.options) } : {}),\n }\n}\n\nconst normalizeIndex = (resource: MongoIndexResourceInput): MongoIndexResource => {\n assertScope(resource.scope)\n if (Object.keys(resource.key).length === 0) throw new Error(\"Index key cannot be empty\")\n const optionNames = new Set(Object.keys(resource.options ?? {}))\n const unsupportedRuntimeOption = Object.keys(resource.runtimeOptions ?? {})\n .find((name) => !runtimeIndexOptions.has(name))\n if (unsupportedRuntimeOption) {\n throw new Error(`Unsupported runtime-managed index option: ${unsupportedRuntimeOption}`)\n }\n const overlappingRuntimeOption = Object.keys(resource.runtimeOptions ?? {})\n .find((name) => optionNames.has(name))\n if (overlappingRuntimeOption) {\n throw new Error(`Index option ${overlappingRuntimeOption} cannot be both fixed and runtime-managed`)\n }\n return {\n scope: resource.scope,\n collection: assertName(resource.collection, \"Index collection\"),\n name: assertName(resource.name, \"Index name\"),\n key: structuredClone(resource.key),\n ...(resource.options ? { options: copyDocument(resource.options) } : {}),\n ...(resource.runtimeOptions ? { runtimeOptions: copyDocument(resource.runtimeOptions) } : {}),\n }\n}\n\nconst normalizeSearchIndex = (resource: MongoSearchIndexResourceInput): MongoSearchIndexResource => {\n assertScope(resource.scope)\n return {\n scope: resource.scope,\n collection: assertName(resource.collection, \"Search index collection\"),\n name: assertName(resource.name, \"Search index name\"),\n definition: structuredClone(resource.definition),\n }\n}\n\nconst normalizeValidator = (\n resource: MongoCollectionValidatorResourceInput,\n): MongoCollectionValidatorResource => {\n assertScope(resource.scope)\n return {\n scope: resource.scope,\n collection: assertName(resource.collection, \"Validator collection\"),\n validator: structuredClone(resource.validator),\n ...(resource.validationLevel ? { validationLevel: resource.validationLevel } : {}),\n ...(resource.validationAction ? { validationAction: resource.validationAction } : {}),\n }\n}\n\nconst sortByIdentity = <T>(resources: readonly T[], identity: (resource: T) => string): readonly T[] =>\n [...resources].sort((left, right) => identity(left).localeCompare(identity(right)))\n\nconst checksumInput = (resources: Omit<MongoResources, \"checksum\">) => ({\n collections: resources.collections.map((resource) => ({\n ...resource,\n options: resource.options ?? {},\n })),\n indexes: resources.indexes.map((resource) => ({\n ...resource,\n key: Object.entries(resource.key),\n options: resource.options ?? {},\n ...(resource.runtimeOptions\n ? { runtimeOptions: Object.keys(resource.runtimeOptions).sort() }\n : {}),\n })),\n searchIndexes: resources.searchIndexes,\n collectionValidators: resources.collectionValidators,\n})\n\nexport const defineMongoResources = (input: MongoResourcesInput = {}): MongoResources => {\n const collections = sortByIdentity(\n uniqueResources((input.collections ?? []).map(normalizeCollection), collectionIdentity, \"collection\"),\n collectionIdentity,\n )\n const indexes = sortByIdentity(\n uniqueResources((input.indexes ?? []).map(normalizeIndex), indexIdentity, \"index\"),\n indexIdentity,\n )\n const searchIndexes = sortByIdentity(\n uniqueResources((input.searchIndexes ?? []).map(normalizeSearchIndex), indexIdentity, \"Search index\"),\n indexIdentity,\n )\n const collectionValidators = sortByIdentity(\n uniqueResources(\n (input.collectionValidators ?? []).map(normalizeValidator),\n validatorIdentity,\n \"collection validator\",\n ),\n validatorIdentity,\n )\n const resources = { collections, indexes, searchIndexes, collectionValidators }\n\n return Object.freeze({\n checksum: canonicalChecksum(checksumInput(resources)),\n ...resources,\n })\n}\n\nexport const filterMongoResources = (resources: MongoResources, scope: MigrationScope): MongoResources =>\n defineMongoResources({\n collections: resources.collections.filter((resource) => resource.scope === scope),\n indexes: resources.indexes.filter((resource) => resource.scope === scope),\n searchIndexes: resources.searchIndexes.filter((resource) => resource.scope === scope),\n collectionValidators: resources.collectionValidators.filter((resource) => resource.scope === scope),\n })\n\nexport const mergeMongoResources = (resourceSets: readonly MongoResources[]): MongoResources => {\n const collections = new Map<string, MongoCollectionResource>()\n const indexes = new Map<string, MongoIndexResource>()\n const searchIndexes = new Map<string, MongoSearchIndexResource>()\n const validators = new Map<string, MongoCollectionValidatorResource>()\n\n const merge = <T>(\n target: Map<string, T>,\n resource: T,\n identity: (value: T) => string,\n label: string,\n comparisonValue: (value: T) => unknown = (value) => value,\n ) => {\n const key = identity(resource)\n const previous = target.get(key)\n if (previous\n && canonicalStringify(comparisonValue(previous)) !== canonicalStringify(comparisonValue(resource))) {\n throw new Error(`Conflicting ${label} resource across migration sources: ${key}`)\n }\n target.set(key, resource)\n }\n\n for (const resources of resourceSets) {\n for (const resource of resources.collections) merge(collections, resource, collectionIdentity, \"collection\")\n for (const resource of resources.indexes) {\n merge(indexes, resource, indexIdentity, \"index\", (value) => ({\n ...value,\n key: Object.entries(value.key),\n }))\n }\n for (const resource of resources.searchIndexes) merge(searchIndexes, resource, indexIdentity, \"Search index\")\n for (const resource of resources.collectionValidators) {\n merge(validators, resource, validatorIdentity, \"collection validator\")\n }\n }\n\n return defineMongoResources({\n collections: [...collections.values()],\n indexes: [...indexes.values()],\n searchIndexes: [...searchIndexes.values()],\n collectionValidators: [...validators.values()],\n })\n}\n","import { canonicalStringify } from \"./canonical\"\nimport type {\n MongoCollectionResource,\n MongoCollectionValidatorResource,\n MongoIndexResource,\n MongoResourceChange,\n MongoResources,\n MongoResourcesDiff,\n MongoSearchIndexResource,\n} from \"./types\"\n\n\nconst collectionIdentity = (resource: MongoCollectionResource): string =>\n `${resource.scope}:${resource.name}`\n\nconst indexIdentity = (resource: MongoIndexResource | MongoSearchIndexResource): string =>\n `${resource.scope}:${resource.collection}:${resource.name}`\n\nconst validatorIdentity = (resource: MongoCollectionValidatorResource): string =>\n `${resource.scope}:${resource.collection}`\n\nconst indexComparisonValue = (resource: MongoIndexResource) => ({\n ...resource,\n key: Object.entries(resource.key),\n runtimeOptions: Object.keys(resource.runtimeOptions ?? {}).sort(),\n})\n\nconst diffSet = <T>(\n before: readonly T[],\n after: readonly T[],\n identity: (resource: T) => string,\n comparisonValue: (resource: T) => unknown = (resource) => resource,\n): readonly MongoResourceChange<T>[] => {\n const beforeById = new Map(before.map((resource) => [identity(resource), resource]))\n const afterById = new Map(after.map((resource) => [identity(resource), resource]))\n const ids = [...new Set([...beforeById.keys(), ...afterById.keys()])].sort()\n\n return ids.flatMap((id): MongoResourceChange<T>[] => {\n const previous = beforeById.get(id)\n const next = afterById.get(id)\n if (!previous && next) return [{ kind: \"added\", after: next }]\n if (previous && !next) return [{ kind: \"removed\", before: previous }]\n if (previous && next\n && canonicalStringify(comparisonValue(previous)) !== canonicalStringify(comparisonValue(next))) {\n return [{ kind: \"changed\", before: previous, after: next }]\n }\n return []\n })\n}\n\nexport const diffMongoResources = (\n before: MongoResources,\n after: MongoResources,\n): MongoResourcesDiff => {\n const collections = diffSet(before.collections, after.collections, collectionIdentity)\n const indexes = diffSet(before.indexes, after.indexes, indexIdentity, indexComparisonValue)\n const searchIndexes = diffSet(before.searchIndexes, after.searchIndexes, indexIdentity)\n const collectionValidators = diffSet(\n before.collectionValidators,\n after.collectionValidators,\n validatorIdentity,\n )\n const changes = [...collections, ...indexes, ...searchIndexes, ...collectionValidators]\n\n return {\n collections,\n indexes,\n searchIndexes,\n collectionValidators,\n changed: changes.length > 0,\n requiresContract: changes.some((change) => change.kind !== \"added\"),\n }\n}\n","import { canonicalChecksum } from \"./canonical\"\nimport { defineMongoResources, filterMongoResources, mergeMongoResources } from \"./resources\"\nimport type {\n CompiledMigration,\n CompiledMigrationRegistry,\n CompiledMigrationSource,\n DefineMigrationRegistryOptions,\n MigrationDefinition,\n MigrationScope,\n MigrationSource,\n MongoResources,\n} from \"./types\"\n\n\nconst migrationIdPattern = /^\\d{8}(?:\\d{6})?-[a-z0-9]+(?:-[a-z0-9]+)*$/\nconst sourceNamePattern = /^(?:@[a-z0-9][a-z0-9._-]*\\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/\nconst scopeRank: Record<MigrationScope, number> = { global: 0, tenant: 1, filesystem: 2 }\nconst scopes = Object.keys(scopeRank) as MigrationScope[]\nconst bootstrapIntegrity = canonicalChecksum({\n operation: \"bootstrap-mongo-resources\",\n protocolVersion: 2,\n revision: 1,\n})\n\nconst hasResources = (resources: MongoResources): boolean => (\n resources.collections.length > 0\n || resources.indexes.length > 0\n || resources.searchIndexes.length > 0\n || resources.collectionValidators.length > 0\n)\n\nconst bootstrapId = (scope: MigrationScope): string => `00000000-bootstrap-${scope}`\n\nconst runResourceBootstrap: MigrationDefinition[\"up\"] = async ({ helpers, resources }) => {\n if (!resources) throw new Error(\"Missing bootstrap resource snapshot\")\n for (const index of resources.after.indexes) {\n if (index.options?.unique !== true) continue\n const sparseFilter = index.options.sparse === true\n ? { $or: Object.keys(index.key).map((field) => ({ [field]: { $exists: true } })) }\n : undefined\n const partialFilter = index.options.partialFilterExpression\n const filter = sparseFilter && partialFilter\n ? { $and: [partialFilter, sparseFilter] }\n : partialFilter ?? sparseFilter\n const duplicates = await helpers.findDuplicateKeys(index.collection, index.key, {\n ...(filter ? { filter } : {}),\n ...(index.options.collation ? { collation: index.options.collation } : {}),\n })\n if (duplicates.length > 0) {\n throw new Error(\n `Cannot create unique index ${index.collection}.${index.name}: duplicate keys found: ${JSON.stringify(duplicates)}`,\n )\n }\n }\n await helpers.reconcileResources(resources.after)\n}\n\nconst createResourceBootstraps = (\n source: MigrationSource,\n baseline: MongoResources,\n): readonly MigrationDefinition[] => scopes.flatMap((scope) => {\n if (!hasResources(filterMongoResources(baseline, scope))) return []\n const id = bootstrapId(scope)\n if (source.migrations.some((migration) => migration.id === id)) {\n throw new Error(`Migration id ${id} is reserved for the ${source.name} resource bootstrap`)\n }\n return [Object.freeze({\n id,\n scope,\n phase: \"expand\" as const,\n resources: Object.freeze({ before: null, after: baseline.checksum }),\n up: runResourceBootstrap,\n __rpcbaseIntegrity: bootstrapIntegrity,\n })]\n})\n\nconst assertMigration = (migration: MigrationDefinition): void => {\n if (!migrationIdPattern.test(migration.id)) {\n throw new Error(`Invalid migration id \"${migration.id}\"`)\n }\n if (!(migration.scope in scopeRank)) throw new Error(`Invalid migration scope for ${migration.id}`)\n if (migration.phase !== \"expand\" && migration.phase !== \"contract\") {\n throw new Error(`Invalid migration phase for ${migration.id}`)\n }\n if (typeof migration.up !== \"function\") throw new Error(`Migration ${migration.id} is missing up()`)\n if (migration.resources && migration.resources.before === migration.resources.after) {\n throw new Error(`Migration ${migration.id} has an unchanged resource transition`)\n }\n}\n\nexport const defineMigration = <TCheckpoint = unknown>(\n migration: MigrationDefinition<TCheckpoint>,\n): MigrationDefinition<TCheckpoint> => {\n assertMigration(migration as MigrationDefinition)\n return Object.freeze({\n ...migration,\n dependsOn: Object.freeze([...(migration.dependsOn ?? [])]),\n ...(migration.resources ? { resources: Object.freeze({ ...migration.resources }) } : {}),\n })\n}\n\nexport const defineMigrationSource = (source: MigrationSource): MigrationSource => {\n const name = source.name.trim()\n if (!sourceNamePattern.test(name)) throw new Error(`Invalid migration source name \"${source.name}\"`)\n if ((source.baseline === undefined) !== (source.resources === undefined)) {\n throw new Error(`Migration source ${name} must declare baseline and resources together`)\n }\n\n let previousId: string | null = null\n const ids = new Set<string>()\n for (const migration of source.migrations) {\n assertMigration(migration)\n if (ids.has(migration.id)) throw new Error(`Duplicate migration id in ${name}: ${migration.id}`)\n if (previousId && migration.id <= previousId) {\n throw new Error(`Migration ids in ${name} must be strictly increasing: ${previousId}, ${migration.id}`)\n }\n ids.add(migration.id)\n previousId = migration.id\n }\n for (const id of [\n ...Object.keys(source.checksums ?? {}),\n ...Object.keys(source.legacyHistoryChecksums ?? {}),\n ]) {\n if (!ids.has(id)) throw new Error(`Migration source ${name} declares a checksum for unknown migration ${id}`)\n }\n for (const [id, checksums] of Object.entries(source.legacyHistoryChecksums ?? {})) {\n if (!Array.isArray(checksums)) {\n throw new Error(`Migration ${name}:${id} has invalid legacy history checksums`)\n }\n }\n\n return Object.freeze({\n ...source,\n name,\n migrations: Object.freeze([...source.migrations]),\n resourceSnapshots: Object.freeze([...(source.resourceSnapshots ?? [])]),\n checksums: Object.freeze({ ...(source.checksums ?? {}) }),\n legacyHistoryChecksums: Object.freeze(Object.fromEntries(\n Object.entries(source.legacyHistoryChecksums ?? {})\n .map(([id, checksums]) => [id, Object.freeze([...checksums])]),\n )),\n })\n}\n\nconst resolveDependencyId = (source: string, dependency: string): string =>\n dependency.includes(\":\") ? dependency : `${source}:${dependency}`\n\nconst historyChecksum = (\n migration: MigrationDefinition,\n source: string,\n codeChecksum: string,\n): string => canonicalChecksum({\n id: migration.id,\n source,\n scope: migration.scope,\n phase: migration.phase,\n dependsOn: migration.dependsOn ?? [],\n resources: migration.resources ?? null,\n codeChecksum,\n})\n\nexport const computeLegacyMigrationHistoryChecksum = (\n migration: MigrationDefinition,\n source: string,\n): string => historyChecksum(migration, source, canonicalChecksum(migration.up.toString()))\n\nconst migrationChecksum = (\n migration: MigrationDefinition,\n source: MigrationSource,\n): {\n checksum: string\n sourceIntegrity?: string\n legacyHistoryChecksums: readonly string[]\n sealed: boolean\n} => {\n const injectedChecksum = (\n migration as MigrationDefinition & { __rpcbaseIntegrity?: unknown }\n ).__rpcbaseIntegrity\n const declaredChecksum = source.checksums?.[migration.id]\n for (const checksum of [injectedChecksum, declaredChecksum]) {\n if (checksum === undefined) continue\n if (typeof checksum !== \"string\" || !/^[a-f0-9]{64}$/.test(checksum)) {\n throw new Error(`Migration ${source.name}:${migration.id} has an invalid source checksum`)\n }\n }\n if (injectedChecksum !== undefined && declaredChecksum !== undefined && injectedChecksum !== declaredChecksum) {\n throw new Error(`Migration ${source.name}:${migration.id} differs from its declared source checksum`)\n }\n const sourceIntegrity = typeof injectedChecksum === \"string\" ? injectedChecksum : declaredChecksum\n const checksum = sourceIntegrity\n ? historyChecksum(migration, source.name, sourceIntegrity)\n : computeLegacyMigrationHistoryChecksum(migration, source.name)\n const legacyHistoryChecksums = source.legacyHistoryChecksums?.[migration.id] ?? []\n const uniqueLegacyHistoryChecksums = new Set<string>()\n for (const legacyChecksum of legacyHistoryChecksums) {\n if (typeof legacyChecksum !== \"string\" || !/^[a-f0-9]{64}$/.test(legacyChecksum)) {\n throw new Error(`Migration ${source.name}:${migration.id} has an invalid legacy history checksum`)\n }\n if (legacyChecksum === checksum || uniqueLegacyHistoryChecksums.has(legacyChecksum)) {\n throw new Error(`Migration ${source.name}:${migration.id} has a duplicate legacy history checksum`)\n }\n uniqueLegacyHistoryChecksums.add(legacyChecksum)\n }\n return {\n checksum,\n ...(sourceIntegrity ? { sourceIntegrity } : {}),\n legacyHistoryChecksums: Object.freeze([...uniqueLegacyHistoryChecksums]),\n sealed: Boolean(sourceIntegrity),\n }\n}\n\nconst sortMigrations = (migrations: readonly CompiledMigration[]): readonly CompiledMigration[] => {\n const byId = new Map(migrations.map((migration) => [migration.qualifiedId, migration]))\n const visiting = new Set<string>()\n const visited = new Set<string>()\n const ordered: CompiledMigration[] = []\n\n const visit = (migration: CompiledMigration) => {\n if (visited.has(migration.qualifiedId)) return\n if (visiting.has(migration.qualifiedId)) {\n throw new Error(`Cyclic migration dependency involving ${migration.qualifiedId}`)\n }\n\n visiting.add(migration.qualifiedId)\n for (const dependencyId of migration.dependsOn) {\n const dependency = byId.get(dependencyId)\n if (!dependency) throw new Error(`Unknown dependency ${dependencyId} for ${migration.qualifiedId}`)\n if (scopeRank[dependency.scope] > scopeRank[migration.scope]) {\n throw new Error(`${migration.qualifiedId} cannot depend on later scope migration ${dependencyId}`)\n }\n if (dependency.source === migration.source\n && dependency.scope === migration.scope\n && dependency.sourcePosition > migration.sourcePosition) {\n throw new Error(`${migration.qualifiedId} cannot depend on a later migration in its source: ${dependencyId}`)\n }\n visit(dependency)\n }\n visiting.delete(migration.qualifiedId)\n visited.add(migration.qualifiedId)\n ordered.push(migration)\n }\n\n for (const migration of [...migrations].sort((left, right) => {\n const scopeDifference = scopeRank[left.scope] - scopeRank[right.scope]\n if (scopeDifference !== 0) return scopeDifference\n const sourceDifference = left.sourcePriority - right.sourcePriority\n if (sourceDifference !== 0) return sourceDifference\n return left.sourcePosition - right.sourcePosition\n })) visit(migration)\n\n return Object.freeze(ordered)\n}\n\nexport const compileMigrationRegistry = (\n inputSources: readonly MigrationSource[],\n options: DefineMigrationRegistryOptions = {},\n): CompiledMigrationRegistry => {\n const sourceNames = new Set<string>()\n const migrations: CompiledMigration[] = []\n const compiledSources: CompiledMigrationSource[] = []\n\n for (const [priority, inputSource] of inputSources.entries()) {\n const source = defineMigrationSource(inputSource)\n if (sourceNames.has(source.name)) throw new Error(`Duplicate migration source: ${source.name}`)\n sourceNames.add(source.name)\n\n const snapshots = new Map<string, ReturnType<typeof defineMongoResources>>()\n for (const snapshot of [\n ...(source.baseline ? [source.baseline] : []),\n ...(source.resourceSnapshots ?? []),\n ...(source.resources ? [source.resources] : []),\n ]) {\n const normalized = defineMongoResources(snapshot)\n if (normalized.checksum !== snapshot.checksum) {\n throw new Error(`Invalid resource snapshot checksum in ${source.name}: ${snapshot.checksum}`)\n }\n snapshots.set(normalized.checksum, normalized)\n }\n\n const baseline = source.baseline ? snapshots.get(source.baseline.checksum) : undefined\n const currentResources = source.resources ? snapshots.get(source.resources.checksum) : undefined\n const migrationDefinitions = [\n ...(baseline ? createResourceBootstraps(source, baseline) : []),\n ...source.migrations,\n ]\n const sourceMigrations = migrationDefinitions.map((migration, sourcePosition) => {\n if (migration.resources) {\n if (migration.resources.before && !snapshots.has(migration.resources.before)) {\n throw new Error(`Missing before resource snapshot for ${source.name}:${migration.id}`)\n }\n if (!snapshots.has(migration.resources.after)) {\n throw new Error(`Missing after resource snapshot for ${source.name}:${migration.id}`)\n }\n }\n\n const integrity = migrationChecksum(migration, source)\n if (options.requireSealed && !integrity.sealed) {\n throw new Error(`Migration ${source.name}:${migration.id} has no sealed source checksum`)\n }\n const compiled: CompiledMigration = Object.freeze({\n ...migration,\n qualifiedId: `${source.name}:${migration.id}`,\n source: source.name,\n sourcePosition,\n sourcePriority: priority,\n dependsOn: Object.freeze((migration.dependsOn ?? []).map((id) => resolveDependencyId(source.name, id))),\n checksum: integrity.checksum,\n ...(integrity.sourceIntegrity ? { sourceIntegrity: integrity.sourceIntegrity } : {}),\n legacyHistoryChecksums: integrity.legacyHistoryChecksums,\n sealed: integrity.sealed,\n })\n migrations.push(compiled)\n return compiled\n })\n\n for (const scope of scopes) {\n let previousChecksum: string | null = null\n let previousResources = defineMongoResources()\n for (const migration of sourceMigrations.filter((item) => item.scope === scope && item.resources)) {\n const transition = migration.resources\n if (!transition) continue\n const beforeResources = transition.before\n ? snapshots.get(transition.before)\n : defineMongoResources()\n if (!beforeResources\n || filterMongoResources(beforeResources, scope).checksum\n !== filterMongoResources(previousResources, scope).checksum) {\n throw new Error(\n `Non-contiguous resource transition for ${migration.qualifiedId}: expected ${previousChecksum ?? \"null\"}`,\n )\n }\n previousChecksum = transition.after\n previousResources = snapshots.get(previousChecksum) ?? defineMongoResources()\n }\n\n const currentForScope = currentResources\n ? filterMongoResources(currentResources, scope)\n : defineMongoResources()\n if (hasResources(currentForScope) || previousChecksum) {\n if (!previousChecksum) throw new Error(`Source ${source.name} has unmanaged ${scope} resources without a migration`)\n const previousSnapshot = snapshots.get(previousChecksum)\n if (!previousSnapshot\n || filterMongoResources(previousSnapshot, scope).checksum !== currentForScope.checksum) {\n throw new Error(`Latest ${scope} resource transition for ${source.name} does not match current resources`)\n }\n }\n }\n\n compiledSources.push(Object.freeze({\n ...source,\n ...(baseline ? { baseline } : {}),\n ...(currentResources ? { resources: currentResources } : {}),\n priority,\n migrations: Object.freeze(sourceMigrations),\n resourceSnapshots: snapshots,\n }))\n }\n\n const ordered = sortMigrations(migrations)\n const migrationsById = new Map<string, CompiledMigration>()\n for (const migration of ordered) {\n if (migrationsById.has(migration.qualifiedId)) throw new Error(`Duplicate migration: ${migration.qualifiedId}`)\n migrationsById.set(migration.qualifiedId, migration)\n }\n\n mergeMongoResources(compiledSources.flatMap((source) => source.resources ? [source.resources] : []))\n\n return Object.freeze({\n protocolVersion: 2,\n sources: Object.freeze(compiledSources),\n migrations: ordered,\n migrationsById,\n checksum: canonicalChecksum(ordered.map((migration) => ({\n id: migration.qualifiedId,\n checksum: migration.checksum,\n }))),\n })\n}\n","import type { Document } from \"mongodb\"\n\n\nconst ignoredIndexOptions = new Set([\"background\", \"key\", \"name\", \"ns\", \"v\"])\nconst falseDefaultOptions = new Set([\"hidden\", \"sparse\", \"unique\"])\nconst collationDefaults = new Map<string, unknown>([\n [\"alternate\", \"non-ignorable\"],\n [\"backwards\", false],\n [\"caseFirst\", \"off\"],\n [\"caseLevel\", false],\n [\"maxVariable\", \"punct\"],\n [\"normalization\", false],\n [\"numericOrdering\", false],\n [\"strength\", 3],\n])\n\nconst isDocument = (value: unknown): value is Document =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst hasDirection = (key: Document, direction: unknown): boolean =>\n Object.values(key).some((value) => value === direction)\n\nconst normalizeCollation = (value: unknown): unknown => {\n if (!isDocument(value)) return value\n return Object.fromEntries(\n Object.entries(value).filter(([name, option]) => (\n name !== \"version\" && collationDefaults.get(name) !== option\n )),\n )\n}\n\nconst normalizeWeights = (value: unknown): unknown => {\n if (!isDocument(value)) return value\n return Object.fromEntries(\n Object.entries(value).filter(([, weight]) => Number(weight) !== 1),\n )\n}\n\nconst normalizeIndexOptions = (options: Document, key: Document): Document => {\n const normalized = Object.fromEntries(\n Object.entries(options).filter(([name, value]) => (\n value !== undefined\n && !ignoredIndexOptions.has(name)\n && !(falseDefaultOptions.has(name) && value === false)\n )),\n )\n if (normalized.collation !== undefined) {\n normalized.collation = normalizeCollation(normalized.collation)\n }\n if (normalized.weights !== undefined) {\n normalized.weights = normalizeWeights(normalized.weights)\n if (isDocument(normalized.weights) && Object.keys(normalized.weights).length === 0) {\n delete normalized.weights\n }\n }\n if (hasDirection(key, \"text\")) {\n if (normalized.default_language === \"english\") delete normalized.default_language\n if (normalized.language_override === \"language\") delete normalized.language_override\n if (Number(normalized.textIndexVersion) === 3) delete normalized.textIndexVersion\n }\n if (hasDirection(key, \"2dsphere\") && Number(normalized[\"2dsphereIndexVersion\"]) === 3) {\n delete normalized[\"2dsphereIndexVersion\"]\n }\n return normalized\n}\n\nconst normalizeIndexKey = (\n key: Document,\n options: Document,\n declaredKey: Document,\n): readonly [string, unknown][] => {\n const entries = Object.entries(key)\n const hasTextRepresentation = entries.some(([name, direction]) => name === \"_fts\" && direction === \"text\")\n && entries.some(([name, direction]) => name === \"_ftsx\" && direction === 1)\n if (!hasTextRepresentation || !isDocument(options.weights)) return entries\n\n const actualTextFields = Object.keys(options.weights)\n const actualTextFieldSet = new Set(actualTextFields)\n const declaredTextFields = Object.entries(declaredKey)\n .filter(([, direction]) => direction === \"text\")\n .map(([name]) => name)\n const orderedTextFields = [\n ...declaredTextFields.filter((name) => actualTextFieldSet.has(name)),\n ...actualTextFields.filter((name) => !declaredTextFields.includes(name)).sort(),\n ]\n\n return entries.flatMap(([name, direction]): [string, unknown][] => {\n if (name === \"_fts\" && direction === \"text\") {\n return orderedTextFields.map((field) => [field, \"text\"])\n }\n if (name === \"_ftsx\" && direction === 1) return []\n return [[name, direction]]\n })\n}\n\nexport type NormalizedIndexDefinition = {\n key: readonly [string, unknown][]\n options: Document\n}\n\nexport const normalizeIndexDefinition = (\n key: Document,\n options: Document = {},\n declaredKey: Document = key,\n): NormalizedIndexDefinition => ({\n key: normalizeIndexKey(key, options, declaredKey),\n options: normalizeIndexOptions(options, key),\n})\n","import type { Db, Document } from \"mongodb\"\n\nimport { canonicalStringify } from \"./canonical\"\nimport { normalizeIndexDefinition } from \"./indexDefinition\"\nimport type {\n MongoResourceDivergence,\n MongoResources,\n} from \"./types\"\n\n\nconst selectKeys = (document: Document | undefined, expected: Document | undefined): Document => {\n if (!expected) return {}\n return Object.fromEntries(\n Object.keys(expected).map((key) => [key, document?.[key]]),\n )\n}\n\nconst normalizeValidatorDefinition = (document: Document | undefined): Document => ({\n ...(document?.validator !== undefined ? { validator: document.validator } : {}),\n ...(document?.validationLevel !== undefined && document.validationLevel !== \"strict\"\n ? { validationLevel: document.validationLevel }\n : {}),\n ...(document?.validationAction !== undefined && document.validationAction !== \"error\"\n ? { validationAction: document.validationAction }\n : {}),\n})\n\nconst same = (left: unknown, right: unknown): boolean =>\n canonicalStringify(left) === canonicalStringify(right)\n\nconst message = (collection: string, resource: string | undefined, detail: string): string =>\n `${collection}${resource ? `.${resource}` : \"\"}: ${detail}`\n\nexport type InspectMongoResourcesOptions = {\n signal?: AbortSignal\n requireSearchReady?: boolean\n}\n\nexport const inspectMongoResources = async (\n db: Db,\n resources: MongoResources,\n options: InspectMongoResourcesOptions = {},\n): Promise<MongoResourceDivergence[]> => {\n const divergences: MongoResourceDivergence[] = []\n const signal = options.signal\n signal?.throwIfAborted()\n\n const collectionNames = new Set([\n ...resources.collections.map((resource) => resource.name),\n ...resources.indexes.map((resource) => resource.collection),\n ...resources.searchIndexes.map((resource) => resource.collection),\n ...resources.collectionValidators.map((resource) => resource.collection),\n ])\n const listedCollections = collectionNames.size > 0\n ? await db.listCollections({ name: { $in: [...collectionNames] } }, { nameOnly: false }).toArray()\n : []\n const collectionsByName = new Map(listedCollections.map((collection) => [collection.name, collection]))\n\n for (const expected of resources.collections) {\n const actual = collectionsByName.get(expected.name)\n if (!actual) {\n divergences.push({\n code: \"missing_collection\",\n scope: expected.scope,\n collection: expected.name,\n message: message(expected.name, undefined, \"managed collection is missing\"),\n })\n continue\n }\n\n const expectedOptions = expected.options ?? {}\n const actualOptions = selectKeys(actual.options, expectedOptions)\n if (!same(actualOptions, expectedOptions)) {\n divergences.push({\n code: \"collection_options_mismatch\",\n scope: expected.scope,\n collection: expected.name,\n expected: expectedOptions,\n actual: actualOptions,\n message: message(expected.name, undefined, \"collection options differ\"),\n })\n }\n }\n\n const indexesByCollection = new Map<string, Document[]>()\n for (const expected of resources.indexes) {\n if (!collectionsByName.has(expected.collection)) {\n divergences.push({\n code: \"missing_index\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n message: message(expected.collection, expected.name, \"index collection is missing\"),\n })\n continue\n }\n\n let indexes = indexesByCollection.get(expected.collection)\n if (!indexes) {\n indexes = await db.collection(expected.collection).listIndexes().toArray()\n indexesByCollection.set(expected.collection, indexes)\n }\n const actual = indexes.find((index) => index.name === expected.name)\n if (!actual) {\n divergences.push({\n code: \"missing_index\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n message: message(expected.collection, expected.name, \"managed index is missing\"),\n })\n continue\n }\n const actualDefinition = normalizeIndexDefinition(actual.key ?? {}, actual, expected.key)\n const expectedDefinition = normalizeIndexDefinition(expected.key, {\n ...(expected.options ?? {}),\n ...(expected.runtimeOptions ?? {}),\n })\n if (!same(actualDefinition.key, expectedDefinition.key)) {\n divergences.push({\n code: \"index_key_mismatch\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n expected: expected.key,\n actual: Object.fromEntries(actualDefinition.key),\n message: message(expected.collection, expected.name, \"index keys differ\"),\n })\n }\n const expectedOptions = expectedDefinition.options\n const actualOptions = actualDefinition.options\n if (!same(actualOptions, expectedOptions)) {\n const runtimeOptionNames = new Set(Object.keys(expected.runtimeOptions ?? {}))\n const fixedOptions = (indexOptions: Document) => Object.fromEntries(\n Object.entries(indexOptions).filter(([name]) => !runtimeOptionNames.has(name)),\n )\n const runtimeOnly = runtimeOptionNames.size > 0\n && same(fixedOptions(actualOptions), fixedOptions(expectedOptions))\n divergences.push({\n code: runtimeOnly ? \"runtime_index_options_mismatch\" : \"index_options_mismatch\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n expected: expectedOptions,\n actual: actualOptions,\n message: message(expected.collection, expected.name, \"index options differ\"),\n })\n }\n }\n\n for (const expected of resources.collectionValidators) {\n const collection = collectionsByName.get(expected.collection)\n const actual = collection?.options as Document | undefined\n const expectedValidator = normalizeValidatorDefinition({\n validator: expected.validator,\n ...(expected.validationLevel ? { validationLevel: expected.validationLevel } : {}),\n ...(expected.validationAction ? { validationAction: expected.validationAction } : {}),\n })\n const actualValidator = normalizeValidatorDefinition(actual)\n if (!collection || !same(actualValidator, expectedValidator)) {\n divergences.push({\n code: \"collection_validator_mismatch\",\n scope: expected.scope,\n collection: expected.collection,\n expected: expectedValidator,\n actual: collection ? actualValidator : undefined,\n message: message(expected.collection, undefined, \"collection validator differs\"),\n })\n }\n }\n\n const searchIndexesByCollection = new Map<string, Document[] | Error>()\n for (const expected of resources.searchIndexes) {\n let indexes = searchIndexesByCollection.get(expected.collection)\n if (!indexes) {\n try {\n indexes = await db.collection(expected.collection).listSearchIndexes().toArray()\n } catch (error) {\n indexes = error instanceof Error ? error : new Error(String(error))\n }\n searchIndexesByCollection.set(expected.collection, indexes)\n }\n if (indexes instanceof Error) {\n divergences.push({\n code: \"search_unavailable\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n actual: indexes.message,\n message: message(expected.collection, expected.name, \"MongoDB Search inspection is unavailable\"),\n })\n continue\n }\n const actual = indexes.find((index) => index.name === expected.name)\n if (!actual) {\n divergences.push({\n code: \"missing_search_index\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n message: message(expected.collection, expected.name, \"managed Search index is missing\"),\n })\n continue\n }\n if (!same(actual.latestDefinition, expected.definition)) {\n divergences.push({\n code: \"search_index_definition_mismatch\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n expected: expected.definition,\n actual: actual.latestDefinition,\n message: message(expected.collection, expected.name, \"Search index definition differs\"),\n })\n }\n if (options.requireSearchReady && (actual.status !== \"READY\" || actual.queryable !== true)) {\n divergences.push({\n code: \"search_index_not_ready\",\n scope: expected.scope,\n collection: expected.collection,\n resource: expected.name,\n expected: { status: \"READY\", queryable: true },\n actual: { status: actual.status, queryable: actual.queryable },\n message: message(expected.collection, expected.name, \"Search index is not ready and queryable\"),\n })\n }\n }\n\n signal?.throwIfAborted()\n return divergences\n}\n","import type { Db, Document } from \"mongodb\"\n\nimport { canonicalStringify } from \"./canonical\"\nimport { normalizeIndexDefinition } from \"./indexDefinition\"\nimport type { MigrationHelpers, MongoResources } from \"./types\"\n\n\nconst namespaceExists = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const value = error as { code?: unknown; codeName?: unknown }\n return value.code === 48 || value.codeName === \"NamespaceExists\"\n}\n\nconst namespaceMissing = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const value = error as { code?: unknown; codeName?: unknown }\n return value.code === 26 || value.codeName === \"NamespaceNotFound\"\n}\n\nconst indexMissing = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const value = error as { code?: unknown; codeName?: unknown }\n return value.code === 27 || value.codeName === \"IndexNotFound\"\n}\n\nconst same = (left: unknown, right: unknown): boolean =>\n canonicalStringify(left) === canonicalStringify(right)\n\nconst wait = async (milliseconds: number, signal: AbortSignal): Promise<void> => {\n signal.throwIfAborted()\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort)\n resolve()\n }, milliseconds)\n const onAbort = () => {\n clearTimeout(timer)\n reject(signal.reason)\n }\n signal.addEventListener(\"abort\", onAbort, { once: true })\n })\n signal.throwIfAborted()\n}\n\nexport type CreateMigrationHelpersOptions = {\n searchTimeoutMs?: number\n searchPollIntervalMs?: number\n}\n\nexport const createMigrationHelpers = (\n db: Db,\n signal: AbortSignal,\n options: CreateMigrationHelpersOptions = {},\n): MigrationHelpers => {\n const searchTimeoutMs = options.searchTimeoutMs ?? 10 * 60_000\n const searchPollIntervalMs = options.searchPollIntervalMs ?? 1_000\n\n const ensureCollection: MigrationHelpers[\"ensureCollection\"] = async (name, collectionOptions = {}) => {\n signal.throwIfAborted()\n const existing = await db.listCollections({ name }, { nameOnly: true }).hasNext()\n if (existing) return\n try {\n await db.createCollection(name, collectionOptions)\n } catch (error) {\n if (!namespaceExists(error)) throw error\n }\n }\n\n const dropCollectionIfExists: MigrationHelpers[\"dropCollectionIfExists\"] = async (name) => {\n signal.throwIfAborted()\n try {\n await db.dropCollection(name)\n } catch (error) {\n if (!namespaceMissing(error)) throw error\n }\n }\n\n const ensureIndex: MigrationHelpers[\"ensureIndex\"] = async (collectionName, key, indexOptions) => {\n signal.throwIfAborted()\n await ensureCollection(collectionName)\n const collection = db.collection(collectionName)\n const indexes = await collection.listIndexes().toArray()\n const existing = indexes.find((index) => index.name === indexOptions.name)\n if (existing) {\n const actualDefinition = normalizeIndexDefinition(existing.key ?? {}, existing, key)\n const expectedDefinition = normalizeIndexDefinition(key, indexOptions)\n if (!same(actualDefinition, expectedDefinition)) {\n throw new Error(`Index ${collectionName}.${indexOptions.name} exists with a different definition`)\n }\n return\n }\n await collection.createIndex(key, indexOptions)\n }\n\n const dropIndexIfExists: MigrationHelpers[\"dropIndexIfExists\"] = async (collectionName, name) => {\n signal.throwIfAborted()\n try {\n await db.collection(collectionName).dropIndex(name)\n } catch (error) {\n if (!namespaceMissing(error) && !indexMissing(error)) throw error\n }\n }\n\n const findDuplicateKeys: MigrationHelpers[\"findDuplicateKeys\"] = async (collectionName, key, duplicateOptions = {}) => {\n signal.throwIfAborted()\n const id = Object.keys(key).map((path) => `$${path}`)\n const pipeline: Document[] = []\n if (duplicateOptions.filter) pipeline.push({ $match: duplicateOptions.filter })\n pipeline.push(\n { $group: { _id: id, count: { $sum: 1 } } },\n { $match: { count: { $gt: 1 } } },\n { $limit: duplicateOptions.limit ?? 20 },\n )\n const documents = await db.collection(collectionName).aggregate(\n pipeline,\n duplicateOptions.collation ? { collation: duplicateOptions.collation } : {},\n ).toArray()\n return documents.map((document) => ({ key: document._id, count: Number(document.count) }))\n }\n\n const waitForSearchIndex = async (collectionName: string, name: string): Promise<void> => {\n const deadline = Date.now() + searchTimeoutMs\n while (Date.now() < deadline) {\n signal.throwIfAborted()\n const indexes = await db.collection(collectionName).listSearchIndexes(name).toArray() as Document[]\n const index = indexes[0]\n if (index?.status === \"READY\" && index.queryable === true) return\n if (index?.status === \"FAILED\") throw new Error(`Search index ${collectionName}.${name} failed to build`)\n await wait(searchPollIntervalMs, signal)\n }\n throw new Error(`Timed out waiting for Search index ${collectionName}.${name}`)\n }\n\n const ensureSearchIndex: MigrationHelpers[\"ensureSearchIndex\"] = async (collectionName, name, definition) => {\n signal.throwIfAborted()\n await ensureCollection(collectionName)\n const collection = db.collection(collectionName)\n const indexes = await collection.listSearchIndexes(name).toArray() as Document[]\n const existing = indexes[0]\n if (!existing) {\n await collection.createSearchIndex({ name, definition })\n } else if (!same(existing.latestDefinition, definition)) {\n await collection.updateSearchIndex(name, definition)\n }\n await waitForSearchIndex(collectionName, name)\n }\n\n const dropSearchIndexIfExists: MigrationHelpers[\"dropSearchIndexIfExists\"] = async (collectionName, name) => {\n signal.throwIfAborted()\n const collection = db.collection(collectionName)\n const indexes = await collection.listSearchIndexes(name).toArray()\n if (indexes.length === 0) return\n await collection.dropSearchIndex(name)\n const deadline = Date.now() + searchTimeoutMs\n while (Date.now() < deadline) {\n signal.throwIfAborted()\n if ((await collection.listSearchIndexes(name).toArray()).length === 0) return\n await wait(searchPollIntervalMs, signal)\n }\n throw new Error(`Timed out deleting Search index ${collectionName}.${name}`)\n }\n\n const setCollectionValidator: MigrationHelpers[\"setCollectionValidator\"] = async (\n collection,\n validator,\n validatorOptions = {},\n ) => {\n signal.throwIfAborted()\n await ensureCollection(collection)\n await db.command({ collMod: collection, validator, ...validatorOptions })\n }\n\n const helpers: MigrationHelpers = {\n ensureCollection,\n dropCollectionIfExists,\n ensureIndex,\n dropIndexIfExists,\n findDuplicateKeys,\n ensureSearchIndex,\n dropSearchIndexIfExists,\n setCollectionValidator,\n reconcileResources: async (resources: MongoResources) => {\n for (const collection of resources.collections) {\n await ensureCollection(collection.name, collection.options)\n }\n for (const validator of resources.collectionValidators) {\n await setCollectionValidator(validator.collection, validator.validator, {\n ...(validator.validationLevel ? { validationLevel: validator.validationLevel } : {}),\n ...(validator.validationAction ? { validationAction: validator.validationAction } : {}),\n })\n }\n for (const index of resources.indexes) {\n await ensureIndex(index.collection, index.key, {\n name: index.name,\n ...(index.options ?? {}),\n ...(index.runtimeOptions ?? {}),\n })\n }\n for (const index of resources.searchIndexes) {\n await ensureSearchIndex(index.collection, index.name, index.definition)\n }\n },\n }\n\n return helpers\n}\n\nexport const reconcileRuntimeIndexOptions = async (\n db: Db,\n resources: MongoResources,\n signal: AbortSignal,\n): Promise<void> => {\n for (const index of resources.indexes) {\n const runtimeOptions = index.runtimeOptions ?? {}\n if (Object.keys(runtimeOptions).length === 0) continue\n signal.throwIfAborted()\n let indexes: Document[]\n try {\n indexes = await db.collection(index.collection).listIndexes().toArray()\n } catch (error) {\n if (namespaceMissing(error)) continue\n throw error\n }\n const actual = indexes.find((candidate) => candidate.name === index.name)\n if (!actual) continue\n const actualDefinition = normalizeIndexDefinition(actual.key ?? {}, actual, index.key)\n const expectedDefinition = normalizeIndexDefinition(index.key, {\n ...(index.options ?? {}),\n ...runtimeOptions,\n })\n const runtimeOptionNames = new Set(Object.keys(runtimeOptions))\n const fixedOptions = (options: Document) => Object.fromEntries(\n Object.entries(options).filter(([name]) => !runtimeOptionNames.has(name)),\n )\n if (!same(actualDefinition.key, expectedDefinition.key)\n || !same(fixedOptions(actualDefinition.options), fixedOptions(expectedDefinition.options))) {\n continue\n }\n const differs = Object.keys(runtimeOptions).some((name) => (\n !same(actualDefinition.options[name], expectedDefinition.options[name])\n ))\n if (!differs) continue\n await db.command({\n collMod: index.collection,\n index: { name: index.name, ...runtimeOptions },\n })\n }\n}\n","export class MigrationIntegrityError extends Error {\n readonly code = \"RB_MIGRATION_INTEGRITY\"\n\n constructor(message: string) {\n super(message)\n this.name = \"MigrationIntegrityError\"\n }\n}\n\nexport class MigrationLockUnavailableError extends Error {\n readonly code = \"RB_MIGRATION_LOCK_UNAVAILABLE\"\n\n constructor(message: string) {\n super(message)\n this.name = \"MigrationLockUnavailableError\"\n }\n}\n\nexport class MigrationLockLostError extends Error {\n readonly code = \"RB_MIGRATION_LOCK_LOST\"\n\n constructor(message: string) {\n super(message)\n this.name = \"MigrationLockLostError\"\n }\n}\n","import type { Db, Filter } from \"mongodb\"\n\nimport { MigrationIntegrityError } from \"./errors\"\nimport type {\n CompiledMigration,\n CompiledMigrationRegistry,\n MigrationDatabaseTarget,\n MigrationHistoryRecord,\n MigrationScope,\n} from \"./types\"\n\n\nexport const MIGRATIONS_COLLECTION = \"rbmigrations\"\n\nexport const readMigrationHistory = async (db: Db): Promise<MigrationHistoryRecord[]> =>\n db.collection<MigrationHistoryRecord>(MIGRATIONS_COLLECTION)\n .find({})\n .sort({ source: 1, sourcePosition: 1 })\n .toArray()\n\nexport const isKnownMigrationHistoryChecksum = (\n migration: CompiledMigration,\n checksum: string,\n): boolean => checksum === migration.checksum || migration.legacyHistoryChecksums.includes(checksum)\n\nexport const validateMigrationHistoryRecord = (\n migration: CompiledMigration,\n record: MigrationHistoryRecord,\n targetScope: MigrationScope,\n): string[] => {\n const errors: string[] = []\n if (!isKnownMigrationHistoryChecksum(migration, record.checksum)) {\n errors.push(`${migration.qualifiedId}: checksum differs`)\n }\n if (record.source !== migration.source) errors.push(`${migration.qualifiedId}: source differs`)\n if (record.sourcePosition !== migration.sourcePosition) errors.push(`${migration.qualifiedId}: source position differs`)\n if (record.scope !== migration.scope) errors.push(`${migration.qualifiedId}: scope differs`)\n if (migration.scope !== targetScope) {\n errors.push(`${migration.qualifiedId}: migration history is stored in a ${targetScope} database`)\n }\n if (record.phase !== migration.phase) errors.push(`${migration.qualifiedId}: phase differs`)\n if (!([\"running\", \"applied\", \"failed\"] as const).includes(record.status)) {\n errors.push(`${migration.qualifiedId}: history status is invalid`)\n }\n const expectedBeforeHash = migration.resources?.before ?? undefined\n const expectedAfterHash = migration.resources?.after\n if (record.resourcesBeforeHash !== expectedBeforeHash) {\n errors.push(`${migration.qualifiedId}: resource before checksum differs`)\n }\n if (record.resourcesAfterHash !== expectedAfterHash) {\n errors.push(`${migration.qualifiedId}: resource after checksum differs`)\n }\n return errors\n}\n\nconst checksumNormalizationFilter = (\n migration: CompiledMigration,\n record: MigrationHistoryRecord,\n): Filter<MigrationHistoryRecord> => ({\n _id: migration.qualifiedId,\n checksum: record.checksum,\n source: migration.source,\n sourcePosition: migration.sourcePosition,\n scope: migration.scope,\n phase: migration.phase,\n status: record.status,\n resourcesBeforeHash: migration.resources?.before ?? { $exists: false },\n resourcesAfterHash: migration.resources?.after ?? { $exists: false },\n})\n\nexport const normalizeLegacyMigrationHistory = async (\n registry: CompiledMigrationRegistry,\n target: MigrationDatabaseTarget,\n options: {\n assertOwned(): Promise<void>\n signal?: AbortSignal\n },\n): Promise<number> => {\n const history = await readMigrationHistory(target.db)\n const collection = target.db.collection<MigrationHistoryRecord>(MIGRATIONS_COLLECTION)\n let normalized = 0\n for (const record of history) {\n options.signal?.throwIfAborted()\n const migration = registry.migrationsById.get(record._id)\n if (!migration\n || record.checksum === migration.checksum\n || !migration.legacyHistoryChecksums.includes(record.checksum)\n || validateMigrationHistoryRecord(migration, record, target.scope).length > 0) continue\n\n await options.assertOwned()\n const result = await collection.updateOne(\n checksumNormalizationFilter(migration, record),\n { $set: { checksum: migration.checksum } },\n { writeConcern: { w: \"majority\" } },\n )\n if (result.matchedCount === 1) {\n normalized += 1\n continue\n }\n\n const current = await collection.findOne({ _id: migration.qualifiedId })\n if (current?.checksum !== migration.checksum) {\n throw new MigrationIntegrityError(\n `${migration.qualifiedId}: history state changed while normalizing its legacy checksum`,\n )\n }\n }\n return normalized\n}\n","import type { Db, MongoClient } from \"mongodb\"\n\nimport type { MigrationDatabaseProvider } from \"./types\"\n\n\nconst normalizeAppName = (value: string): string => {\n const appName = value.trim()\n if (!appName) throw new Error(\"Missing appName\")\n if (/[/\\\\.\"$*<>:|?]/.test(appName)) throw new Error(`Invalid appName: ${appName}`)\n return appName\n}\n\nconst normalizeTenantId = (value: string): string => {\n const tenantId = value.trim()\n if (!tenantId) throw new Error(\"Missing tenantId\")\n if (/[/\\\\.\"$*<>:|?]/.test(tenantId)) throw new Error(`Invalid tenantId: ${tenantId}`)\n return tenantId\n}\n\nexport type CreateMigrationDatabaseProviderOptions = {\n client: MongoClient\n appName: string\n tenantCollection?: string\n initializingTenantStaleAfterMs?: number\n filesystemRequired?: (tenantId: string, signal: AbortSignal) => boolean | Promise<boolean>\n}\n\nexport const createMigrationDatabaseProvider = (\n options: CreateMigrationDatabaseProviderOptions,\n): MigrationDatabaseProvider => {\n const appName = normalizeAppName(options.appName)\n const globalDbName = `${appName}-global-db`\n const tenantCollection = options.tenantCollection?.trim() || \"rbtenants\"\n const initializingTenantStaleAfterMs = options.initializingTenantStaleAfterMs ?? 5 * 60_000\n if (!Number.isFinite(initializingTenantStaleAfterMs) || initializingTenantStaleAfterMs < 0) {\n throw new Error(\"initializingTenantStaleAfterMs must be a non-negative finite number\")\n }\n\n const staleInitializingFilter = () => ({\n provisioningStatus: \"initializing\",\n $or: [\n { provisioningStartedAt: { $exists: false } },\n { provisioningStartedAt: { $lte: new Date(Date.now() - initializingTenantStaleAfterMs) } },\n ],\n })\n\n return {\n global: () => options.client.db(globalDbName),\n tenantIds: async (signal) => {\n signal.throwIfAborted()\n const documents = await options.client.db(globalDbName)\n .collection<{ tenantId?: unknown; provisioningStatus?: unknown }>(tenantCollection)\n .find({\n $or: [\n { provisioningStatus: { $exists: false } },\n { provisioningStatus: \"active\" },\n staleInitializingFilter(),\n ],\n }, { projection: { tenantId: 1 } })\n .sort({ tenantId: 1 })\n .toArray()\n signal.throwIfAborted()\n return [...new Set(documents.flatMap((document) => (\n typeof document.tenantId === \"string\" && document.tenantId.trim()\n ? [normalizeTenantId(document.tenantId)]\n : []\n )))]\n },\n tenantExists: async (tenantId, signal) => {\n signal.throwIfAborted()\n const normalized = normalizeTenantId(tenantId)\n const tenant = await options.client.db(globalDbName)\n .collection(tenantCollection)\n .findOne({ tenantId: normalized }, { projection: { _id: 1 } })\n signal.throwIfAborted()\n return Boolean(tenant)\n },\n tenant: (tenantId) => options.client.db(`${appName}-${normalizeTenantId(tenantId)}-db`),\n activateRecoveredTenant: async (tenantId, signal) => {\n signal.throwIfAborted()\n const result = await options.client.db(globalDbName)\n .collection(tenantCollection)\n .updateOne(\n { tenantId: normalizeTenantId(tenantId), ...staleInitializingFilter() },\n {\n $set: { provisioningStatus: \"active\", provisionedAt: new Date() },\n $unset: { provisioningError: \"\" },\n },\n )\n signal.throwIfAborted()\n return result.matchedCount === 1\n },\n filesystemRequired: options.filesystemRequired ?? (() => false),\n filesystem: (tenantId) => options.client.db(`${appName}-${normalizeTenantId(tenantId)}-filesystem-db`),\n }\n}\n\nexport const getMigrationDatabaseName = (db: Db): string => db.databaseName\n","import { filterMongoResources, mergeMongoResources } from \"./resources\"\nimport { inspectMongoResources } from \"./inspectResources\"\nimport { readMigrationHistory, validateMigrationHistoryRecord } from \"./history\"\nimport type {\n CompiledMigration,\n CompiledMigrationRegistry,\n MigrationDatabasePlan,\n MigrationDatabaseProvider,\n MigrationDatabaseTarget,\n MigrationHistoryRecord,\n MigrationPlan,\n MigrationPlanItem,\n MigrationPlanOptions,\n MigrationScope,\n MongoResources,\n} from \"./types\"\n\n\nconst neverAbortedSignal = new AbortController().signal\n\nconst toPlanItem = (migration: CompiledMigration): MigrationPlanItem => ({\n id: migration.qualifiedId,\n checksum: migration.checksum,\n source: migration.source,\n scope: migration.scope,\n phase: migration.phase,\n dependsOn: migration.dependsOn,\n})\n\nconst historyById = (history: readonly MigrationHistoryRecord[]): Map<string, MigrationHistoryRecord> =>\n new Map(history.map((record) => [record._id, record]))\n\nconst validateSourcePrefixes = (\n registry: CompiledMigrationRegistry,\n scope: MigrationScope,\n records: ReadonlyMap<string, MigrationHistoryRecord>,\n): string[] => {\n const errors: string[] = []\n for (const source of registry.sources) {\n let gap: CompiledMigration | null = null\n for (const migration of source.migrations.filter((item) => item.scope === scope)) {\n const applied = records.get(migration.qualifiedId)?.status === \"applied\"\n if (!applied && !gap) gap = migration\n if (applied && gap) {\n errors.push(`${migration.qualifiedId}: applied after missing migration ${gap.qualifiedId}`)\n }\n }\n }\n return errors\n}\n\nexport const getExpectedResources = (\n registry: CompiledMigrationRegistry,\n scope: MigrationScope,\n history: readonly MigrationHistoryRecord[],\n): MongoResources => {\n const records = historyById(history)\n const snapshots: MongoResources[] = []\n\n for (const source of registry.sources) {\n let checksum: string | null = null\n for (const migration of source.migrations) {\n if (migration.scope !== scope || !migration.resources) continue\n if (records.get(migration.qualifiedId)?.status === \"applied\") checksum = migration.resources.after\n }\n if (!checksum) continue\n const snapshot = source.resourceSnapshots.get(checksum)\n if (!snapshot) throw new Error(`Missing resource snapshot ${checksum} for ${source.name}`)\n snapshots.push(filterMongoResources(snapshot, scope))\n }\n\n return mergeMongoResources(snapshots)\n}\n\nexport const planMigrationTarget = async (\n registry: CompiledMigrationRegistry,\n target: MigrationDatabaseTarget,\n options: Pick<MigrationPlanOptions, \"allowNewerApplied\" | \"signal\"> = {},\n): Promise<MigrationDatabasePlan> => {\n const signal = options.signal ?? neverAbortedSignal\n signal.throwIfAborted()\n const history = await readMigrationHistory(target.db)\n const records = historyById(history)\n const relevant = registry.migrations.filter((migration) => migration.scope === target.scope)\n const integrityErrors: string[] = []\n const unknown: string[] = []\n\n for (const record of history) {\n const migration = registry.migrationsById.get(record._id)\n if (migration) {\n integrityErrors.push(...validateMigrationHistoryRecord(migration, record, target.scope))\n continue\n }\n\n unknown.push(record._id)\n const allowedNewerMigration = options.allowNewerApplied\n && record.status === \"applied\"\n && record.scope === target.scope\n if (!allowedNewerMigration) integrityErrors.push(`${record._id}: applied migration is absent from the registry`)\n }\n\n integrityErrors.push(...validateSourcePrefixes(registry, target.scope, records))\n\n const applied = relevant\n .filter((migration) => records.get(migration.qualifiedId)?.status === \"applied\")\n .map((migration) => migration.qualifiedId)\n const pending = relevant\n .filter((migration) => !records.has(migration.qualifiedId))\n .map(toPlanItem)\n const running = relevant\n .filter((migration) => records.get(migration.qualifiedId)?.status === \"running\")\n .map((migration) => migration.qualifiedId)\n const failed = relevant\n .filter((migration) => records.get(migration.qualifiedId)?.status === \"failed\")\n .map((migration) => migration.qualifiedId)\n const expectedResources = getExpectedResources(registry, target.scope, history)\n const resourceDivergences = options.allowNewerApplied && unknown.length > 0\n ? []\n : await inspectMongoResources(target.db, expectedResources, {\n signal,\n requireSearchReady: true,\n })\n\n return {\n database: target.db.databaseName,\n scope: target.scope,\n ...(target.tenantId ? { tenantId: target.tenantId } : {}),\n applied,\n pending,\n running,\n failed,\n unknown,\n integrityErrors,\n resourceDivergences,\n }\n}\n\nexport const collectMigrationTargets = async (\n provider: MigrationDatabaseProvider,\n options: Pick<MigrationPlanOptions, \"tenantId\" | \"signal\"> = {},\n): Promise<MigrationDatabaseTarget[]> => {\n const signal = options.signal ?? neverAbortedSignal\n const global = await provider.global()\n const targets: MigrationDatabaseTarget[] = [{ db: global, scope: \"global\" }]\n let tenantIds: string[]\n if (options.tenantId) {\n if (provider.tenantExists && !await provider.tenantExists(options.tenantId, signal)) {\n throw new Error(`Unknown tenant: ${options.tenantId}`)\n }\n tenantIds = [options.tenantId]\n } else {\n tenantIds = [...await provider.tenantIds(signal)]\n }\n\n for (const tenantId of tenantIds) {\n targets.push({ db: await provider.tenant(tenantId), scope: \"tenant\", tenantId })\n }\n if (provider.filesystem) {\n for (const tenantId of tenantIds) {\n const required = await provider.filesystemRequired?.(tenantId, signal) ?? false\n if (required) targets.push({ db: await provider.filesystem(tenantId), scope: \"filesystem\", tenantId })\n }\n }\n return targets\n}\n\nexport const planMigrations = async (\n registry: CompiledMigrationRegistry,\n provider: MigrationDatabaseProvider,\n options: MigrationPlanOptions = {},\n): Promise<MigrationPlan> => {\n const targets = await collectMigrationTargets(provider, options)\n const databases: MigrationDatabasePlan[] = []\n for (const target of targets) databases.push(await planMigrationTarget(registry, target, options))\n return {\n protocolVersion: 2,\n registryChecksum: registry.checksum,\n databases,\n hasPending: databases.some((database) => (\n database.pending.length > 0 || database.running.length > 0 || database.failed.length > 0\n )),\n hasErrors: databases.some((database) => (\n database.integrityErrors.length > 0\n || (\n database.running.length === 0\n && database.failed.length === 0\n && database.resourceDivergences.some((divergence) => (\n divergence.code !== \"runtime_index_options_mismatch\"\n ))\n )\n )),\n }\n}\n","import { randomUUID } from \"node:crypto\"\n\nimport type { Db, Document } from \"mongodb\"\n\nimport { MigrationLockLostError, MigrationLockUnavailableError } from \"./errors\"\n\n\nexport const MIGRATION_LOCKS_COLLECTION = \"rbmigrationlocks\"\n\ntype MigrationLockDocument = Document & {\n _id: string\n owner: string\n runId: string\n fence: number\n expiresAt: Date\n}\n\nexport type MigrationLock = {\n owner: string\n runId: string\n fence: number\n signal: AbortSignal\n assertOwned(): Promise<void>\n release(): Promise<void>\n}\n\nexport type AcquireMigrationLockOptions = {\n lockId?: string\n owner?: string\n runId?: string\n leaseMs?: number\n heartbeatMs?: number\n}\n\nconst isDuplicateKey = (error: unknown): boolean =>\n Boolean(error && typeof error === \"object\" && \"code\" in error && (error as { code?: unknown }).code === 11000)\n\nexport const acquireMigrationLock = async (\n db: Db,\n options: AcquireMigrationLockOptions = {},\n): Promise<MigrationLock> => {\n const lockId = options.lockId?.trim() || \"default\"\n const owner = options.owner?.trim() || randomUUID()\n const runId = options.runId?.trim() || randomUUID()\n const leaseMs = options.leaseMs ?? 120_000\n const heartbeatMs = options.heartbeatMs ?? 30_000\n if (leaseMs <= 0) throw new Error(\"Migration lock lease must be positive\")\n if (heartbeatMs <= 0 || heartbeatMs >= leaseMs) {\n throw new Error(\"Migration lock heartbeat must be positive and shorter than the lease\")\n }\n\n const collection = db.collection<MigrationLockDocument>(MIGRATION_LOCKS_COLLECTION)\n let document: MigrationLockDocument | null\n try {\n await collection.updateOne(\n { _id: lockId },\n {\n $setOnInsert: {\n owner: \"\",\n runId: \"\",\n fence: 0,\n expiresAt: new Date(0),\n },\n },\n { upsert: true, writeConcern: { w: \"majority\" } },\n )\n document = await collection.findOneAndUpdate(\n {\n _id: lockId,\n $expr: {\n $or: [\n { $lte: [{ $ifNull: [\"$expiresAt\", new Date(0)] }, \"$$NOW\"] },\n { $eq: [\"$owner\", owner] },\n ],\n },\n },\n [\n {\n $set: {\n owner,\n runId,\n fence: { $add: [{ $ifNull: [\"$fence\", 0] }, 1] },\n acquiredAt: \"$$NOW\",\n heartbeatAt: \"$$NOW\",\n expiresAt: { $dateAdd: { startDate: \"$$NOW\", unit: \"millisecond\", amount: leaseMs } },\n },\n },\n ],\n { returnDocument: \"after\", writeConcern: { w: \"majority\" } },\n )\n } catch (error) {\n if (isDuplicateKey(error)) {\n throw new MigrationLockUnavailableError(`Migration lock ${lockId} is held by another runner`)\n }\n throw error\n }\n if (!document || document.owner !== owner || document.runId !== runId) {\n throw new MigrationLockUnavailableError(`Migration lock ${lockId} could not be acquired`)\n }\n\n const fence = document.fence\n const abortController = new AbortController()\n let state: \"active\" | \"lost\" | \"released\" = \"active\"\n let heartbeatTimer: ReturnType<typeof setTimeout> | undefined\n let heartbeatPromise: Promise<void> | null = null\n\n const lose = (reason: string, cause?: unknown): MigrationLockLostError => {\n const error = new MigrationLockLostError(`Migration lock ${lockId} was lost: ${reason}`)\n if (cause !== undefined) error.cause = cause\n if (state === \"active\") {\n state = \"lost\"\n if (heartbeatTimer) clearTimeout(heartbeatTimer)\n abortController.abort(error)\n }\n return error\n }\n\n const assertOwned = async (): Promise<void> => {\n if (state === \"lost\") throw abortController.signal.reason\n if (state !== \"active\") throw new MigrationLockLostError(`Migration lock ${lockId} is no longer active`)\n const owned = await collection.findOne({\n _id: lockId,\n owner,\n runId,\n fence,\n $expr: { $gt: [\"$expiresAt\", \"$$NOW\"] },\n }, { projection: { _id: 1 } })\n if (!owned) throw lose(\"ownership or lease expiry could not be confirmed\")\n }\n\n const heartbeat = async (): Promise<void> => {\n if (state !== \"active\") return\n const result = await collection.updateOne(\n {\n _id: lockId,\n owner,\n runId,\n fence,\n $expr: { $gt: [\"$expiresAt\", \"$$NOW\"] },\n },\n [{\n $set: {\n heartbeatAt: \"$$NOW\",\n expiresAt: { $dateAdd: { startDate: \"$$NOW\", unit: \"millisecond\", amount: leaseMs } },\n },\n }],\n { writeConcern: { w: \"majority\" } },\n )\n if (result.modifiedCount !== 1) throw lose(\"heartbeat was rejected\")\n }\n\n const scheduleHeartbeat = () => {\n if (state !== \"active\") return\n heartbeatTimer = setTimeout(() => {\n heartbeatPromise = heartbeat()\n .catch((error) => {\n if (state === \"active\") lose(\"heartbeat failed\", error)\n })\n .finally(() => {\n heartbeatPromise = null\n scheduleHeartbeat()\n })\n }, heartbeatMs)\n heartbeatTimer.unref?.()\n }\n\n const release = async (): Promise<void> => {\n if (state === \"released\") return\n if (heartbeatTimer) clearTimeout(heartbeatTimer)\n if (heartbeatPromise) await heartbeatPromise.catch(() => undefined)\n if (state === \"lost\") return\n state = \"released\"\n await collection.updateOne(\n { _id: lockId, owner, runId, fence },\n {\n $set: { expiresAt: new Date(0), releasedAt: new Date() },\n $unset: { owner: \"\", runId: \"\" },\n },\n { writeConcern: { w: \"majority\" } },\n )\n }\n\n scheduleHeartbeat()\n return { owner, runId, fence, signal: abortController.signal, assertOwned, release }\n}\n","import type { Collection } from \"mongodb\"\n\nimport { MigrationIntegrityError, MigrationLockLostError } from \"./errors\"\nimport { createMigrationHelpers, reconcileRuntimeIndexOptions } from \"./helpers\"\nimport {\n MIGRATIONS_COLLECTION,\n normalizeLegacyMigrationHistory,\n readMigrationHistory,\n} from \"./history\"\nimport { inspectMongoResources } from \"./inspectResources\"\nimport { acquireMigrationLock, type MigrationLock } from \"./lock\"\nimport { filterMongoResources } from \"./resources\"\nimport {\n collectMigrationTargets,\n getExpectedResources,\n planMigrationTarget,\n planMigrations,\n} from \"./planner\"\nimport type {\n CompiledMigration,\n CompiledMigrationRegistry,\n MigrationCheckpoint,\n MigrationDatabasePlan,\n MigrationDatabaseProvider,\n MigrationDatabaseTarget,\n MigrationHistoryRecord,\n MigrationPlan,\n MigrationScope,\n MongoResources,\n RunMigrationsOptions,\n} from \"./types\"\n\n\nconst errorMessage = (error: unknown): string => {\n const message = error instanceof Error ? error.message : String(error)\n return message.slice(0, 8_000)\n}\n\nconst combineSignals = (...signals: Array<AbortSignal | undefined>): AbortSignal => {\n const active = signals.filter((signal): signal is AbortSignal => Boolean(signal))\n if (active.length === 0) return new AbortController().signal\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n\nconst assertPlanCanRun = (plan: MigrationDatabasePlan): void => {\n const retrying = plan.running.length > 0 || plan.failed.length > 0\n const errors = [\n ...plan.integrityErrors,\n ...(retrying ? [] : plan.resourceDivergences\n .filter((divergence) => divergence.code !== \"runtime_index_options_mismatch\")\n .map((divergence) => divergence.message)),\n ]\n if (errors.length > 0) {\n throw new MigrationIntegrityError(`${plan.database}: ${errors.join(\"; \")}`)\n }\n}\n\nconst recordForMigration = (\n migration: CompiledMigration,\n lock: MigrationLock,\n attempt: number,\n release: string | undefined,\n): MigrationHistoryRecord => ({\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n source: migration.source,\n sourcePosition: migration.sourcePosition,\n scope: migration.scope,\n phase: migration.phase,\n status: \"running\",\n attempt,\n ...(migration.resources?.before ? { resourcesBeforeHash: migration.resources.before } : {}),\n ...(migration.resources ? { resourcesAfterHash: migration.resources.after } : {}),\n ...(release ? { release } : {}),\n runId: lock.runId,\n fence: lock.fence,\n startedAt: new Date(),\n heartbeatAt: new Date(),\n})\n\nconst startMigration = async (\n collection: Collection<MigrationHistoryRecord>,\n migration: CompiledMigration,\n lock: MigrationLock,\n release: string | undefined,\n): Promise<MigrationHistoryRecord> => {\n await lock.assertOwned()\n const existing = await collection.findOne({ _id: migration.qualifiedId })\n if (existing?.status === \"applied\") return existing\n if (existing && existing.checksum !== migration.checksum) {\n throw new MigrationIntegrityError(`${migration.qualifiedId}: checksum differs`)\n }\n\n const record = recordForMigration(migration, lock, (existing?.attempt ?? 0) + 1, release)\n if (!existing) {\n await collection.insertOne(record, { writeConcern: { w: \"majority\" } })\n return record\n }\n\n const { _id: _recordId, ...recordUpdates } = record\n const result = await collection.findOneAndUpdate(\n {\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n status: { $in: [\"running\", \"failed\"] },\n },\n {\n $set: {\n ...recordUpdates,\n ...(existing.checkpoint !== undefined ? { checkpoint: existing.checkpoint } : {}),\n },\n $unset: { error: \"\", appliedAt: \"\", durationMs: \"\" },\n },\n { returnDocument: \"after\", writeConcern: { w: \"majority\" } },\n )\n if (!result) throw new MigrationIntegrityError(`${migration.qualifiedId}: history state changed while starting`)\n return result\n}\n\nconst createCheckpoint = <T>(\n collection: Collection<MigrationHistoryRecord>,\n migration: CompiledMigration,\n record: MigrationHistoryRecord,\n lock: MigrationLock,\n): MigrationCheckpoint<T> => {\n let value = record.checkpoint as T | undefined\n const update = async (next: T | undefined, clear: boolean): Promise<void> => {\n await lock.assertOwned()\n const result = await collection.updateOne(\n {\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n status: \"running\",\n runId: lock.runId,\n fence: lock.fence,\n },\n clear\n ? { $unset: { checkpoint: \"\" }, $set: { heartbeatAt: new Date() } }\n : { $set: { checkpoint: next, heartbeatAt: new Date() } },\n { writeConcern: { w: \"majority\" } },\n )\n if (result.matchedCount !== 1) {\n throw new MigrationLockLostError(`${migration.qualifiedId}: checkpoint ownership was lost`)\n }\n value = next\n }\n\n return {\n get value() {\n return value\n },\n save: async (next) => update(next, false),\n clear: async () => update(undefined, true),\n }\n}\n\nconst markFailed = async (\n collection: Collection<MigrationHistoryRecord>,\n migration: CompiledMigration,\n lock: MigrationLock,\n error: unknown,\n): Promise<void> => {\n await collection.updateOne(\n {\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n status: \"running\",\n runId: lock.runId,\n fence: lock.fence,\n },\n { $set: { status: \"failed\", error: errorMessage(error), heartbeatAt: new Date() } },\n { writeConcern: { w: \"majority\" } },\n )\n}\n\nconst markApplied = async (\n collection: Collection<MigrationHistoryRecord>,\n migration: CompiledMigration,\n record: MigrationHistoryRecord,\n lock: MigrationLock,\n): Promise<void> => {\n await lock.assertOwned()\n const appliedAt = new Date()\n const result = await collection.updateOne(\n {\n _id: migration.qualifiedId,\n checksum: migration.checksum,\n status: \"running\",\n runId: lock.runId,\n fence: lock.fence,\n },\n {\n $set: {\n status: \"applied\",\n appliedAt,\n heartbeatAt: appliedAt,\n durationMs: appliedAt.getTime() - record.startedAt.getTime(),\n },\n $unset: { error: \"\" },\n },\n { writeConcern: { w: \"majority\" } },\n )\n if (result.matchedCount !== 1) throw new MigrationLockLostError(`${migration.qualifiedId}: apply ownership was lost`)\n}\n\nconst getExpectedTransitionSnapshot = (\n snapshots: ReadonlyMap<string, MongoResources>,\n checksum: string,\n scope: MigrationScope,\n): MongoResources => {\n const snapshot = snapshots.get(checksum)\n if (!snapshot) throw new MigrationIntegrityError(`Missing resource snapshot ${checksum}`)\n return filterMongoResources(snapshot, scope)\n}\n\nconst applyMigration = async (\n registry: CompiledMigrationRegistry,\n target: MigrationDatabaseTarget,\n migration: CompiledMigration,\n lock: MigrationLock,\n signal: AbortSignal,\n release: string | undefined,\n): Promise<void> => {\n signal.throwIfAborted()\n const collection = target.db.collection<MigrationHistoryRecord>(MIGRATIONS_COLLECTION)\n const record = await startMigration(collection, migration, lock, release)\n if (record.status === \"applied\") return\n const checkpoint = createCheckpoint(collection, migration, record, lock)\n const source = registry.sources.find((item) => item.name === migration.source)\n const resourceTransition = migration.resources && source\n ? {\n ...(migration.resources.before\n ? { before: getExpectedTransitionSnapshot(source.resourceSnapshots, migration.resources.before, target.scope) }\n : {}),\n after: getExpectedTransitionSnapshot(source.resourceSnapshots, migration.resources.after, target.scope),\n }\n : undefined\n\n try {\n await migration.up({\n db: target.db,\n ...(target.tenantId ? { tenantId: target.tenantId } : {}),\n checkpoint,\n signal,\n helpers: createMigrationHelpers(target.db, signal),\n ...(resourceTransition ? { resources: resourceTransition } : {}),\n })\n signal.throwIfAborted()\n\n if (migration.resources) {\n const history = await readMigrationHistory(target.db)\n const hypothetical = history.map((item) => item._id === migration.qualifiedId\n ? { ...item, status: \"applied\" as const }\n : item)\n const expected = getExpectedResources(registry, target.scope, hypothetical)\n const divergences = await inspectMongoResources(target.db, expected, {\n signal,\n requireSearchReady: true,\n })\n if (divergences.length > 0) {\n throw new MigrationIntegrityError(divergences.map((divergence) => divergence.message).join(\"; \"))\n }\n }\n\n await markApplied(collection, migration, record, lock)\n } catch (error) {\n await markFailed(collection, migration, lock, error).catch(() => undefined)\n throw error\n }\n}\n\nconst sourcePredecessorsApplied = (\n registry: CompiledMigrationRegistry,\n migration: CompiledMigration,\n applied: ReadonlySet<string>,\n): boolean => registry.sources\n .find((source) => source.name === migration.source)\n ?.migrations\n .filter((candidate) => candidate.scope === migration.scope && candidate.sourcePosition < migration.sourcePosition)\n .every((candidate) => applied.has(candidate.qualifiedId)) ?? false\n\nconst runTarget = async (\n registry: CompiledMigrationRegistry,\n target: MigrationDatabaseTarget,\n lock: MigrationLock,\n signal: AbortSignal,\n options: RunMigrationsOptions,\n earlierScopeDependencyApplied: (dependency: CompiledMigration) => Promise<boolean>,\n): Promise<Set<string>> => {\n let plan = await planMigrationTarget(registry, target, { signal })\n assertPlanCanRun(plan)\n if (plan.resourceDivergences.some((divergence) => divergence.code === \"runtime_index_options_mismatch\")) {\n const history = await readMigrationHistory(target.db)\n const expectedResources = getExpectedResources(registry, target.scope, history)\n await reconcileRuntimeIndexOptions(target.db, expectedResources, signal)\n plan = await planMigrationTarget(registry, target, { signal })\n assertPlanCanRun(plan)\n }\n const applied = new Set(plan.applied)\n\n const migrationsToRun = registry.migrations.filter((migration) => (\n migration.scope === target.scope && !applied.has(migration.qualifiedId)\n ))\n for (const migration of migrationsToRun) {\n if (!sourcePredecessorsApplied(registry, migration, applied)) continue\n let dependenciesReady = true\n for (const dependencyId of migration.dependsOn) {\n const dependency = registry.migrationsById.get(dependencyId)\n if (!dependency) throw new MigrationIntegrityError(`Unknown dependency ${dependencyId}`)\n const ready = dependency.scope === target.scope\n ? applied.has(dependencyId)\n : await earlierScopeDependencyApplied(dependency)\n if (!ready) {\n dependenciesReady = false\n break\n }\n }\n if (!dependenciesReady) continue\n await applyMigration(registry, target, migration, lock, signal, options.release)\n applied.add(migration.qualifiedId)\n }\n return applied\n}\n\nconst runWithConcurrency = async <T>(\n values: readonly T[],\n concurrency: number,\n action: (value: T) => Promise<void>,\n): Promise<void> => {\n let nextIndex = 0\n let failed = false\n let failure: unknown\n const workers = Array.from({ length: Math.min(concurrency, values.length) }, async () => {\n while (nextIndex < values.length && !failed) {\n const index = nextIndex\n nextIndex += 1\n try {\n await action(values[index])\n } catch (error) {\n if (!failed) failure = error\n failed = true\n }\n }\n })\n await Promise.all(workers)\n if (failed) throw failure\n}\n\nexport const runMigrations = async (\n registry: CompiledMigrationRegistry,\n provider: MigrationDatabaseProvider,\n options: RunMigrationsOptions = {},\n): Promise<MigrationPlan> => {\n const concurrency = options.concurrency ?? 4\n if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(\"Migration concurrency must be a positive integer\")\n const globalDb = await provider.global()\n const lock = await acquireMigrationLock(globalDb, {\n lockId: options.lockId,\n leaseMs: options.leaseMs,\n heartbeatMs: options.heartbeatMs,\n })\n const signal = combineSignals(options.signal, lock.signal)\n\n try {\n const targets = await collectMigrationTargets(provider, { tenantId: options.tenantId, signal })\n await runWithConcurrency(targets, concurrency, async(target) => {\n await normalizeLegacyMigrationHistory(registry, target, {\n assertOwned: lock.assertOwned,\n signal,\n })\n })\n const globalTarget = targets.find((target) => target.scope === \"global\")\n if (!globalTarget) throw new Error(\"Migration provider did not return a global database\")\n let globalApplied = new Set<string>()\n if (options.initializeTenant) {\n const globalPlan = await planMigrationTarget(registry, globalTarget, { signal })\n assertPlanCanRun(globalPlan)\n if (globalPlan.pending.length > 0 || globalPlan.running.length > 0 || globalPlan.failed.length > 0) {\n throw new MigrationIntegrityError(\"Global migrations must be current before initializing a tenant\")\n }\n globalApplied = new Set(globalPlan.applied)\n } else {\n globalApplied = await runTarget(\n registry,\n globalTarget,\n lock,\n signal,\n options,\n async () => false,\n )\n }\n\n const tenantApplied = new Map<string, Set<string>>()\n const tenantTargets = targets.filter((target) => target.scope === \"tenant\")\n await runWithConcurrency(tenantTargets, concurrency, async (target) => {\n const applied = await runTarget(registry, target, lock, signal, options, async (dependency) => (\n dependency.scope === \"global\" && globalApplied.has(dependency.qualifiedId)\n ))\n if (target.tenantId) tenantApplied.set(target.tenantId, applied)\n })\n\n const filesystemTargets = targets.filter((target) => target.scope === \"filesystem\")\n await runWithConcurrency(filesystemTargets, concurrency, async (target) => {\n const appliedForTenant = target.tenantId ? tenantApplied.get(target.tenantId) : undefined\n await runTarget(registry, target, lock, signal, options, async (dependency) => {\n if (dependency.scope === \"global\") return globalApplied.has(dependency.qualifiedId)\n if (dependency.scope === \"tenant\") return appliedForTenant?.has(dependency.qualifiedId) ?? false\n return false\n })\n })\n\n const plan = await planMigrations(registry, provider, { tenantId: options.tenantId, signal })\n let activatedRecoveredTenant = false\n if (!options.initializeTenant && provider.activateRecoveredTenant) {\n for (const tenantId of tenantApplied.keys()) {\n const tenantPlans = plan.databases.filter((database) => database.tenantId === tenantId)\n const current = tenantPlans.length > 0 && tenantPlans.every((database) => (\n database.pending.length === 0\n && database.running.length === 0\n && database.failed.length === 0\n && database.integrityErrors.length === 0\n && database.resourceDivergences.length === 0\n ))\n if (!current) continue\n if (await provider.activateRecoveredTenant(tenantId, signal)) {\n activatedRecoveredTenant = true\n }\n }\n }\n\n return activatedRecoveredTenant\n ? await planMigrations(registry, provider, { tenantId: options.tenantId, signal })\n : plan\n } finally {\n await lock.release()\n }\n}\n\nexport const initializeTenantMigrations = async (\n registry: CompiledMigrationRegistry,\n provider: MigrationDatabaseProvider,\n tenantId: string,\n options: Omit<RunMigrationsOptions, \"tenantId\" | \"initializeTenant\"> = {},\n): Promise<MigrationPlan> => await runMigrations(registry, provider, {\n ...options,\n tenantId,\n initializeTenant: true,\n})\n","import { MigrationIntegrityError } from \"./errors\"\nimport { planMigrations } from \"./planner\"\nimport type {\n CompiledMigrationRegistry,\n MigrationDatabaseProvider,\n MigrationPlan,\n MigrationPlanOptions,\n} from \"./types\"\n\n\nexport const assertMigrationsCurrent = async (\n registry: CompiledMigrationRegistry,\n provider: MigrationDatabaseProvider,\n options: MigrationPlanOptions = {},\n): Promise<MigrationPlan> => {\n const plan = await planMigrations(registry, provider, options)\n const errors: string[] = []\n for (const database of plan.databases) {\n if (database.pending.length > 0) errors.push(`${database.database}: ${database.pending.length} migration(s) pending`)\n if (database.running.length > 0) errors.push(`${database.database}: migration running`)\n if (database.failed.length > 0) errors.push(`${database.database}: migration failed`)\n errors.push(...database.integrityErrors.map((error) => `${database.database}: ${error}`))\n errors.push(...database.resourceDivergences\n .filter((divergence) => divergence.code !== \"runtime_index_options_mismatch\")\n .map((divergence) => `${database.database}: ${divergence.message}`))\n }\n if (errors.length > 0) throw new MigrationIntegrityError(errors.join(\"; \"))\n return plan\n}\n","import { existsSync, readFileSync } from \"node:fs\"\nimport { dirname, extname, isAbsolute, resolve } from \"node:path\"\n\nimport { ImportType, initSync, parse } from \"es-module-lexer\"\n\nimport { canonicalChecksum, sha256 } from \"./canonical\"\n\n\nconst relativeImportPattern = /^(?:\\.\\.?\\/)/\nconst migrationCallPattern = /defineMigration(?:<[^>]+>)?\\s*\\(\\s*\\{/\nconst incompleteCollectionMigrationPattern = /Implement the collection option migration for/\nconst typeOnlyImportPattern = /^import\\s+type\\b/\n\ninitSync()\n\nconst resolveLocalImport = (importer: string, specifier: string): string => {\n const base = resolve(dirname(importer), specifier)\n const candidates = extname(base)\n ? [base]\n : [\n `${base}.ts`,\n `${base}.tsx`,\n `${base}.js`,\n `${base}.mjs`,\n resolve(base, \"index.ts\"),\n resolve(base, \"index.tsx\"),\n resolve(base, \"index.js\"),\n ]\n const resolved = candidates.find((candidate) => existsSync(candidate))\n if (!resolved) throw new Error(`Cannot resolve migration import ${specifier} from ${importer}`)\n return resolved\n}\n\nconst collectIntegrityFiles = (\n entry: string,\n rootDir: string,\n files: Map<string, string>,\n visiting: Set<string>,\n): void => {\n const filePath = resolve(entry)\n if (visiting.has(filePath) || files.has(filePath)) return\n if (!filePath.startsWith(`${rootDir}/`) && filePath !== rootDir) {\n throw new Error(`Migration dependency escapes integrity root: ${filePath}`)\n }\n visiting.add(filePath)\n const source = readFileSync(filePath, \"utf8\")\n const [imports] = parse(source, filePath)\n\n for (const imported of imports) {\n if (imported.t === ImportType.Dynamic\n || imported.t === ImportType.DynamicSourcePhase\n || imported.t === ImportType.DynamicDeferPhase) {\n throw new Error(`Dynamic imports are not allowed in migrations: ${filePath}`)\n }\n if (imported.t === ImportType.ImportMeta) continue\n const declaration = source.slice(imported.ss, imported.se)\n if (typeOnlyImportPattern.test(declaration)) continue\n const specifier = imported.n\n if (!specifier) throw new Error(`Cannot resolve migration import in ${filePath}`)\n if (specifier === \"@rpcbase/migrations\") continue\n if (!relativeImportPattern.test(specifier)) {\n throw new Error(`Mutable runtime import \"${specifier}\" is not allowed in migration ${filePath}`)\n }\n collectIntegrityFiles(resolveLocalImport(filePath, specifier), rootDir, files, visiting)\n }\n\n visiting.delete(filePath)\n files.set(filePath, source)\n}\n\nexport type ComputeMigrationIntegrityOptions = {\n rootDir?: string\n}\n\nexport const computeMigrationIntegrity = (\n entry: string,\n options: ComputeMigrationIntegrityOptions = {},\n): string => {\n const entryPath = resolve(entry)\n const rootDir = resolve(options.rootDir ?? dirname(entryPath))\n const files = new Map<string, string>()\n collectIntegrityFiles(entryPath, rootDir, files, new Set())\n return canonicalChecksum(\n [...files.entries()]\n .map(([filePath, source]) => ({ path: filePath.slice(rootDir.length), checksum: sha256(source) }))\n .sort((left, right) => left.path.localeCompare(right.path)),\n )\n}\n\nexport type MigrationIntegrityPluginOptions = {\n rootDir?: string\n}\n\nexport const createMigrationIntegrityPlugin = (options: MigrationIntegrityPluginOptions = {}) => ({\n name: \"rpcbase-migration-integrity\",\n enforce: \"pre\" as const,\n transform(code: string, id: string) {\n const cleanId = id.split(\"?\", 1)[0]\n if (!isAbsolute(cleanId) || !migrationCallPattern.test(code)) return null\n if (incompleteCollectionMigrationPattern.test(code)) {\n throw new Error(`Incomplete collection option migration: ${cleanId}`)\n }\n const rootDir = resolve(options.rootDir ?? dirname(cleanId))\n const integrity = computeMigrationIntegrity(cleanId, { rootDir })\n const transformed = code.replace(\n migrationCallPattern,\n (match) => `${match}\\n __rpcbaseIntegrity: ${JSON.stringify(integrity)},`,\n )\n return { code: transformed, map: null }\n },\n})\n","import { randomUUID } from \"node:crypto\"\n\nimport type { Db, MongoClient } from \"mongodb\"\n\nimport { assertMigrationsCurrent } from \"./assertCurrent\"\nimport { createMigrationDatabaseProvider } from \"./databaseProvider\"\nimport { createMigrationHelpers } from \"./helpers\"\nimport { MIGRATIONS_COLLECTION } from \"./history\"\nimport { compileMigrationRegistry, defineMigration, defineMigrationSource } from \"./registry\"\nimport { runMigrations } from \"./runner\"\nimport type {\n CompiledMigrationRegistry,\n MigrationContext,\n MigrationDefinition,\n MigrationHistoryRecord,\n MigrationScope,\n} from \"./types\"\n\n\nconst testAppNamePattern = /^rbmtest-[a-f0-9]{24}$/\nconst testTenantIdPattern = /^[a-z0-9][a-z0-9_-]{0,15}$/\n\nconst createTestAppName = (): string => `rbmtest-${randomUUID().replaceAll(\"-\", \"\").slice(0, 24)}`\n\nconst assertTestAppName = (appName: string): void => {\n if (!testAppNamePattern.test(appName)) {\n throw new Error(`Refusing to use unsafe migrations test app name: ${appName}`)\n }\n}\n\nconst databaseNames = (appName: string, tenantId: string): string[] => [\n `${appName}-global-db`,\n `${appName}-${tenantId}-db`,\n `${appName}-${tenantId}-filesystem-db`,\n]\n\nexport type TestMigrationRegistryOptions = {\n client: MongoClient\n registry: CompiledMigrationRegistry\n appName?: string\n tenantId?: string\n signal?: AbortSignal\n}\n\nexport type TestMigrationRegistryResult = {\n appName: string\n tenantId: string\n checkpointRecoveryAttempt: number\n}\n\nexport const testMigrationRegistry = async (\n options: TestMigrationRegistryOptions,\n): Promise<TestMigrationRegistryResult> => {\n const appName = options.appName ?? createTestAppName()\n const recoveryAppName = createTestAppName()\n const tenantId = options.tenantId ?? \"tenant\"\n assertTestAppName(appName)\n assertTestAppName(recoveryAppName)\n if (!testTenantIdPattern.test(tenantId)) {\n throw new Error(`Refusing to use unsafe migrations test tenant id: ${tenantId}`)\n }\n const databases = [\n ...databaseNames(appName, tenantId),\n ...databaseNames(recoveryAppName, tenantId),\n ]\n\n try {\n const provider = createMigrationDatabaseProvider({\n client: options.client,\n appName,\n filesystemRequired: () => true,\n })\n const globalDb = await provider.global()\n await globalDb.collection(\"rbtenants\").insertOne({\n tenantId,\n provisioningStatus: \"active\",\n })\n await runMigrations(options.registry, provider, {\n concurrency: 1,\n signal: options.signal,\n })\n await assertMigrationsCurrent(options.registry, provider, { signal: options.signal })\n\n const recoveryMigration = defineMigration<number>({\n id: \"20000101000000-checkpoint-recovery\",\n scope: \"global\",\n phase: \"expand\",\n async up({ checkpoint }) {\n if (checkpoint.value === 1) return\n await checkpoint.save(1)\n throw new Error(\"simulated migration interruption\")\n },\n })\n const recoveryRegistry = compileMigrationRegistry([defineMigrationSource({\n name: \"rbmtest\",\n migrations: [recoveryMigration],\n })])\n const recoveryProvider = createMigrationDatabaseProvider({\n client: options.client,\n appName: recoveryAppName,\n })\n await runMigrations(recoveryRegistry, recoveryProvider, {\n signal: options.signal,\n }).then(\n () => { throw new Error(\"Checkpoint recovery probe did not interrupt\") },\n (error) => {\n if (!(error instanceof Error) || error.message !== \"simulated migration interruption\") throw error\n },\n )\n await runMigrations(recoveryRegistry, recoveryProvider, { signal: options.signal })\n await assertMigrationsCurrent(recoveryRegistry, recoveryProvider, { signal: options.signal })\n const recoveryDb = await recoveryProvider.global()\n const history = await recoveryDb\n .collection<MigrationHistoryRecord>(MIGRATIONS_COLLECTION)\n .findOne({ _id: \"rbmtest:20000101000000-checkpoint-recovery\" })\n if (!history || history.status !== \"applied\" || history.checkpoint !== 1 || history.attempt !== 2) {\n throw new Error(\"Checkpoint recovery probe did not resume from its saved checkpoint\")\n }\n\n return { appName, tenantId, checkpointRecoveryAttempt: history.attempt }\n } finally {\n await Promise.all(databases.map(async (databaseName) => {\n if (!databaseName.startsWith(`${appName}-`) && !databaseName.startsWith(`${recoveryAppName}-`)) {\n throw new Error(`Refusing to clean unsafe migrations test database: ${databaseName}`)\n }\n await options.client.db(databaseName).dropDatabase()\n }))\n }\n}\n\nexport type TestSingleMigrationOptions<TCheckpoint = unknown> = {\n client: MongoClient\n migration: MigrationDefinition<TCheckpoint>\n scope?: MigrationScope\n tenantId?: string\n prepare(db: Db): Promise<void>\n verify(db: Db): Promise<void>\n checkpoint?: TCheckpoint\n signal?: AbortSignal\n}\n\nexport const testSingleMigration = async <TCheckpoint = unknown>(\n options: TestSingleMigrationOptions<TCheckpoint>,\n): Promise<void> => {\n const appName = createTestAppName()\n assertTestAppName(appName)\n const tenantId = options.tenantId ?? \"tenant\"\n const scope = options.scope ?? options.migration.scope\n if (scope !== \"global\" && !testTenantIdPattern.test(tenantId)) {\n throw new Error(`Refusing to use unsafe migrations test tenant id: ${tenantId}`)\n }\n const databaseName = scope === \"global\"\n ? `${appName}-global-db`\n : scope === \"filesystem\"\n ? `${appName}-${tenantId}-filesystem-db`\n : `${appName}-${tenantId}-db`\n const db = options.client.db(databaseName)\n const controller = new AbortController()\n const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal\n try {\n await options.prepare(db)\n let checkpointValue = options.checkpoint\n const context: MigrationContext<TCheckpoint> = {\n db,\n ...(scope === \"global\" ? {} : { tenantId }),\n checkpoint: {\n get value() {\n return checkpointValue\n },\n save: async (value) => { checkpointValue = value },\n clear: async () => { checkpointValue = undefined },\n },\n signal,\n helpers: createMigrationHelpers(db, signal),\n }\n await options.migration.up(context)\n await options.verify(db)\n } finally {\n controller.abort()\n await db.dropDatabase()\n }\n}\n"],"mappings":";;;;;;AAKA,IAAM,4BAA4B,UAA4B;CAC5D,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,wBAAwB;CAEnE,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAgC,CAAC,CAC7C,QAAQ,GAAG,UAAU,SAAS,KAAA,CAAS,CAAC,CACxC,MAAM,CAAC,OAAO,CAAC,WAAW,KAAK,cAAc,KAAK,CAAC,CAAC,CACpD,KAAK,CAAC,KAAK,UAAU,CAAC,KAAK,yBAAyB,IAAI,CAAC,CAAC,CAC/D;CAGF,OAAO;AACT;AAEA,IAAM,kBAAkB,UACtB,yBAAyB,KAAK,MAAM,UAAU,OAAO,EAAE,SAAS,MAAM,CAAC,CAAC;AAE1E,IAAa,sBAAsB,UAA2B,KAAK,UAAU,eAAe,KAAK,CAAC;AAElG,IAAa,UAAU,UACrB,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAEjD,IAAa,qBAAqB,UAA2B,OAAO,mBAAmB,KAAK,CAAC;;;ACV7F,IAAM,2BAAS,IAAI,IAAoB;CAAC;CAAU;CAAU;AAAY,CAAC;AACzE,IAAM,sCAAsB,IAAI,IAAI,CAAC,oBAAoB,CAAC;AAE1D,IAAM,cAAc,OAAe,UAA0B;CAC3D,MAAM,aAAa,MAAM,KAAK;CAC9B,IAAI,CAAC,YAAY,MAAM,IAAI,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BAAqB,CAyD/B,CAAA;AAED,eAAO,MAAM,uBAAuB,GAClC,UAAU,yBAAyB,EACnC,UAAS,IAAI,CAAC,oBAAoB,EAAE,UAAU,GAAG,QAAQ,CAAM,KAC9D,OAAO,CAAC,uBAAuB,EAAE,CAwBnC,CAAA;AAED,eAAO,MAAM,cAAc,GACzB,UAAU,yBAAyB,EACnC,UAAU,yBAAyB,EACnC,UAAS,oBAAyB,KACjC,OAAO,CAAC,aAAa,CAsBvB,CAAA"}
@@ -1,5 +1,6 @@
1
1
  import { CompiledMigrationRegistry, DefineMigrationRegistryOptions, MigrationDefinition, MigrationSource } from './types';
2
2
  export declare const defineMigration: <TCheckpoint = unknown>(migration: MigrationDefinition<TCheckpoint>) => MigrationDefinition<TCheckpoint>;
3
3
  export declare const defineMigrationSource: (source: MigrationSource) => MigrationSource;
4
+ export declare const computeLegacyMigrationHistoryChecksum: (migration: MigrationDefinition, source: string) => string;
4
5
  export declare const compileMigrationRegistry: (inputSources: readonly MigrationSource[], options?: DefineMigrationRegistryOptions) => CompiledMigrationRegistry;
5
6
  //# sourceMappingURL=registry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,yBAAyB,EAEzB,8BAA8B,EAC9B,mBAAmB,EAEnB,eAAe,EAEhB,MAAM,SAAS,CAAA;AA+EhB,eAAO,MAAM,eAAe,GAAI,WAAW,GAAG,OAAO,EACnD,WAAW,mBAAmB,CAAC,WAAW,CAAC,KAC1C,mBAAmB,CAAC,WAAW,CAOjC,CAAA;AAED,eAAO,MAAM,qBAAqB,GAAI,QAAQ,eAAe,KAAG,eA0B/D,CAAA;AAyED,eAAO,MAAM,wBAAwB,GACnC,cAAc,SAAS,eAAe,EAAE,EACxC,UAAS,8BAAmC,KAC3C,yBAuHF,CAAA"}
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,yBAAyB,EAEzB,8BAA8B,EAC9B,mBAAmB,EAEnB,eAAe,EAEhB,MAAM,SAAS,CAAA;AA+EhB,eAAO,MAAM,eAAe,GAAI,WAAW,GAAG,OAAO,EACnD,WAAW,mBAAmB,CAAC,WAAW,CAAC,KAC1C,mBAAmB,CAAC,WAAW,CAOjC,CAAA;AAED,eAAO,MAAM,qBAAqB,GAAI,QAAQ,eAAe,KAAG,eAyC/D,CAAA;AAmBD,eAAO,MAAM,qCAAqC,GAChD,WAAW,mBAAmB,EAC9B,QAAQ,MAAM,KACb,MAAwF,CAAA;AAyF3F,eAAO,MAAM,wBAAwB,GACnC,cAAc,SAAS,eAAe,EAAE,EACxC,UAAS,8BAAmC,KAC3C,yBAyHF,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../src/runner.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAEV,yBAAyB,EAGzB,yBAAyB,EAGzB,aAAa,EAGb,oBAAoB,EACrB,MAAM,SAAS,CAAA;AA+ThB,eAAO,MAAM,aAAa,GACxB,UAAU,yBAAyB,EACnC,UAAU,yBAAyB,EACnC,UAAS,oBAAyB,KACjC,OAAO,CAAC,aAAa,CA8EvB,CAAA;AAED,eAAO,MAAM,0BAA0B,GACrC,UAAU,yBAAyB,EACnC,UAAU,yBAAyB,EACnC,UAAU,MAAM,EAChB,UAAS,IAAI,CAAC,oBAAoB,EAAE,UAAU,GAAG,kBAAkB,CAAM,KACxE,OAAO,CAAC,aAAa,CAItB,CAAA"}
1
+ {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../src/runner.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAEV,yBAAyB,EAGzB,yBAAyB,EAGzB,aAAa,EAGb,oBAAoB,EACrB,MAAM,SAAS,CAAA;AA+ThB,eAAO,MAAM,aAAa,GACxB,UAAU,yBAAyB,EACnC,UAAU,yBAAyB,EACnC,UAAS,oBAAyB,KACjC,OAAO,CAAC,aAAa,CAoFvB,CAAA;AAED,eAAO,MAAM,0BAA0B,GACrC,UAAU,yBAAyB,EACnC,UAAU,yBAAyB,EACnC,UAAU,MAAM,EAChB,UAAS,IAAI,CAAC,oBAAoB,EAAE,UAAU,GAAG,kBAAkB,CAAM,KACxE,OAAO,CAAC,aAAa,CAItB,CAAA"}
package/dist/types.d.ts CHANGED
@@ -130,6 +130,7 @@ export type MigrationSource = {
130
130
  resources?: MongoResources;
131
131
  resourceSnapshots?: readonly MongoResources[];
132
132
  checksums?: Readonly<Record<string, string>>;
133
+ legacyHistoryChecksums?: Readonly<Record<string, readonly string[]>>;
133
134
  };
134
135
  export type CompiledMigration = Omit<MigrationDefinition, "dependsOn"> & {
135
136
  qualifiedId: string;
@@ -138,6 +139,8 @@ export type CompiledMigration = Omit<MigrationDefinition, "dependsOn"> & {
138
139
  sourcePriority: number;
139
140
  dependsOn: readonly string[];
140
141
  checksum: string;
142
+ sourceIntegrity?: string;
143
+ legacyHistoryChecksums: readonly string[];
141
144
  sealed: boolean;
142
145
  };
143
146
  export type CompiledMigrationSource = Omit<MigrationSource, "migrations" | "resourceSnapshots"> & {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAG7D,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,QAAQ,GAAG,YAAY,CAAA;AAC/D,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,UAAU,CAAA;AAElD,MAAM,MAAM,2BAA2B,GAAG;IACxC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,MAAM,MAAM,mBAAmB,CAAC,CAAC,GAAG,OAAO,IAAI;IAC7C,QAAQ,CAAC,KAAK,EAAE,CAAC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M,MAAM,oBAAoB,GAAG;IACjC,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB,CAAA;AAED,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,oBAAoB,EAAE,mBAAmB,CAAC,GAAG;IACnF,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rpcbase/migrations",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"
@@ -73,11 +73,11 @@
73
73
  }
74
74
  },
75
75
  "dependencies": {
76
- "es-module-lexer": "2.3.1",
76
+ "es-module-lexer": "2.3.2",
77
77
  "mongodb": "7.5.0"
78
78
  },
79
79
  "devDependencies": {
80
- "@types/node": "26.2.0",
81
- "vitest": "4.1.10"
80
+ "@types/node": "26.3.0",
81
+ "vitest": "4.1.11"
82
82
  }
83
83
  }