@prisma/orm-target-mongo 8.0.0-rc.24-dev.22 → 8.0.0-rc.24-dev.24

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.
@@ -1,7 +1,7 @@
1
1
  import { t as createMongoAdapter } from "./mongo-adapter-taYKXxCQ-ZFnwRXO7.mjs";
2
2
  import { MongoCodecRegistry } from "@prisma/orm-family-mongo/codec";
3
3
  import { AnyMongoDdlCommand, ListCollectionsCommand, ListIndexesCommand, MongoInspectionCommandVisitor } from "@prisma/orm-family-mongo/query-ast/control";
4
- import { ControlDriverInstance } from "@prisma/orm-framework/components/control";
4
+ import { ControlDriverInstance, DatabasePolicies, MarkerDestination } from "@prisma/orm-framework/components/control";
5
5
  import { ContractMarkerRecord, LedgerEntryRecord } from "@prisma/orm-framework/contract/types";
6
6
  import { MongoSchemaIR } from "@prisma/orm-family-mongo/schema-ir";
7
7
  import { Db, Document } from "mongodb";
@@ -44,16 +44,8 @@ declare class MongoControlAdapterImpl implements MongoControlAdapter<'mongo'> {
44
44
  executeDdl(driver: MongoQueryable, command: AnyMongoDdlCommand): Promise<void>;
45
45
  readMarker(driver: ControlDriverInstance<'mongo', 'mongo'>, space: string): Promise<ContractMarkerRecord | null>;
46
46
  readAllMarkers(driver: ControlDriverInstance<'mongo', 'mongo'>): Promise<ReadonlyMap<string, ContractMarkerRecord>>;
47
- initMarker(driver: ControlDriverInstance<'mongo', 'mongo'>, space: string, destination: {
48
- readonly storageHash: string;
49
- readonly profileHash: string;
50
- readonly invariants?: readonly string[];
51
- }): Promise<void>;
52
- updateMarker(driver: ControlDriverInstance<'mongo', 'mongo'>, space: string, expectedFrom: string, destination: {
53
- readonly storageHash: string;
54
- readonly profileHash: string;
55
- readonly invariants?: readonly string[];
56
- }): Promise<boolean>;
47
+ initMarker(driver: ControlDriverInstance<'mongo', 'mongo'>, space: string, destination: MarkerDestination): Promise<void>;
48
+ updateMarker(driver: ControlDriverInstance<'mongo', 'mongo'>, space: string, expectedFrom: string, destination: MarkerDestination, checkedPolicies?: DatabasePolicies): Promise<boolean>;
57
49
  writeLedgerEntry(driver: ControlDriverInstance<'mongo', 'mongo'>, space: string, entry: {
58
50
  readonly edgeId: string;
59
51
  readonly from: string;
@@ -1 +1 @@
1
- {"version":3,"file":"adapter__control.d.mts","names":[],"sources":["../../../../3-targets/mongo/2-adapter/dist/control.d.mts"],"mappings":";;;;;;;;;;;iBAUiB,iBAAiB,IAAI,KAAK,QAAQ;;;;;;;;;cASrC,mCAAmC,8BAA8B,QAAQ;mBACpE;EACjB,YAAY,IAAI;EAChB,YAAY,KAAK,qBAAqB,QAAQ;EAC9C,gBAAgB,MAAM,yBAAyB,QAAQ;;;;;;;;;;;;;cAa3C,mCAAmC;;WAEtC;WACA;WACA;EACT,YAAY,SAAS;EACrB,WAAW,QAAQ,gBAAgB,SAAS,qBAAqB;EACjE,WAAW,QAAQ,yCAAyC,gBAAgB,QAAQ;EACpF,eAAe,QAAQ,0CAA0C,QAAQ,oBAAoB;EAC7F,WAAW,QAAQ,yCAAyC,eAAe;aAChE;aACA;aACA;MACP;EACJ,aAAa,QAAQ,yCAAyC,eAAe,sBAAsB;aACxF;aACA;aACA;MACP;EACJ,iBAAiB,QAAQ,yCAAyC,eAAe;aACtE;aACA;aACA;aACA;aACA;aACA;MACP;EACJ,WAAW,QAAQ,yCAAyC,iBAAiB,iBAAiB;EAC9F,iBAAiB,QAAQ,0CAA0C,QAAQ;EAC3E,yBAAyB,QAAQ,0CAA0C;;;;iBAI5D,qBAAqB,QAAQ,yCAAyC,UAAU;iBAChF,UAAU,QAAQ,0CAA0C;;;cAG/D,wBAAwB"}
1
+ {"version":3,"file":"adapter__control.d.mts","names":[],"sources":["../../../../3-targets/mongo/2-adapter/dist/control.d.mts"],"mappings":";;;;;;;;;;;iBAUiB,iBAAiB,IAAI,KAAK,QAAQ;;;;;;;;;cASrC,mCAAmC,8BAA8B,QAAQ;mBACpE;EACjB,YAAY,IAAI;EAChB,YAAY,KAAK,qBAAqB,QAAQ;EAC9C,gBAAgB,MAAM,yBAAyB,QAAQ;;;;;;;;;;;;;cAa3C,mCAAmC;;WAEtC;WACA;WACA;EACT,YAAY,SAAS;EACrB,WAAW,QAAQ,gBAAgB,SAAS,qBAAqB;EACjE,WAAW,QAAQ,yCAAyC,gBAAgB,QAAQ;EACpF,eAAe,QAAQ,0CAA0C,QAAQ,oBAAoB;EAC7F,WAAW,QAAQ,yCAAyC,eAAe,aAAa,oBAAoB;EAC5G,aAAa,QAAQ,yCAAyC,eAAe,sBAAsB,aAAa,mBAAmB,kBAAkB,mBAAmB;EACxK,iBAAiB,QAAQ,yCAAyC,eAAe;aACtE;aACA;aACA;aACA;aACA;aACA;MACP;EACJ,WAAW,QAAQ,yCAAyC,iBAAiB,iBAAiB;EAC9F,iBAAiB,QAAQ,0CAA0C,QAAQ;EAC3E,yBAAyB,QAAQ,0CAA0C;;;;iBAI5D,qBAAqB,QAAQ,yCAAyC,UAAU;iBAChF,UAAU,QAAQ,0CAA0C;;;cAG/D,wBAAwB"}
@@ -1,15 +1,16 @@
1
1
  import { t as createMongoAdapter } from "./mongo-adapter-DemWVyNv-ClNih50Z.mjs";
2
2
  import { structuredError } from "@prisma/orm-framework/utils/structured-error";
3
+ import { ifDefined } from "@prisma/orm-framework/utils/defined";
3
4
  import { type } from "arktype";
4
5
  import { blindCast } from "@prisma/orm-framework/utils/casts";
5
6
  import { assembleMongoCodecRegistry } from "@prisma/orm-family-mongo/codec";
6
- import { MongoAggFieldRef, MongoAggLiteral, MongoAggOperator } from "@prisma/orm-family-mongo/query-ast/execution";
7
+ import { MongoAggCond, MongoAggFieldRef, MongoAggLiteral, MongoAggMap, MongoAggOperator, MongoExprFilter } from "@prisma/orm-family-mongo/query-ast/execution";
7
8
  import { expr, fn } from "@prisma/orm-family-mongo/query-builder";
8
9
  import { collection } from "@prisma/orm-family-mongo/query-builder/contract-free";
9
- import { APP_SPACE_ID } from "@prisma/orm-framework/components/control";
10
+ import { APP_SPACE_ID, DATABASE_POLICIES_KEYS, DATABASE_POLICIES_META_KEY, DATA_PROTECTION_KEYS, DEFAULT_DATABASE_POLICIES, storedDatabasePolicies } from "@prisma/orm-framework/components/control";
10
11
  import { MongoSchemaCollection, MongoSchemaCollectionOptions, MongoSchemaIR, MongoSchemaIndex, MongoSchemaValidator } from "@prisma/orm-family-mongo/schema-ir";
11
- import { MongoServerError } from "mongodb";
12
12
  import { parseMarkerRowSafely, withMarkerReadErrorHandling } from "@prisma/orm-framework/errors/execution";
13
+ import { MongoServerError } from "mongodb";
13
14
  import { ledgerOriginFromStored } from "@prisma/orm-toolchain/migration-tools/ledger-origin";
14
15
  //#region ../../../3-targets/mongo/2-adapter/dist/control.mjs
15
16
  const PRISMA_MIGRATIONS_COLLECTION = "_prisma_migrations";
@@ -182,6 +183,54 @@ function requireMongoControlDriver(driver) {
182
183
  function extractDb(driver) {
183
184
  return requireMongoControlDriver(driver).db;
184
185
  }
186
+ function policiesDocument(policies) {
187
+ const stored = storedDatabasePolicies(policies);
188
+ return {
189
+ change: stored.change,
190
+ dataProtection: { ...stored.dataProtection }
191
+ };
192
+ }
193
+ const POLICIES_PATH = `meta.${DATABASE_POLICIES_META_KEY}`;
194
+ function typeOf(path) {
195
+ return MongoAggOperator.of("$type", MongoAggFieldRef.of(path));
196
+ }
197
+ /**
198
+ * Holds while `path` is missing, or is an object carrying no key outside `keys`: the framework parser
199
+ * rejects any other key, so a marker with one does not hold the checked policies.
200
+ */
201
+ function missingOrObjectOf(path, keys) {
202
+ const keysAtPath = MongoAggMap.of(MongoAggOperator.of("$objectToArray", MongoAggFieldRef.of(path)), MongoAggFieldRef.of("$entry.k"), "entry");
203
+ return MongoAggCond.of(MongoAggOperator.of("$eq", [typeOf(path), MongoAggLiteral.of("object")]), MongoAggOperator.of("$setIsSubset", [keysAtPath, MongoAggLiteral.of([...keys])]), MongoAggOperator.of("$eq", [typeOf(path), MongoAggLiteral.of("missing")]));
204
+ }
205
+ function missingWhenDefault(path, isDefault) {
206
+ return isDefault ? MongoAggOperator.of("$eq", [typeOf(path), MongoAggLiteral.of("missing")]) : MongoAggLiteral.of(false);
207
+ }
208
+ function settingHolds(path, value, defaultValue) {
209
+ return MongoAggOperator.of("$or", [MongoAggOperator.of("$eq", [MongoAggFieldRef.of(path), MongoAggLiteral.of(value)]), missingWhenDefault(path, value === defaultValue)]);
210
+ }
211
+ function sameStrategies(a, b) {
212
+ const left = new Set(a);
213
+ const right = new Set(b);
214
+ return left.size === right.size && [...left].every((strategy) => right.has(strategy));
215
+ }
216
+ /**
217
+ * An aggregation predicate that holds while the marker's `meta.policies` reads as `checkedPolicies`,
218
+ * however it is stored. It follows the framework parser and its defaults: no key outside
219
+ * {@link DATABASE_POLICIES_KEYS} and {@link DATA_PROTECTION_KEYS}, `change` compared as a set, each
220
+ * data protection setting by value, and an absent setting matching only its default.
221
+ */
222
+ function policiesHoldExpr(checkedPolicies) {
223
+ const changePath = `${POLICIES_PATH}.change`;
224
+ const dataProtectionPath = `${POLICIES_PATH}.dataProtection`;
225
+ const defaults = DEFAULT_DATABASE_POLICIES;
226
+ const { change, dataProtection } = checkedPolicies;
227
+ return MongoAggOperator.of("$and", [
228
+ missingOrObjectOf(POLICIES_PATH, DATABASE_POLICIES_KEYS),
229
+ MongoAggCond.of(MongoAggOperator.of("$isArray", MongoAggFieldRef.of(changePath)), MongoAggOperator.of("$setEquals", [MongoAggFieldRef.of(changePath), MongoAggLiteral.of([...change])]), missingWhenDefault(changePath, sameStrategies(change, defaults.change))),
230
+ missingOrObjectOf(dataProtectionPath, DATA_PROTECTION_KEYS),
231
+ ...DATA_PROTECTION_KEYS.map((key) => settingHolds(`${dataProtectionPath}.${key}`, dataProtection[key], defaults.dataProtection[key]))
232
+ ]);
233
+ }
185
234
  /**
186
235
  * Mongo control adapter for control-plane operations like introspection
187
236
  * and marker-ledger CAS. Implements the family-level `MongoControlAdapter`
@@ -273,6 +322,7 @@ var MongoControlAdapterImpl = class {
273
322
  return out;
274
323
  }
275
324
  async initMarker(driver, space, destination) {
325
+ const { databasePolicies } = destination;
276
326
  const document = {
277
327
  _id: space,
278
328
  space,
@@ -282,23 +332,23 @@ var MongoControlAdapterImpl = class {
282
332
  canonicalVersion: null,
283
333
  updatedAt: /* @__PURE__ */ new Date(),
284
334
  appTag: null,
285
- meta: {},
335
+ meta: databasePolicies === void 0 ? {} : { [DATABASE_POLICIES_META_KEY]: policiesDocument(databasePolicies) },
286
336
  invariants: [...destination.invariants ?? []]
287
337
  };
288
338
  await this.#execute(driver, this.#markerLedgerCollection.insertOne(document));
289
339
  }
290
- async updateMarker(driver, space, expectedFrom, destination) {
291
- const { invariants } = destination;
292
- return (await this.#execute(driver, this.#markerLedgerCollection.match((f) => f._id.eq(space)).match((f) => f.space.eq(space)).match((f) => f.storageHash.eq(expectedFrom)).findOneAndUpdate((f) => [f.stage.set(invariants === void 0 ? {
293
- storageHash: MongoAggLiteral.of(destination.storageHash),
294
- profileHash: MongoAggLiteral.of(destination.profileHash),
295
- updatedAt: MongoAggLiteral.of(/* @__PURE__ */ new Date())
296
- } : {
340
+ async updateMarker(driver, space, expectedFrom, destination, checkedPolicies) {
341
+ const { invariants, databasePolicies } = destination;
342
+ const fields = {
297
343
  storageHash: MongoAggLiteral.of(destination.storageHash),
298
344
  profileHash: MongoAggLiteral.of(destination.profileHash),
299
345
  updatedAt: MongoAggLiteral.of(/* @__PURE__ */ new Date()),
300
- invariants: this.#invariantMergeExpr(invariants)
301
- })], { upsert: false }))).length > 0;
346
+ ...ifDefined("invariants", invariants === void 0 ? void 0 : this.#invariantMergeExpr(invariants)),
347
+ ...ifDefined(POLICIES_PATH, databasePolicies === void 0 ? void 0 : MongoAggLiteral.of(policiesDocument(databasePolicies)))
348
+ };
349
+ const atExpectedHash = this.#markerLedgerCollection.match((f) => f._id.eq(space)).match((f) => f.space.eq(space)).match((f) => f.storageHash.eq(expectedFrom));
350
+ const guarded = checkedPolicies === void 0 ? atExpectedHash : atExpectedHash.match(() => MongoExprFilter.of(policiesHoldExpr(checkedPolicies)));
351
+ return (await this.#execute(driver, guarded.findOneAndUpdate((f) => [f.stage.set(fields)], { upsert: false }))).length > 0;
302
352
  }
303
353
  async writeLedgerEntry(driver, space, entry) {
304
354
  const document = {
@@ -359,9 +409,10 @@ var MongoControlAdapterImpl = class {
359
409
  driver: controlDriver,
360
410
  executeDdl: (command) => this.executeDdl(controlDriver, command),
361
411
  markerOps: {
412
+ markerLocation: this.markerLocation,
362
413
  readMarker: (space) => this.readMarker(controlDriver, space),
363
414
  initMarker: (space, destination) => this.initMarker(controlDriver, space, destination),
364
- updateMarker: (space, expectedFrom, destination) => this.updateMarker(controlDriver, space, expectedFrom, destination),
415
+ updateMarker: (space, expectedFrom, destination, checkedPolicies) => this.updateMarker(controlDriver, space, expectedFrom, destination, checkedPolicies),
365
416
  writeLedgerEntry: (space, entry) => this.writeLedgerEntry(controlDriver, space, entry)
366
417
  },
367
418
  introspectSchema: () => this.introspectSchema(controlDriver)
@@ -1 +1 @@
1
- {"version":3,"file":"adapter__control.mjs","names":["#adapter","#execute","#markerLedgerCollection","#invariantMergeExpr"],"sources":["../../../../3-targets/mongo/2-adapter/dist/control.mjs"],"sourcesContent":["import { t as createMongoAdapter } from \"./mongo-adapter-DemWVyNv.mjs\";\nimport { MongoAggFieldRef, MongoAggLiteral, MongoAggOperator } from \"@internal/mongo-query-ast/execution\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { structuredError } from \"@internal/utils/structured-error\";\nimport { assembleMongoCodecRegistry } from \"@internal/mongo-codec\";\nimport { MongoSchemaCollection, MongoSchemaCollectionOptions, MongoSchemaIR, MongoSchemaIndex, MongoSchemaValidator } from \"@internal/mongo-schema-ir\";\nimport { MongoServerError } from \"mongodb\";\nimport { parseMarkerRowSafely, withMarkerReadErrorHandling } from \"@internal/errors/execution\";\nimport { APP_SPACE_ID } from \"@internal/framework-components/control\";\nimport { ledgerOriginFromStored } from \"@internal/migration-tools/ledger-origin\";\nimport { expr, fn } from \"@internal/mongo-query-builder\";\nimport { collection } from \"@internal/mongo-query-builder/contract-free\";\nimport { type } from \"arktype\";\n//#region src/core/introspect-schema.ts\nconst PRISMA_MIGRATIONS_COLLECTION = \"_prisma_migrations\";\nfunction parseIndexKeys(keySpec) {\n\tconst keys = [];\n\tfor (const [field, direction] of Object.entries(keySpec)) keys.push({\n\t\tfield,\n\t\tdirection\n\t});\n\treturn keys;\n}\n/**\n* Exported for unit tests to exercise the defensive `!key` guard; not part of\n* the public API. Callers in this package use it via the `introspectSchema`\n* pipeline only.\n*/\nfunction isDefaultIdIndex(doc) {\n\tconst key = doc[\"key\"];\n\tif (!key) return false;\n\tconst entries = Object.entries(key);\n\treturn entries.length === 1 && entries[0]?.[0] === \"_id\" && entries[0]?.[1] === 1;\n}\nfunction parseIndex(doc) {\n\tconst keySpec = doc[\"key\"];\n\treturn new MongoSchemaIndex({\n\t\tname: String(doc[\"name\"]),\n\t\tkeys: parseIndexKeys(keySpec),\n\t\tunique: doc[\"unique\"],\n\t\tsparse: doc[\"sparse\"],\n\t\texpireAfterSeconds: doc[\"expireAfterSeconds\"],\n\t\tpartialFilterExpression: doc[\"partialFilterExpression\"],\n\t\twildcardProjection: doc[\"wildcardProjection\"],\n\t\tcollation: doc[\"collation\"] ? blindCast(doc[\"collation\"]) : void 0,\n\t\tweights: doc[\"weights\"],\n\t\tdefault_language: doc[\"default_language\"],\n\t\tlanguage_override: doc[\"language_override\"]\n\t});\n}\nfunction parseValidator(options) {\n\tconst validator = options[\"validator\"];\n\tif (!validator) return void 0;\n\tconst jsonSchema = validator[\"$jsonSchema\"];\n\tif (!jsonSchema) return void 0;\n\treturn new MongoSchemaValidator({\n\t\tjsonSchema,\n\t\tvalidationLevel: options[\"validationLevel\"] ?? \"strict\",\n\t\tvalidationAction: options[\"validationAction\"] ?? \"error\"\n\t});\n}\nfunction parseCollectionOptions(info) {\n\tconst options = info[\"options\"];\n\tif (!options) return void 0;\n\tconst capped = options[\"capped\"];\n\tconst size = options[\"size\"];\n\tconst max = options[\"max\"];\n\tconst timeseries = options[\"timeseries\"];\n\tconst collation = options[\"collation\"] ? blindCast(options[\"collation\"]) : void 0;\n\tconst changeStreamPreAndPostImages = options[\"changeStreamPreAndPostImages\"];\n\tconst clusteredIndex = options[\"clusteredIndex\"];\n\tif (!(capped || timeseries || collation || changeStreamPreAndPostImages || clusteredIndex)) return void 0;\n\treturn new MongoSchemaCollectionOptions({\n\t\t...capped ? { capped: {\n\t\t\tsize: size ?? 0,\n\t\t\t...max != null ? { max } : {}\n\t\t} } : {},\n\t\t...timeseries ? { timeseries } : {},\n\t\t...collation ? { collation } : {},\n\t\t...changeStreamPreAndPostImages ? { changeStreamPreAndPostImages } : {},\n\t\t...clusteredIndex ? { clusteredIndex } : {}\n\t});\n}\nasync function introspectSchema(db) {\n\tconst collectionInfos = await db.listCollections().toArray();\n\tconst collections = [];\n\tfor (const info of collectionInfos) {\n\t\tconst name = info[\"name\"];\n\t\tconst type = info[\"type\"];\n\t\tif (name === PRISMA_MIGRATIONS_COLLECTION) continue;\n\t\tif (name.startsWith(\"system.\")) continue;\n\t\tif (type === \"view\") continue;\n\t\tconst indexes = (await db.collection(name).listIndexes().toArray()).filter((doc) => !isDefaultIdIndex(doc)).map(parseIndex);\n\t\tconst validator = parseValidator(\"options\" in info ? info[\"options\"] : {});\n\t\tconst options = parseCollectionOptions(info);\n\t\tcollections.push(new MongoSchemaCollection({\n\t\t\tname,\n\t\t\tindexes,\n\t\t\t...validator ? { validator } : {},\n\t\t\t...options ? { options } : {}\n\t\t}));\n\t}\n\treturn new MongoSchemaIR(collections, { fromDatabase: true });\n}\n//#endregion\n//#region src/core/migrations/inspection-executor.ts\n/**\n* Executes the read-only catalog inspections (`listCollections` / `listIndexes`)\n* that migration prechecks/postchecks and operation preview evaluate, directly\n* against `db`. Routing these checks through the adapter's lowering seam is\n* deferred to the `typed-migration-verification-queries` slice.\n*/\nvar MongoInspectionExecutor = class {\n\tdb;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tasync listIndexes(cmd) {\n\t\ttry {\n\t\t\treturn await this.db.collection(cmd.collection).listIndexes().toArray();\n\t\t} catch (error) {\n\t\t\tif (error instanceof MongoServerError && error.code === 26) return [];\n\t\t\tthrow error;\n\t\t}\n\t}\n\tasync listCollections(_cmd) {\n\t\treturn this.db.listCollections().toArray();\n\t}\n};\n//#endregion\n//#region src/core/errors.ts\nfunction mongoAdapterError(code, message, options) {\n\treturn structuredError(code, message, options);\n}\nfunction describeReceivedValue(value) {\n\tif (value === null) return \"null\";\n\tif (typeof value !== \"object\") return typeof value;\n\treturn `object with keys [${Object.keys(value).join(\", \")}]`;\n}\n//#endregion\n//#region src/core/marker-ledger.ts\nconst COLLECTION = \"_prisma_migrations\";\nconst MONGO_MARKER_COLLECTION = COLLECTION;\nconst MONGO_LEDGER_COLLECTION = `_prisma_migrations ledger documents in ${COLLECTION}`;\nconst MongoMarkerDocSchema = type({\n\tspace: \"string\",\n\tstorageHash: \"string\",\n\tprofileHash: \"string\",\n\t\"contractJson?\": \"unknown | null\",\n\t\"canonicalVersion?\": \"number | null\",\n\t\"updatedAt?\": \"Date\",\n\t\"appTag?\": \"string | null\",\n\t\"meta?\": type({ \"[string]\": \"unknown\" }).or(\"null\"),\n\t\"invariants?\": type(\"string\").array(),\n\t\"+\": \"delete\"\n});\nfunction parseMongoMarkerDoc(doc) {\n\tconst result = MongoMarkerDocSchema(doc);\n\tif (result instanceof type.errors) throw mongoAdapterError(\"CONTRACT.MARKER_ROW_CORRUPT\", `Invalid marker doc on ${COLLECTION}: ${result.summary}`, { meta: {\n\t\tcollection: COLLECTION,\n\t\tdetail: result.summary\n\t} });\n\treturn {\n\t\tstorageHash: result.storageHash,\n\t\tprofileHash: result.profileHash,\n\t\tcontractJson: result.contractJson ?? null,\n\t\tcanonicalVersion: result.canonicalVersion ?? null,\n\t\tupdatedAt: result.updatedAt ?? /* @__PURE__ */ new Date(),\n\t\tappTag: result.appTag ?? null,\n\t\tmeta: result.meta ?? {},\n\t\tinvariants: result.invariants ?? []\n\t};\n}\nfunction parseMongoMarkerDocSafely(doc, space) {\n\treturn parseMarkerRowSafely(doc, parseMongoMarkerDoc, {\n\t\tspace,\n\t\tmarkerLocation: MONGO_MARKER_COLLECTION\n\t});\n}\n//#endregion\n//#region src/core/marker-ledger-collection.ts\nconst MARKER_LEDGER_COLLECTION = \"_prisma_migrations\";\n//#endregion\n//#region src/core/migrations/mongo-control-driver.ts\nfunction isMongoControlDriver(driver) {\n\treturn driver.familyId === \"mongo\" && driver.targetId === \"mongo\" && \"execute\" in driver && typeof driver.execute === \"function\";\n}\nfunction requireMongoControlDriver(driver) {\n\tif (!isMongoControlDriver(driver)) throw mongoAdapterError(\"CONFIG.VALIDATION_FAILED\", \"Expected a Mongo control driver created by mongoControlDriver.create() from `@internal/driver-mongo/control`.\", { meta: { received: describeReceivedValue(driver) } });\n\treturn driver;\n}\nfunction extractDb(driver) {\n\treturn requireMongoControlDriver(driver).db;\n}\n//#endregion\n//#region src/core/migrations/mongo-control-adapter.ts\n/**\n* Mongo control adapter for control-plane operations like introspection\n* and marker-ledger CAS. Implements the family-level `MongoControlAdapter`\n* SPI. Every marker/ledger operation builds a canonical command inline via\n* the contract-free fluent builder and dispatches it through the family\n* adapter's lowering path (`createMongoAdapter().lower(plan, {})`) onto the\n* Mongo wire transport (`driver.execute(wireCommand)`) — the same route SQL\n* marker/ledger ops take through `adapter.lower()` → `driver.query()`.\n*/\nvar MongoControlAdapterImpl = class {\n\tfamilyId = \"mongo\";\n\ttargetId = \"mongo\";\n\tmarkerLocation = MONGO_MARKER_COLLECTION;\n\t#adapter;\n\t#markerLedgerCollection = collection(MARKER_LEDGER_COLLECTION);\n\tconstructor(codecs) {\n\t\tthis.#adapter = createMongoAdapter(codecs);\n\t}\n\tasync #execute(driver, command) {\n\t\tconst plan = {\n\t\t\tcollection: MARKER_LEDGER_COLLECTION,\n\t\t\tcommand,\n\t\t\tmeta: {\n\t\t\t\ttarget: \"mongo\",\n\t\t\t\ttargetFamily: \"mongo\",\n\t\t\t\tstorageHash: \"\",\n\t\t\t\tlane: \"control\"\n\t\t\t}\n\t\t};\n\t\tconst wireCommand = await this.#adapter.lower(plan, {});\n\t\tif (!isMongoControlDriver(driver)) throw mongoAdapterError(\"CONFIG.VALIDATION_FAILED\", \"Mongo control adapter requires a Mongo control driver with an execute() transport. Provide a MongoControlDriver from `@internal/driver-mongo/control`.\", { meta: { received: describeReceivedValue(driver) } });\n\t\tconst rows = [];\n\t\tfor await (const row of driver.execute(wireCommand)) rows.push(row);\n\t\treturn rows;\n\t}\n\tasync executeDdl(driver, command) {\n\t\tconst wire = await this.#adapter.lower({ command }, {});\n\t\tawait driver.run(wire);\n\t}\n\t/**\n\t* Server-side invariant-merge aggregation expression:\n\t* `$sortArray({ input: $setUnion([$ifNull('$invariants', []), incoming]), sortBy: 1 })`.\n\t*\n\t* Built through the typed agg-expr layer — `fn.setUnion` plus the generic\n\t* `MongoAggOperator` for `$ifNull` / `$sortArray` (neither has a named `fn`\n\t* helper). Returns a `MongoAggOperator` that is passed directly to\n\t* `f.stage.set({ invariants: ... })` in the update pipeline.\n\t*/\n\t#invariantMergeExpr(incoming) {\n\t\tconst existingOrEmpty = MongoAggOperator.of(\"$ifNull\", [MongoAggFieldRef.of(\"invariants\"), MongoAggLiteral.of([])]);\n\t\tconst merged = fn.setUnion({\n\t\t\t_field: {\n\t\t\t\tcodecId: \"mongo/array@1\",\n\t\t\t\tnullable: false\n\t\t\t},\n\t\t\tnode: existingOrEmpty\n\t\t}, {\n\t\t\t_field: {\n\t\t\t\tcodecId: \"mongo/array@1\",\n\t\t\t\tnullable: false\n\t\t\t},\n\t\t\tnode: MongoAggLiteral.of([...incoming])\n\t\t});\n\t\treturn MongoAggOperator.of(\"$sortArray\", {\n\t\t\tinput: merged.node,\n\t\t\tsortBy: MongoAggLiteral.of(1)\n\t\t});\n\t}\n\tasync readMarker(driver, space) {\n\t\tconst doc = (await withMarkerReadErrorHandling(() => this.#execute(driver, this.#markerLedgerCollection.aggregate().match((f) => f._id.eq(space)).match((f) => f.space.eq(space)).limit(1).build()), {\n\t\t\tspace,\n\t\t\tmarkerLocation: MONGO_MARKER_COLLECTION\n\t\t}))[0];\n\t\tif (!doc) return null;\n\t\treturn parseMongoMarkerDocSafely(doc, space);\n\t}\n\tasync readAllMarkers(driver) {\n\t\tconst docs = await withMarkerReadErrorHandling(() => this.#execute(driver, this.#markerLedgerCollection.aggregate().match((f) => f._id.type(\"string\")).match((f) => f.space.type(\"string\")).match((f) => expr(fn.eq(f._id, f.space))).build()), {\n\t\t\tspace: APP_SPACE_ID,\n\t\t\tmarkerLocation: MONGO_MARKER_COLLECTION\n\t\t});\n\t\tconst out = /* @__PURE__ */ new Map();\n\t\tfor (const doc of docs) {\n\t\t\tconst space = doc[\"space\"];\n\t\t\t/* v8 ignore next -- @preserve type-narrowing guard: the $match stage above filters on `space: { $type: 'string' }`, so this branch is unreachable at runtime. The check exists so the `out.set(space, ...)` call below can accept `string`. */\n\t\t\tif (typeof space !== \"string\") continue;\n\t\t\tout.set(space, parseMongoMarkerDocSafely(doc, space));\n\t\t}\n\t\treturn out;\n\t}\n\tasync initMarker(driver, space, destination) {\n\t\tconst document = {\n\t\t\t_id: space,\n\t\t\tspace,\n\t\t\tstorageHash: destination.storageHash,\n\t\t\tprofileHash: destination.profileHash,\n\t\t\tcontractJson: null,\n\t\t\tcanonicalVersion: null,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\tappTag: null,\n\t\t\tmeta: {},\n\t\t\tinvariants: [...destination.invariants ?? []]\n\t\t};\n\t\tawait this.#execute(driver, this.#markerLedgerCollection.insertOne(document));\n\t}\n\tasync updateMarker(driver, space, expectedFrom, destination) {\n\t\tconst { invariants } = destination;\n\t\treturn (await this.#execute(driver, this.#markerLedgerCollection.match((f) => f._id.eq(space)).match((f) => f.space.eq(space)).match((f) => f.storageHash.eq(expectedFrom)).findOneAndUpdate((f) => [f.stage.set(invariants === void 0 ? {\n\t\t\tstorageHash: MongoAggLiteral.of(destination.storageHash),\n\t\t\tprofileHash: MongoAggLiteral.of(destination.profileHash),\n\t\t\tupdatedAt: MongoAggLiteral.of(/* @__PURE__ */ new Date())\n\t\t} : {\n\t\t\tstorageHash: MongoAggLiteral.of(destination.storageHash),\n\t\t\tprofileHash: MongoAggLiteral.of(destination.profileHash),\n\t\t\tupdatedAt: MongoAggLiteral.of(/* @__PURE__ */ new Date()),\n\t\t\tinvariants: this.#invariantMergeExpr(invariants)\n\t\t})], { upsert: false }))).length > 0;\n\t}\n\tasync writeLedgerEntry(driver, space, entry) {\n\t\tconst document = {\n\t\t\ttype: \"ledger\",\n\t\t\tspace,\n\t\t\tedgeId: entry.edgeId,\n\t\t\tfrom: entry.from,\n\t\t\tto: entry.to,\n\t\t\tmigrationName: entry.migrationName,\n\t\t\tmigrationHash: entry.migrationHash,\n\t\t\toperations: blindCast(entry.operations),\n\t\t\tappliedAt: /* @__PURE__ */ new Date()\n\t\t};\n\t\tawait this.#execute(driver, this.#markerLedgerCollection.insertOne(document));\n\t}\n\tasync readLedger(driver, space) {\n\t\tconst ledgerContext = {\n\t\t\tspace: space ?? \"*\",\n\t\t\tmarkerLocation: MONGO_LEDGER_COLLECTION\n\t\t};\n\t\tconst chain = this.#markerLedgerCollection.aggregate().match((f) => f.type.eq(\"ledger\"));\n\t\tconst command = space === void 0 ? chain.sort({ _id: 1 }).build() : chain.match((f) => f.space.eq(space)).sort({ _id: 1 }).build();\n\t\tconst docs = await withMarkerReadErrorHandling(() => this.#execute(driver, command), ledgerContext);\n\t\tconst entries = [];\n\t\tfor (const doc of docs) {\n\t\t\tconst migrationName = doc[\"migrationName\"];\n\t\t\tconst migrationHash = doc[\"migrationHash\"];\n\t\t\tconst from = doc[\"from\"];\n\t\t\tconst to = doc[\"to\"];\n\t\t\tconst docSpace = doc[\"space\"];\n\t\t\tif (typeof migrationName !== \"string\" || typeof migrationHash !== \"string\") continue;\n\t\t\tif (typeof from !== \"string\" || typeof to !== \"string\") continue;\n\t\t\tif (typeof docSpace !== \"string\") continue;\n\t\t\tconst appliedAt = doc[\"appliedAt\"];\n\t\t\tconst appliedAtDate = appliedAt instanceof Date ? appliedAt : appliedAt !== void 0 ? new Date(String(appliedAt)) : /* @__PURE__ */ new Date();\n\t\t\tconst operations = doc[\"operations\"];\n\t\t\tconst opList = Array.isArray(operations) ? operations : [];\n\t\t\tentries.push({\n\t\t\t\tspace: docSpace,\n\t\t\t\tmigrationName,\n\t\t\t\tmigrationHash,\n\t\t\t\tfrom: ledgerOriginFromStored(from),\n\t\t\t\tto,\n\t\t\t\tappliedAt: appliedAtDate,\n\t\t\t\toperationCount: opList.length\n\t\t\t});\n\t\t}\n\t\treturn entries;\n\t}\n\tasync introspectSchema(driver) {\n\t\treturn introspectSchema(extractDb(driver));\n\t}\n\tcreateRunnerDependencies(driver) {\n\t\tconst controlDriver = requireMongoControlDriver(driver);\n\t\treturn {\n\t\t\tinspectionExecutor: new MongoInspectionExecutor(controlDriver.db),\n\t\t\tadapter: this.#adapter,\n\t\t\tdriver: controlDriver,\n\t\t\texecuteDdl: (command) => this.executeDdl(controlDriver, command),\n\t\t\tmarkerOps: {\n\t\t\t\treadMarker: (space) => this.readMarker(controlDriver, space),\n\t\t\t\tinitMarker: (space, destination) => this.initMarker(controlDriver, space, destination),\n\t\t\t\tupdateMarker: (space, expectedFrom, destination) => this.updateMarker(controlDriver, space, expectedFrom, destination),\n\t\t\t\twriteLedgerEntry: (space, entry) => this.writeLedgerEntry(controlDriver, space, entry)\n\t\t\t},\n\t\t\tintrospectSchema: () => this.introspectSchema(controlDriver)\n\t\t};\n\t}\n};\n//#endregion\n//#region src/exports/control.ts\nconst mongoAdapterDescriptor = {\n\tkind: \"adapter\",\n\tid: \"mongo\",\n\tfamilyId: \"mongo\",\n\ttargetId: \"mongo\",\n\tversion: \"0.0.1\",\n\ttypes: { codecTypes: {\n\t\timport: {\n\t\t\tpackage: \"@internal/target-mongo/codec-types\",\n\t\t\tnamed: \"CodecTypes\",\n\t\t\talias: \"MongoCodecTypes\"\n\t\t},\n\t\tparameterizedOutputTypes: {\n\t\t\tpackage: \"@internal/target-mongo/codec-types\",\n\t\t\tnamed: \"ParameterizedOutputTypesForTypeParams\",\n\t\t\talias: \"MongoParameterizedOutputTypes\"\n\t\t}\n\t} },\n\tcreate(stack) {\n\t\treturn new MongoControlAdapterImpl(assembleMongoCodecRegistry([\n\t\t\tstack.target,\n\t\t\t...stack.adapter === void 0 ? [] : [stack.adapter],\n\t\t\t...stack.extensions\n\t\t]));\n\t}\n};\n//#endregion\nexport { MongoControlAdapterImpl, MongoInspectionExecutor, createMongoAdapter, mongoAdapterDescriptor as default, mongoAdapterDescriptor, extractDb, introspectSchema, isMongoControlDriver };\n\n//# sourceMappingURL=control.mjs.map"],"mappings":";;;;;;;;;;;;;;AAcA,MAAM,+BAA+B;AACrC,SAAS,eAAe,SAAS;CAChC,MAAM,OAAO,CAAC;CACd,KAAK,MAAM,CAAC,OAAO,cAAc,OAAO,QAAQ,OAAO,GAAG,KAAK,KAAK;EACnE;EACA;CACD,CAAC;CACD,OAAO;AACR;;;;;;AAMA,SAAS,iBAAiB,KAAK;CAC9B,MAAM,MAAM,IAAI;CAChB,IAAI,CAAC,KAAK,OAAO;CACjB,MAAM,UAAU,OAAO,QAAQ,GAAG;CAClC,OAAO,QAAQ,WAAW,KAAK,QAAQ,EAAE,GAAG,OAAO,SAAS,QAAQ,EAAE,GAAG,OAAO;AACjF;AACA,SAAS,WAAW,KAAK;CACxB,MAAM,UAAU,IAAI;CACpB,OAAO,IAAI,iBAAiB;EAC3B,MAAM,OAAO,IAAI,OAAO;EACxB,MAAM,eAAe,OAAO;EAC5B,QAAQ,IAAI;EACZ,QAAQ,IAAI;EACZ,oBAAoB,IAAI;EACxB,yBAAyB,IAAI;EAC7B,oBAAoB,IAAI;EACxB,WAAW,IAAI,eAAe,UAAU,IAAI,YAAY,IAAI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AAc,gBAAgB,KAAK,aAAa,eAAe,OAAO,cAAc,WAAW;IACrH,mBAAmB,OAAO,UAAU,KAAK,iBAAiB,eAAe,OAAO,KAAK;GACtF;GACA,wBAAwB,KAAK,iBAAiB,aAAa;EAC5D;CACD;AACD;AAGA,MAAM,yBAAyB;CAC9B,MAAM;CACN,IAAI;CACJ,UAAU;CACV,UAAU;CACV,SAAS;CACT,OAAO,EAAE,YAAY;EACpB,QAAQ;GACP,SAAS;GACT,OAAO;GACP,OAAO;EACR;EACA,0BAA0B;GACzB,SAAS;GACT,OAAO;GACP,OAAO;EACR;CACD,EAAE;CACF,OAAO,OAAO;EACb,OAAO,IAAI,wBAAwB,2BAA2B;GAC7D,MAAM;GACN,GAAG,MAAM,YAAY,KAAK,IAAI,CAAC,IAAI,CAAC,MAAM,OAAO;GACjD,GAAG,MAAM;EACV,CAAC,CAAC;CACH;AACD"}
1
+ {"version":3,"file":"adapter__control.mjs","names":["#adapter","#execute","#markerLedgerCollection","#invariantMergeExpr"],"sources":["../../../../3-targets/mongo/2-adapter/dist/control.mjs"],"sourcesContent":["import { t as createMongoAdapter } from \"./mongo-adapter-DemWVyNv.mjs\";\nimport { MongoAggCond, MongoAggFieldRef, MongoAggLiteral, MongoAggMap, MongoAggOperator, MongoExprFilter } from \"@internal/mongo-query-ast/execution\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport { structuredError } from \"@internal/utils/structured-error\";\nimport { assembleMongoCodecRegistry } from \"@internal/mongo-codec\";\nimport { MongoSchemaCollection, MongoSchemaCollectionOptions, MongoSchemaIR, MongoSchemaIndex, MongoSchemaValidator } from \"@internal/mongo-schema-ir\";\nimport { MongoServerError } from \"mongodb\";\nimport { parseMarkerRowSafely, withMarkerReadErrorHandling } from \"@internal/errors/execution\";\nimport { APP_SPACE_ID, DATABASE_POLICIES_KEYS, DATABASE_POLICIES_META_KEY, DATA_PROTECTION_KEYS, DEFAULT_DATABASE_POLICIES, storedDatabasePolicies } from \"@internal/framework-components/control\";\nimport { ledgerOriginFromStored } from \"@internal/migration-tools/ledger-origin\";\nimport { expr, fn } from \"@internal/mongo-query-builder\";\nimport { collection } from \"@internal/mongo-query-builder/contract-free\";\nimport { type } from \"arktype\";\n//#region src/core/introspect-schema.ts\nconst PRISMA_MIGRATIONS_COLLECTION = \"_prisma_migrations\";\nfunction parseIndexKeys(keySpec) {\n\tconst keys = [];\n\tfor (const [field, direction] of Object.entries(keySpec)) keys.push({\n\t\tfield,\n\t\tdirection\n\t});\n\treturn keys;\n}\n/**\n* Exported for unit tests to exercise the defensive `!key` guard; not part of\n* the public API. Callers in this package use it via the `introspectSchema`\n* pipeline only.\n*/\nfunction isDefaultIdIndex(doc) {\n\tconst key = doc[\"key\"];\n\tif (!key) return false;\n\tconst entries = Object.entries(key);\n\treturn entries.length === 1 && entries[0]?.[0] === \"_id\" && entries[0]?.[1] === 1;\n}\nfunction parseIndex(doc) {\n\tconst keySpec = doc[\"key\"];\n\treturn new MongoSchemaIndex({\n\t\tname: String(doc[\"name\"]),\n\t\tkeys: parseIndexKeys(keySpec),\n\t\tunique: doc[\"unique\"],\n\t\tsparse: doc[\"sparse\"],\n\t\texpireAfterSeconds: doc[\"expireAfterSeconds\"],\n\t\tpartialFilterExpression: doc[\"partialFilterExpression\"],\n\t\twildcardProjection: doc[\"wildcardProjection\"],\n\t\tcollation: doc[\"collation\"] ? blindCast(doc[\"collation\"]) : void 0,\n\t\tweights: doc[\"weights\"],\n\t\tdefault_language: doc[\"default_language\"],\n\t\tlanguage_override: doc[\"language_override\"]\n\t});\n}\nfunction parseValidator(options) {\n\tconst validator = options[\"validator\"];\n\tif (!validator) return void 0;\n\tconst jsonSchema = validator[\"$jsonSchema\"];\n\tif (!jsonSchema) return void 0;\n\treturn new MongoSchemaValidator({\n\t\tjsonSchema,\n\t\tvalidationLevel: options[\"validationLevel\"] ?? \"strict\",\n\t\tvalidationAction: options[\"validationAction\"] ?? \"error\"\n\t});\n}\nfunction parseCollectionOptions(info) {\n\tconst options = info[\"options\"];\n\tif (!options) return void 0;\n\tconst capped = options[\"capped\"];\n\tconst size = options[\"size\"];\n\tconst max = options[\"max\"];\n\tconst timeseries = options[\"timeseries\"];\n\tconst collation = options[\"collation\"] ? blindCast(options[\"collation\"]) : void 0;\n\tconst changeStreamPreAndPostImages = options[\"changeStreamPreAndPostImages\"];\n\tconst clusteredIndex = options[\"clusteredIndex\"];\n\tif (!(capped || timeseries || collation || changeStreamPreAndPostImages || clusteredIndex)) return void 0;\n\treturn new MongoSchemaCollectionOptions({\n\t\t...capped ? { capped: {\n\t\t\tsize: size ?? 0,\n\t\t\t...max != null ? { max } : {}\n\t\t} } : {},\n\t\t...timeseries ? { timeseries } : {},\n\t\t...collation ? { collation } : {},\n\t\t...changeStreamPreAndPostImages ? { changeStreamPreAndPostImages } : {},\n\t\t...clusteredIndex ? { clusteredIndex } : {}\n\t});\n}\nasync function introspectSchema(db) {\n\tconst collectionInfos = await db.listCollections().toArray();\n\tconst collections = [];\n\tfor (const info of collectionInfos) {\n\t\tconst name = info[\"name\"];\n\t\tconst type = info[\"type\"];\n\t\tif (name === PRISMA_MIGRATIONS_COLLECTION) continue;\n\t\tif (name.startsWith(\"system.\")) continue;\n\t\tif (type === \"view\") continue;\n\t\tconst indexes = (await db.collection(name).listIndexes().toArray()).filter((doc) => !isDefaultIdIndex(doc)).map(parseIndex);\n\t\tconst validator = parseValidator(\"options\" in info ? info[\"options\"] : {});\n\t\tconst options = parseCollectionOptions(info);\n\t\tcollections.push(new MongoSchemaCollection({\n\t\t\tname,\n\t\t\tindexes,\n\t\t\t...validator ? { validator } : {},\n\t\t\t...options ? { options } : {}\n\t\t}));\n\t}\n\treturn new MongoSchemaIR(collections, { fromDatabase: true });\n}\n//#endregion\n//#region src/core/migrations/inspection-executor.ts\n/**\n* Executes the read-only catalog inspections (`listCollections` / `listIndexes`)\n* that migration prechecks/postchecks and operation preview evaluate, directly\n* against `db`. Routing these checks through the adapter's lowering seam is\n* deferred to the `typed-migration-verification-queries` slice.\n*/\nvar MongoInspectionExecutor = class {\n\tdb;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tasync listIndexes(cmd) {\n\t\ttry {\n\t\t\treturn await this.db.collection(cmd.collection).listIndexes().toArray();\n\t\t} catch (error) {\n\t\t\tif (error instanceof MongoServerError && error.code === 26) return [];\n\t\t\tthrow error;\n\t\t}\n\t}\n\tasync listCollections(_cmd) {\n\t\treturn this.db.listCollections().toArray();\n\t}\n};\n//#endregion\n//#region src/core/errors.ts\nfunction mongoAdapterError(code, message, options) {\n\treturn structuredError(code, message, options);\n}\nfunction describeReceivedValue(value) {\n\tif (value === null) return \"null\";\n\tif (typeof value !== \"object\") return typeof value;\n\treturn `object with keys [${Object.keys(value).join(\", \")}]`;\n}\n//#endregion\n//#region src/core/marker-ledger.ts\nconst COLLECTION = \"_prisma_migrations\";\nconst MONGO_MARKER_COLLECTION = COLLECTION;\nconst MONGO_LEDGER_COLLECTION = `_prisma_migrations ledger documents in ${COLLECTION}`;\nconst MongoMarkerDocSchema = type({\n\tspace: \"string\",\n\tstorageHash: \"string\",\n\tprofileHash: \"string\",\n\t\"contractJson?\": \"unknown | null\",\n\t\"canonicalVersion?\": \"number | null\",\n\t\"updatedAt?\": \"Date\",\n\t\"appTag?\": \"string | null\",\n\t\"meta?\": type({ \"[string]\": \"unknown\" }).or(\"null\"),\n\t\"invariants?\": type(\"string\").array(),\n\t\"+\": \"delete\"\n});\nfunction parseMongoMarkerDoc(doc) {\n\tconst result = MongoMarkerDocSchema(doc);\n\tif (result instanceof type.errors) throw mongoAdapterError(\"CONTRACT.MARKER_ROW_CORRUPT\", `Invalid marker doc on ${COLLECTION}: ${result.summary}`, { meta: {\n\t\tcollection: COLLECTION,\n\t\tdetail: result.summary\n\t} });\n\treturn {\n\t\tstorageHash: result.storageHash,\n\t\tprofileHash: result.profileHash,\n\t\tcontractJson: result.contractJson ?? null,\n\t\tcanonicalVersion: result.canonicalVersion ?? null,\n\t\tupdatedAt: result.updatedAt ?? /* @__PURE__ */ new Date(),\n\t\tappTag: result.appTag ?? null,\n\t\tmeta: result.meta ?? {},\n\t\tinvariants: result.invariants ?? []\n\t};\n}\nfunction parseMongoMarkerDocSafely(doc, space) {\n\treturn parseMarkerRowSafely(doc, parseMongoMarkerDoc, {\n\t\tspace,\n\t\tmarkerLocation: MONGO_MARKER_COLLECTION\n\t});\n}\n//#endregion\n//#region src/core/marker-ledger-collection.ts\nconst MARKER_LEDGER_COLLECTION = \"_prisma_migrations\";\n//#endregion\n//#region src/core/migrations/mongo-control-driver.ts\nfunction isMongoControlDriver(driver) {\n\treturn driver.familyId === \"mongo\" && driver.targetId === \"mongo\" && \"execute\" in driver && typeof driver.execute === \"function\";\n}\nfunction requireMongoControlDriver(driver) {\n\tif (!isMongoControlDriver(driver)) throw mongoAdapterError(\"CONFIG.VALIDATION_FAILED\", \"Expected a Mongo control driver created by mongoControlDriver.create() from `@internal/driver-mongo/control`.\", { meta: { received: describeReceivedValue(driver) } });\n\treturn driver;\n}\nfunction extractDb(driver) {\n\treturn requireMongoControlDriver(driver).db;\n}\n//#endregion\n//#region src/core/migrations/mongo-control-adapter.ts\nfunction policiesDocument(policies) {\n\tconst stored = storedDatabasePolicies(policies);\n\treturn {\n\t\tchange: stored.change,\n\t\tdataProtection: { ...stored.dataProtection }\n\t};\n}\nconst POLICIES_PATH = `meta.${DATABASE_POLICIES_META_KEY}`;\nfunction typeOf(path) {\n\treturn MongoAggOperator.of(\"$type\", MongoAggFieldRef.of(path));\n}\n/**\n* Holds while `path` is missing, or is an object carrying no key outside `keys`: the framework parser\n* rejects any other key, so a marker with one does not hold the checked policies.\n*/\nfunction missingOrObjectOf(path, keys) {\n\tconst keysAtPath = MongoAggMap.of(MongoAggOperator.of(\"$objectToArray\", MongoAggFieldRef.of(path)), MongoAggFieldRef.of(\"$entry.k\"), \"entry\");\n\treturn MongoAggCond.of(MongoAggOperator.of(\"$eq\", [typeOf(path), MongoAggLiteral.of(\"object\")]), MongoAggOperator.of(\"$setIsSubset\", [keysAtPath, MongoAggLiteral.of([...keys])]), MongoAggOperator.of(\"$eq\", [typeOf(path), MongoAggLiteral.of(\"missing\")]));\n}\nfunction missingWhenDefault(path, isDefault) {\n\treturn isDefault ? MongoAggOperator.of(\"$eq\", [typeOf(path), MongoAggLiteral.of(\"missing\")]) : MongoAggLiteral.of(false);\n}\nfunction settingHolds(path, value, defaultValue) {\n\treturn MongoAggOperator.of(\"$or\", [MongoAggOperator.of(\"$eq\", [MongoAggFieldRef.of(path), MongoAggLiteral.of(value)]), missingWhenDefault(path, value === defaultValue)]);\n}\nfunction sameStrategies(a, b) {\n\tconst left = new Set(a);\n\tconst right = new Set(b);\n\treturn left.size === right.size && [...left].every((strategy) => right.has(strategy));\n}\n/**\n* An aggregation predicate that holds while the marker's `meta.policies` reads as `checkedPolicies`,\n* however it is stored. It follows the framework parser and its defaults: no key outside\n* {@link DATABASE_POLICIES_KEYS} and {@link DATA_PROTECTION_KEYS}, `change` compared as a set, each\n* data protection setting by value, and an absent setting matching only its default.\n*/\nfunction policiesHoldExpr(checkedPolicies) {\n\tconst changePath = `${POLICIES_PATH}.change`;\n\tconst dataProtectionPath = `${POLICIES_PATH}.dataProtection`;\n\tconst defaults = DEFAULT_DATABASE_POLICIES;\n\tconst { change, dataProtection } = checkedPolicies;\n\treturn MongoAggOperator.of(\"$and\", [\n\t\tmissingOrObjectOf(POLICIES_PATH, DATABASE_POLICIES_KEYS),\n\t\tMongoAggCond.of(MongoAggOperator.of(\"$isArray\", MongoAggFieldRef.of(changePath)), MongoAggOperator.of(\"$setEquals\", [MongoAggFieldRef.of(changePath), MongoAggLiteral.of([...change])]), missingWhenDefault(changePath, sameStrategies(change, defaults.change))),\n\t\tmissingOrObjectOf(dataProtectionPath, DATA_PROTECTION_KEYS),\n\t\t...DATA_PROTECTION_KEYS.map((key) => settingHolds(`${dataProtectionPath}.${key}`, dataProtection[key], defaults.dataProtection[key]))\n\t]);\n}\n/**\n* Mongo control adapter for control-plane operations like introspection\n* and marker-ledger CAS. Implements the family-level `MongoControlAdapter`\n* SPI. Every marker/ledger operation builds a canonical command inline via\n* the contract-free fluent builder and dispatches it through the family\n* adapter's lowering path (`createMongoAdapter().lower(plan, {})`) onto the\n* Mongo wire transport (`driver.execute(wireCommand)`) — the same route SQL\n* marker/ledger ops take through `adapter.lower()` → `driver.query()`.\n*/\nvar MongoControlAdapterImpl = class {\n\tfamilyId = \"mongo\";\n\ttargetId = \"mongo\";\n\tmarkerLocation = MONGO_MARKER_COLLECTION;\n\t#adapter;\n\t#markerLedgerCollection = collection(MARKER_LEDGER_COLLECTION);\n\tconstructor(codecs) {\n\t\tthis.#adapter = createMongoAdapter(codecs);\n\t}\n\tasync #execute(driver, command) {\n\t\tconst plan = {\n\t\t\tcollection: MARKER_LEDGER_COLLECTION,\n\t\t\tcommand,\n\t\t\tmeta: {\n\t\t\t\ttarget: \"mongo\",\n\t\t\t\ttargetFamily: \"mongo\",\n\t\t\t\tstorageHash: \"\",\n\t\t\t\tlane: \"control\"\n\t\t\t}\n\t\t};\n\t\tconst wireCommand = await this.#adapter.lower(plan, {});\n\t\tif (!isMongoControlDriver(driver)) throw mongoAdapterError(\"CONFIG.VALIDATION_FAILED\", \"Mongo control adapter requires a Mongo control driver with an execute() transport. Provide a MongoControlDriver from `@internal/driver-mongo/control`.\", { meta: { received: describeReceivedValue(driver) } });\n\t\tconst rows = [];\n\t\tfor await (const row of driver.execute(wireCommand)) rows.push(row);\n\t\treturn rows;\n\t}\n\tasync executeDdl(driver, command) {\n\t\tconst wire = await this.#adapter.lower({ command }, {});\n\t\tawait driver.run(wire);\n\t}\n\t/**\n\t* Server-side invariant-merge aggregation expression:\n\t* `$sortArray({ input: $setUnion([$ifNull('$invariants', []), incoming]), sortBy: 1 })`.\n\t*\n\t* Built through the typed agg-expr layer — `fn.setUnion` plus the generic\n\t* `MongoAggOperator` for `$ifNull` / `$sortArray` (neither has a named `fn`\n\t* helper). Returns a `MongoAggOperator` that is passed directly to\n\t* `f.stage.set({ invariants: ... })` in the update pipeline.\n\t*/\n\t#invariantMergeExpr(incoming) {\n\t\tconst existingOrEmpty = MongoAggOperator.of(\"$ifNull\", [MongoAggFieldRef.of(\"invariants\"), MongoAggLiteral.of([])]);\n\t\tconst merged = fn.setUnion({\n\t\t\t_field: {\n\t\t\t\tcodecId: \"mongo/array@1\",\n\t\t\t\tnullable: false\n\t\t\t},\n\t\t\tnode: existingOrEmpty\n\t\t}, {\n\t\t\t_field: {\n\t\t\t\tcodecId: \"mongo/array@1\",\n\t\t\t\tnullable: false\n\t\t\t},\n\t\t\tnode: MongoAggLiteral.of([...incoming])\n\t\t});\n\t\treturn MongoAggOperator.of(\"$sortArray\", {\n\t\t\tinput: merged.node,\n\t\t\tsortBy: MongoAggLiteral.of(1)\n\t\t});\n\t}\n\tasync readMarker(driver, space) {\n\t\tconst doc = (await withMarkerReadErrorHandling(() => this.#execute(driver, this.#markerLedgerCollection.aggregate().match((f) => f._id.eq(space)).match((f) => f.space.eq(space)).limit(1).build()), {\n\t\t\tspace,\n\t\t\tmarkerLocation: MONGO_MARKER_COLLECTION\n\t\t}))[0];\n\t\tif (!doc) return null;\n\t\treturn parseMongoMarkerDocSafely(doc, space);\n\t}\n\tasync readAllMarkers(driver) {\n\t\tconst docs = await withMarkerReadErrorHandling(() => this.#execute(driver, this.#markerLedgerCollection.aggregate().match((f) => f._id.type(\"string\")).match((f) => f.space.type(\"string\")).match((f) => expr(fn.eq(f._id, f.space))).build()), {\n\t\t\tspace: APP_SPACE_ID,\n\t\t\tmarkerLocation: MONGO_MARKER_COLLECTION\n\t\t});\n\t\tconst out = /* @__PURE__ */ new Map();\n\t\tfor (const doc of docs) {\n\t\t\tconst space = doc[\"space\"];\n\t\t\t/* v8 ignore next -- @preserve type-narrowing guard: the $match stage above filters on `space: { $type: 'string' }`, so this branch is unreachable at runtime. The check exists so the `out.set(space, ...)` call below can accept `string`. */\n\t\t\tif (typeof space !== \"string\") continue;\n\t\t\tout.set(space, parseMongoMarkerDocSafely(doc, space));\n\t\t}\n\t\treturn out;\n\t}\n\tasync initMarker(driver, space, destination) {\n\t\tconst { databasePolicies } = destination;\n\t\tconst document = {\n\t\t\t_id: space,\n\t\t\tspace,\n\t\t\tstorageHash: destination.storageHash,\n\t\t\tprofileHash: destination.profileHash,\n\t\t\tcontractJson: null,\n\t\t\tcanonicalVersion: null,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t\tappTag: null,\n\t\t\tmeta: databasePolicies === void 0 ? {} : { [DATABASE_POLICIES_META_KEY]: policiesDocument(databasePolicies) },\n\t\t\tinvariants: [...destination.invariants ?? []]\n\t\t};\n\t\tawait this.#execute(driver, this.#markerLedgerCollection.insertOne(document));\n\t}\n\tasync updateMarker(driver, space, expectedFrom, destination, checkedPolicies) {\n\t\tconst { invariants, databasePolicies } = destination;\n\t\tconst fields = {\n\t\t\tstorageHash: MongoAggLiteral.of(destination.storageHash),\n\t\t\tprofileHash: MongoAggLiteral.of(destination.profileHash),\n\t\t\tupdatedAt: MongoAggLiteral.of(/* @__PURE__ */ new Date()),\n\t\t\t...ifDefined(\"invariants\", invariants === void 0 ? void 0 : this.#invariantMergeExpr(invariants)),\n\t\t\t...ifDefined(POLICIES_PATH, databasePolicies === void 0 ? void 0 : MongoAggLiteral.of(policiesDocument(databasePolicies)))\n\t\t};\n\t\tconst atExpectedHash = this.#markerLedgerCollection.match((f) => f._id.eq(space)).match((f) => f.space.eq(space)).match((f) => f.storageHash.eq(expectedFrom));\n\t\tconst guarded = checkedPolicies === void 0 ? atExpectedHash : atExpectedHash.match(() => MongoExprFilter.of(policiesHoldExpr(checkedPolicies)));\n\t\treturn (await this.#execute(driver, guarded.findOneAndUpdate((f) => [f.stage.set(fields)], { upsert: false }))).length > 0;\n\t}\n\tasync writeLedgerEntry(driver, space, entry) {\n\t\tconst document = {\n\t\t\ttype: \"ledger\",\n\t\t\tspace,\n\t\t\tedgeId: entry.edgeId,\n\t\t\tfrom: entry.from,\n\t\t\tto: entry.to,\n\t\t\tmigrationName: entry.migrationName,\n\t\t\tmigrationHash: entry.migrationHash,\n\t\t\toperations: blindCast(entry.operations),\n\t\t\tappliedAt: /* @__PURE__ */ new Date()\n\t\t};\n\t\tawait this.#execute(driver, this.#markerLedgerCollection.insertOne(document));\n\t}\n\tasync readLedger(driver, space) {\n\t\tconst ledgerContext = {\n\t\t\tspace: space ?? \"*\",\n\t\t\tmarkerLocation: MONGO_LEDGER_COLLECTION\n\t\t};\n\t\tconst chain = this.#markerLedgerCollection.aggregate().match((f) => f.type.eq(\"ledger\"));\n\t\tconst command = space === void 0 ? chain.sort({ _id: 1 }).build() : chain.match((f) => f.space.eq(space)).sort({ _id: 1 }).build();\n\t\tconst docs = await withMarkerReadErrorHandling(() => this.#execute(driver, command), ledgerContext);\n\t\tconst entries = [];\n\t\tfor (const doc of docs) {\n\t\t\tconst migrationName = doc[\"migrationName\"];\n\t\t\tconst migrationHash = doc[\"migrationHash\"];\n\t\t\tconst from = doc[\"from\"];\n\t\t\tconst to = doc[\"to\"];\n\t\t\tconst docSpace = doc[\"space\"];\n\t\t\tif (typeof migrationName !== \"string\" || typeof migrationHash !== \"string\") continue;\n\t\t\tif (typeof from !== \"string\" || typeof to !== \"string\") continue;\n\t\t\tif (typeof docSpace !== \"string\") continue;\n\t\t\tconst appliedAt = doc[\"appliedAt\"];\n\t\t\tconst appliedAtDate = appliedAt instanceof Date ? appliedAt : appliedAt !== void 0 ? new Date(String(appliedAt)) : /* @__PURE__ */ new Date();\n\t\t\tconst operations = doc[\"operations\"];\n\t\t\tconst opList = Array.isArray(operations) ? operations : [];\n\t\t\tentries.push({\n\t\t\t\tspace: docSpace,\n\t\t\t\tmigrationName,\n\t\t\t\tmigrationHash,\n\t\t\t\tfrom: ledgerOriginFromStored(from),\n\t\t\t\tto,\n\t\t\t\tappliedAt: appliedAtDate,\n\t\t\t\toperationCount: opList.length\n\t\t\t});\n\t\t}\n\t\treturn entries;\n\t}\n\tasync introspectSchema(driver) {\n\t\treturn introspectSchema(extractDb(driver));\n\t}\n\tcreateRunnerDependencies(driver) {\n\t\tconst controlDriver = requireMongoControlDriver(driver);\n\t\treturn {\n\t\t\tinspectionExecutor: new MongoInspectionExecutor(controlDriver.db),\n\t\t\tadapter: this.#adapter,\n\t\t\tdriver: controlDriver,\n\t\t\texecuteDdl: (command) => this.executeDdl(controlDriver, command),\n\t\t\tmarkerOps: {\n\t\t\t\tmarkerLocation: this.markerLocation,\n\t\t\t\treadMarker: (space) => this.readMarker(controlDriver, space),\n\t\t\t\tinitMarker: (space, destination) => this.initMarker(controlDriver, space, destination),\n\t\t\t\tupdateMarker: (space, expectedFrom, destination, checkedPolicies) => this.updateMarker(controlDriver, space, expectedFrom, destination, checkedPolicies),\n\t\t\t\twriteLedgerEntry: (space, entry) => this.writeLedgerEntry(controlDriver, space, entry)\n\t\t\t},\n\t\t\tintrospectSchema: () => this.introspectSchema(controlDriver)\n\t\t};\n\t}\n};\n//#endregion\n//#region src/exports/control.ts\nconst mongoAdapterDescriptor = {\n\tkind: \"adapter\",\n\tid: \"mongo\",\n\tfamilyId: \"mongo\",\n\ttargetId: \"mongo\",\n\tversion: \"0.0.1\",\n\ttypes: { codecTypes: {\n\t\timport: {\n\t\t\tpackage: \"@internal/target-mongo/codec-types\",\n\t\t\tnamed: \"CodecTypes\",\n\t\t\talias: \"MongoCodecTypes\"\n\t\t},\n\t\tparameterizedOutputTypes: {\n\t\t\tpackage: \"@internal/target-mongo/codec-types\",\n\t\t\tnamed: \"ParameterizedOutputTypesForTypeParams\",\n\t\t\talias: \"MongoParameterizedOutputTypes\"\n\t\t}\n\t} },\n\tcreate(stack) {\n\t\treturn new MongoControlAdapterImpl(assembleMongoCodecRegistry([\n\t\t\tstack.target,\n\t\t\t...stack.adapter === void 0 ? [] : [stack.adapter],\n\t\t\t...stack.extensions\n\t\t]));\n\t}\n};\n//#endregion\nexport { MongoControlAdapterImpl, MongoInspectionExecutor, createMongoAdapter, mongoAdapterDescriptor as default, mongoAdapterDescriptor, extractDb, introspectSchema, isMongoControlDriver };\n\n//# sourceMappingURL=control.mjs.map"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAM,+BAA+B;AACrC,SAAS,eAAe,SAAS;CAChC,MAAM,OAAO,CAAC;CACd,KAAK,MAAM,CAAC,OAAO,cAAc,OAAO,QAAQ,OAAO,GAAG,KAAK,KAAK;EACnE;EACA;CACD,CAAC;CACD,OAAO;AACR;;;;;;AAMA,SAAS,iBAAiB,KAAK;CAC9B,MAAM,MAAM,IAAI;CAChB,IAAI,CAAC,KAAK,OAAO;CACjB,MAAM,UAAU,OAAO,QAAQ,GAAG;CAClC,OAAO,QAAQ,WAAW,KAAK,QAAQ,EAAE,GAAG,OAAO,SAAS,QAAQ,EAAE,GAAG,OAAO;AACjF;AACA,SAAS,WAAW,KAAK;CACxB,MAAM,UAAU,IAAI;CACpB,OAAO,IAAI,iBAAiB;EAC3B,MAAM,OAAO,IAAI,OAAO;EACxB,MAAM,eAAe,OAAO;EAC5B,QAAQ,IAAI;EACZ,QAAQ,IAAI;EACZ,oBAAoB,IAAI;EACxB,yBAAyB,IAAI;EAC7B,oBAAoB,IAAI;EACxB,WAAW,IAAI,eAAe,UAAU,IAAI,YAAY,IAAI,KAAK;EACjE,SAAS,IAAI;EACb,kBAAkB,IAAI;EACtB,mBAAmB,IAAI;CACxB,CAAC;AACF;AACA,SAAS,eAAe,SAAS;CAChC,MAAM,YAAY,QAAQ;CAC1B,IAAI,CAAC,WAAW,OAAO,KAAK;CAC5B,MAAM,aAAa,UAAU;CAC7B,IAAI,CAAC,YAAY,OAAO,KAAK;CAC7B,OAAO,IAAI,qBAAqB;EAC/B;EACA,iBAAiB,QAAQ,sBAAsB;EAC/C,kBAAkB,QAAQ,uBAAuB;CAClD,CAAC;AACF;AACA,SAAS,uBAAuB,MAAM;CACrC,MAAM,UAAU,KAAK;CACrB,IAAI,CAAC,SAAS,OA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ACA;IACA,MAAM,uBAAuB,IAAI;IACjC;IACA,WAAW;IACX,gBAAgB,OAAO;GACxB,CAAC;EACF;EACA,OAAO;CACR;CACA,MAAM,iBAAiB,QAAQ;EAC9B,OAAO,iBAAiB,UAAU,MAAM,CAAC;CAC1C;CACA,yBAAyB,QAAQ;EAChC,MAAM,gBAAgB,0BAA0B,MAAM;EACtD,OAAO;GACN,oBAAoB,IAAI,wBAAwB,cAAc,EAAE;GAChE,SAAS,KAAKD;GACd,QAAQ;GACR,aAAa,YAAY,KAAK,WAAW,eAAe,OAAO;GAC/D,WAAW;IACV,gBAAgB,KAAK;IACrB,aAAa,UAAU,KAAK,WAAW,eAAe,KAAK;IAC3D,aAAa,OAAO,gBAAgB,KAAK,WAAW,eAAe,OAAO,WAAW;IACrF,eAAe,OAAO,cAAc,aAAa,oBAAoB,KAAK,aAAa,eAAe,OAAO,cAAc,aAAa,eAAe;IACvJ,mBAAmB,OAAO,UAAU,KAAK,iBAAiB,eAAe,OAAO,KAAK;GACtF;GACA,wBAAwB,KAAK,iBAAiB,aAAa;EAC5D;CACD;AACD;AAGA,MAAM,yBAAyB;CAC9B,MAAM;CACN,IAAI;CACJ,UAAU;CACV,UAAU;CACV,SAAS;CACT,OAAO,EAAE,YAAY;EACpB,QAAQ;GACP,SAAS;GACT,OAAO;GACP,OAAO;EACR;EACA,0BAA0B;GACzB,SAAS;GACT,OAAO;GACP,OAAO;EACR;CACD,EAAE;CACF,OAAO,OAAO;EACb,OAAO,IAAI,wBAAwB,2BAA2B;GAC7D,MAAM;GACN,GAAG,MAAM,YAAY,KAAK,IAAI,CAAC,IAAI,CAAC,MAAM,OAAO;GACjD,GAAG,MAAM;EACV,CAAC,CAAC;CACH;AACD"}
@@ -6,7 +6,7 @@ import { Result } from "@prisma/orm-framework/utils/result";
6
6
  import { MongoCollection, MongoCollectionInput, MongoContract, MongoNamespaceEntries, MongoStorage, MongoValueSetInput } from "@prisma/orm-family-mongo/contract";
7
7
  import { AnyMongoMigrationOperation, MongoAndExpr, MongoExistsExpr, MongoExprFilter, MongoFieldFilter, MongoFilterExpr, MongoFilterVisitor, MongoNotExpr, MongoOrExpr } from "@prisma/orm-family-mongo/query-ast/control";
8
8
  import { MongoControlTargetDescriptor } from "@prisma/orm-family-mongo/family/control";
9
- import { MigrationOperationPolicy, MigrationPlan, MigrationPlanOperation, MigrationPlanWithAuthoringSurface, MigrationPlanner, MigrationPlannerConflict, MigrationPlannerResult, MigrationRunnerExecutionChecks, MigrationRunnerFailure, MigrationRunnerPerSpaceSuccessValue, MigrationScaffoldContext, OperationContext, PlanOrigin, ResolvedMigrationStatement, SchemaDiffIssue, SchemaVerifyOptions, VerifyDatabaseSchemaResult } from "@prisma/orm-framework/components/control";
9
+ import { DatabasePolicies, MigrationOperationPolicy, MigrationPlan, MigrationPlanOperation, MigrationPlanWithAuthoringSurface, MigrationPlanner, MigrationPlannerConflict, MigrationPlannerResult, MigrationRunnerExecutionChecks, MigrationRunnerFailure, MigrationRunnerPerSpaceOptions, MigrationRunnerPerSpaceSuccessValue, MigrationScaffoldContext, OperationContext, PlanOrigin, ResolvedMigrationStatement, SchemaDiffIssue, SchemaVerifyOptions, VerifyDatabaseSchemaResult } from "@prisma/orm-framework/components/control";
10
10
  import { MongoContractSerializerBase, MongoSchemaVerifierBase } from "@prisma/orm-family-mongo/family/ir";
11
11
  import { Contract } from "@prisma/orm-framework/contract/types";
12
12
  import { MongoSchemaIR } from "@prisma/orm-family-mongo/schema-ir";
@@ -135,7 +135,7 @@ declare class MongoMigrationPlanner implements MigrationPlanner<'mongo', 'mongo'
135
135
  type MongoMigrationRunnerErrorCode = 'MIGRATION.EXECUTION_FAILED' | 'MIGRATION.MARKER_CAS_FAILURE' | 'MIGRATION.MARKER_ORIGIN_MISMATCH' | 'MIGRATION.POLICY_VIOLATION' | 'MIGRATION.POSTCHECK_FAILED' | 'MIGRATION.PRECHECK_FAILED' | 'MIGRATION.SCHEMA_VERIFY_FAILED';
136
136
  //#endregion
137
137
  //#region src/core/migrations/mongo-runner.d.ts
138
- interface MongoMigrationRunnerExecuteOptions {
138
+ interface MongoMigrationRunnerExecuteOptions extends Pick<MigrationRunnerPerSpaceOptions, 'databasePolicies'> {
139
139
  readonly plan: MigrationPlan;
140
140
  readonly destinationContract: MongoContract;
141
141
  readonly policy: MigrationOperationPolicy;
@@ -162,6 +162,8 @@ interface MongoMigrationRunnerExecuteOptions {
162
162
  readonly migrationEdges: readonly AggregateMigrationEdgeRef[];
163
163
  /** Whether an earlier space of the same apply already changed the database. */
164
164
  readonly databaseChangedBefore?: boolean;
165
+ /** The policies the run checked; the application space's marker is written only while its policies read as these. */
166
+ readonly checkedPolicies?: DatabasePolicies;
165
167
  }
166
168
  /** A failure of the Mongo runner: one of the codes it returns. */
167
169
  interface MongoMigrationRunnerFailure extends MigrationRunnerFailure {
@@ -178,6 +180,11 @@ declare class MongoMigrationRunner {
178
180
  execute(options: MongoMigrationRunnerExecuteOptions): Promise<MongoMigrationRunnerResult>;
179
181
  /** Applies the plan, calling `wrote` after each command that changes the database. */
180
182
  private apply;
183
+ /**
184
+ * Writes the marker while it still holds `expectedFrom` and, for the application space, while its
185
+ * policies read as those the run checked.
186
+ */
187
+ private updateMarker;
181
188
  private recordLedgerEntries;
182
189
  private executeDmlOperation;
183
190
  /**
@@ -386,4 +393,4 @@ declare class MongoTargetUnboundDatabase extends MongoTargetDatabase {
386
393
  }
387
394
  //#endregion
388
395
  export { deserializeMongoOps as _, MongoMigrationRunnerExecuteOptions as a, renderOps as b, MongoTargetContract as c, MongoTargetSchemaVerifier as d, MongoTargetUnboundDatabase as f, deserializeMongoOp as g, RenderMigrationMeta as h, MongoMigrationRunnerErrorCode as i, MongoTargetContractSerializer as l, PlannerProducedMongoMigration as m, MongoMigrationPlanner as n, MongoMigrationRunnerFailure as o, PlanCallsResult as p, MongoMigrationRunner as r, MongoMigrationRunnerResult as s, FilterEvaluator as t, MongoTargetDatabase as u, mongoTargetDescriptor as v, serializeMongoOps as x, renderCallsToTypeScript as y };
389
- //# sourceMappingURL=control-Dc2P_CN-.d.mts.map
396
+ //# sourceMappingURL=control-ByHwQ1ve.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"control-ByHwQ1ve.d.mts","names":[],"sources":["../../../../3-targets/mongo/1-target/dist/control.d.mts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA6BK,sBAAsB,KAAK;WACrB,SAAS;;;;;;;;;;;;;;cAcN,uBAAuB,6BAA6B;;;cAGpD,2BAA2B;UAC/B;EACR,SAAS,QAAQ,iBAAiB,KAAK;EACvC,MAAM,MAAM;EACZ,IAAI,MAAM;EACV,GAAG,MAAM;EACT,IAAI,MAAM;EACV,OAAO,MAAM;EACb,KAAK,OAAO;;;;iBAIG,mBAAmB,gBAAgB;iBACnC,oBAAoB,2BAA2B;iBAC/C,kBAAkB,cAAc;;;;KAI5C,cAAc,kBAAkB,gBAAgB,oBAAoB,gBAAgB,iBAAiB,sBAAsB,sBAAsB,oBAAoB,yBAAyB,wBAAwB;;;;;;;;UAQjN;WACC,QAAQ;;WAER,4BAA4B;;WAE5B,mBAAmB;;;;KAIzB;WACM;WACA,OAAO;;WAEP,mBAAmB;;WAEnB;WACA,WAAW;;cAER,iCAAiC;EAC7C,UAAU;aACC;aACA;aACA,QAAQ;aACR,qBAAqB,cAAc;;aAEnC,cAAc;;aAEd,iBAAiB;MACxB;EACJ,KAAK;aACM;aACA;aACA,QAAQ;;aAER,cAAc;;aAEd,QAAQ;;aAER,qBAAqB;aACrB,qBAAqB,cAAc;;;;;;aAMnC;MACP;;;;;;;;;;EAUJ,eAAe,SAAS,2BAA2B;;;;;KAKhD;;;UAGK,2CAA2C,KAAK;WAC/C,MAAM;WACN,qBAAqB;WACrB,QAAQ;WACR;IACP,kBAAkB,IAAI;IACtB,qBAAqB,IAAI;;WAElB,kBAAkB;WAClB,qBAAqB,cAAc;WACnC;WACA,UAAU;;;;;;;;;;;WAWV,qBAAqB,QAAQ,+BAA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
@@ -8,12 +8,12 @@ import { type } from "arktype";
8
8
  import { blindCast } from "@prisma/orm-framework/utils/casts";
9
9
  import { setFallbackTemporal } from "@prisma/orm-framework/type-implementations/temporal";
10
10
  import { NamespaceBase, UNBOUND_NAMESPACE_ID, elementCoordinates, freezeNode, hydrateNamespaceEntities } from "@prisma/orm-framework/components/ir";
11
- import { notOk, ok } from "@prisma/orm-framework/utils/result";
11
+ import { notOk, ok, okVoid } from "@prisma/orm-framework/utils/result";
12
12
  import { MongoCollection, MongoStorage, canonicalize, collectionControlPoliciesOf, collectionControlPolicyOf, collectionOfModel, defaultMongoIndexName, embeddingModelOf, hasOwnFieldStoredAs, indexLookupKey, isEmbedRelation, modelAndBasesOf, modelFieldStoredAs, modelKey, mongoModelsOf, otherModelsReached, ownEmbedStoredNamesOf, ownStoredNameOf, ownStoredNamesOf, propertyBsonTypesOf, recursiveGroupsOf, sameKindOfDocumentIn, selectedVariantOf, validatorDocumentShapesOf, validatorFieldNamesOf, validatorRootShapesOf, valueObjectKey, valueObjectStoredNamesOf, variantFilter } from "@prisma/orm-family-mongo/contract";
13
13
  import { CollModCommand, CreateCollectionCommand, CreateIndexCommand, DropCollectionCommand, DropIndexCommand, ListCollectionsCommand, ListIndexesCommand, MongoAndExpr, MongoExistsExpr, MongoFieldFilter, MongoNotExpr, MongoOrExpr, RenameCollectionCommand, isInspectionCheckSource, isMongoDmlOperation } from "@prisma/orm-family-mongo/query-ast/control";
14
14
  import { AggregateCommand, MongoAddFieldsStage, MongoLimitStage, MongoLookupStage, MongoMatchStage, MongoMergeStage, MongoProjectStage, MongoSortStage, RawAggregateCommand, RawDeleteManyCommand, RawDeleteOneCommand, RawFindOneAndDeleteCommand, RawFindOneAndUpdateCommand, RawInsertManyCommand, RawInsertOneCommand, RawUpdateManyCommand, RawUpdateOneCommand } from "@prisma/orm-family-mongo/query-ast/execution";
15
- import { canonicalizeSchemasForVerification, contractToMongoSchemaIR, diffMongoSchemas, fieldRewriteOf } from "@prisma/orm-family-mongo/family/control";
16
- import { APP_SPACE_ID, VERIFY_CODE_SCHEMA_FAILURE, contractSnapshotJsonSpecifier, contractSnapshotTypesSpecifier, describeMigrationStatement, enumValueCoordinateFromJson, enumValueCoordinateJson, enumValueStatementText, expectAbsent, expectPresent, extractCodecLookup, failedPostcheckWhy, failedPrecheckWhy, fieldStatementText, issueOutcome, migrationRunnerFailure, migrationSubjectKey, modelDisplayName, modelStatementText, schemaCheckWhy, valueObjectFieldStatementText, withDatabaseUnchanged, withFailingSpace } from "@prisma/orm-framework/components/control";
15
+ import { canonicalizeSchemasForVerification, contractToMongoSchemaIR, diffMongoSchemas, fieldRewriteOf, markerSwapFailure } from "@prisma/orm-family-mongo/family/control";
16
+ import { APP_SPACE_ID, VERIFY_CODE_SCHEMA_FAILURE, compareMarkerDatabasePolicies, contractSnapshotJsonSpecifier, contractSnapshotTypesSpecifier, databasePoliciesMovedFailure, describeMigrationStatement, enumValueCoordinateFromJson, enumValueCoordinateJson, enumValueStatementText, expectAbsent, expectPresent, extractCodecLookup, failedPostcheckWhy, failedPrecheckWhy, fieldStatementText, issueOutcome, migrationRunnerFailure, migrationSubjectKey, modelDisplayName, modelStatementText, schemaCheckWhy, valueObjectFieldStatementText, withDatabaseUnchanged, withFailingSpace } from "@prisma/orm-framework/components/control";
17
17
  import { Temporal } from "temporal-polyfill/full/implementation";
18
18
  import { MongoContractSerializerBase, MongoSchemaVerifierBase } from "@prisma/orm-family-mongo/family/ir";
19
19
  import { composeMongoEntityKinds } from "@prisma/orm-family-mongo/contract/entity-kinds";
@@ -26,6 +26,7 @@ import { TsExpression, jsonToTsSource, renderImports, tsObjectSource, tsStringLi
26
26
  import { Migration } from "@prisma/orm-toolchain/migration-tools/migration";
27
27
  import { resolveRequirementSpecifiers } from "@prisma/orm-framework/components/emission";
28
28
  import { detectScaffoldRuntime, shebangLineFor } from "@prisma/orm-toolchain/migration-tools/migration-ts";
29
+ import { errorMarkerPoliciesCorrupt } from "@prisma/orm-framework/errors/execution";
29
30
  import { verifyMongoSchema } from "@prisma/orm-family-mongo/family/schema-verify";
30
31
  //#region ../../../3-targets/mongo/1-target/dist/control.mjs
31
32
  /**
@@ -5255,6 +5256,26 @@ function failedCheckOf(operationId, phase, check) {
5255
5256
  function runnerFailure(code, summary, options) {
5256
5257
  return notOk(migrationRunnerFailure(code, summary, options));
5257
5258
  }
5259
+ function storageHashMovedFailure(space, expectedFrom, found, destination) {
5260
+ return migrationRunnerFailure("MIGRATION.MARKER_CAS_FAILURE", "Marker was modified by another process during migration execution.", { meta: {
5261
+ reason: "storageHash",
5262
+ space,
5263
+ expectedStorageHash: expectedFrom,
5264
+ foundStorageHash: found?.storageHash ?? null,
5265
+ destinationStorageHash: destination.storageHash
5266
+ } });
5267
+ }
5268
+ function markerChangedFailure(space, expectedFrom, destination) {
5269
+ return migrationRunnerFailure("MIGRATION.MARKER_CAS_FAILURE", "Marker was modified by another process during migration execution.", {
5270
+ why: "Another process changed the marker and changed it back while this run was writing it. Run the command again.",
5271
+ meta: {
5272
+ reason: "markerChanged",
5273
+ space,
5274
+ expectedStorageHash: expectedFrom,
5275
+ destinationStorageHash: destination.storageHash
5276
+ }
5277
+ });
5278
+ }
5258
5279
  /** The mongosh query that finds the documents a DML operation's first precheck matches. */
5259
5280
  function precheckFind(op, collection) {
5260
5281
  const source = op.precheck[0]?.source.command;
@@ -5699,6 +5720,25 @@ function bypassValidationRefusal(op, plan, error) {
5699
5720
  }
5700
5721
  });
5701
5722
  }
5723
+ /**
5724
+ * Compares the policies a caller checked with the application space's marker, before the run's
5725
+ * first operation. The application space's marker is later written only while they still hold.
5726
+ */
5727
+ async function checkDatabasePolicies(markerOps, checked) {
5728
+ const comparison = compareMarkerDatabasePolicies(await markerOps.readMarker(APP_SPACE_ID), checked);
5729
+ switch (comparison.kind) {
5730
+ case "held": return okVoid();
5731
+ case "moved": return notOk(withDatabaseUnchanged(databasePoliciesMovedFailure(checked, comparison.found), true));
5732
+ case "unreadable": throw markerPoliciesCorrupt(markerOps, comparison.why);
5733
+ }
5734
+ }
5735
+ function markerPoliciesCorrupt(markerOps, why) {
5736
+ return errorMarkerPoliciesCorrupt({
5737
+ why,
5738
+ space: APP_SPACE_ID,
5739
+ markerLocation: markerOps.markerLocation
5740
+ });
5741
+ }
5702
5742
  const MONGO_CONVERSION_FAILURE = 241;
5703
5743
  /** The innermost cause MongoDB gives in an error's message, without its closing period. */
5704
5744
  function mongoErrorText(error) {
@@ -5923,7 +5963,8 @@ var MongoMigrationRunner = class {
5923
5963
  const existingInvariantSet = new Set(existingMarker?.invariants ?? []);
5924
5964
  const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariantSet.has(id));
5925
5965
  const markerAlreadyAtDestination = existingMarker !== null && existingMarker.storageHash === destination.storageHash && existingMarker.profileHash === profileHash;
5926
- if (!(operationsExecuted === 0 && markerAlreadyAtDestination && incomingIsSubsetOfExisting)) {
5966
+ const isNoOp = operationsExecuted === 0 && markerAlreadyAtDestination && incomingIsSubsetOfExisting;
5967
+ if (!isNoOp || options.databasePolicies !== void 0) {
5927
5968
  const liveSchema = await this.deps.introspectSchema();
5928
5969
  const rawVerifyResult = verifyMongoSchema({
5929
5970
  contract: options.destinationContract,
@@ -5938,32 +5979,40 @@ var MongoMigrationRunner = class {
5938
5979
  meta: { schemaIssues: verifyResult.schema.issues }
5939
5980
  });
5940
5981
  if (existingMarker) {
5941
- if (!await markerOps.updateMarker(space, existingMarker.storageHash, {
5982
+ const swapFailure = await this.updateMarker(markerOps, space, existingMarker.storageHash, {
5942
5983
  storageHash: destination.storageHash,
5943
5984
  profileHash,
5944
- invariants: incomingInvariants
5945
- })) {
5946
- const found = await markerOps.readMarker(space);
5947
- return runnerFailure("MIGRATION.MARKER_CAS_FAILURE", "Marker was modified by another process during migration execution.", { meta: {
5948
- space,
5949
- expectedStorageHash: existingMarker.storageHash,
5950
- foundStorageHash: found?.storageHash ?? null,
5951
- destinationStorageHash: destination.storageHash
5952
- } });
5953
- }
5985
+ invariants: incomingInvariants,
5986
+ ...ifDefined("databasePolicies", options.databasePolicies)
5987
+ }, options.checkedPolicies);
5988
+ if (swapFailure !== void 0) return notOk(swapFailure);
5954
5989
  } else await markerOps.initMarker(space, {
5955
5990
  storageHash: destination.storageHash,
5956
5991
  profileHash,
5957
- invariants: incomingInvariants
5992
+ invariants: incomingInvariants,
5993
+ ...ifDefined("databasePolicies", options.databasePolicies)
5958
5994
  });
5959
5995
  wrote();
5960
- await this.recordLedgerEntries(markerOps, space, options);
5996
+ if (!isNoOp) await this.recordLedgerEntries(markerOps, space, options);
5961
5997
  }
5962
5998
  return ok({
5963
5999
  operationsPlanned: operations.length,
5964
6000
  operationsExecuted
5965
6001
  });
5966
6002
  }
6003
+ /**
6004
+ * Writes the marker while it still holds `expectedFrom` and, for the application space, while its
6005
+ * policies read as those the run checked.
6006
+ */
6007
+ async updateMarker(markerOps, space, expectedFrom, destination, checkedPolicies) {
6008
+ if (await markerOps.updateMarker(space, expectedFrom, destination, checkedPolicies)) return;
6009
+ const found = await markerOps.readMarker(space);
6010
+ const failure = markerSwapFailure(found, expectedFrom, checkedPolicies);
6011
+ if (failure.kind === "policiesUnreadable") throw markerPoliciesCorrupt(markerOps, failure.why);
6012
+ if (failure.kind === "policiesMoved" && checkedPolicies !== void 0) return databasePoliciesMovedFailure(checkedPolicies, failure.found);
6013
+ if (failure.kind === "markerChanged") return markerChangedFailure(space, expectedFrom, destination);
6014
+ return storageHashMovedFailure(space, expectedFrom, found, destination);
6015
+ }
5967
6016
  async recordLedgerEntries(markerOps, space, options) {
5968
6017
  const plan = options.plan;
5969
6018
  const edges = options.migrationEdges;
@@ -6467,7 +6516,12 @@ const mongoTargetDescriptor = {
6467
6516
  destinationContract: blindCast(runnerOptions.destinationContract)
6468
6517
  });
6469
6518
  };
6470
- return { async execute({ driver, perSpaceOptions }) {
6519
+ return { async execute({ driver, perSpaceOptions, expectedDatabasePolicies }) {
6520
+ if (expectedDatabasePolicies !== void 0) {
6521
+ cachedDeps ??= family.createRunnerDependencies({ driver });
6522
+ const checked = await checkDatabasePolicies(cachedDeps.markerOps, expectedDatabasePolicies);
6523
+ if (!checked.ok) return notOk(checked.failure);
6524
+ }
6471
6525
  const contracts = perSpaceOptions.map((opts) => blindCast(opts.destinationContract));
6472
6526
  const perSpaceResults = [];
6473
6527
  let changedDatabase = false;
@@ -6480,7 +6534,8 @@ const mongoTargetDescriptor = {
6480
6534
  const result = await runMongo(driver, {
6481
6535
  ...runnerOptions,
6482
6536
  scopeVerifyResult,
6483
- databaseChangedBefore: changedDatabase
6537
+ databaseChangedBefore: changedDatabase,
6538
+ ...space === APP_SPACE_ID ? ifDefined("checkedPolicies", expectedDatabasePolicies) : {}
6484
6539
  });
6485
6540
  if (!result.ok) return notOk(withFailingSpace(result.failure, space));
6486
6541
  const { changedDatabase: spaceChanged, ...value } = result.value;
@@ -6507,4 +6562,4 @@ const mongoTargetDescriptor = {
6507
6562
  //#endregion
6508
6563
  export { schemaIndexToCreateIndexOptions as C, schemaCollectionToCreateCollectionOptions as S, deserializeMongoOp as _, DropIndexCall as a, renderCallsToTypeScript as b, MongoMigrationRunner as c, MongoTargetSchemaVerifier as d, MongoTargetUnboundDatabase as f, UnsetFieldCall as g, RenameFieldCall as h, DropCollectionCall as i, MongoTargetContractSerializer as l, RenameCollectionCall as m, CreateCollectionCall as n, FilterEvaluator as o, PlannerProducedMongoMigration as p, CreateIndexCall as r, MongoMigrationPlanner as s, CollModCall as t, MongoTargetDatabase as u, deserializeMongoOps as v, serializeMongoOps as w, renderOps as x, mongoTargetDescriptor as y };
6509
6564
 
6510
- //# sourceMappingURL=control-HkDN7RLR.mjs.map
6565
+ //# sourceMappingURL=control-D2tbWwPF.mjs.map