@prisma-next/target-mongo 0.11.0-dev.56 → 0.11.0-dev.58

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/control.mjs CHANGED
@@ -1425,12 +1425,15 @@ const mongoTargetDescriptor = {
1425
1425
  * consumes the destination contract directly.
1426
1426
  */
1427
1427
  function toSpaceMember(opts) {
1428
+ const contract = blindCast(opts.destinationContract);
1428
1429
  return createContractSpaceMember({
1429
1430
  spaceId: opts.space,
1430
1431
  packages: [],
1431
1432
  refs: {},
1432
1433
  headRef: null,
1433
- resolveContract: () => blindCast(opts.destinationContract)
1434
+ refsDir: "",
1435
+ resolveContract: () => contract,
1436
+ deserializeContract: (raw) => blindCast(raw)
1434
1437
  });
1435
1438
  }
1436
1439
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":["record"],"sources":["../src/core/op-factory-call.ts","../src/core/render-ops.ts","../src/core/render-typescript.ts","../src/core/planner-produced-migration.ts","../src/core/mongo-planner.ts","../src/core/filter-evaluator.ts","../src/core/mongo-ops-serializer.ts","../src/core/mongo-runner.ts","../src/core/mongo-target-database.ts","../src/core/mongo-target-contract-serializer.ts","../src/core/mongo-target-schema-verifier.ts","../src/core/control-target.ts"],"sourcesContent":["/**\n * Mongo migration IR: one concrete `*Call` class per pure factory under\n * `migration-factories.ts`, plus a shared `OpFactoryCallNode` abstract\n * base. Every call class carries the literal arguments its backing\n * factory would receive, computes a human-readable `label` in its\n * constructor, and implements two polymorphic hooks:\n *\n * - `toOp()` — converts the IR node to a runtime\n * `MongoMigrationPlanOperation` by delegating to the matching pure\n * factory in `migration-factories.ts`.\n * - `renderTypeScript()` / `importRequirements()` — inherited from\n * `TsExpression`. Used by `renderCallsToTypeScript` to emit the call\n * as a TypeScript expression inside the scaffolded `migration.ts`.\n *\n * The abstract base and all concrete classes are package-private.\n * External consumers see only the framework-level `OpFactoryCall`\n * interface and the `OpFactoryCall` union.\n */\n\nimport type {\n OpFactoryCall as FrameworkOpFactoryCall,\n MigrationOperationClass,\n} from '@prisma-next/framework-components/control';\nimport type {\n CollModOptions,\n CreateCollectionOptions,\n CreateIndexOptions,\n MongoIndexKey,\n MongoMigrationPlanOperation,\n} from '@prisma-next/mongo-query-ast/control';\nimport type {\n MongoSchemaCollection,\n MongoSchemaCollectionOptions,\n MongoSchemaIndex,\n MongoSchemaValidator,\n} from '@prisma-next/mongo-schema-ir';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport {\n collMod,\n createCollection,\n createIndex,\n dropCollection,\n dropIndex,\n} from './migration-factories';\n\nexport interface CollModMeta {\n readonly id?: string;\n readonly label?: string;\n readonly operationClass?: MigrationOperationClass;\n}\n\nconst TARGET_MIGRATION_MODULE = '@prisma-next/target-mongo/migration';\n\nabstract class OpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n abstract readonly factoryName: string;\n abstract readonly operationClass: MigrationOperationClass;\n abstract readonly label: string;\n abstract toOp(): MongoMigrationPlanOperation;\n\n importRequirements(): readonly ImportRequirement[] {\n return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];\n }\n\n protected freeze(): void {\n Object.freeze(this);\n }\n}\n\nfunction formatKeys(keys: ReadonlyArray<MongoIndexKey>): string {\n return keys.map((k) => `${k.field}:${k.direction}`).join(', ');\n}\n\nexport class CreateIndexCall extends OpFactoryCallNode {\n readonly factoryName = 'createIndex' as const;\n readonly operationClass = 'additive' as const;\n readonly collection: string;\n readonly keys: ReadonlyArray<MongoIndexKey>;\n readonly options: CreateIndexOptions | undefined;\n readonly label: string;\n\n constructor(\n collection: string,\n keys: ReadonlyArray<MongoIndexKey>,\n options?: CreateIndexOptions,\n ) {\n super();\n this.collection = collection;\n this.keys = keys;\n this.options = options;\n this.label = `Create index on ${collection} (${formatKeys(keys)})`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return createIndex(this.collection, this.keys, this.options);\n }\n\n renderTypeScript(): string {\n return this.options\n ? `createIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)}, ${jsonToTsSource(this.options)})`\n : `createIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)})`;\n }\n}\n\nexport class DropIndexCall extends OpFactoryCallNode {\n readonly factoryName = 'dropIndex' as const;\n readonly operationClass = 'destructive' as const;\n readonly collection: string;\n readonly keys: ReadonlyArray<MongoIndexKey>;\n readonly label: string;\n\n constructor(collection: string, keys: ReadonlyArray<MongoIndexKey>) {\n super();\n this.collection = collection;\n this.keys = keys;\n this.label = `Drop index on ${collection} (${formatKeys(keys)})`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return dropIndex(this.collection, this.keys);\n }\n\n renderTypeScript(): string {\n return `dropIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)})`;\n }\n}\n\nexport class CreateCollectionCall extends OpFactoryCallNode {\n readonly factoryName = 'createCollection' as const;\n readonly operationClass = 'additive' as const;\n readonly collection: string;\n readonly options: CreateCollectionOptions | undefined;\n readonly label: string;\n\n constructor(collection: string, options?: CreateCollectionOptions) {\n super();\n this.collection = collection;\n this.options = options;\n this.label = `Create collection ${collection}`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return createCollection(this.collection, this.options);\n }\n\n renderTypeScript(): string {\n return this.options\n ? `createCollection(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)})`\n : `createCollection(${jsonToTsSource(this.collection)})`;\n }\n}\n\nexport class DropCollectionCall extends OpFactoryCallNode {\n readonly factoryName = 'dropCollection' as const;\n readonly operationClass = 'destructive' as const;\n readonly collection: string;\n readonly label: string;\n\n constructor(collection: string) {\n super();\n this.collection = collection;\n this.label = `Drop collection ${collection}`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return dropCollection(this.collection);\n }\n\n renderTypeScript(): string {\n return `dropCollection(${jsonToTsSource(this.collection)})`;\n }\n}\n\nexport class CollModCall extends OpFactoryCallNode {\n readonly factoryName = 'collMod' as const;\n readonly collection: string;\n readonly options: CollModOptions;\n readonly meta: CollModMeta | undefined;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n\n constructor(collection: string, options: CollModOptions, meta?: CollModMeta) {\n super();\n this.collection = collection;\n this.options = options;\n this.meta = meta;\n this.operationClass = meta?.operationClass ?? 'destructive';\n this.label = meta?.label ?? `Modify collection ${collection}`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return collMod(this.collection, this.options, this.meta);\n }\n\n renderTypeScript(): string {\n return this.meta\n ? `collMod(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)}, ${jsonToTsSource(this.meta)})`\n : `collMod(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)})`;\n }\n}\n\nexport type OpFactoryCall =\n | CreateIndexCall\n | DropIndexCall\n | CreateCollectionCall\n | DropCollectionCall\n | CollModCall;\n\nexport function schemaIndexToCreateIndexOptions(index: MongoSchemaIndex): CreateIndexOptions {\n return {\n unique: index.unique || undefined,\n sparse: index.sparse,\n expireAfterSeconds: index.expireAfterSeconds,\n partialFilterExpression: index.partialFilterExpression,\n wildcardProjection: index.wildcardProjection,\n collation: index.collation,\n weights: index.weights,\n default_language: index.default_language,\n language_override: index.language_override,\n };\n}\n\nexport function schemaCollectionToCreateCollectionOptions(\n coll: MongoSchemaCollection,\n): CreateCollectionOptions | undefined {\n const opts: MongoSchemaCollectionOptions | undefined = coll.options;\n const validator: MongoSchemaValidator | undefined = coll.validator;\n if (!opts && !validator) return undefined;\n return {\n capped: opts?.capped ? true : undefined,\n size: opts?.capped?.size,\n max: opts?.capped?.max,\n timeseries: opts?.timeseries,\n collation: opts?.collation,\n clusteredIndex: opts?.clusteredIndex\n ? {\n key: { _id: 1 } as Record<string, number>,\n unique: true as boolean,\n ...(opts.clusteredIndex.name != null ? { name: opts.clusteredIndex.name } : {}),\n }\n : undefined,\n validator: validator ? { $jsonSchema: validator.jsonSchema } : undefined,\n validationLevel: validator?.validationLevel,\n validationAction: validator?.validationAction,\n changeStreamPreAndPostImages: opts?.changeStreamPreAndPostImages,\n };\n}\n","import type { MongoMigrationPlanOperation } from '@prisma-next/mongo-query-ast/control';\nimport type { OpFactoryCall } from './op-factory-call';\n\nexport function renderOps(calls: ReadonlyArray<OpFactoryCall>): MongoMigrationPlanOperation[] {\n return calls.map((call) => call.toOp());\n}\n","import { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';\nimport { type ImportRequirement, renderImports } from '@prisma-next/ts-render';\nimport type { OpFactoryCall } from './op-factory-call';\n\nexport interface RenderMigrationMeta {\n readonly from: string | null;\n readonly to: string;\n}\n\n/**\n * Always-present base imports for the rendered scaffold:\n *\n * - `Migration` from `@prisma-next/family-mongo/migration` — the\n * user-facing Mongo `Migration` base; subclasses don't need to\n * redeclare `targetId` or thread family/target generics.\n * - `MigrationCLI` from `@prisma-next/cli/migration-cli` — the\n * migration-file CLI entrypoint that loads `prisma-next.config.ts`,\n * assembles a `ControlStack`, and instantiates the migration class.\n * The migration file owns this dependency directly: pulling CLI\n * machinery in at script run time is acceptable because the script's\n * whole purpose is to be invoked from the project that owns the\n * config. (Mirrors the postgres facade pattern; pulling `MigrationCLI`\n * into `@prisma-next/family-mongo/migration` so a Mongo migration only\n * needs one import is tracked separately as a follow-up.)\n */\nconst BASE_IMPORTS: readonly ImportRequirement[] = [\n { moduleSpecifier: '@prisma-next/family-mongo/migration', symbol: 'Migration' },\n { moduleSpecifier: '@prisma-next/cli/migration-cli', symbol: 'MigrationCLI' },\n];\n\n/**\n * Render a list of Mongo `OpFactoryCall`s as a `migration.ts`\n * source string. The result is shebanged, extends the user-facing\n * `Migration` (i.e. `MongoMigration`) from `@prisma-next/family-mongo`, and\n * implements the abstract `operations` and `describe` members. `meta` is\n * always rendered — `describe()` is part of the `Migration` contract, so\n * even an empty stub must satisfy it; callers pass `from: null` for a\n * baseline `migration-new` scaffold (and a real `to` hash either way).\n *\n * The walk is polymorphic: each call node contributes its own\n * `renderTypeScript()` expression and declares its own\n * `importRequirements()`. The top-level renderer aggregates imports\n * across all nodes and emits one `import { … } from \"…\"` line per module.\n * The `Migration` and `MigrationCLI` imports are always emitted — they're\n * structural to the rendered scaffold (extends `Migration`, calls\n * `MigrationCLI.run`), not driven by any node.\n */\nexport function renderCallsToTypeScript(\n calls: ReadonlyArray<OpFactoryCall>,\n meta: RenderMigrationMeta,\n): string {\n const imports = buildImports(calls);\n const operationsBody = calls.map((c) => c.renderTypeScript()).join(',\\n');\n\n return [\n shebangLineFor(detectScaffoldRuntime()),\n imports,\n '',\n 'class M extends Migration {',\n buildDescribeMethod(meta),\n ' override get operations() {',\n ' return [',\n indent(operationsBody, 6),\n ' ];',\n ' }',\n '}',\n '',\n 'export default M;',\n 'MigrationCLI.run(import.meta.url, M);',\n '',\n ].join('\\n');\n}\n\nfunction buildImports(calls: ReadonlyArray<OpFactoryCall>): string {\n const requirements: ImportRequirement[] = [...BASE_IMPORTS];\n for (const call of calls) {\n for (const req of call.importRequirements()) {\n requirements.push(req);\n }\n }\n return renderImports(requirements);\n}\n\nfunction buildDescribeMethod(meta: RenderMigrationMeta): string {\n const lines: string[] = [];\n lines.push(' override describe() {');\n lines.push(' return {');\n lines.push(` from: ${JSON.stringify(meta.from)},`);\n lines.push(` to: ${JSON.stringify(meta.to)},`);\n lines.push(' };');\n lines.push(' }');\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction indent(text: string, spaces: number): string {\n const pad = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${pad}${line}` : line))\n .join('\\n');\n}\n","import type { MigrationPlanWithAuthoringSurface } from '@prisma-next/framework-components/control';\nimport { Migration, type MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { AnyMongoMigrationOperation } from '@prisma-next/mongo-query-ast/control';\nimport type { OpFactoryCall } from './op-factory-call';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\n\n/**\n * Planner-produced Mongo migration, returned by `MongoMigrationPlanner.plan(...)`\n * and `MongoMigrationPlanner.emptyMigration(...)`.\n *\n * Unlike user-authored migrations (which extend `MongoMigration` from\n * `@prisma-next/family-mongo/migration`), this class lives inside the target\n * and holds the richer authoring IR (`OpFactoryCall[]`) needed to render\n * itself back to TypeScript source. It implements\n * `MigrationPlanWithAuthoringSurface` so that the CLI can uniformly ask any\n * planner result to serialize itself to a `migration.ts`.\n *\n * Extends the framework `Migration` base class directly (not\n * `MongoMigration`) because `MongoMigration` lives in `@prisma-next/family-mongo`,\n * which depends on this package — extending it here would create a dependency\n * cycle.\n */\nexport class PlannerProducedMongoMigration\n extends Migration<AnyMongoMigrationOperation>\n implements MigrationPlanWithAuthoringSurface\n{\n readonly targetId = 'mongo' as const;\n\n constructor(\n private readonly calls: readonly OpFactoryCall[],\n private readonly meta: MigrationMeta,\n ) {\n super();\n }\n\n override get operations(): readonly AnyMongoMigrationOperation[] {\n return renderOps(this.calls);\n }\n\n override describe(): MigrationMeta {\n return this.meta;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.calls, {\n from: this.meta.from,\n to: this.meta.to,\n });\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { contractToMongoSchemaIR } from '@prisma-next/family-mongo/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationOperationClass,\n MigrationOperationPolicy,\n MigrationPlanner,\n MigrationPlannerConflict,\n MigrationPlannerResult,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n} from '@prisma-next/framework-components/control';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type {\n MongoSchemaCollection,\n MongoSchemaCollectionOptions,\n MongoSchemaIndex,\n MongoSchemaIR,\n MongoSchemaValidator,\n} from '@prisma-next/mongo-schema-ir';\nimport { canonicalize, deepEqual } from '@prisma-next/mongo-schema-ir';\nimport type { OpFactoryCall } from './op-factory-call';\nimport {\n CollModCall,\n CreateCollectionCall,\n CreateIndexCall,\n DropCollectionCall,\n DropIndexCall,\n schemaCollectionToCreateCollectionOptions,\n schemaIndexToCreateIndexOptions,\n} from './op-factory-call';\nimport { PlannerProducedMongoMigration } from './planner-produced-migration';\n\nfunction buildIndexLookupKey(index: MongoSchemaIndex): string {\n const keys = index.keys.map((k) => `${k.field}:${k.direction}`).join(',');\n const opts = [\n index.unique ? 'unique' : '',\n index.sparse ? 'sparse' : '',\n index.expireAfterSeconds != null ? `ttl:${index.expireAfterSeconds}` : '',\n index.partialFilterExpression ? `pfe:${canonicalize(index.partialFilterExpression)}` : '',\n index.wildcardProjection ? `wp:${canonicalize(index.wildcardProjection)}` : '',\n index.collation ? `col:${canonicalize(index.collation)}` : '',\n index.weights ? `wt:${canonicalize(index.weights)}` : '',\n index.default_language ? `dl:${index.default_language}` : '',\n index.language_override ? `lo:${index.language_override}` : '',\n ]\n .filter(Boolean)\n .join(';');\n return opts ? `${keys}|${opts}` : keys;\n}\n\nfunction validatorsEqual(\n a: MongoSchemaValidator | undefined,\n b: MongoSchemaValidator | undefined,\n): boolean {\n if (!a && !b) return true;\n if (!a || !b) return false;\n return (\n a.validationLevel === b.validationLevel &&\n a.validationAction === b.validationAction &&\n canonicalize(a.jsonSchema) === canonicalize(b.jsonSchema)\n );\n}\n\nfunction classifyValidatorUpdate(\n origin: MongoSchemaValidator,\n dest: MongoSchemaValidator,\n): 'widening' | 'destructive' {\n // Moving to a stricter action or level narrows the accepted value space.\n if (origin.validationAction !== dest.validationAction && dest.validationAction === 'error') {\n return 'destructive';\n }\n if (origin.validationLevel !== dest.validationLevel && dest.validationLevel === 'strict') {\n return 'destructive';\n }\n\n if (canonicalize(origin.jsonSchema) === canonicalize(dest.jsonSchema)) {\n return 'widening';\n }\n\n // Check whether the schema change only adds non-required properties (widening).\n return isWideningSchemaChange(origin.jsonSchema, dest.jsonSchema) ? 'widening' : 'destructive';\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/**\n * Returns true when `dest` is a structural superset of `origin` for the common\n * additive case: adding non-required properties to a top-level object schema.\n * Anything uncertain falls through to the safe `destructive` default.\n */\nfunction isWideningSchemaChange(\n origin: Record<string, unknown>,\n dest: Record<string, unknown>,\n): boolean {\n // Only handle top-level object schemas.\n if (origin['bsonType'] !== 'object' || dest['bsonType'] !== 'object') {\n return false;\n }\n\n // Any change to keys besides 'required' and 'properties' is uncertain → destructive.\n const allKeys = new Set([...Object.keys(origin), ...Object.keys(dest)]);\n for (const key of allKeys) {\n if (key === 'required' || key === 'properties') continue;\n if (canonicalize(origin[key]) !== canonicalize(dest[key])) return false;\n }\n\n // dest.required must be a subset of origin.required — no new required fields.\n const originRequired = new Set<unknown>(\n Array.isArray(origin['required']) ? origin['required'] : [],\n );\n const destRequired = Array.isArray(dest['required']) ? dest['required'] : [];\n for (const field of destRequired) {\n if (!originRequired.has(field)) return false;\n }\n\n // All properties that existed in origin must still exist unchanged.\n // New properties in dest (absent from origin) are allowed — widening.\n const originProps = isPlainObject(origin['properties']) ? origin['properties'] : {};\n const destProps = isPlainObject(dest['properties']) ? dest['properties'] : {};\n for (const field of Object.keys(originProps)) {\n if (!Object.hasOwn(destProps, field)) return false; // Property removed → destructive.\n if (canonicalize(originProps[field]) !== canonicalize(destProps[field])) return false; // Property narrowed → destructive.\n }\n\n return true;\n}\n\nfunction hasImmutableOptionChange(\n origin: MongoSchemaCollectionOptions | undefined,\n dest: MongoSchemaCollectionOptions | undefined,\n): string | undefined {\n if (canonicalize(origin?.capped) !== canonicalize(dest?.capped)) return 'capped';\n if (canonicalize(origin?.timeseries) !== canonicalize(dest?.timeseries)) return 'timeseries';\n if (canonicalize(origin?.collation) !== canonicalize(dest?.collation)) return 'collation';\n if (canonicalize(origin?.clusteredIndex) !== canonicalize(dest?.clusteredIndex))\n return 'clusteredIndex';\n return undefined;\n}\n\nfunction collectionHasOptions(coll: MongoSchemaCollection): boolean {\n return !!(coll.options || coll.validator);\n}\n\nexport type PlanCallsResult =\n | { readonly kind: 'success'; readonly calls: OpFactoryCall[] }\n | { readonly kind: 'failure'; readonly conflicts: MigrationPlannerConflict[] };\n\nexport class MongoMigrationPlanner implements MigrationPlanner<'mongo', 'mongo'> {\n planCalls(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n }): PlanCallsResult {\n const contract = options.contract as MongoContract;\n const originIR = options.schema as MongoSchemaIR;\n const destinationIR = contractToMongoSchemaIR(contract);\n\n const collCreates: OpFactoryCall[] = [];\n const drops: OpFactoryCall[] = [];\n const creates: OpFactoryCall[] = [];\n const validatorOps: OpFactoryCall[] = [];\n const mutableOptionOps: OpFactoryCall[] = [];\n const collDrops: OpFactoryCall[] = [];\n const conflicts: MigrationPlannerConflict[] = [];\n\n const allCollectionNames = new Set([\n ...originIR.collectionNames,\n ...destinationIR.collectionNames,\n ]);\n\n for (const collName of [...allCollectionNames].sort()) {\n const originColl = originIR.collection(collName);\n const destColl = destinationIR.collection(collName);\n\n if (!originColl) {\n // Provision contract-declared collections that are absent from\n // the live database. MongoDB lazily materialises a collection\n // on first write, so subsequent `createIndex` calls in the same\n // plan would create the collection for us implicitly — but the\n // schema verifier treats an unmaterialised contract collection\n // as a `missing_table` issue, so a plan that lacks both options\n // and indexes (e.g. a plain `users` collection from the init\n // scaffold) ends up provisioning nothing and failing verify.\n // The planner therefore emits an explicit createCollection for\n // any contract collection that has options/validator OR no\n // indexes to ride along on. Collections that have indexes\n // continue to rely on createIndex for materialisation, keeping\n // existing plans byte-stable.\n if (destColl && (collectionHasOptions(destColl) || destColl.indexes.length === 0)) {\n const opts = collectionHasOptions(destColl)\n ? schemaCollectionToCreateCollectionOptions(destColl)\n : undefined;\n collCreates.push(new CreateCollectionCall(collName, opts));\n }\n } else if (!destColl) {\n collDrops.push(new DropCollectionCall(collName));\n } else {\n const immutableChange = hasImmutableOptionChange(originColl.options, destColl.options);\n if (immutableChange) {\n conflicts.push({\n kind: 'policy-violation',\n summary: `Cannot change immutable collection option '${immutableChange}' on ${collName}`,\n why: `MongoDB does not support modifying the '${immutableChange}' option after collection creation`,\n });\n }\n\n const mutableCall = planMutableOptionsDiffCall(\n collName,\n originColl.options,\n destColl.options,\n );\n if (mutableCall) mutableOptionOps.push(mutableCall);\n\n const validatorCall = planValidatorDiffCall(\n collName,\n originColl.validator,\n destColl.validator,\n );\n if (validatorCall) validatorOps.push(validatorCall);\n }\n\n const originLookup = new Map<string, MongoSchemaIndex>();\n if (originColl) {\n for (const idx of originColl.indexes) {\n originLookup.set(buildIndexLookupKey(idx), idx);\n }\n }\n\n const destLookup = new Map<string, MongoSchemaIndex>();\n if (destColl) {\n for (const idx of destColl.indexes) {\n destLookup.set(buildIndexLookupKey(idx), idx);\n }\n }\n\n for (const [lookupKey, idx] of originLookup) {\n if (!destLookup.has(lookupKey)) {\n drops.push(new DropIndexCall(collName, idx.keys));\n }\n }\n\n for (const [lookupKey, idx] of destLookup) {\n if (!originLookup.has(lookupKey)) {\n creates.push(\n new CreateIndexCall(collName, idx.keys, schemaIndexToCreateIndexOptions(idx)),\n );\n }\n }\n }\n\n if (conflicts.length > 0) {\n return { kind: 'failure', conflicts };\n }\n\n const allCalls = [\n ...collCreates,\n ...drops,\n ...creates,\n ...validatorOps,\n ...mutableOptionOps,\n ...collDrops,\n ];\n\n for (const call of allCalls) {\n if (!options.policy.allowedOperationClasses.includes(call.operationClass)) {\n conflicts.push({\n kind: 'policy-violation',\n summary: `${call.operationClass} operation disallowed: ${call.label}`,\n why: `Policy does not allow '${call.operationClass}' operations`,\n });\n }\n }\n\n if (conflicts.length > 0) {\n return { kind: 'failure', conflicts };\n }\n\n return { kind: 'success', calls: allCalls };\n }\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts at),\n * or `null` for reconciliation flows. Used to populate `describe().from`\n * on the produced plan as `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n }): MigrationPlannerResult {\n const contract = options.contract as MongoContract;\n const result = this.planCalls(options);\n if (result.kind === 'failure') return result;\n return {\n kind: 'success',\n plan: new PlannerProducedMongoMigration(result.calls, {\n from: options.fromContract?.storage.storageHash ?? null,\n to: contract.storage.storageHash,\n }),\n };\n }\n\n /**\n * Produce an empty `migration.ts` authoring surface for `migration new`.\n *\n * The \"empty migration\" is a `PlannerProducedMongoMigration` with no\n * operations; `renderTypeScript()` emits a stub class with the correct\n * `from`/`to` metadata that the user then fills in with operations. The\n * contract path on the context is unused — Mongo's emitted source does\n * not import from the generated contract `.d.ts`.\n */\n emptyMigration(context: MigrationScaffoldContext): MigrationPlanWithAuthoringSurface {\n return new PlannerProducedMongoMigration([], {\n from: context.fromHash,\n to: context.toHash,\n });\n }\n}\n\nfunction planValidatorDiffCall(\n collName: string,\n originValidator: MongoSchemaValidator | undefined,\n destValidator: MongoSchemaValidator | undefined,\n): OpFactoryCall | undefined {\n if (validatorsEqual(originValidator, destValidator)) return undefined;\n\n if (destValidator) {\n const operationClass: MigrationOperationClass = originValidator\n ? classifyValidatorUpdate(originValidator, destValidator)\n : 'destructive';\n return new CollModCall(\n collName,\n {\n validator: { $jsonSchema: destValidator.jsonSchema },\n validationLevel: destValidator.validationLevel,\n validationAction: destValidator.validationAction,\n },\n {\n id: `validator.${collName}.${originValidator ? 'update' : 'add'}`,\n label: `${originValidator ? 'Update' : 'Add'} validator on ${collName}`,\n operationClass,\n },\n );\n }\n\n return new CollModCall(\n collName,\n {\n validator: {},\n validationLevel: 'strict',\n validationAction: 'error',\n },\n {\n id: `validator.${collName}.remove`,\n label: `Remove validator on ${collName}`,\n operationClass: 'widening',\n },\n );\n}\n\nfunction planMutableOptionsDiffCall(\n collName: string,\n origin: MongoSchemaCollectionOptions | undefined,\n dest: MongoSchemaCollectionOptions | undefined,\n): OpFactoryCall | undefined {\n const originCSPPI = origin?.changeStreamPreAndPostImages;\n const destCSPPI = dest?.changeStreamPreAndPostImages;\n if (deepEqual(originCSPPI, destCSPPI)) return undefined;\n\n const desiredCSPPI = destCSPPI ?? { enabled: false };\n return new CollModCall(\n collName,\n {\n changeStreamPreAndPostImages: desiredCSPPI,\n },\n {\n id: `options.${collName}.update`,\n label: `Update mutable options on ${collName}`,\n operationClass: desiredCSPPI.enabled ? 'widening' : 'destructive',\n },\n );\n}\n","import type {\n MongoAndExpr,\n MongoExistsExpr,\n MongoExprFilter,\n MongoFieldFilter,\n MongoFilterExpr,\n MongoFilterVisitor,\n MongoNotExpr,\n MongoOrExpr,\n} from '@prisma-next/mongo-query-ast/control';\nimport { deepEqual } from '@prisma-next/mongo-schema-ir';\nimport type { MongoValue } from '@prisma-next/mongo-value';\n\nfunction getNestedField(doc: Record<string, unknown>, path: string): unknown {\n const parts = path.split('.');\n let current: unknown = doc;\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== 'object') {\n return undefined;\n }\n const record = current as Record<string, unknown>;\n if (!Object.hasOwn(record, part)) {\n return undefined;\n }\n current = record[part];\n }\n return current;\n}\n\nfunction evaluateFieldOp(op: string, actual: unknown, expected: MongoValue): boolean {\n switch (op) {\n case '$eq':\n return deepEqual(actual, expected);\n case '$ne':\n return !deepEqual(actual, expected);\n case '$gt':\n return typeof actual === typeof expected && (actual as number) > (expected as number);\n case '$gte':\n return typeof actual === typeof expected && (actual as number) >= (expected as number);\n case '$lt':\n return typeof actual === typeof expected && (actual as number) < (expected as number);\n case '$lte':\n return typeof actual === typeof expected && (actual as number) <= (expected as number);\n case '$in':\n return Array.isArray(expected) && expected.some((v) => deepEqual(actual, v));\n default:\n throw new Error(`Unsupported filter operator in migration check: ${op}`);\n }\n}\n\nexport class FilterEvaluator implements MongoFilterVisitor<boolean> {\n private doc: Record<string, unknown> = {};\n\n evaluate(filter: MongoFilterExpr, doc: Record<string, unknown>): boolean {\n this.doc = doc;\n return filter.accept(this);\n }\n\n field(expr: MongoFieldFilter): boolean {\n const value = getNestedField(this.doc, expr.field);\n return evaluateFieldOp(expr.op, value, expr.value);\n }\n\n and(expr: MongoAndExpr): boolean {\n return expr.exprs.every((child) => child.accept(this));\n }\n\n or(expr: MongoOrExpr): boolean {\n return expr.exprs.some((child) => child.accept(this));\n }\n\n not(expr: MongoNotExpr): boolean {\n return !expr.expr.accept(this);\n }\n\n exists(expr: MongoExistsExpr): boolean {\n const has = getNestedField(this.doc, expr.field) !== undefined;\n return expr.exists ? has : !has;\n }\n\n expr(_expr: MongoExprFilter): boolean {\n throw new Error('Aggregation expression filters are not supported in migration checks');\n }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { MigrationOperationClass } from '@prisma-next/framework-components/control';\nimport {\n type AnyMongoDdlCommand,\n type AnyMongoInspectionCommand,\n type AnyMongoMigrationOperation,\n CollModCommand,\n CreateCollectionCommand,\n CreateIndexCommand,\n DropCollectionCommand,\n DropIndexCommand,\n ListCollectionsCommand,\n ListIndexesCommand,\n MongoAndExpr,\n type MongoDataTransformCheck,\n type MongoDataTransformOperation,\n MongoExistsExpr,\n MongoFieldFilter,\n type MongoFilterExpr,\n type MongoMigrationCheck,\n type MongoMigrationPlanOperation,\n type MongoMigrationStep,\n MongoNotExpr,\n MongoOrExpr,\n} from '@prisma-next/mongo-query-ast/control';\nimport {\n AggregateCommand,\n type AnyMongoCommand,\n MongoAddFieldsStage,\n MongoLimitStage,\n MongoLookupStage,\n MongoMatchStage,\n MongoMergeStage,\n type MongoPipelineStage,\n MongoProjectStage,\n type MongoQueryPlan,\n MongoSortStage,\n type MongoUpdatePipelineStage,\n RawAggregateCommand,\n RawDeleteManyCommand,\n RawDeleteOneCommand,\n RawFindOneAndDeleteCommand,\n RawFindOneAndUpdateCommand,\n RawInsertManyCommand,\n RawInsertOneCommand,\n RawUpdateManyCommand,\n RawUpdateOneCommand,\n} from '@prisma-next/mongo-query-ast/execution';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type } from 'arktype';\n\nconst IndexKeyDirection = type('1 | -1 | \"text\" | \"2dsphere\" | \"2d\" | \"hashed\"');\nconst IndexKeyJson = type({ field: 'string', direction: IndexKeyDirection });\n\nconst CreateIndexJson = type({\n kind: '\"createIndex\"',\n collection: 'string',\n keys: IndexKeyJson.array().atLeastLength(1),\n 'unique?': 'boolean',\n 'sparse?': 'boolean',\n 'expireAfterSeconds?': 'number',\n 'partialFilterExpression?': 'Record<string, unknown>',\n 'name?': 'string',\n 'wildcardProjection?': 'Record<string, unknown>',\n 'collation?': 'Record<string, unknown>',\n 'weights?': 'Record<string, unknown>',\n 'default_language?': 'string',\n 'language_override?': 'string',\n});\n\nconst DropIndexJson = type({\n kind: '\"dropIndex\"',\n collection: 'string',\n name: 'string',\n});\n\nconst CreateCollectionJson = type({\n kind: '\"createCollection\"',\n collection: 'string',\n 'validator?': 'Record<string, unknown>',\n 'validationLevel?': '\"strict\" | \"moderate\"',\n 'validationAction?': '\"error\" | \"warn\"',\n 'capped?': 'boolean',\n 'size?': 'number',\n 'max?': 'number',\n 'timeseries?': 'Record<string, unknown>',\n 'collation?': 'Record<string, unknown>',\n 'changeStreamPreAndPostImages?': 'Record<string, unknown>',\n 'clusteredIndex?': 'Record<string, unknown>',\n});\n\nconst DropCollectionJson = type({\n kind: '\"dropCollection\"',\n collection: 'string',\n});\n\nconst CollModJson = type({\n kind: '\"collMod\"',\n collection: 'string',\n 'validator?': 'Record<string, unknown>',\n 'validationLevel?': '\"strict\" | \"moderate\"',\n 'validationAction?': '\"error\" | \"warn\"',\n 'changeStreamPreAndPostImages?': 'Record<string, unknown>',\n});\n\nconst ListIndexesJson = type({\n kind: '\"listIndexes\"',\n collection: 'string',\n});\n\nconst ListCollectionsJson = type({\n kind: '\"listCollections\"',\n});\n\nconst FieldFilterJson = type({\n kind: '\"field\"',\n field: 'string',\n op: 'string',\n value: 'unknown',\n});\n\nconst ExistsFilterJson = type({\n kind: '\"exists\"',\n field: 'string',\n exists: 'boolean',\n});\n\n// ============================================================================\n// DML command schemas\n// ============================================================================\n\nconst RawInsertOneJson = type({\n kind: '\"rawInsertOne\"',\n collection: 'string',\n document: 'Record<string, unknown>',\n});\n\nconst RawInsertManyJson = type({\n kind: '\"rawInsertMany\"',\n collection: 'string',\n documents: 'Record<string, unknown>[]',\n});\n\nconst RawUpdateOneJson = type({\n kind: '\"rawUpdateOne\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n update: 'Record<string, unknown> | Record<string, unknown>[]',\n});\n\nconst RawUpdateManyJson = type({\n kind: '\"rawUpdateMany\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n update: 'Record<string, unknown> | Record<string, unknown>[]',\n});\n\nconst RawDeleteOneJson = type({\n kind: '\"rawDeleteOne\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n});\n\nconst RawDeleteManyJson = type({\n kind: '\"rawDeleteMany\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n});\n\nconst RawAggregateJson = type({\n kind: '\"rawAggregate\"',\n collection: 'string',\n pipeline: 'Record<string, unknown>[]',\n});\n\nconst RawFindOneAndUpdateJson = type({\n kind: '\"rawFindOneAndUpdate\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n update: 'Record<string, unknown> | Record<string, unknown>[]',\n upsert: 'boolean',\n});\n\nconst RawFindOneAndDeleteJson = type({\n kind: '\"rawFindOneAndDelete\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n});\n\nconst TypedAggregateJson = type({\n kind: '\"aggregate\"',\n collection: 'string',\n pipeline: 'Record<string, unknown>[]',\n});\n\nconst PlanMetaJson = type({\n target: 'string',\n storageHash: 'string',\n lane: 'string',\n 'targetFamily?': 'string',\n 'profileHash?': 'string',\n 'annotations?': 'Record<string, unknown>',\n});\n\nconst QueryPlanJson = type({\n collection: 'string',\n command: 'Record<string, unknown>',\n meta: PlanMetaJson,\n});\n\n// ============================================================================\n// DDL check/step schemas\n// ============================================================================\n\nconst CheckJson = type({\n description: 'string',\n source: 'Record<string, unknown>',\n filter: 'Record<string, unknown>',\n expect: '\"exists\" | \"notExists\"',\n});\n\nconst StepJson = type({\n description: 'string',\n command: 'Record<string, unknown>',\n});\n\nconst DdlOperationJson = type({\n id: 'string',\n label: 'string',\n operationClass: '\"additive\" | \"widening\" | \"destructive\"',\n precheck: 'Record<string, unknown>[]',\n execute: 'Record<string, unknown>[]',\n postcheck: 'Record<string, unknown>[]',\n});\n\nconst DataTransformCheckJson = type({\n description: 'string',\n source: 'Record<string, unknown>',\n filter: 'Record<string, unknown>',\n expect: '\"exists\" | \"notExists\"',\n});\n\nconst DataTransformOperationJson = type({\n id: 'string',\n label: 'string',\n operationClass: '\"data\"',\n name: 'string',\n precheck: 'Record<string, unknown>[]',\n run: 'Record<string, unknown>[]',\n postcheck: 'Record<string, unknown>[]',\n});\n\nfunction validate<T>(schema: { assert: (data: unknown) => T }, data: unknown, context: string): T {\n try {\n return schema.assert(stripUndefinedDeep(data));\n } catch (error) {\n /* v8 ignore start -- assertion libraries always throw Error instances */\n const message = error instanceof Error ? error.message : String(error);\n /* v8 ignore stop */\n throw new Error(`Invalid ${context}: ${message}`);\n }\n}\n\n/**\n * Strip `undefined`-valued properties before they reach arktype's optional-key\n * assertions.\n *\n * Op IRs (e.g. `CreateCollectionCommand`) assign every optional field on\n * every instance — fields the caller did not provide land as\n * `undefined`-valued properties. arktype treats `{ foo?: 'boolean' }` as\n * \"key may be absent, but if present must be boolean\", so the bare instance\n * fails validation when it crosses the deserialize boundary in-process\n * (no JSON round-trip happens between planner → runner). This helper\n * recovers the JSON-round-tripped shape (undefined keys absent) without\n * forcing every caller to round-trip.\n *\n * Returns the original value reference whenever no change is needed.\n * That preserves prototype-bound payload values such as BSON wrappers\n * (`ObjectId`, `Decimal128`, `Binary`, …) which embed no `undefined`\n * own-enumerable properties and therefore never trigger a rebuild.\n * Top-level op IRs (class instances with `undefined` optional fields)\n * still get flattened to plain records as required by arktype.\n */\nfunction stripUndefinedDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n let changed = false;\n const next = value.map((item) => {\n const stripped = stripUndefinedDeep(item);\n if (stripped !== item) changed = true;\n return stripped;\n });\n return changed ? next : value;\n }\n if (value === null || typeof value !== 'object') {\n return value;\n }\n const entries = Object.entries(value as Record<string, unknown>);\n const out: Record<string, unknown> = {};\n let changed = false;\n for (const [key, val] of entries) {\n if (val === undefined) {\n changed = true;\n continue;\n }\n const stripped = stripUndefinedDeep(val);\n if (stripped !== val) changed = true;\n out[key] = stripped;\n }\n return changed ? out : value;\n}\n\nfunction deserializeFilterExpr(json: unknown): MongoFilterExpr {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'field': {\n const data = validate(FieldFilterJson, json, 'field filter');\n return MongoFieldFilter.of(data.field, data.op, data.value as never);\n }\n case 'and': {\n const exprs = record['exprs'];\n if (!Array.isArray(exprs)) throw new Error('Invalid and filter: missing exprs array');\n return MongoAndExpr.of(exprs.map(deserializeFilterExpr));\n }\n case 'or': {\n const exprs = record['exprs'];\n if (!Array.isArray(exprs)) throw new Error('Invalid or filter: missing exprs array');\n return MongoOrExpr.of(exprs.map(deserializeFilterExpr));\n }\n case 'not': {\n const expr = record['expr'];\n if (!expr || typeof expr !== 'object') throw new Error('Invalid not filter: missing expr');\n return new MongoNotExpr(deserializeFilterExpr(expr));\n }\n case 'exists': {\n const data = validate(ExistsFilterJson, json, 'exists filter');\n return new MongoExistsExpr(data.field, data.exists);\n }\n default:\n throw new Error(`Unknown filter expression kind: ${kind}`);\n }\n}\n\n// ============================================================================\n// Pipeline stage deserialization\n// ============================================================================\n\nexport function deserializePipelineStage(json: unknown): MongoPipelineStage {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'match':\n return new MongoMatchStage(deserializeFilterExpr(record['filter']));\n case 'limit':\n return new MongoLimitStage(record['limit'] as number);\n case 'sort':\n return new MongoSortStage(record['sort'] as Record<string, 1 | -1>);\n case 'project':\n return new MongoProjectStage(record['projection'] as Record<string, 0 | 1>);\n case 'addFields':\n return new MongoAddFieldsStage(record['fields'] as Record<string, never>);\n case 'lookup': {\n const opts: {\n from: string;\n as: string;\n localField?: string;\n foreignField?: string;\n pipeline?: ReadonlyArray<MongoPipelineStage>;\n let_?: Record<string, never>;\n } = {\n from: record['from'] as string,\n as: record['as'] as string,\n };\n if (record['localField'] !== undefined) opts.localField = record['localField'] as string;\n if (record['foreignField'] !== undefined)\n opts.foreignField = record['foreignField'] as string;\n if (record['pipeline'] !== undefined)\n opts.pipeline = (record['pipeline'] as unknown[]).map(deserializePipelineStage);\n if (record['let_'] !== undefined) opts.let_ = record['let_'] as Record<string, never>;\n return new MongoLookupStage(opts);\n }\n case 'merge': {\n const opts: {\n into: string | { db: string; coll: string };\n on?: string | ReadonlyArray<string>;\n whenMatched?: string | ReadonlyArray<MongoUpdatePipelineStage>;\n whenNotMatched?: string;\n } = {\n into: record['into'] as string | { db: string; coll: string },\n };\n if (record['on'] !== undefined) opts.on = record['on'] as string | string[];\n if (record['whenMatched'] !== undefined) {\n const wm = record['whenMatched'];\n opts.whenMatched =\n typeof wm === 'string'\n ? wm\n : ((wm as unknown[]).map(deserializePipelineStage) as MongoUpdatePipelineStage[]);\n }\n if (record['whenNotMatched'] !== undefined)\n opts.whenNotMatched = record['whenNotMatched'] as string;\n return new MongoMergeStage(opts);\n }\n default:\n throw new Error(`Unknown pipeline stage kind: ${kind}`);\n }\n}\n\n// ============================================================================\n// DML command deserialization\n// ============================================================================\n\nexport function deserializeDmlCommand(json: unknown): AnyMongoCommand {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'rawInsertOne': {\n const data = validate(RawInsertOneJson, json, 'rawInsertOne command');\n return new RawInsertOneCommand(data.collection, data.document);\n }\n case 'rawInsertMany': {\n const data = validate(RawInsertManyJson, json, 'rawInsertMany command');\n return new RawInsertManyCommand(data.collection, data.documents);\n }\n case 'rawUpdateOne': {\n const data = validate(RawUpdateOneJson, json, 'rawUpdateOne command');\n return new RawUpdateOneCommand(data.collection, data.filter, data.update);\n }\n case 'rawUpdateMany': {\n const data = validate(RawUpdateManyJson, json, 'rawUpdateMany command');\n return new RawUpdateManyCommand(data.collection, data.filter, data.update);\n }\n case 'rawDeleteOne': {\n const data = validate(RawDeleteOneJson, json, 'rawDeleteOne command');\n return new RawDeleteOneCommand(data.collection, data.filter);\n }\n case 'rawDeleteMany': {\n const data = validate(RawDeleteManyJson, json, 'rawDeleteMany command');\n return new RawDeleteManyCommand(data.collection, data.filter);\n }\n case 'rawAggregate': {\n const data = validate(RawAggregateJson, json, 'rawAggregate command');\n return new RawAggregateCommand(data.collection, data.pipeline);\n }\n case 'rawFindOneAndUpdate': {\n const data = validate(RawFindOneAndUpdateJson, json, 'rawFindOneAndUpdate command');\n return new RawFindOneAndUpdateCommand(data.collection, data.filter, data.update, data.upsert);\n }\n case 'rawFindOneAndDelete': {\n const data = validate(RawFindOneAndDeleteJson, json, 'rawFindOneAndDelete command');\n return new RawFindOneAndDeleteCommand(data.collection, data.filter);\n }\n case 'aggregate': {\n const data = validate(TypedAggregateJson, json, 'aggregate command');\n const pipeline = data.pipeline.map(deserializePipelineStage);\n return new AggregateCommand(data.collection, pipeline);\n }\n default:\n throw new Error(`Unknown DML command kind: ${kind}`);\n }\n}\n\n// ============================================================================\n// MongoQueryPlan deserialization\n// ============================================================================\n\nexport function deserializeMongoQueryPlan(json: unknown): MongoQueryPlan {\n const data = validate(QueryPlanJson, json, 'Mongo query plan');\n const command = deserializeDmlCommand(data.command);\n const m = data.meta;\n const meta: PlanMeta = {\n target: m.target,\n storageHash: m.storageHash,\n lane: m.lane,\n ...ifDefined('targetFamily', m.targetFamily),\n ...ifDefined('profileHash', m.profileHash),\n ...ifDefined('annotations', m.annotations),\n };\n return { collection: data.collection, command, meta };\n}\n\n// ============================================================================\n// DDL command deserialization\n// ============================================================================\n\nfunction deserializeDdlCommand(json: unknown): AnyMongoDdlCommand {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'createIndex': {\n const data = validate(CreateIndexJson, json, 'createIndex command');\n return new CreateIndexCommand(data.collection, data.keys, {\n ...ifDefined('unique', data.unique),\n ...ifDefined('sparse', data.sparse),\n ...ifDefined('expireAfterSeconds', data.expireAfterSeconds),\n ...ifDefined('partialFilterExpression', data.partialFilterExpression),\n ...ifDefined('name', data.name),\n ...ifDefined(\n 'wildcardProjection',\n data.wildcardProjection as Record<string, 0 | 1> | undefined,\n ),\n ...ifDefined('collation', data.collation),\n ...ifDefined('weights', data.weights as Record<string, number> | undefined),\n ...ifDefined('default_language', data.default_language),\n ...ifDefined('language_override', data.language_override),\n });\n }\n case 'dropIndex': {\n const data = validate(DropIndexJson, json, 'dropIndex command');\n return new DropIndexCommand(data.collection, data.name);\n }\n case 'createCollection': {\n const data = validate(CreateCollectionJson, json, 'createCollection command');\n return new CreateCollectionCommand(data.collection, {\n validator: data.validator,\n validationLevel: data.validationLevel,\n validationAction: data.validationAction,\n capped: data.capped,\n size: data.size,\n max: data.max,\n timeseries: data.timeseries as CreateCollectionCommand['timeseries'],\n collation: data.collation,\n changeStreamPreAndPostImages: data.changeStreamPreAndPostImages as\n | { enabled: boolean }\n | undefined,\n clusteredIndex: data.clusteredIndex as CreateCollectionCommand['clusteredIndex'],\n });\n }\n case 'dropCollection': {\n const data = validate(DropCollectionJson, json, 'dropCollection command');\n return new DropCollectionCommand(data.collection);\n }\n case 'collMod': {\n const data = validate(CollModJson, json, 'collMod command');\n return new CollModCommand(data.collection, {\n validator: data.validator,\n validationLevel: data.validationLevel,\n validationAction: data.validationAction,\n changeStreamPreAndPostImages: data.changeStreamPreAndPostImages as\n | { enabled: boolean }\n | undefined,\n });\n }\n default:\n throw new Error(`Unknown DDL command kind: ${kind}`);\n }\n}\n\nfunction deserializeInspectionCommand(json: unknown): AnyMongoInspectionCommand {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'listIndexes': {\n const data = validate(ListIndexesJson, json, 'listIndexes command');\n return new ListIndexesCommand(data.collection);\n }\n case 'listCollections': {\n validate(ListCollectionsJson, json, 'listCollections command');\n return new ListCollectionsCommand();\n }\n default:\n throw new Error(`Unknown inspection command kind: ${kind}`);\n }\n}\n\nfunction deserializeCheck(json: unknown): MongoMigrationCheck {\n const data = validate(CheckJson, json, 'migration check');\n return {\n description: data.description,\n source: deserializeInspectionCommand(data.source),\n filter: deserializeFilterExpr(data.filter),\n expect: data.expect,\n };\n}\n\nfunction deserializeStep(json: unknown): MongoMigrationStep {\n const data = validate(StepJson, json, 'migration step');\n return {\n description: data.description,\n command: deserializeDdlCommand(data.command),\n };\n}\n\nfunction isDataTransformJson(json: unknown): boolean {\n return (\n typeof json === 'object' &&\n json !== null &&\n (json as Record<string, unknown>)['operationClass'] === 'data'\n );\n}\n\nfunction deserializeDdlOp(json: unknown): MongoMigrationPlanOperation {\n const data = validate(DdlOperationJson, json, 'migration operation');\n return {\n id: data.id,\n label: data.label,\n operationClass: data.operationClass as MigrationOperationClass,\n precheck: data.precheck.map(deserializeCheck),\n execute: data.execute.map(deserializeStep),\n postcheck: data.postcheck.map(deserializeCheck),\n };\n}\n\nfunction deserializeDataTransformCheck(json: unknown): MongoDataTransformCheck {\n const data = validate(DataTransformCheckJson, json, 'data transform check');\n return {\n description: data.description,\n source: deserializeMongoQueryPlan(data.source),\n filter: deserializeFilterExpr(data.filter),\n expect: data.expect,\n };\n}\n\nfunction deserializeDataTransformOp(json: unknown): MongoDataTransformOperation {\n const data = validate(DataTransformOperationJson, json, 'data transform operation');\n return {\n id: data.id,\n label: data.label,\n operationClass: 'data',\n name: data.name,\n precheck: data.precheck.map(deserializeDataTransformCheck),\n run: data.run.map(deserializeMongoQueryPlan),\n postcheck: data.postcheck.map(deserializeDataTransformCheck),\n };\n}\n\nexport function deserializeMongoOp(json: unknown): AnyMongoMigrationOperation {\n if (isDataTransformJson(json)) {\n return deserializeDataTransformOp(json);\n }\n return deserializeDdlOp(json);\n}\n\nexport function deserializeMongoOps(json: readonly unknown[]): AnyMongoMigrationOperation[] {\n return json.map(deserializeMongoOp);\n}\n\nexport function serializeMongoOps(ops: readonly AnyMongoMigrationOperation[]): string {\n return JSON.stringify(ops, null, 2);\n}\n","import type { MarkerOperations, MongoRunnerDependencies } from '@prisma-next/adapter-mongo/control';\nimport type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { errorRunnerFailed } from '@prisma-next/errors/execution';\nimport { verifyMongoSchema } from '@prisma-next/family-mongo/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport {\n APP_SPACE_ID,\n type MigrationOperationPolicy,\n type MigrationPlan,\n type MigrationPlanOperation,\n type MigrationRunnerExecutionChecks,\n type MigrationRunnerFailure,\n type MigrationRunnerResult,\n type OperationContext,\n} from '@prisma-next/framework-components/control';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type { MongoAdapter, MongoDriver } from '@prisma-next/mongo-lowering';\nimport type {\n AnyMongoMigrationOperation,\n MongoDataTransformCheck,\n MongoDataTransformOperation,\n MongoInspectionCommandVisitor,\n MongoMigrationCheck,\n MongoMigrationPlanOperation,\n} from '@prisma-next/mongo-query-ast/control';\nimport type { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { FilterEvaluator } from './filter-evaluator';\nimport { deserializeMongoOps } from './mongo-ops-serializer';\n\nconst READ_ONLY_CHECK_COMMAND_KINDS: ReadonlySet<string> = new Set(['aggregate', 'rawAggregate']);\n\nexport type { MarkerOperations, MongoRunnerDependencies };\n\nexport interface MongoMigrationRunnerExecuteOptions {\n readonly plan: MigrationPlan;\n readonly destinationContract: MongoContract;\n readonly policy: MigrationOperationPolicy;\n readonly callbacks?: {\n onOperationStart?(op: MigrationPlanOperation): void;\n onOperationComplete?(op: MigrationPlanOperation): void;\n };\n readonly executionChecks?: MigrationRunnerExecutionChecks;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n readonly strictVerification?: boolean;\n readonly context?: OperationContext;\n /**\n * Per-space schema projection. When set, the runner applies this\n * function to the introspected schema before invoking\n * `verifyMongoSchema`, so per-space verification only sees the slice\n * the destination contract actually claims.\n *\n * The descriptor's `executeAcrossSpaces` injects this callback,\n * derived from the sibling spaces in the aggregate. Single-space\n * callers leave it unset and verify against the whole introspected\n * schema (the pre-aggregate behaviour).\n */\n readonly projectSchema?: (schema: MongoSchemaIR) => MongoSchemaIR;\n}\n\nfunction runnerFailure(\n code: string,\n summary: string,\n opts?: { why?: string; meta?: Record<string, unknown> },\n): MigrationRunnerResult {\n return notOk<MigrationRunnerFailure>({\n code,\n summary,\n ...opts,\n });\n}\n\nexport class MongoMigrationRunner {\n constructor(private readonly deps: MongoRunnerDependencies) {}\n\n async execute(options: MongoMigrationRunnerExecuteOptions): Promise<MigrationRunnerResult> {\n const { commandExecutor, inspectionExecutor, adapter, driver, markerOps } = this.deps;\n const operations = deserializeMongoOps(options.plan.operations as readonly unknown[]);\n // Plans produced by the contract-space-aware planner stamp `spaceId`\n // onto the plan; pre-port single-space callers leave it absent and\n // fall through to the application's well-known space.\n const space = options.plan.spaceId ?? APP_SPACE_ID;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, operations);\n if (policyCheck) return policyCheck;\n\n const existingMarker = await markerOps.readMarker(space);\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (markerCheck) return markerCheck;\n\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false;\n const runPostchecks = checks?.postchecks !== false;\n const runIdempotency = checks?.idempotencyChecks !== false;\n\n const filterEvaluator = new FilterEvaluator();\n\n let operationsExecuted = 0;\n\n for (const operation of operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n if (operation.operationClass === 'data') {\n const result = await this.executeDataTransform(\n operation as MongoDataTransformOperation,\n adapter,\n driver,\n filterEvaluator,\n runIdempotency,\n runPrechecks,\n runPostchecks,\n );\n if (result.failure) return result.failure;\n if (result.executed) operationsExecuted += 1;\n continue;\n }\n\n const ddlOp = operation as MongoMigrationPlanOperation;\n\n if (runPostchecks && runIdempotency) {\n const allSatisfied = await this.allChecksSatisfied(\n ddlOp.postcheck,\n inspectionExecutor,\n filterEvaluator,\n );\n if (allSatisfied) continue;\n }\n\n if (runPrechecks) {\n const precheckResult = await this.evaluateChecks(\n ddlOp.precheck,\n inspectionExecutor,\n filterEvaluator,\n );\n if (!precheckResult) {\n return runnerFailure(\n 'PRECHECK_FAILED',\n `Operation ${operation.id} failed during precheck`,\n { meta: { operationId: operation.id } },\n );\n }\n }\n\n for (const step of ddlOp.execute) {\n await step.command.accept(commandExecutor);\n }\n\n if (runPostchecks) {\n const postcheckResult = await this.evaluateChecks(\n ddlOp.postcheck,\n inspectionExecutor,\n filterEvaluator,\n );\n if (!postcheckResult) {\n return runnerFailure(\n 'POSTCHECK_FAILED',\n `Operation ${operation.id} failed during postcheck`,\n { meta: { operationId: operation.id } },\n );\n }\n }\n\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n\n const destination = options.plan.destination;\n const profileHash = options.destinationContract.profileHash ?? destination.storageHash;\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariantSet = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) =>\n existingInvariantSet.has(id),\n );\n const markerAlreadyAtDestination =\n existingMarker !== null &&\n existingMarker.storageHash === destination.storageHash &&\n existingMarker.profileHash === profileHash;\n\n // Skip marker/ledger writes (and schema verification) only when the apply\n // is a true no-op: no operations executed, marker already at destination,\n // and every incoming invariant is already in the stored set.\n //\n // Divergence from the SQL runners (postgres/sqlite): those runners gate\n // the no-op skip on `isSelfEdge` (origin === destination) only, so a\n // non-self-edge `db update` that introspects-as-no-op still writes a\n // ledger entry. Mongo skips even those because the runner has no\n // structural distinction between self-edge and re-apply — invariant-\n // aware routing here does not yet differentiate between the two\n // ledger semantics. If the SQL audit-trail behavior should hold for\n // Mongo too, gate this `isNoOp` on a self-edge check (or, conversely,\n // align the SQL runners to skip non-self-edge no-ops uniformly).\n const isNoOp =\n operationsExecuted === 0 && markerAlreadyAtDestination && incomingIsSubsetOfExisting;\n\n if (!isNoOp) {\n const liveSchema = await this.deps.introspectSchema();\n // In a multi-space aggregate the live database holds collections\n // owned by sibling spaces; the descriptor's `executeAcrossSpaces`\n // injects a `projectSchema` that strips them so per-space verify\n // only checks the slice this contract claims. Single-space\n // callers leave the projection identity (no-op).\n const verifySchema = options.projectSchema ? options.projectSchema(liveSchema) : liveSchema;\n const verifyResult = verifyMongoSchema({\n contract: options.destinationContract,\n schema: verifySchema,\n strict: options.strictVerification ?? true,\n frameworkComponents: options.frameworkComponents,\n ...(options.context ? { context: options.context } : {}),\n });\n if (!verifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', verifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: { issues: verifyResult.schema.issues },\n });\n }\n\n if (existingMarker) {\n const updated = await markerOps.updateMarker(space, existingMarker.storageHash, {\n storageHash: destination.storageHash,\n profileHash,\n invariants: incomingInvariants,\n });\n if (!updated) {\n return runnerFailure(\n 'MARKER_CAS_FAILURE',\n 'Marker was modified by another process during migration execution.',\n {\n meta: {\n space,\n expectedStorageHash: existingMarker.storageHash,\n destinationStorageHash: destination.storageHash,\n },\n },\n );\n }\n } else {\n await markerOps.initMarker(space, {\n storageHash: destination.storageHash,\n profileHash,\n invariants: incomingInvariants,\n });\n }\n\n const originHash = existingMarker?.storageHash ?? '';\n await markerOps.writeLedgerEntry(space, {\n edgeId: `${originHash}->${destination.storageHash}`,\n from: originHash,\n to: destination.storageHash,\n });\n }\n\n return ok({ operationsPlanned: operations.length, operationsExecuted });\n }\n\n private async executeDataTransform(\n op: MongoDataTransformOperation,\n adapter: MongoAdapter,\n driver: MongoDriver,\n filterEvaluator: FilterEvaluator,\n runIdempotency: boolean,\n runPrechecks: boolean,\n runPostchecks: boolean,\n ): Promise<{ executed: boolean; failure?: MigrationRunnerResult }> {\n if (runPostchecks && runIdempotency && op.postcheck.length > 0) {\n const allSatisfied = await this.evaluateDataTransformChecks(\n op.postcheck,\n adapter,\n driver,\n filterEvaluator,\n );\n if (allSatisfied) return { executed: false };\n }\n\n if (runPrechecks && op.precheck.length > 0) {\n const passed = await this.evaluateDataTransformChecks(\n op.precheck,\n adapter,\n driver,\n filterEvaluator,\n );\n if (!passed) {\n return {\n executed: false,\n failure: runnerFailure('PRECHECK_FAILED', `Operation ${op.id} failed during precheck`, {\n meta: { operationId: op.id, name: op.name },\n }),\n };\n }\n }\n\n for (const plan of op.run) {\n const wireCommand = await adapter.lower(plan, {});\n for await (const _ of driver.execute(wireCommand)) {\n /* consume */\n }\n }\n\n if (runPostchecks && op.postcheck.length > 0) {\n const passed = await this.evaluateDataTransformChecks(\n op.postcheck,\n adapter,\n driver,\n filterEvaluator,\n );\n if (!passed) {\n return {\n executed: false,\n failure: runnerFailure('POSTCHECK_FAILED', `Operation ${op.id} failed during postcheck`, {\n meta: { operationId: op.id, name: op.name },\n }),\n };\n }\n }\n\n return { executed: true };\n }\n\n private async evaluateDataTransformChecks(\n checks: readonly MongoDataTransformCheck[],\n adapter: MongoAdapter,\n driver: MongoDriver,\n filterEvaluator: FilterEvaluator,\n ): Promise<boolean> {\n for (const check of checks) {\n const commandKind = check.source.command.kind;\n if (!READ_ONLY_CHECK_COMMAND_KINDS.has(commandKind)) {\n throw errorRunnerFailed(\n `Data-transform check rejected: command kind \"${commandKind}\" is not read-only`,\n {\n why: 'Data-transform checks must use aggregate or rawAggregate commands so the pre/postcheck path cannot mutate the database.',\n fix: 'Author the check.source as an aggregate pipeline (or rawAggregate) rather than a DML write command.',\n meta: {\n checkDescription: check.description,\n commandKind,\n collection: check.source.collection,\n },\n },\n );\n }\n const wireCommand = await adapter.lower(check.source, {});\n let matchFound = false;\n for await (const row of driver.execute<Record<string, unknown>>(wireCommand)) {\n if (filterEvaluator.evaluate(check.filter, row)) {\n matchFound = true;\n break;\n }\n }\n const passed = check.expect === 'exists' ? matchFound : !matchFound;\n if (!passed) return false;\n }\n return true;\n }\n\n private async evaluateChecks(\n checks: readonly MongoMigrationCheck[],\n inspectionExecutor: MongoInspectionCommandVisitor<Promise<Record<string, unknown>[]>>,\n filterEvaluator: FilterEvaluator,\n ): Promise<boolean> {\n for (const check of checks) {\n const documents = await check.source.accept(inspectionExecutor);\n const matchFound = documents.some((doc) =>\n filterEvaluator.evaluate(check.filter, doc as Record<string, unknown>),\n );\n const passed = check.expect === 'exists' ? matchFound : !matchFound;\n if (!passed) return false;\n }\n return true;\n }\n\n private async allChecksSatisfied(\n checks: readonly MongoMigrationCheck[],\n inspectionExecutor: MongoInspectionCommandVisitor<Promise<Record<string, unknown>[]>>,\n filterEvaluator: FilterEvaluator,\n ): Promise<boolean> {\n if (checks.length === 0) return false;\n return this.evaluateChecks(checks, inspectionExecutor, filterEvaluator);\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly AnyMongoMigrationOperation[],\n ): MigrationRunnerResult | undefined {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${[...allowedClasses].join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n },\n },\n );\n }\n }\n return undefined;\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: MigrationPlan,\n ): MigrationRunnerResult | undefined {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller has done its own\n // correctness check (typically `db update` via live-schema\n // introspection) and does not rely on marker continuity.\n return undefined;\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n { meta: { expectedOriginStorageHash: origin.storageHash } },\n );\n }\n\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n\n return undefined;\n }\n}\n","import {\n freezeNode,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { MongoCollection, type MongoCollectionInput } from '@prisma-next/mongo-contract';\n\nexport interface MongoTargetDatabaseInput {\n readonly id: string;\n readonly collections?: Record<string, MongoCollection | MongoCollectionInput>;\n}\n\n/**\n * Mongo target `Namespace` concretion. In Mongo the \"namespace\" concept\n * binds to the connection's `db` field — a `MongoTargetDatabase` instance\n * names the database the collections live under. The unbound singleton\n * (below) is the late-bound slot whose binding the connection's `db`\n * resolves at runtime rather than at authoring time.\n *\n * Qualifier emission is the rendering seam: query / DDL emission asks the\n * namespace for its qualifier (e.g. `\"<db>.<collection>\"`) and consumes\n * the result polymorphically. The unbound singleton overrides these\n * methods to elide the prefix entirely — call sites stay polymorphic and\n * never branch on `id === UNBOUND_NAMESPACE_ID`.\n */\nexport class MongoTargetDatabase extends NamespaceBase {\n readonly kind = 'database' as const;\n readonly id: string;\n readonly collections: Readonly<Record<string, MongoCollection>>;\n\n constructor(input: MongoTargetDatabaseInput) {\n super();\n this.id = input.id;\n this.collections = Object.freeze(\n Object.fromEntries(\n Object.entries(input.collections ?? {}).map(([name, c]) => [\n name,\n c instanceof MongoCollection ? c : new MongoCollection(c),\n ]),\n ),\n );\n freezeNode(this);\n }\n\n /**\n * The bare qualifier as it would appear in a rendered string. The\n * unbound-database singleton overrides this to return `''`.\n */\n qualifier(): string {\n return this.id;\n }\n\n /**\n * Qualify a collection name with the database prefix. The\n * unbound-database singleton overrides this to emit just the\n * collection name. Used by emission/introspection paths that need a\n * fully-qualified reference.\n */\n qualifyCollection(collectionName: string): string {\n return `${this.id}.${collectionName}`;\n }\n}\n\n/**\n * Singleton subclass for the reserved sentinel namespace id\n * (`UNBOUND_NAMESPACE_ID`) — the late-bound slot whose binding the\n * connection's `db` resolves at runtime. Overrides qualifier emission\n * to elide the database prefix; call sites that consume `qualifier()`\n * / `qualifyCollection()` get unqualified output without branching on\n * the namespace id.\n *\n * This is the target-side materialization of \"the framework provides\n * affordances; targets implement specifics\": the framework names the\n * sentinel; Mongo decides what late-bound means here (the collection\n * name, naked — the database is supplied by the live connection).\n */\nexport class MongoTargetUnboundDatabase extends MongoTargetDatabase {\n static readonly instance: MongoTargetUnboundDatabase = new MongoTargetUnboundDatabase();\n\n private constructor() {\n super({ id: UNBOUND_NAMESPACE_ID });\n }\n\n override qualifier(): string {\n return '';\n }\n\n override qualifyCollection(collectionName: string): string {\n return collectionName;\n }\n}\n","import { MongoContractSerializerBase } from '@prisma-next/family-mongo/ir';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { type MongoContract, MongoStorage } from '@prisma-next/mongo-contract';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport type { MongoTargetContract } from './mongo-target-contract';\nimport { MongoTargetDatabase, MongoTargetUnboundDatabase } from './mongo-target-database';\n\nexport class MongoTargetContractSerializer extends MongoContractSerializerBase<MongoTargetContract> {\n protected constructTargetContract(validated: MongoContract): MongoTargetContract {\n const { storage, ...rest } = validated;\n const namespaces = Object.fromEntries(\n Object.entries(storage.namespaces).map(([nsId, nsData]) => {\n const collections = nsData.collections;\n const collectionCount = Object.keys(collections).length;\n if (nsId === UNBOUND_NAMESPACE_ID && collectionCount === 0) {\n return [nsId, MongoTargetUnboundDatabase.instance];\n }\n return [\n nsId,\n new MongoTargetDatabase({\n id: nsData.id,\n collections,\n }),\n ];\n }),\n );\n const targetStorage = new MongoStorage({\n storageHash: storage.storageHash,\n namespaces,\n });\n return { ...rest, storage: targetStorage };\n }\n\n override serializeContract(contract: MongoTargetContract): JsonObject {\n const { storage, ...rest } = contract;\n const namespacesJson: Record<string, JsonObject> = {};\n for (const [nsId, ns] of Object.entries(storage.namespaces)) {\n const collectionsOut: Record<string, JsonObject> = {};\n for (const [collName, coll] of Object.entries(ns.collections)) {\n collectionsOut[collName] = JSON.parse(JSON.stringify(coll)) as JsonObject;\n }\n namespacesJson[nsId] = {\n id: ns.id,\n kind: 'mongo-database',\n collections: collectionsOut,\n };\n }\n return {\n ...rest,\n storage: {\n storageHash: String(storage.storageHash),\n namespaces: namespacesJson,\n },\n // `rest` carries Contract fields typed against framework interfaces\n // (e.g. `ContractExecutionSection`) that TypeScript can't structurally\n // prove are JSON-compatible without a per-field re-validation pass.\n // The runtime invariant is that an emitted MongoTargetContract has\n // already been through validation and contains only JSON-safe values,\n // so the two-step cast is intentional. Mirrors the pattern in\n // PostgresContractSerializer.serializeContract.\n } as unknown as JsonObject;\n }\n}\n","import {\n canonicalizeSchemasForVerification,\n contractToMongoSchemaIR,\n diffMongoSchemas,\n} from '@prisma-next/family-mongo/control';\nimport { MongoSchemaVerifierBase } from '@prisma-next/family-mongo/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { Namespace } from '@prisma-next/framework-components/ir';\nimport type { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';\nimport type { MongoTargetContract } from './mongo-target-contract';\n\n/**\n * Mongo target `SchemaVerifier` concretion. Extends the family base's\n * namespace-walk scaffolding and contributes the per-namespace diff via\n * `verifyNamespace`; the diff body reuses the existing target-side\n * helpers (`contractToMongoSchemaIR`, `canonicalizeSchemasForVerification`,\n * `diffMongoSchemas`) so production verification behaviour is unchanged.\n *\n * Today's invariant: every Mongo contract carries exactly one\n * namespace (the unbound singleton, materialised as\n * `MongoTargetUnboundDatabase`), so the family-base namespace walk\n * dispatches exactly once and the per-namespace body runs the existing\n * whole-schema diff. Future per-collection namespace assignment will\n * have this hook project the diff to the namespace's owned collections.\n *\n * `verifyTargetExtensions` returns the empty list — Mongo has no\n * target-only kinds today.\n *\n * Strict diff mode is `false` for SPI-routed calls; production\n * verification today still goes through `verifyMongoSchema` which\n * receives strict from the CLI.\n */\nexport class MongoTargetSchemaVerifier extends MongoSchemaVerifierBase<\n MongoTargetContract,\n MongoSchemaIR\n> {\n protected verifyNamespace(options: {\n readonly contract: MongoTargetContract;\n readonly schema: MongoSchemaIR;\n readonly namespaceId: string;\n readonly namespace: Namespace;\n }): readonly SchemaIssue[] {\n const expectedIR = contractToMongoSchemaIR(options.contract);\n const { live, expected } = canonicalizeSchemasForVerification(options.schema, expectedIR);\n const { issues } = diffMongoSchemas(live, expected, false);\n return issues;\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<MongoTargetContract, MongoSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n}\n","import {\n createMongoRunnerDeps,\n extractDb,\n type MongoRunnerDependencies,\n} from '@prisma-next/adapter-mongo/control';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { MongoDriverImpl } from '@prisma-next/driver-mongo';\nimport type {\n MongoControlFamilyInstance,\n MongoControlTargetDescriptor,\n} from '@prisma-next/family-mongo/control';\nimport { contractToMongoSchemaIR } from '@prisma-next/family-mongo/control';\nimport type {\n MigrationRunner,\n MigrationRunnerResult,\n MigrationRunnerSuccessValue,\n MultiSpaceCapableRunner,\n MultiSpaceRunnerFailure,\n MultiSpaceRunnerPerSpaceOptions,\n MultiSpaceRunnerResult,\n} from '@prisma-next/framework-components/control';\nimport {\n createContractSpaceMember,\n projectSchemaToSpace,\n} from '@prisma-next/migration-tools/aggregate';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type { MongoSchemaCollection } from '@prisma-next/mongo-schema-ir';\nimport { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { mongoTargetDescriptorMeta } from './descriptor-meta';\nimport { MongoMigrationPlanner } from './mongo-planner';\nimport { MongoMigrationRunner, type MongoMigrationRunnerExecuteOptions } from './mongo-runner';\nimport type { MongoTargetContract } from './mongo-target-contract';\nimport { MongoTargetContractSerializer } from './mongo-target-contract-serializer';\nimport { MongoTargetSchemaVerifier } from './mongo-target-schema-verifier';\n\nexport type { MongoControlTargetDescriptor };\n\n/**\n * `migration.ts` default-exports a `Migration` subclass whose `operations`\n * getter returns the ordered list of operations and whose `describe()`\n * returns the manifest identity metadata. `MongoMigrationPlanner.plan()`\n * returns a `MigrationPlanWithAuthoringSurface` that knows how to render\n * itself back to such a file; `MongoMigrationPlanner.emptyMigration()`\n * returns the same shape for `migration new`. Users run the scaffolded\n * `migration.ts` directly (via `node migration.ts`) to self-emit\n * `ops.json` and attest the `migrationHash`.\n */\nexport const mongoTargetDescriptor: MongoControlTargetDescriptor<MongoTargetContract> = {\n ...mongoTargetDescriptorMeta,\n contractSerializer: new MongoTargetContractSerializer(),\n schemaVerifier: new MongoTargetSchemaVerifier(),\n migrations: {\n createPlanner(_family: MongoControlFamilyInstance) {\n return new MongoMigrationPlanner();\n },\n createRunner(family: MongoControlFamilyInstance) {\n // Deps are bound to the first driver passed to execute() and cached for\n // subsequent calls. Callers must not change the driver between calls.\n let cachedDeps: MongoRunnerDependencies | undefined;\n\n const runMongo = async (\n driver: Parameters<MigrationRunner<'mongo', 'mongo'>['execute']>[0]['driver'],\n runnerOptions: Omit<MongoMigrationRunnerExecuteOptions, 'destinationContract'> & {\n readonly destinationContract: unknown;\n },\n ): Promise<MigrationRunnerResult> => {\n cachedDeps ??= createMongoRunnerDeps(\n driver,\n MongoDriverImpl.fromDb(extractDb(driver)),\n family,\n );\n // The framework `MigrationRunner` interface types `destinationContract`\n // as `unknown`; the Mongo runner narrows to `MongoContract`. Validation\n // happens upstream — `migrate` calls\n // `familyInstance.deserializeContract(contract)` on the project-root\n // contract loaded from disk before routing it here, so this cast\n // preserves the framework signature without weakening the runner's\n // typed surface.\n return new MongoMigrationRunner(cachedDeps).execute({\n ...runnerOptions,\n destinationContract: runnerOptions.destinationContract as MongoContract,\n });\n };\n\n const runner: MigrationRunner<'mongo', 'mongo'> & MultiSpaceCapableRunner<'mongo', 'mongo'> =\n {\n async execute(options) {\n const { driver, ...runnerOptions } = options;\n return runMongo(driver, runnerOptions);\n },\n // Mongo cannot wrap DDL ops in a session transaction (createCollection,\n // createIndex, collMod, setValidation all bypass transactions even on\n // replica sets), so the cross-space envelope is *resumable* rather than\n // transactional. Per-space-internal verify-gated marker atomicity\n // already lives in `runner.execute`: ops apply, schema is introspected\n // and verified, and the marker advances only on verify-pass. This loop\n // composes that guarantee across spaces — earlier-advanced markers are\n // not rolled back when a later space fails. Re-running reads each\n // marker, finds spaces 1..N−1 at-head (no-op skip), retries N onward.\n //\n // Per-space verify is sliced via `projectSchemaToSpace`: the live DB\n // holds collections owned by sibling spaces, but each space's verify\n // only sees the slice that space's contract actually claims. Without\n // the projection an aggregate of two spaces could not pass strict\n // verify (every other-space collection would look like an extra).\n //\n // See `docs/architecture docs/subsystems/10. MongoDB Family.md` §\n // Contract spaces and ADR 212 — Contract spaces.\n async executeAcrossSpaces({ driver, perSpaceOptions }): Promise<MultiSpaceRunnerResult> {\n const members = perSpaceOptions.map(toSpaceMember);\n const perSpaceResults: Array<{\n space: string;\n value: MigrationRunnerSuccessValue;\n }> = [];\n for (let i = 0; i < perSpaceOptions.length; i++) {\n const spaceOptions = perSpaceOptions[i];\n if (!spaceOptions) continue;\n const member = members[i];\n if (!member) continue;\n const others = members.filter((_, j) => j !== i);\n const projectSchema = (schema: MongoSchemaIR): MongoSchemaIR => {\n // `projectSchemaToSpace` returns a plain object\n // `{...schemaIR, collections: prunedArray}` (not a\n // `MongoSchemaIR` instance), so the descriptor rewraps\n // the pruned collections into a fresh `MongoSchemaIR`\n // before handing it to `verifyMongoSchema` (which\n // depends on the class's `collectionNames` /\n // `collection(name)` accessors).\n const projected = projectSchemaToSpace(schema, member, others) as {\n readonly collections: ReadonlyArray<MongoSchemaCollection>;\n };\n return new MongoSchemaIR(projected.collections);\n };\n const result = await runMongo(driver, { ...spaceOptions, projectSchema });\n if (!result.ok) {\n return notOk<MultiSpaceRunnerFailure>({\n ...result.failure,\n failingSpace: spaceOptions.space,\n });\n }\n perSpaceResults.push({ space: spaceOptions.space, value: result.value });\n }\n return ok({ perSpaceResults });\n },\n };\n return runner;\n },\n contractToSchema(contract: Contract | null) {\n return contractToMongoSchemaIR(contract as MongoContract | null);\n },\n },\n create() {\n return { familyId: 'mongo' as const, targetId: 'mongo' as const };\n },\n};\n\n/**\n * Synthesise a {@link projectSchemaToSpace}-compatible member from a\n * per-space option entry. The projector only reads `spaceId` and\n * `contract()`; migration graph state is empty because the runner\n * consumes the destination contract directly.\n */\nfunction toSpaceMember(opts: MultiSpaceRunnerPerSpaceOptions<'mongo', 'mongo'>) {\n return createContractSpaceMember({\n spaceId: opts.space,\n packages: [],\n refs: {},\n headRef: null,\n resolveContract: () =>\n blindCast<Contract, 'destinationContract validated at aggregate boundary'>(\n opts.destinationContract,\n ),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,0BAA0B;AAEhC,IAAe,oBAAf,cAAyC,aAA+C;CAMtF,qBAAmD;EACjD,OAAO,CAAC;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;EAAY,CAAC;CAChF;CAEA,SAAyB;EACvB,OAAO,OAAO,IAAI;CACpB;AACF;AAEA,SAAS,WAAW,MAA4C;CAC9D,OAAO,KAAK,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,EAAE,WAAW,EAAE,KAAK,IAAI;AAC/D;AAEA,IAAa,kBAAb,cAAqC,kBAAkB;CACrD,cAAuB;CACvB,iBAA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AwB,QAAgC;EACjE;CACF;CACA,SAAS;EACP,OAAO;GAAE,UAAU;GAAkB,UAAU;EAAiB;CAClE;AACF;;;;;;;AAQA,SAAS,cAAc,MAAyD;CAC9E,OAAO,0BAA0B;EAC/B,SAAS,KAAK;EACd,UAAU,CAAC;EACX,MAAM,CAAC;EACP,SAAS;EACT,uBACE,UACE,KAAK,mBACP;CACJ,CAAC;AACH"}
1
+ {"version":3,"file":"control.mjs","names":["record"],"sources":["../src/core/op-factory-call.ts","../src/core/render-ops.ts","../src/core/render-typescript.ts","../src/core/planner-produced-migration.ts","../src/core/mongo-planner.ts","../src/core/filter-evaluator.ts","../src/core/mongo-ops-serializer.ts","../src/core/mongo-runner.ts","../src/core/mongo-target-database.ts","../src/core/mongo-target-contract-serializer.ts","../src/core/mongo-target-schema-verifier.ts","../src/core/control-target.ts"],"sourcesContent":["/**\n * Mongo migration IR: one concrete `*Call` class per pure factory under\n * `migration-factories.ts`, plus a shared `OpFactoryCallNode` abstract\n * base. Every call class carries the literal arguments its backing\n * factory would receive, computes a human-readable `label` in its\n * constructor, and implements two polymorphic hooks:\n *\n * - `toOp()` — converts the IR node to a runtime\n * `MongoMigrationPlanOperation` by delegating to the matching pure\n * factory in `migration-factories.ts`.\n * - `renderTypeScript()` / `importRequirements()` — inherited from\n * `TsExpression`. Used by `renderCallsToTypeScript` to emit the call\n * as a TypeScript expression inside the scaffolded `migration.ts`.\n *\n * The abstract base and all concrete classes are package-private.\n * External consumers see only the framework-level `OpFactoryCall`\n * interface and the `OpFactoryCall` union.\n */\n\nimport type {\n OpFactoryCall as FrameworkOpFactoryCall,\n MigrationOperationClass,\n} from '@prisma-next/framework-components/control';\nimport type {\n CollModOptions,\n CreateCollectionOptions,\n CreateIndexOptions,\n MongoIndexKey,\n MongoMigrationPlanOperation,\n} from '@prisma-next/mongo-query-ast/control';\nimport type {\n MongoSchemaCollection,\n MongoSchemaCollectionOptions,\n MongoSchemaIndex,\n MongoSchemaValidator,\n} from '@prisma-next/mongo-schema-ir';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport {\n collMod,\n createCollection,\n createIndex,\n dropCollection,\n dropIndex,\n} from './migration-factories';\n\nexport interface CollModMeta {\n readonly id?: string;\n readonly label?: string;\n readonly operationClass?: MigrationOperationClass;\n}\n\nconst TARGET_MIGRATION_MODULE = '@prisma-next/target-mongo/migration';\n\nabstract class OpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n abstract readonly factoryName: string;\n abstract readonly operationClass: MigrationOperationClass;\n abstract readonly label: string;\n abstract toOp(): MongoMigrationPlanOperation;\n\n importRequirements(): readonly ImportRequirement[] {\n return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];\n }\n\n protected freeze(): void {\n Object.freeze(this);\n }\n}\n\nfunction formatKeys(keys: ReadonlyArray<MongoIndexKey>): string {\n return keys.map((k) => `${k.field}:${k.direction}`).join(', ');\n}\n\nexport class CreateIndexCall extends OpFactoryCallNode {\n readonly factoryName = 'createIndex' as const;\n readonly operationClass = 'additive' as const;\n readonly collection: string;\n readonly keys: ReadonlyArray<MongoIndexKey>;\n readonly options: CreateIndexOptions | undefined;\n readonly label: string;\n\n constructor(\n collection: string,\n keys: ReadonlyArray<MongoIndexKey>,\n options?: CreateIndexOptions,\n ) {\n super();\n this.collection = collection;\n this.keys = keys;\n this.options = options;\n this.label = `Create index on ${collection} (${formatKeys(keys)})`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return createIndex(this.collection, this.keys, this.options);\n }\n\n renderTypeScript(): string {\n return this.options\n ? `createIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)}, ${jsonToTsSource(this.options)})`\n : `createIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)})`;\n }\n}\n\nexport class DropIndexCall extends OpFactoryCallNode {\n readonly factoryName = 'dropIndex' as const;\n readonly operationClass = 'destructive' as const;\n readonly collection: string;\n readonly keys: ReadonlyArray<MongoIndexKey>;\n readonly label: string;\n\n constructor(collection: string, keys: ReadonlyArray<MongoIndexKey>) {\n super();\n this.collection = collection;\n this.keys = keys;\n this.label = `Drop index on ${collection} (${formatKeys(keys)})`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return dropIndex(this.collection, this.keys);\n }\n\n renderTypeScript(): string {\n return `dropIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)})`;\n }\n}\n\nexport class CreateCollectionCall extends OpFactoryCallNode {\n readonly factoryName = 'createCollection' as const;\n readonly operationClass = 'additive' as const;\n readonly collection: string;\n readonly options: CreateCollectionOptions | undefined;\n readonly label: string;\n\n constructor(collection: string, options?: CreateCollectionOptions) {\n super();\n this.collection = collection;\n this.options = options;\n this.label = `Create collection ${collection}`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return createCollection(this.collection, this.options);\n }\n\n renderTypeScript(): string {\n return this.options\n ? `createCollection(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)})`\n : `createCollection(${jsonToTsSource(this.collection)})`;\n }\n}\n\nexport class DropCollectionCall extends OpFactoryCallNode {\n readonly factoryName = 'dropCollection' as const;\n readonly operationClass = 'destructive' as const;\n readonly collection: string;\n readonly label: string;\n\n constructor(collection: string) {\n super();\n this.collection = collection;\n this.label = `Drop collection ${collection}`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return dropCollection(this.collection);\n }\n\n renderTypeScript(): string {\n return `dropCollection(${jsonToTsSource(this.collection)})`;\n }\n}\n\nexport class CollModCall extends OpFactoryCallNode {\n readonly factoryName = 'collMod' as const;\n readonly collection: string;\n readonly options: CollModOptions;\n readonly meta: CollModMeta | undefined;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n\n constructor(collection: string, options: CollModOptions, meta?: CollModMeta) {\n super();\n this.collection = collection;\n this.options = options;\n this.meta = meta;\n this.operationClass = meta?.operationClass ?? 'destructive';\n this.label = meta?.label ?? `Modify collection ${collection}`;\n this.freeze();\n }\n\n toOp(): MongoMigrationPlanOperation {\n return collMod(this.collection, this.options, this.meta);\n }\n\n renderTypeScript(): string {\n return this.meta\n ? `collMod(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)}, ${jsonToTsSource(this.meta)})`\n : `collMod(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)})`;\n }\n}\n\nexport type OpFactoryCall =\n | CreateIndexCall\n | DropIndexCall\n | CreateCollectionCall\n | DropCollectionCall\n | CollModCall;\n\nexport function schemaIndexToCreateIndexOptions(index: MongoSchemaIndex): CreateIndexOptions {\n return {\n unique: index.unique || undefined,\n sparse: index.sparse,\n expireAfterSeconds: index.expireAfterSeconds,\n partialFilterExpression: index.partialFilterExpression,\n wildcardProjection: index.wildcardProjection,\n collation: index.collation,\n weights: index.weights,\n default_language: index.default_language,\n language_override: index.language_override,\n };\n}\n\nexport function schemaCollectionToCreateCollectionOptions(\n coll: MongoSchemaCollection,\n): CreateCollectionOptions | undefined {\n const opts: MongoSchemaCollectionOptions | undefined = coll.options;\n const validator: MongoSchemaValidator | undefined = coll.validator;\n if (!opts && !validator) return undefined;\n return {\n capped: opts?.capped ? true : undefined,\n size: opts?.capped?.size,\n max: opts?.capped?.max,\n timeseries: opts?.timeseries,\n collation: opts?.collation,\n clusteredIndex: opts?.clusteredIndex\n ? {\n key: { _id: 1 } as Record<string, number>,\n unique: true as boolean,\n ...(opts.clusteredIndex.name != null ? { name: opts.clusteredIndex.name } : {}),\n }\n : undefined,\n validator: validator ? { $jsonSchema: validator.jsonSchema } : undefined,\n validationLevel: validator?.validationLevel,\n validationAction: validator?.validationAction,\n changeStreamPreAndPostImages: opts?.changeStreamPreAndPostImages,\n };\n}\n","import type { MongoMigrationPlanOperation } from '@prisma-next/mongo-query-ast/control';\nimport type { OpFactoryCall } from './op-factory-call';\n\nexport function renderOps(calls: ReadonlyArray<OpFactoryCall>): MongoMigrationPlanOperation[] {\n return calls.map((call) => call.toOp());\n}\n","import { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';\nimport { type ImportRequirement, renderImports } from '@prisma-next/ts-render';\nimport type { OpFactoryCall } from './op-factory-call';\n\nexport interface RenderMigrationMeta {\n readonly from: string | null;\n readonly to: string;\n}\n\n/**\n * Always-present base imports for the rendered scaffold:\n *\n * - `Migration` from `@prisma-next/family-mongo/migration` — the\n * user-facing Mongo `Migration` base; subclasses don't need to\n * redeclare `targetId` or thread family/target generics.\n * - `MigrationCLI` from `@prisma-next/cli/migration-cli` — the\n * migration-file CLI entrypoint that loads `prisma-next.config.ts`,\n * assembles a `ControlStack`, and instantiates the migration class.\n * The migration file owns this dependency directly: pulling CLI\n * machinery in at script run time is acceptable because the script's\n * whole purpose is to be invoked from the project that owns the\n * config. (Mirrors the postgres facade pattern; pulling `MigrationCLI`\n * into `@prisma-next/family-mongo/migration` so a Mongo migration only\n * needs one import is tracked separately as a follow-up.)\n */\nconst BASE_IMPORTS: readonly ImportRequirement[] = [\n { moduleSpecifier: '@prisma-next/family-mongo/migration', symbol: 'Migration' },\n { moduleSpecifier: '@prisma-next/cli/migration-cli', symbol: 'MigrationCLI' },\n];\n\n/**\n * Render a list of Mongo `OpFactoryCall`s as a `migration.ts`\n * source string. The result is shebanged, extends the user-facing\n * `Migration` (i.e. `MongoMigration`) from `@prisma-next/family-mongo`, and\n * implements the abstract `operations` and `describe` members. `meta` is\n * always rendered — `describe()` is part of the `Migration` contract, so\n * even an empty stub must satisfy it; callers pass `from: null` for a\n * baseline `migration-new` scaffold (and a real `to` hash either way).\n *\n * The walk is polymorphic: each call node contributes its own\n * `renderTypeScript()` expression and declares its own\n * `importRequirements()`. The top-level renderer aggregates imports\n * across all nodes and emits one `import { … } from \"…\"` line per module.\n * The `Migration` and `MigrationCLI` imports are always emitted — they're\n * structural to the rendered scaffold (extends `Migration`, calls\n * `MigrationCLI.run`), not driven by any node.\n */\nexport function renderCallsToTypeScript(\n calls: ReadonlyArray<OpFactoryCall>,\n meta: RenderMigrationMeta,\n): string {\n const imports = buildImports(calls);\n const operationsBody = calls.map((c) => c.renderTypeScript()).join(',\\n');\n\n return [\n shebangLineFor(detectScaffoldRuntime()),\n imports,\n '',\n 'class M extends Migration {',\n buildDescribeMethod(meta),\n ' override get operations() {',\n ' return [',\n indent(operationsBody, 6),\n ' ];',\n ' }',\n '}',\n '',\n 'export default M;',\n 'MigrationCLI.run(import.meta.url, M);',\n '',\n ].join('\\n');\n}\n\nfunction buildImports(calls: ReadonlyArray<OpFactoryCall>): string {\n const requirements: ImportRequirement[] = [...BASE_IMPORTS];\n for (const call of calls) {\n for (const req of call.importRequirements()) {\n requirements.push(req);\n }\n }\n return renderImports(requirements);\n}\n\nfunction buildDescribeMethod(meta: RenderMigrationMeta): string {\n const lines: string[] = [];\n lines.push(' override describe() {');\n lines.push(' return {');\n lines.push(` from: ${JSON.stringify(meta.from)},`);\n lines.push(` to: ${JSON.stringify(meta.to)},`);\n lines.push(' };');\n lines.push(' }');\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction indent(text: string, spaces: number): string {\n const pad = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${pad}${line}` : line))\n .join('\\n');\n}\n","import type { MigrationPlanWithAuthoringSurface } from '@prisma-next/framework-components/control';\nimport { Migration, type MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { AnyMongoMigrationOperation } from '@prisma-next/mongo-query-ast/control';\nimport type { OpFactoryCall } from './op-factory-call';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\n\n/**\n * Planner-produced Mongo migration, returned by `MongoMigrationPlanner.plan(...)`\n * and `MongoMigrationPlanner.emptyMigration(...)`.\n *\n * Unlike user-authored migrations (which extend `MongoMigration` from\n * `@prisma-next/family-mongo/migration`), this class lives inside the target\n * and holds the richer authoring IR (`OpFactoryCall[]`) needed to render\n * itself back to TypeScript source. It implements\n * `MigrationPlanWithAuthoringSurface` so that the CLI can uniformly ask any\n * planner result to serialize itself to a `migration.ts`.\n *\n * Extends the framework `Migration` base class directly (not\n * `MongoMigration`) because `MongoMigration` lives in `@prisma-next/family-mongo`,\n * which depends on this package — extending it here would create a dependency\n * cycle.\n */\nexport class PlannerProducedMongoMigration\n extends Migration<AnyMongoMigrationOperation>\n implements MigrationPlanWithAuthoringSurface\n{\n readonly targetId = 'mongo' as const;\n\n constructor(\n private readonly calls: readonly OpFactoryCall[],\n private readonly meta: MigrationMeta,\n ) {\n super();\n }\n\n override get operations(): readonly AnyMongoMigrationOperation[] {\n return renderOps(this.calls);\n }\n\n override describe(): MigrationMeta {\n return this.meta;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.calls, {\n from: this.meta.from,\n to: this.meta.to,\n });\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { contractToMongoSchemaIR } from '@prisma-next/family-mongo/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationOperationClass,\n MigrationOperationPolicy,\n MigrationPlanner,\n MigrationPlannerConflict,\n MigrationPlannerResult,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n} from '@prisma-next/framework-components/control';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type {\n MongoSchemaCollection,\n MongoSchemaCollectionOptions,\n MongoSchemaIndex,\n MongoSchemaIR,\n MongoSchemaValidator,\n} from '@prisma-next/mongo-schema-ir';\nimport { canonicalize, deepEqual } from '@prisma-next/mongo-schema-ir';\nimport type { OpFactoryCall } from './op-factory-call';\nimport {\n CollModCall,\n CreateCollectionCall,\n CreateIndexCall,\n DropCollectionCall,\n DropIndexCall,\n schemaCollectionToCreateCollectionOptions,\n schemaIndexToCreateIndexOptions,\n} from './op-factory-call';\nimport { PlannerProducedMongoMigration } from './planner-produced-migration';\n\nfunction buildIndexLookupKey(index: MongoSchemaIndex): string {\n const keys = index.keys.map((k) => `${k.field}:${k.direction}`).join(',');\n const opts = [\n index.unique ? 'unique' : '',\n index.sparse ? 'sparse' : '',\n index.expireAfterSeconds != null ? `ttl:${index.expireAfterSeconds}` : '',\n index.partialFilterExpression ? `pfe:${canonicalize(index.partialFilterExpression)}` : '',\n index.wildcardProjection ? `wp:${canonicalize(index.wildcardProjection)}` : '',\n index.collation ? `col:${canonicalize(index.collation)}` : '',\n index.weights ? `wt:${canonicalize(index.weights)}` : '',\n index.default_language ? `dl:${index.default_language}` : '',\n index.language_override ? `lo:${index.language_override}` : '',\n ]\n .filter(Boolean)\n .join(';');\n return opts ? `${keys}|${opts}` : keys;\n}\n\nfunction validatorsEqual(\n a: MongoSchemaValidator | undefined,\n b: MongoSchemaValidator | undefined,\n): boolean {\n if (!a && !b) return true;\n if (!a || !b) return false;\n return (\n a.validationLevel === b.validationLevel &&\n a.validationAction === b.validationAction &&\n canonicalize(a.jsonSchema) === canonicalize(b.jsonSchema)\n );\n}\n\nfunction classifyValidatorUpdate(\n origin: MongoSchemaValidator,\n dest: MongoSchemaValidator,\n): 'widening' | 'destructive' {\n // Moving to a stricter action or level narrows the accepted value space.\n if (origin.validationAction !== dest.validationAction && dest.validationAction === 'error') {\n return 'destructive';\n }\n if (origin.validationLevel !== dest.validationLevel && dest.validationLevel === 'strict') {\n return 'destructive';\n }\n\n if (canonicalize(origin.jsonSchema) === canonicalize(dest.jsonSchema)) {\n return 'widening';\n }\n\n // Check whether the schema change only adds non-required properties (widening).\n return isWideningSchemaChange(origin.jsonSchema, dest.jsonSchema) ? 'widening' : 'destructive';\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/**\n * Returns true when `dest` is a structural superset of `origin` for the common\n * additive case: adding non-required properties to a top-level object schema.\n * Anything uncertain falls through to the safe `destructive` default.\n */\nfunction isWideningSchemaChange(\n origin: Record<string, unknown>,\n dest: Record<string, unknown>,\n): boolean {\n // Only handle top-level object schemas.\n if (origin['bsonType'] !== 'object' || dest['bsonType'] !== 'object') {\n return false;\n }\n\n // Any change to keys besides 'required' and 'properties' is uncertain → destructive.\n const allKeys = new Set([...Object.keys(origin), ...Object.keys(dest)]);\n for (const key of allKeys) {\n if (key === 'required' || key === 'properties') continue;\n if (canonicalize(origin[key]) !== canonicalize(dest[key])) return false;\n }\n\n // dest.required must be a subset of origin.required — no new required fields.\n const originRequired = new Set<unknown>(\n Array.isArray(origin['required']) ? origin['required'] : [],\n );\n const destRequired = Array.isArray(dest['required']) ? dest['required'] : [];\n for (const field of destRequired) {\n if (!originRequired.has(field)) return false;\n }\n\n // All properties that existed in origin must still exist unchanged.\n // New properties in dest (absent from origin) are allowed — widening.\n const originProps = isPlainObject(origin['properties']) ? origin['properties'] : {};\n const destProps = isPlainObject(dest['properties']) ? dest['properties'] : {};\n for (const field of Object.keys(originProps)) {\n if (!Object.hasOwn(destProps, field)) return false; // Property removed → destructive.\n if (canonicalize(originProps[field]) !== canonicalize(destProps[field])) return false; // Property narrowed → destructive.\n }\n\n return true;\n}\n\nfunction hasImmutableOptionChange(\n origin: MongoSchemaCollectionOptions | undefined,\n dest: MongoSchemaCollectionOptions | undefined,\n): string | undefined {\n if (canonicalize(origin?.capped) !== canonicalize(dest?.capped)) return 'capped';\n if (canonicalize(origin?.timeseries) !== canonicalize(dest?.timeseries)) return 'timeseries';\n if (canonicalize(origin?.collation) !== canonicalize(dest?.collation)) return 'collation';\n if (canonicalize(origin?.clusteredIndex) !== canonicalize(dest?.clusteredIndex))\n return 'clusteredIndex';\n return undefined;\n}\n\nfunction collectionHasOptions(coll: MongoSchemaCollection): boolean {\n return !!(coll.options || coll.validator);\n}\n\nexport type PlanCallsResult =\n | { readonly kind: 'success'; readonly calls: OpFactoryCall[] }\n | { readonly kind: 'failure'; readonly conflicts: MigrationPlannerConflict[] };\n\nexport class MongoMigrationPlanner implements MigrationPlanner<'mongo', 'mongo'> {\n planCalls(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n }): PlanCallsResult {\n const contract = options.contract as MongoContract;\n const originIR = options.schema as MongoSchemaIR;\n const destinationIR = contractToMongoSchemaIR(contract);\n\n const collCreates: OpFactoryCall[] = [];\n const drops: OpFactoryCall[] = [];\n const creates: OpFactoryCall[] = [];\n const validatorOps: OpFactoryCall[] = [];\n const mutableOptionOps: OpFactoryCall[] = [];\n const collDrops: OpFactoryCall[] = [];\n const conflicts: MigrationPlannerConflict[] = [];\n\n const allCollectionNames = new Set([\n ...originIR.collectionNames,\n ...destinationIR.collectionNames,\n ]);\n\n for (const collName of [...allCollectionNames].sort()) {\n const originColl = originIR.collection(collName);\n const destColl = destinationIR.collection(collName);\n\n if (!originColl) {\n // Provision contract-declared collections that are absent from\n // the live database. MongoDB lazily materialises a collection\n // on first write, so subsequent `createIndex` calls in the same\n // plan would create the collection for us implicitly — but the\n // schema verifier treats an unmaterialised contract collection\n // as a `missing_table` issue, so a plan that lacks both options\n // and indexes (e.g. a plain `users` collection from the init\n // scaffold) ends up provisioning nothing and failing verify.\n // The planner therefore emits an explicit createCollection for\n // any contract collection that has options/validator OR no\n // indexes to ride along on. Collections that have indexes\n // continue to rely on createIndex for materialisation, keeping\n // existing plans byte-stable.\n if (destColl && (collectionHasOptions(destColl) || destColl.indexes.length === 0)) {\n const opts = collectionHasOptions(destColl)\n ? schemaCollectionToCreateCollectionOptions(destColl)\n : undefined;\n collCreates.push(new CreateCollectionCall(collName, opts));\n }\n } else if (!destColl) {\n collDrops.push(new DropCollectionCall(collName));\n } else {\n const immutableChange = hasImmutableOptionChange(originColl.options, destColl.options);\n if (immutableChange) {\n conflicts.push({\n kind: 'policy-violation',\n summary: `Cannot change immutable collection option '${immutableChange}' on ${collName}`,\n why: `MongoDB does not support modifying the '${immutableChange}' option after collection creation`,\n });\n }\n\n const mutableCall = planMutableOptionsDiffCall(\n collName,\n originColl.options,\n destColl.options,\n );\n if (mutableCall) mutableOptionOps.push(mutableCall);\n\n const validatorCall = planValidatorDiffCall(\n collName,\n originColl.validator,\n destColl.validator,\n );\n if (validatorCall) validatorOps.push(validatorCall);\n }\n\n const originLookup = new Map<string, MongoSchemaIndex>();\n if (originColl) {\n for (const idx of originColl.indexes) {\n originLookup.set(buildIndexLookupKey(idx), idx);\n }\n }\n\n const destLookup = new Map<string, MongoSchemaIndex>();\n if (destColl) {\n for (const idx of destColl.indexes) {\n destLookup.set(buildIndexLookupKey(idx), idx);\n }\n }\n\n for (const [lookupKey, idx] of originLookup) {\n if (!destLookup.has(lookupKey)) {\n drops.push(new DropIndexCall(collName, idx.keys));\n }\n }\n\n for (const [lookupKey, idx] of destLookup) {\n if (!originLookup.has(lookupKey)) {\n creates.push(\n new CreateIndexCall(collName, idx.keys, schemaIndexToCreateIndexOptions(idx)),\n );\n }\n }\n }\n\n if (conflicts.length > 0) {\n return { kind: 'failure', conflicts };\n }\n\n const allCalls = [\n ...collCreates,\n ...drops,\n ...creates,\n ...validatorOps,\n ...mutableOptionOps,\n ...collDrops,\n ];\n\n for (const call of allCalls) {\n if (!options.policy.allowedOperationClasses.includes(call.operationClass)) {\n conflicts.push({\n kind: 'policy-violation',\n summary: `${call.operationClass} operation disallowed: ${call.label}`,\n why: `Policy does not allow '${call.operationClass}' operations`,\n });\n }\n }\n\n if (conflicts.length > 0) {\n return { kind: 'failure', conflicts };\n }\n\n return { kind: 'success', calls: allCalls };\n }\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts at),\n * or `null` for reconciliation flows. Used to populate `describe().from`\n * on the produced plan as `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n }): MigrationPlannerResult {\n const contract = options.contract as MongoContract;\n const result = this.planCalls(options);\n if (result.kind === 'failure') return result;\n return {\n kind: 'success',\n plan: new PlannerProducedMongoMigration(result.calls, {\n from: options.fromContract?.storage.storageHash ?? null,\n to: contract.storage.storageHash,\n }),\n };\n }\n\n /**\n * Produce an empty `migration.ts` authoring surface for `migration new`.\n *\n * The \"empty migration\" is a `PlannerProducedMongoMigration` with no\n * operations; `renderTypeScript()` emits a stub class with the correct\n * `from`/`to` metadata that the user then fills in with operations. The\n * contract path on the context is unused — Mongo's emitted source does\n * not import from the generated contract `.d.ts`.\n */\n emptyMigration(context: MigrationScaffoldContext): MigrationPlanWithAuthoringSurface {\n return new PlannerProducedMongoMigration([], {\n from: context.fromHash,\n to: context.toHash,\n });\n }\n}\n\nfunction planValidatorDiffCall(\n collName: string,\n originValidator: MongoSchemaValidator | undefined,\n destValidator: MongoSchemaValidator | undefined,\n): OpFactoryCall | undefined {\n if (validatorsEqual(originValidator, destValidator)) return undefined;\n\n if (destValidator) {\n const operationClass: MigrationOperationClass = originValidator\n ? classifyValidatorUpdate(originValidator, destValidator)\n : 'destructive';\n return new CollModCall(\n collName,\n {\n validator: { $jsonSchema: destValidator.jsonSchema },\n validationLevel: destValidator.validationLevel,\n validationAction: destValidator.validationAction,\n },\n {\n id: `validator.${collName}.${originValidator ? 'update' : 'add'}`,\n label: `${originValidator ? 'Update' : 'Add'} validator on ${collName}`,\n operationClass,\n },\n );\n }\n\n return new CollModCall(\n collName,\n {\n validator: {},\n validationLevel: 'strict',\n validationAction: 'error',\n },\n {\n id: `validator.${collName}.remove`,\n label: `Remove validator on ${collName}`,\n operationClass: 'widening',\n },\n );\n}\n\nfunction planMutableOptionsDiffCall(\n collName: string,\n origin: MongoSchemaCollectionOptions | undefined,\n dest: MongoSchemaCollectionOptions | undefined,\n): OpFactoryCall | undefined {\n const originCSPPI = origin?.changeStreamPreAndPostImages;\n const destCSPPI = dest?.changeStreamPreAndPostImages;\n if (deepEqual(originCSPPI, destCSPPI)) return undefined;\n\n const desiredCSPPI = destCSPPI ?? { enabled: false };\n return new CollModCall(\n collName,\n {\n changeStreamPreAndPostImages: desiredCSPPI,\n },\n {\n id: `options.${collName}.update`,\n label: `Update mutable options on ${collName}`,\n operationClass: desiredCSPPI.enabled ? 'widening' : 'destructive',\n },\n );\n}\n","import type {\n MongoAndExpr,\n MongoExistsExpr,\n MongoExprFilter,\n MongoFieldFilter,\n MongoFilterExpr,\n MongoFilterVisitor,\n MongoNotExpr,\n MongoOrExpr,\n} from '@prisma-next/mongo-query-ast/control';\nimport { deepEqual } from '@prisma-next/mongo-schema-ir';\nimport type { MongoValue } from '@prisma-next/mongo-value';\n\nfunction getNestedField(doc: Record<string, unknown>, path: string): unknown {\n const parts = path.split('.');\n let current: unknown = doc;\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== 'object') {\n return undefined;\n }\n const record = current as Record<string, unknown>;\n if (!Object.hasOwn(record, part)) {\n return undefined;\n }\n current = record[part];\n }\n return current;\n}\n\nfunction evaluateFieldOp(op: string, actual: unknown, expected: MongoValue): boolean {\n switch (op) {\n case '$eq':\n return deepEqual(actual, expected);\n case '$ne':\n return !deepEqual(actual, expected);\n case '$gt':\n return typeof actual === typeof expected && (actual as number) > (expected as number);\n case '$gte':\n return typeof actual === typeof expected && (actual as number) >= (expected as number);\n case '$lt':\n return typeof actual === typeof expected && (actual as number) < (expected as number);\n case '$lte':\n return typeof actual === typeof expected && (actual as number) <= (expected as number);\n case '$in':\n return Array.isArray(expected) && expected.some((v) => deepEqual(actual, v));\n default:\n throw new Error(`Unsupported filter operator in migration check: ${op}`);\n }\n}\n\nexport class FilterEvaluator implements MongoFilterVisitor<boolean> {\n private doc: Record<string, unknown> = {};\n\n evaluate(filter: MongoFilterExpr, doc: Record<string, unknown>): boolean {\n this.doc = doc;\n return filter.accept(this);\n }\n\n field(expr: MongoFieldFilter): boolean {\n const value = getNestedField(this.doc, expr.field);\n return evaluateFieldOp(expr.op, value, expr.value);\n }\n\n and(expr: MongoAndExpr): boolean {\n return expr.exprs.every((child) => child.accept(this));\n }\n\n or(expr: MongoOrExpr): boolean {\n return expr.exprs.some((child) => child.accept(this));\n }\n\n not(expr: MongoNotExpr): boolean {\n return !expr.expr.accept(this);\n }\n\n exists(expr: MongoExistsExpr): boolean {\n const has = getNestedField(this.doc, expr.field) !== undefined;\n return expr.exists ? has : !has;\n }\n\n expr(_expr: MongoExprFilter): boolean {\n throw new Error('Aggregation expression filters are not supported in migration checks');\n }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { MigrationOperationClass } from '@prisma-next/framework-components/control';\nimport {\n type AnyMongoDdlCommand,\n type AnyMongoInspectionCommand,\n type AnyMongoMigrationOperation,\n CollModCommand,\n CreateCollectionCommand,\n CreateIndexCommand,\n DropCollectionCommand,\n DropIndexCommand,\n ListCollectionsCommand,\n ListIndexesCommand,\n MongoAndExpr,\n type MongoDataTransformCheck,\n type MongoDataTransformOperation,\n MongoExistsExpr,\n MongoFieldFilter,\n type MongoFilterExpr,\n type MongoMigrationCheck,\n type MongoMigrationPlanOperation,\n type MongoMigrationStep,\n MongoNotExpr,\n MongoOrExpr,\n} from '@prisma-next/mongo-query-ast/control';\nimport {\n AggregateCommand,\n type AnyMongoCommand,\n MongoAddFieldsStage,\n MongoLimitStage,\n MongoLookupStage,\n MongoMatchStage,\n MongoMergeStage,\n type MongoPipelineStage,\n MongoProjectStage,\n type MongoQueryPlan,\n MongoSortStage,\n type MongoUpdatePipelineStage,\n RawAggregateCommand,\n RawDeleteManyCommand,\n RawDeleteOneCommand,\n RawFindOneAndDeleteCommand,\n RawFindOneAndUpdateCommand,\n RawInsertManyCommand,\n RawInsertOneCommand,\n RawUpdateManyCommand,\n RawUpdateOneCommand,\n} from '@prisma-next/mongo-query-ast/execution';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type } from 'arktype';\n\nconst IndexKeyDirection = type('1 | -1 | \"text\" | \"2dsphere\" | \"2d\" | \"hashed\"');\nconst IndexKeyJson = type({ field: 'string', direction: IndexKeyDirection });\n\nconst CreateIndexJson = type({\n kind: '\"createIndex\"',\n collection: 'string',\n keys: IndexKeyJson.array().atLeastLength(1),\n 'unique?': 'boolean',\n 'sparse?': 'boolean',\n 'expireAfterSeconds?': 'number',\n 'partialFilterExpression?': 'Record<string, unknown>',\n 'name?': 'string',\n 'wildcardProjection?': 'Record<string, unknown>',\n 'collation?': 'Record<string, unknown>',\n 'weights?': 'Record<string, unknown>',\n 'default_language?': 'string',\n 'language_override?': 'string',\n});\n\nconst DropIndexJson = type({\n kind: '\"dropIndex\"',\n collection: 'string',\n name: 'string',\n});\n\nconst CreateCollectionJson = type({\n kind: '\"createCollection\"',\n collection: 'string',\n 'validator?': 'Record<string, unknown>',\n 'validationLevel?': '\"strict\" | \"moderate\"',\n 'validationAction?': '\"error\" | \"warn\"',\n 'capped?': 'boolean',\n 'size?': 'number',\n 'max?': 'number',\n 'timeseries?': 'Record<string, unknown>',\n 'collation?': 'Record<string, unknown>',\n 'changeStreamPreAndPostImages?': 'Record<string, unknown>',\n 'clusteredIndex?': 'Record<string, unknown>',\n});\n\nconst DropCollectionJson = type({\n kind: '\"dropCollection\"',\n collection: 'string',\n});\n\nconst CollModJson = type({\n kind: '\"collMod\"',\n collection: 'string',\n 'validator?': 'Record<string, unknown>',\n 'validationLevel?': '\"strict\" | \"moderate\"',\n 'validationAction?': '\"error\" | \"warn\"',\n 'changeStreamPreAndPostImages?': 'Record<string, unknown>',\n});\n\nconst ListIndexesJson = type({\n kind: '\"listIndexes\"',\n collection: 'string',\n});\n\nconst ListCollectionsJson = type({\n kind: '\"listCollections\"',\n});\n\nconst FieldFilterJson = type({\n kind: '\"field\"',\n field: 'string',\n op: 'string',\n value: 'unknown',\n});\n\nconst ExistsFilterJson = type({\n kind: '\"exists\"',\n field: 'string',\n exists: 'boolean',\n});\n\n// ============================================================================\n// DML command schemas\n// ============================================================================\n\nconst RawInsertOneJson = type({\n kind: '\"rawInsertOne\"',\n collection: 'string',\n document: 'Record<string, unknown>',\n});\n\nconst RawInsertManyJson = type({\n kind: '\"rawInsertMany\"',\n collection: 'string',\n documents: 'Record<string, unknown>[]',\n});\n\nconst RawUpdateOneJson = type({\n kind: '\"rawUpdateOne\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n update: 'Record<string, unknown> | Record<string, unknown>[]',\n});\n\nconst RawUpdateManyJson = type({\n kind: '\"rawUpdateMany\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n update: 'Record<string, unknown> | Record<string, unknown>[]',\n});\n\nconst RawDeleteOneJson = type({\n kind: '\"rawDeleteOne\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n});\n\nconst RawDeleteManyJson = type({\n kind: '\"rawDeleteMany\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n});\n\nconst RawAggregateJson = type({\n kind: '\"rawAggregate\"',\n collection: 'string',\n pipeline: 'Record<string, unknown>[]',\n});\n\nconst RawFindOneAndUpdateJson = type({\n kind: '\"rawFindOneAndUpdate\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n update: 'Record<string, unknown> | Record<string, unknown>[]',\n upsert: 'boolean',\n});\n\nconst RawFindOneAndDeleteJson = type({\n kind: '\"rawFindOneAndDelete\"',\n collection: 'string',\n filter: 'Record<string, unknown>',\n});\n\nconst TypedAggregateJson = type({\n kind: '\"aggregate\"',\n collection: 'string',\n pipeline: 'Record<string, unknown>[]',\n});\n\nconst PlanMetaJson = type({\n target: 'string',\n storageHash: 'string',\n lane: 'string',\n 'targetFamily?': 'string',\n 'profileHash?': 'string',\n 'annotations?': 'Record<string, unknown>',\n});\n\nconst QueryPlanJson = type({\n collection: 'string',\n command: 'Record<string, unknown>',\n meta: PlanMetaJson,\n});\n\n// ============================================================================\n// DDL check/step schemas\n// ============================================================================\n\nconst CheckJson = type({\n description: 'string',\n source: 'Record<string, unknown>',\n filter: 'Record<string, unknown>',\n expect: '\"exists\" | \"notExists\"',\n});\n\nconst StepJson = type({\n description: 'string',\n command: 'Record<string, unknown>',\n});\n\nconst DdlOperationJson = type({\n id: 'string',\n label: 'string',\n operationClass: '\"additive\" | \"widening\" | \"destructive\"',\n precheck: 'Record<string, unknown>[]',\n execute: 'Record<string, unknown>[]',\n postcheck: 'Record<string, unknown>[]',\n});\n\nconst DataTransformCheckJson = type({\n description: 'string',\n source: 'Record<string, unknown>',\n filter: 'Record<string, unknown>',\n expect: '\"exists\" | \"notExists\"',\n});\n\nconst DataTransformOperationJson = type({\n id: 'string',\n label: 'string',\n operationClass: '\"data\"',\n name: 'string',\n precheck: 'Record<string, unknown>[]',\n run: 'Record<string, unknown>[]',\n postcheck: 'Record<string, unknown>[]',\n});\n\nfunction validate<T>(schema: { assert: (data: unknown) => T }, data: unknown, context: string): T {\n try {\n return schema.assert(stripUndefinedDeep(data));\n } catch (error) {\n /* v8 ignore start -- assertion libraries always throw Error instances */\n const message = error instanceof Error ? error.message : String(error);\n /* v8 ignore stop */\n throw new Error(`Invalid ${context}: ${message}`);\n }\n}\n\n/**\n * Strip `undefined`-valued properties before they reach arktype's optional-key\n * assertions.\n *\n * Op IRs (e.g. `CreateCollectionCommand`) assign every optional field on\n * every instance — fields the caller did not provide land as\n * `undefined`-valued properties. arktype treats `{ foo?: 'boolean' }` as\n * \"key may be absent, but if present must be boolean\", so the bare instance\n * fails validation when it crosses the deserialize boundary in-process\n * (no JSON round-trip happens between planner → runner). This helper\n * recovers the JSON-round-tripped shape (undefined keys absent) without\n * forcing every caller to round-trip.\n *\n * Returns the original value reference whenever no change is needed.\n * That preserves prototype-bound payload values such as BSON wrappers\n * (`ObjectId`, `Decimal128`, `Binary`, …) which embed no `undefined`\n * own-enumerable properties and therefore never trigger a rebuild.\n * Top-level op IRs (class instances with `undefined` optional fields)\n * still get flattened to plain records as required by arktype.\n */\nfunction stripUndefinedDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n let changed = false;\n const next = value.map((item) => {\n const stripped = stripUndefinedDeep(item);\n if (stripped !== item) changed = true;\n return stripped;\n });\n return changed ? next : value;\n }\n if (value === null || typeof value !== 'object') {\n return value;\n }\n const entries = Object.entries(value as Record<string, unknown>);\n const out: Record<string, unknown> = {};\n let changed = false;\n for (const [key, val] of entries) {\n if (val === undefined) {\n changed = true;\n continue;\n }\n const stripped = stripUndefinedDeep(val);\n if (stripped !== val) changed = true;\n out[key] = stripped;\n }\n return changed ? out : value;\n}\n\nfunction deserializeFilterExpr(json: unknown): MongoFilterExpr {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'field': {\n const data = validate(FieldFilterJson, json, 'field filter');\n return MongoFieldFilter.of(data.field, data.op, data.value as never);\n }\n case 'and': {\n const exprs = record['exprs'];\n if (!Array.isArray(exprs)) throw new Error('Invalid and filter: missing exprs array');\n return MongoAndExpr.of(exprs.map(deserializeFilterExpr));\n }\n case 'or': {\n const exprs = record['exprs'];\n if (!Array.isArray(exprs)) throw new Error('Invalid or filter: missing exprs array');\n return MongoOrExpr.of(exprs.map(deserializeFilterExpr));\n }\n case 'not': {\n const expr = record['expr'];\n if (!expr || typeof expr !== 'object') throw new Error('Invalid not filter: missing expr');\n return new MongoNotExpr(deserializeFilterExpr(expr));\n }\n case 'exists': {\n const data = validate(ExistsFilterJson, json, 'exists filter');\n return new MongoExistsExpr(data.field, data.exists);\n }\n default:\n throw new Error(`Unknown filter expression kind: ${kind}`);\n }\n}\n\n// ============================================================================\n// Pipeline stage deserialization\n// ============================================================================\n\nexport function deserializePipelineStage(json: unknown): MongoPipelineStage {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'match':\n return new MongoMatchStage(deserializeFilterExpr(record['filter']));\n case 'limit':\n return new MongoLimitStage(record['limit'] as number);\n case 'sort':\n return new MongoSortStage(record['sort'] as Record<string, 1 | -1>);\n case 'project':\n return new MongoProjectStage(record['projection'] as Record<string, 0 | 1>);\n case 'addFields':\n return new MongoAddFieldsStage(record['fields'] as Record<string, never>);\n case 'lookup': {\n const opts: {\n from: string;\n as: string;\n localField?: string;\n foreignField?: string;\n pipeline?: ReadonlyArray<MongoPipelineStage>;\n let_?: Record<string, never>;\n } = {\n from: record['from'] as string,\n as: record['as'] as string,\n };\n if (record['localField'] !== undefined) opts.localField = record['localField'] as string;\n if (record['foreignField'] !== undefined)\n opts.foreignField = record['foreignField'] as string;\n if (record['pipeline'] !== undefined)\n opts.pipeline = (record['pipeline'] as unknown[]).map(deserializePipelineStage);\n if (record['let_'] !== undefined) opts.let_ = record['let_'] as Record<string, never>;\n return new MongoLookupStage(opts);\n }\n case 'merge': {\n const opts: {\n into: string | { db: string; coll: string };\n on?: string | ReadonlyArray<string>;\n whenMatched?: string | ReadonlyArray<MongoUpdatePipelineStage>;\n whenNotMatched?: string;\n } = {\n into: record['into'] as string | { db: string; coll: string },\n };\n if (record['on'] !== undefined) opts.on = record['on'] as string | string[];\n if (record['whenMatched'] !== undefined) {\n const wm = record['whenMatched'];\n opts.whenMatched =\n typeof wm === 'string'\n ? wm\n : ((wm as unknown[]).map(deserializePipelineStage) as MongoUpdatePipelineStage[]);\n }\n if (record['whenNotMatched'] !== undefined)\n opts.whenNotMatched = record['whenNotMatched'] as string;\n return new MongoMergeStage(opts);\n }\n default:\n throw new Error(`Unknown pipeline stage kind: ${kind}`);\n }\n}\n\n// ============================================================================\n// DML command deserialization\n// ============================================================================\n\nexport function deserializeDmlCommand(json: unknown): AnyMongoCommand {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'rawInsertOne': {\n const data = validate(RawInsertOneJson, json, 'rawInsertOne command');\n return new RawInsertOneCommand(data.collection, data.document);\n }\n case 'rawInsertMany': {\n const data = validate(RawInsertManyJson, json, 'rawInsertMany command');\n return new RawInsertManyCommand(data.collection, data.documents);\n }\n case 'rawUpdateOne': {\n const data = validate(RawUpdateOneJson, json, 'rawUpdateOne command');\n return new RawUpdateOneCommand(data.collection, data.filter, data.update);\n }\n case 'rawUpdateMany': {\n const data = validate(RawUpdateManyJson, json, 'rawUpdateMany command');\n return new RawUpdateManyCommand(data.collection, data.filter, data.update);\n }\n case 'rawDeleteOne': {\n const data = validate(RawDeleteOneJson, json, 'rawDeleteOne command');\n return new RawDeleteOneCommand(data.collection, data.filter);\n }\n case 'rawDeleteMany': {\n const data = validate(RawDeleteManyJson, json, 'rawDeleteMany command');\n return new RawDeleteManyCommand(data.collection, data.filter);\n }\n case 'rawAggregate': {\n const data = validate(RawAggregateJson, json, 'rawAggregate command');\n return new RawAggregateCommand(data.collection, data.pipeline);\n }\n case 'rawFindOneAndUpdate': {\n const data = validate(RawFindOneAndUpdateJson, json, 'rawFindOneAndUpdate command');\n return new RawFindOneAndUpdateCommand(data.collection, data.filter, data.update, data.upsert);\n }\n case 'rawFindOneAndDelete': {\n const data = validate(RawFindOneAndDeleteJson, json, 'rawFindOneAndDelete command');\n return new RawFindOneAndDeleteCommand(data.collection, data.filter);\n }\n case 'aggregate': {\n const data = validate(TypedAggregateJson, json, 'aggregate command');\n const pipeline = data.pipeline.map(deserializePipelineStage);\n return new AggregateCommand(data.collection, pipeline);\n }\n default:\n throw new Error(`Unknown DML command kind: ${kind}`);\n }\n}\n\n// ============================================================================\n// MongoQueryPlan deserialization\n// ============================================================================\n\nexport function deserializeMongoQueryPlan(json: unknown): MongoQueryPlan {\n const data = validate(QueryPlanJson, json, 'Mongo query plan');\n const command = deserializeDmlCommand(data.command);\n const m = data.meta;\n const meta: PlanMeta = {\n target: m.target,\n storageHash: m.storageHash,\n lane: m.lane,\n ...ifDefined('targetFamily', m.targetFamily),\n ...ifDefined('profileHash', m.profileHash),\n ...ifDefined('annotations', m.annotations),\n };\n return { collection: data.collection, command, meta };\n}\n\n// ============================================================================\n// DDL command deserialization\n// ============================================================================\n\nfunction deserializeDdlCommand(json: unknown): AnyMongoDdlCommand {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'createIndex': {\n const data = validate(CreateIndexJson, json, 'createIndex command');\n return new CreateIndexCommand(data.collection, data.keys, {\n ...ifDefined('unique', data.unique),\n ...ifDefined('sparse', data.sparse),\n ...ifDefined('expireAfterSeconds', data.expireAfterSeconds),\n ...ifDefined('partialFilterExpression', data.partialFilterExpression),\n ...ifDefined('name', data.name),\n ...ifDefined(\n 'wildcardProjection',\n data.wildcardProjection as Record<string, 0 | 1> | undefined,\n ),\n ...ifDefined('collation', data.collation),\n ...ifDefined('weights', data.weights as Record<string, number> | undefined),\n ...ifDefined('default_language', data.default_language),\n ...ifDefined('language_override', data.language_override),\n });\n }\n case 'dropIndex': {\n const data = validate(DropIndexJson, json, 'dropIndex command');\n return new DropIndexCommand(data.collection, data.name);\n }\n case 'createCollection': {\n const data = validate(CreateCollectionJson, json, 'createCollection command');\n return new CreateCollectionCommand(data.collection, {\n validator: data.validator,\n validationLevel: data.validationLevel,\n validationAction: data.validationAction,\n capped: data.capped,\n size: data.size,\n max: data.max,\n timeseries: data.timeseries as CreateCollectionCommand['timeseries'],\n collation: data.collation,\n changeStreamPreAndPostImages: data.changeStreamPreAndPostImages as\n | { enabled: boolean }\n | undefined,\n clusteredIndex: data.clusteredIndex as CreateCollectionCommand['clusteredIndex'],\n });\n }\n case 'dropCollection': {\n const data = validate(DropCollectionJson, json, 'dropCollection command');\n return new DropCollectionCommand(data.collection);\n }\n case 'collMod': {\n const data = validate(CollModJson, json, 'collMod command');\n return new CollModCommand(data.collection, {\n validator: data.validator,\n validationLevel: data.validationLevel,\n validationAction: data.validationAction,\n changeStreamPreAndPostImages: data.changeStreamPreAndPostImages as\n | { enabled: boolean }\n | undefined,\n });\n }\n default:\n throw new Error(`Unknown DDL command kind: ${kind}`);\n }\n}\n\nfunction deserializeInspectionCommand(json: unknown): AnyMongoInspectionCommand {\n const record = json as Record<string, unknown>;\n const kind = record['kind'] as string;\n switch (kind) {\n case 'listIndexes': {\n const data = validate(ListIndexesJson, json, 'listIndexes command');\n return new ListIndexesCommand(data.collection);\n }\n case 'listCollections': {\n validate(ListCollectionsJson, json, 'listCollections command');\n return new ListCollectionsCommand();\n }\n default:\n throw new Error(`Unknown inspection command kind: ${kind}`);\n }\n}\n\nfunction deserializeCheck(json: unknown): MongoMigrationCheck {\n const data = validate(CheckJson, json, 'migration check');\n return {\n description: data.description,\n source: deserializeInspectionCommand(data.source),\n filter: deserializeFilterExpr(data.filter),\n expect: data.expect,\n };\n}\n\nfunction deserializeStep(json: unknown): MongoMigrationStep {\n const data = validate(StepJson, json, 'migration step');\n return {\n description: data.description,\n command: deserializeDdlCommand(data.command),\n };\n}\n\nfunction isDataTransformJson(json: unknown): boolean {\n return (\n typeof json === 'object' &&\n json !== null &&\n (json as Record<string, unknown>)['operationClass'] === 'data'\n );\n}\n\nfunction deserializeDdlOp(json: unknown): MongoMigrationPlanOperation {\n const data = validate(DdlOperationJson, json, 'migration operation');\n return {\n id: data.id,\n label: data.label,\n operationClass: data.operationClass as MigrationOperationClass,\n precheck: data.precheck.map(deserializeCheck),\n execute: data.execute.map(deserializeStep),\n postcheck: data.postcheck.map(deserializeCheck),\n };\n}\n\nfunction deserializeDataTransformCheck(json: unknown): MongoDataTransformCheck {\n const data = validate(DataTransformCheckJson, json, 'data transform check');\n return {\n description: data.description,\n source: deserializeMongoQueryPlan(data.source),\n filter: deserializeFilterExpr(data.filter),\n expect: data.expect,\n };\n}\n\nfunction deserializeDataTransformOp(json: unknown): MongoDataTransformOperation {\n const data = validate(DataTransformOperationJson, json, 'data transform operation');\n return {\n id: data.id,\n label: data.label,\n operationClass: 'data',\n name: data.name,\n precheck: data.precheck.map(deserializeDataTransformCheck),\n run: data.run.map(deserializeMongoQueryPlan),\n postcheck: data.postcheck.map(deserializeDataTransformCheck),\n };\n}\n\nexport function deserializeMongoOp(json: unknown): AnyMongoMigrationOperation {\n if (isDataTransformJson(json)) {\n return deserializeDataTransformOp(json);\n }\n return deserializeDdlOp(json);\n}\n\nexport function deserializeMongoOps(json: readonly unknown[]): AnyMongoMigrationOperation[] {\n return json.map(deserializeMongoOp);\n}\n\nexport function serializeMongoOps(ops: readonly AnyMongoMigrationOperation[]): string {\n return JSON.stringify(ops, null, 2);\n}\n","import type { MarkerOperations, MongoRunnerDependencies } from '@prisma-next/adapter-mongo/control';\nimport type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { errorRunnerFailed } from '@prisma-next/errors/execution';\nimport { verifyMongoSchema } from '@prisma-next/family-mongo/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport {\n APP_SPACE_ID,\n type MigrationOperationPolicy,\n type MigrationPlan,\n type MigrationPlanOperation,\n type MigrationRunnerExecutionChecks,\n type MigrationRunnerFailure,\n type MigrationRunnerResult,\n type OperationContext,\n} from '@prisma-next/framework-components/control';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type { MongoAdapter, MongoDriver } from '@prisma-next/mongo-lowering';\nimport type {\n AnyMongoMigrationOperation,\n MongoDataTransformCheck,\n MongoDataTransformOperation,\n MongoInspectionCommandVisitor,\n MongoMigrationCheck,\n MongoMigrationPlanOperation,\n} from '@prisma-next/mongo-query-ast/control';\nimport type { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { FilterEvaluator } from './filter-evaluator';\nimport { deserializeMongoOps } from './mongo-ops-serializer';\n\nconst READ_ONLY_CHECK_COMMAND_KINDS: ReadonlySet<string> = new Set(['aggregate', 'rawAggregate']);\n\nexport type { MarkerOperations, MongoRunnerDependencies };\n\nexport interface MongoMigrationRunnerExecuteOptions {\n readonly plan: MigrationPlan;\n readonly destinationContract: MongoContract;\n readonly policy: MigrationOperationPolicy;\n readonly callbacks?: {\n onOperationStart?(op: MigrationPlanOperation): void;\n onOperationComplete?(op: MigrationPlanOperation): void;\n };\n readonly executionChecks?: MigrationRunnerExecutionChecks;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n readonly strictVerification?: boolean;\n readonly context?: OperationContext;\n /**\n * Per-space schema projection. When set, the runner applies this\n * function to the introspected schema before invoking\n * `verifyMongoSchema`, so per-space verification only sees the slice\n * the destination contract actually claims.\n *\n * The descriptor's `executeAcrossSpaces` injects this callback,\n * derived from the sibling spaces in the aggregate. Single-space\n * callers leave it unset and verify against the whole introspected\n * schema (the pre-aggregate behaviour).\n */\n readonly projectSchema?: (schema: MongoSchemaIR) => MongoSchemaIR;\n}\n\nfunction runnerFailure(\n code: string,\n summary: string,\n opts?: { why?: string; meta?: Record<string, unknown> },\n): MigrationRunnerResult {\n return notOk<MigrationRunnerFailure>({\n code,\n summary,\n ...opts,\n });\n}\n\nexport class MongoMigrationRunner {\n constructor(private readonly deps: MongoRunnerDependencies) {}\n\n async execute(options: MongoMigrationRunnerExecuteOptions): Promise<MigrationRunnerResult> {\n const { commandExecutor, inspectionExecutor, adapter, driver, markerOps } = this.deps;\n const operations = deserializeMongoOps(options.plan.operations as readonly unknown[]);\n // Plans produced by the contract-space-aware planner stamp `spaceId`\n // onto the plan; pre-port single-space callers leave it absent and\n // fall through to the application's well-known space.\n const space = options.plan.spaceId ?? APP_SPACE_ID;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, operations);\n if (policyCheck) return policyCheck;\n\n const existingMarker = await markerOps.readMarker(space);\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (markerCheck) return markerCheck;\n\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false;\n const runPostchecks = checks?.postchecks !== false;\n const runIdempotency = checks?.idempotencyChecks !== false;\n\n const filterEvaluator = new FilterEvaluator();\n\n let operationsExecuted = 0;\n\n for (const operation of operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n if (operation.operationClass === 'data') {\n const result = await this.executeDataTransform(\n operation as MongoDataTransformOperation,\n adapter,\n driver,\n filterEvaluator,\n runIdempotency,\n runPrechecks,\n runPostchecks,\n );\n if (result.failure) return result.failure;\n if (result.executed) operationsExecuted += 1;\n continue;\n }\n\n const ddlOp = operation as MongoMigrationPlanOperation;\n\n if (runPostchecks && runIdempotency) {\n const allSatisfied = await this.allChecksSatisfied(\n ddlOp.postcheck,\n inspectionExecutor,\n filterEvaluator,\n );\n if (allSatisfied) continue;\n }\n\n if (runPrechecks) {\n const precheckResult = await this.evaluateChecks(\n ddlOp.precheck,\n inspectionExecutor,\n filterEvaluator,\n );\n if (!precheckResult) {\n return runnerFailure(\n 'PRECHECK_FAILED',\n `Operation ${operation.id} failed during precheck`,\n { meta: { operationId: operation.id } },\n );\n }\n }\n\n for (const step of ddlOp.execute) {\n await step.command.accept(commandExecutor);\n }\n\n if (runPostchecks) {\n const postcheckResult = await this.evaluateChecks(\n ddlOp.postcheck,\n inspectionExecutor,\n filterEvaluator,\n );\n if (!postcheckResult) {\n return runnerFailure(\n 'POSTCHECK_FAILED',\n `Operation ${operation.id} failed during postcheck`,\n { meta: { operationId: operation.id } },\n );\n }\n }\n\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n\n const destination = options.plan.destination;\n const profileHash = options.destinationContract.profileHash ?? destination.storageHash;\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariantSet = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) =>\n existingInvariantSet.has(id),\n );\n const markerAlreadyAtDestination =\n existingMarker !== null &&\n existingMarker.storageHash === destination.storageHash &&\n existingMarker.profileHash === profileHash;\n\n // Skip marker/ledger writes (and schema verification) only when the apply\n // is a true no-op: no operations executed, marker already at destination,\n // and every incoming invariant is already in the stored set.\n //\n // Divergence from the SQL runners (postgres/sqlite): those runners gate\n // the no-op skip on `isSelfEdge` (origin === destination) only, so a\n // non-self-edge `db update` that introspects-as-no-op still writes a\n // ledger entry. Mongo skips even those because the runner has no\n // structural distinction between self-edge and re-apply — invariant-\n // aware routing here does not yet differentiate between the two\n // ledger semantics. If the SQL audit-trail behavior should hold for\n // Mongo too, gate this `isNoOp` on a self-edge check (or, conversely,\n // align the SQL runners to skip non-self-edge no-ops uniformly).\n const isNoOp =\n operationsExecuted === 0 && markerAlreadyAtDestination && incomingIsSubsetOfExisting;\n\n if (!isNoOp) {\n const liveSchema = await this.deps.introspectSchema();\n // In a multi-space aggregate the live database holds collections\n // owned by sibling spaces; the descriptor's `executeAcrossSpaces`\n // injects a `projectSchema` that strips them so per-space verify\n // only checks the slice this contract claims. Single-space\n // callers leave the projection identity (no-op).\n const verifySchema = options.projectSchema ? options.projectSchema(liveSchema) : liveSchema;\n const verifyResult = verifyMongoSchema({\n contract: options.destinationContract,\n schema: verifySchema,\n strict: options.strictVerification ?? true,\n frameworkComponents: options.frameworkComponents,\n ...(options.context ? { context: options.context } : {}),\n });\n if (!verifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', verifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: { issues: verifyResult.schema.issues },\n });\n }\n\n if (existingMarker) {\n const updated = await markerOps.updateMarker(space, existingMarker.storageHash, {\n storageHash: destination.storageHash,\n profileHash,\n invariants: incomingInvariants,\n });\n if (!updated) {\n return runnerFailure(\n 'MARKER_CAS_FAILURE',\n 'Marker was modified by another process during migration execution.',\n {\n meta: {\n space,\n expectedStorageHash: existingMarker.storageHash,\n destinationStorageHash: destination.storageHash,\n },\n },\n );\n }\n } else {\n await markerOps.initMarker(space, {\n storageHash: destination.storageHash,\n profileHash,\n invariants: incomingInvariants,\n });\n }\n\n const originHash = existingMarker?.storageHash ?? '';\n await markerOps.writeLedgerEntry(space, {\n edgeId: `${originHash}->${destination.storageHash}`,\n from: originHash,\n to: destination.storageHash,\n });\n }\n\n return ok({ operationsPlanned: operations.length, operationsExecuted });\n }\n\n private async executeDataTransform(\n op: MongoDataTransformOperation,\n adapter: MongoAdapter,\n driver: MongoDriver,\n filterEvaluator: FilterEvaluator,\n runIdempotency: boolean,\n runPrechecks: boolean,\n runPostchecks: boolean,\n ): Promise<{ executed: boolean; failure?: MigrationRunnerResult }> {\n if (runPostchecks && runIdempotency && op.postcheck.length > 0) {\n const allSatisfied = await this.evaluateDataTransformChecks(\n op.postcheck,\n adapter,\n driver,\n filterEvaluator,\n );\n if (allSatisfied) return { executed: false };\n }\n\n if (runPrechecks && op.precheck.length > 0) {\n const passed = await this.evaluateDataTransformChecks(\n op.precheck,\n adapter,\n driver,\n filterEvaluator,\n );\n if (!passed) {\n return {\n executed: false,\n failure: runnerFailure('PRECHECK_FAILED', `Operation ${op.id} failed during precheck`, {\n meta: { operationId: op.id, name: op.name },\n }),\n };\n }\n }\n\n for (const plan of op.run) {\n const wireCommand = await adapter.lower(plan, {});\n for await (const _ of driver.execute(wireCommand)) {\n /* consume */\n }\n }\n\n if (runPostchecks && op.postcheck.length > 0) {\n const passed = await this.evaluateDataTransformChecks(\n op.postcheck,\n adapter,\n driver,\n filterEvaluator,\n );\n if (!passed) {\n return {\n executed: false,\n failure: runnerFailure('POSTCHECK_FAILED', `Operation ${op.id} failed during postcheck`, {\n meta: { operationId: op.id, name: op.name },\n }),\n };\n }\n }\n\n return { executed: true };\n }\n\n private async evaluateDataTransformChecks(\n checks: readonly MongoDataTransformCheck[],\n adapter: MongoAdapter,\n driver: MongoDriver,\n filterEvaluator: FilterEvaluator,\n ): Promise<boolean> {\n for (const check of checks) {\n const commandKind = check.source.command.kind;\n if (!READ_ONLY_CHECK_COMMAND_KINDS.has(commandKind)) {\n throw errorRunnerFailed(\n `Data-transform check rejected: command kind \"${commandKind}\" is not read-only`,\n {\n why: 'Data-transform checks must use aggregate or rawAggregate commands so the pre/postcheck path cannot mutate the database.',\n fix: 'Author the check.source as an aggregate pipeline (or rawAggregate) rather than a DML write command.',\n meta: {\n checkDescription: check.description,\n commandKind,\n collection: check.source.collection,\n },\n },\n );\n }\n const wireCommand = await adapter.lower(check.source, {});\n let matchFound = false;\n for await (const row of driver.execute<Record<string, unknown>>(wireCommand)) {\n if (filterEvaluator.evaluate(check.filter, row)) {\n matchFound = true;\n break;\n }\n }\n const passed = check.expect === 'exists' ? matchFound : !matchFound;\n if (!passed) return false;\n }\n return true;\n }\n\n private async evaluateChecks(\n checks: readonly MongoMigrationCheck[],\n inspectionExecutor: MongoInspectionCommandVisitor<Promise<Record<string, unknown>[]>>,\n filterEvaluator: FilterEvaluator,\n ): Promise<boolean> {\n for (const check of checks) {\n const documents = await check.source.accept(inspectionExecutor);\n const matchFound = documents.some((doc) =>\n filterEvaluator.evaluate(check.filter, doc as Record<string, unknown>),\n );\n const passed = check.expect === 'exists' ? matchFound : !matchFound;\n if (!passed) return false;\n }\n return true;\n }\n\n private async allChecksSatisfied(\n checks: readonly MongoMigrationCheck[],\n inspectionExecutor: MongoInspectionCommandVisitor<Promise<Record<string, unknown>[]>>,\n filterEvaluator: FilterEvaluator,\n ): Promise<boolean> {\n if (checks.length === 0) return false;\n return this.evaluateChecks(checks, inspectionExecutor, filterEvaluator);\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly AnyMongoMigrationOperation[],\n ): MigrationRunnerResult | undefined {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${[...allowedClasses].join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n },\n },\n );\n }\n }\n return undefined;\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: MigrationPlan,\n ): MigrationRunnerResult | undefined {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller has done its own\n // correctness check (typically `db update` via live-schema\n // introspection) and does not rely on marker continuity.\n return undefined;\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n { meta: { expectedOriginStorageHash: origin.storageHash } },\n );\n }\n\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n\n return undefined;\n }\n}\n","import {\n freezeNode,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { MongoCollection, type MongoCollectionInput } from '@prisma-next/mongo-contract';\n\nexport interface MongoTargetDatabaseInput {\n readonly id: string;\n readonly collections?: Record<string, MongoCollection | MongoCollectionInput>;\n}\n\n/**\n * Mongo target `Namespace` concretion. In Mongo the \"namespace\" concept\n * binds to the connection's `db` field — a `MongoTargetDatabase` instance\n * names the database the collections live under. The unbound singleton\n * (below) is the late-bound slot whose binding the connection's `db`\n * resolves at runtime rather than at authoring time.\n *\n * Qualifier emission is the rendering seam: query / DDL emission asks the\n * namespace for its qualifier (e.g. `\"<db>.<collection>\"`) and consumes\n * the result polymorphically. The unbound singleton overrides these\n * methods to elide the prefix entirely — call sites stay polymorphic and\n * never branch on `id === UNBOUND_NAMESPACE_ID`.\n */\nexport class MongoTargetDatabase extends NamespaceBase {\n readonly kind = 'database' as const;\n readonly id: string;\n readonly collections: Readonly<Record<string, MongoCollection>>;\n\n constructor(input: MongoTargetDatabaseInput) {\n super();\n this.id = input.id;\n this.collections = Object.freeze(\n Object.fromEntries(\n Object.entries(input.collections ?? {}).map(([name, c]) => [\n name,\n c instanceof MongoCollection ? c : new MongoCollection(c),\n ]),\n ),\n );\n freezeNode(this);\n }\n\n /**\n * The bare qualifier as it would appear in a rendered string. The\n * unbound-database singleton overrides this to return `''`.\n */\n qualifier(): string {\n return this.id;\n }\n\n /**\n * Qualify a collection name with the database prefix. The\n * unbound-database singleton overrides this to emit just the\n * collection name. Used by emission/introspection paths that need a\n * fully-qualified reference.\n */\n qualifyCollection(collectionName: string): string {\n return `${this.id}.${collectionName}`;\n }\n}\n\n/**\n * Singleton subclass for the reserved sentinel namespace id\n * (`UNBOUND_NAMESPACE_ID`) — the late-bound slot whose binding the\n * connection's `db` resolves at runtime. Overrides qualifier emission\n * to elide the database prefix; call sites that consume `qualifier()`\n * / `qualifyCollection()` get unqualified output without branching on\n * the namespace id.\n *\n * This is the target-side materialization of \"the framework provides\n * affordances; targets implement specifics\": the framework names the\n * sentinel; Mongo decides what late-bound means here (the collection\n * name, naked — the database is supplied by the live connection).\n */\nexport class MongoTargetUnboundDatabase extends MongoTargetDatabase {\n static readonly instance: MongoTargetUnboundDatabase = new MongoTargetUnboundDatabase();\n\n private constructor() {\n super({ id: UNBOUND_NAMESPACE_ID });\n }\n\n override qualifier(): string {\n return '';\n }\n\n override qualifyCollection(collectionName: string): string {\n return collectionName;\n }\n}\n","import { MongoContractSerializerBase } from '@prisma-next/family-mongo/ir';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { type MongoContract, MongoStorage } from '@prisma-next/mongo-contract';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport type { MongoTargetContract } from './mongo-target-contract';\nimport { MongoTargetDatabase, MongoTargetUnboundDatabase } from './mongo-target-database';\n\nexport class MongoTargetContractSerializer extends MongoContractSerializerBase<MongoTargetContract> {\n protected constructTargetContract(validated: MongoContract): MongoTargetContract {\n const { storage, ...rest } = validated;\n const namespaces = Object.fromEntries(\n Object.entries(storage.namespaces).map(([nsId, nsData]) => {\n const collections = nsData.collections;\n const collectionCount = Object.keys(collections).length;\n if (nsId === UNBOUND_NAMESPACE_ID && collectionCount === 0) {\n return [nsId, MongoTargetUnboundDatabase.instance];\n }\n return [\n nsId,\n new MongoTargetDatabase({\n id: nsData.id,\n collections,\n }),\n ];\n }),\n );\n const targetStorage = new MongoStorage({\n storageHash: storage.storageHash,\n namespaces,\n });\n return { ...rest, storage: targetStorage };\n }\n\n override serializeContract(contract: MongoTargetContract): JsonObject {\n const { storage, ...rest } = contract;\n const namespacesJson: Record<string, JsonObject> = {};\n for (const [nsId, ns] of Object.entries(storage.namespaces)) {\n const collectionsOut: Record<string, JsonObject> = {};\n for (const [collName, coll] of Object.entries(ns.collections)) {\n collectionsOut[collName] = JSON.parse(JSON.stringify(coll)) as JsonObject;\n }\n namespacesJson[nsId] = {\n id: ns.id,\n kind: 'mongo-database',\n collections: collectionsOut,\n };\n }\n return {\n ...rest,\n storage: {\n storageHash: String(storage.storageHash),\n namespaces: namespacesJson,\n },\n // `rest` carries Contract fields typed against framework interfaces\n // (e.g. `ContractExecutionSection`) that TypeScript can't structurally\n // prove are JSON-compatible without a per-field re-validation pass.\n // The runtime invariant is that an emitted MongoTargetContract has\n // already been through validation and contains only JSON-safe values,\n // so the two-step cast is intentional. Mirrors the pattern in\n // PostgresContractSerializer.serializeContract.\n } as unknown as JsonObject;\n }\n}\n","import {\n canonicalizeSchemasForVerification,\n contractToMongoSchemaIR,\n diffMongoSchemas,\n} from '@prisma-next/family-mongo/control';\nimport { MongoSchemaVerifierBase } from '@prisma-next/family-mongo/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { Namespace } from '@prisma-next/framework-components/ir';\nimport type { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';\nimport type { MongoTargetContract } from './mongo-target-contract';\n\n/**\n * Mongo target `SchemaVerifier` concretion. Extends the family base's\n * namespace-walk scaffolding and contributes the per-namespace diff via\n * `verifyNamespace`; the diff body reuses the existing target-side\n * helpers (`contractToMongoSchemaIR`, `canonicalizeSchemasForVerification`,\n * `diffMongoSchemas`) so production verification behaviour is unchanged.\n *\n * Today's invariant: every Mongo contract carries exactly one\n * namespace (the unbound singleton, materialised as\n * `MongoTargetUnboundDatabase`), so the family-base namespace walk\n * dispatches exactly once and the per-namespace body runs the existing\n * whole-schema diff. Future per-collection namespace assignment will\n * have this hook project the diff to the namespace's owned collections.\n *\n * `verifyTargetExtensions` returns the empty list — Mongo has no\n * target-only kinds today.\n *\n * Strict diff mode is `false` for SPI-routed calls; production\n * verification today still goes through `verifyMongoSchema` which\n * receives strict from the CLI.\n */\nexport class MongoTargetSchemaVerifier extends MongoSchemaVerifierBase<\n MongoTargetContract,\n MongoSchemaIR\n> {\n protected verifyNamespace(options: {\n readonly contract: MongoTargetContract;\n readonly schema: MongoSchemaIR;\n readonly namespaceId: string;\n readonly namespace: Namespace;\n }): readonly SchemaIssue[] {\n const expectedIR = contractToMongoSchemaIR(options.contract);\n const { live, expected } = canonicalizeSchemasForVerification(options.schema, expectedIR);\n const { issues } = diffMongoSchemas(live, expected, false);\n return issues;\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<MongoTargetContract, MongoSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n}\n","import {\n createMongoRunnerDeps,\n extractDb,\n type MongoRunnerDependencies,\n} from '@prisma-next/adapter-mongo/control';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { MongoDriverImpl } from '@prisma-next/driver-mongo';\nimport type {\n MongoControlFamilyInstance,\n MongoControlTargetDescriptor,\n} from '@prisma-next/family-mongo/control';\nimport { contractToMongoSchemaIR } from '@prisma-next/family-mongo/control';\nimport type {\n MigrationRunner,\n MigrationRunnerResult,\n MigrationRunnerSuccessValue,\n MultiSpaceCapableRunner,\n MultiSpaceRunnerFailure,\n MultiSpaceRunnerPerSpaceOptions,\n MultiSpaceRunnerResult,\n} from '@prisma-next/framework-components/control';\nimport {\n createContractSpaceMember,\n projectSchemaToSpace,\n} from '@prisma-next/migration-tools/aggregate';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type { MongoSchemaCollection } from '@prisma-next/mongo-schema-ir';\nimport { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { mongoTargetDescriptorMeta } from './descriptor-meta';\nimport { MongoMigrationPlanner } from './mongo-planner';\nimport { MongoMigrationRunner, type MongoMigrationRunnerExecuteOptions } from './mongo-runner';\nimport type { MongoTargetContract } from './mongo-target-contract';\nimport { MongoTargetContractSerializer } from './mongo-target-contract-serializer';\nimport { MongoTargetSchemaVerifier } from './mongo-target-schema-verifier';\n\nexport type { MongoControlTargetDescriptor };\n\n/**\n * `migration.ts` default-exports a `Migration` subclass whose `operations`\n * getter returns the ordered list of operations and whose `describe()`\n * returns the manifest identity metadata. `MongoMigrationPlanner.plan()`\n * returns a `MigrationPlanWithAuthoringSurface` that knows how to render\n * itself back to such a file; `MongoMigrationPlanner.emptyMigration()`\n * returns the same shape for `migration new`. Users run the scaffolded\n * `migration.ts` directly (via `node migration.ts`) to self-emit\n * `ops.json` and attest the `migrationHash`.\n */\nexport const mongoTargetDescriptor: MongoControlTargetDescriptor<MongoTargetContract> = {\n ...mongoTargetDescriptorMeta,\n contractSerializer: new MongoTargetContractSerializer(),\n schemaVerifier: new MongoTargetSchemaVerifier(),\n migrations: {\n createPlanner(_family: MongoControlFamilyInstance) {\n return new MongoMigrationPlanner();\n },\n createRunner(family: MongoControlFamilyInstance) {\n // Deps are bound to the first driver passed to execute() and cached for\n // subsequent calls. Callers must not change the driver between calls.\n let cachedDeps: MongoRunnerDependencies | undefined;\n\n const runMongo = async (\n driver: Parameters<MigrationRunner<'mongo', 'mongo'>['execute']>[0]['driver'],\n runnerOptions: Omit<MongoMigrationRunnerExecuteOptions, 'destinationContract'> & {\n readonly destinationContract: unknown;\n },\n ): Promise<MigrationRunnerResult> => {\n cachedDeps ??= createMongoRunnerDeps(\n driver,\n MongoDriverImpl.fromDb(extractDb(driver)),\n family,\n );\n // The framework `MigrationRunner` interface types `destinationContract`\n // as `unknown`; the Mongo runner narrows to `MongoContract`. Validation\n // happens upstream — `migrate` calls\n // `familyInstance.deserializeContract(contract)` on the project-root\n // contract loaded from disk before routing it here, so this cast\n // preserves the framework signature without weakening the runner's\n // typed surface.\n return new MongoMigrationRunner(cachedDeps).execute({\n ...runnerOptions,\n destinationContract: runnerOptions.destinationContract as MongoContract,\n });\n };\n\n const runner: MigrationRunner<'mongo', 'mongo'> & MultiSpaceCapableRunner<'mongo', 'mongo'> =\n {\n async execute(options) {\n const { driver, ...runnerOptions } = options;\n return runMongo(driver, runnerOptions);\n },\n // Mongo cannot wrap DDL ops in a session transaction (createCollection,\n // createIndex, collMod, setValidation all bypass transactions even on\n // replica sets), so the cross-space envelope is *resumable* rather than\n // transactional. Per-space-internal verify-gated marker atomicity\n // already lives in `runner.execute`: ops apply, schema is introspected\n // and verified, and the marker advances only on verify-pass. This loop\n // composes that guarantee across spaces — earlier-advanced markers are\n // not rolled back when a later space fails. Re-running reads each\n // marker, finds spaces 1..N−1 at-head (no-op skip), retries N onward.\n //\n // Per-space verify is sliced via `projectSchemaToSpace`: the live DB\n // holds collections owned by sibling spaces, but each space's verify\n // only sees the slice that space's contract actually claims. Without\n // the projection an aggregate of two spaces could not pass strict\n // verify (every other-space collection would look like an extra).\n //\n // See `docs/architecture docs/subsystems/10. MongoDB Family.md` §\n // Contract spaces and ADR 212 — Contract spaces.\n async executeAcrossSpaces({ driver, perSpaceOptions }): Promise<MultiSpaceRunnerResult> {\n const members = perSpaceOptions.map(toSpaceMember);\n const perSpaceResults: Array<{\n space: string;\n value: MigrationRunnerSuccessValue;\n }> = [];\n for (let i = 0; i < perSpaceOptions.length; i++) {\n const spaceOptions = perSpaceOptions[i];\n if (!spaceOptions) continue;\n const member = members[i];\n if (!member) continue;\n const others = members.filter((_, j) => j !== i);\n const projectSchema = (schema: MongoSchemaIR): MongoSchemaIR => {\n // `projectSchemaToSpace` returns a plain object\n // `{...schemaIR, collections: prunedArray}` (not a\n // `MongoSchemaIR` instance), so the descriptor rewraps\n // the pruned collections into a fresh `MongoSchemaIR`\n // before handing it to `verifyMongoSchema` (which\n // depends on the class's `collectionNames` /\n // `collection(name)` accessors).\n const projected = projectSchemaToSpace(schema, member, others) as {\n readonly collections: ReadonlyArray<MongoSchemaCollection>;\n };\n return new MongoSchemaIR(projected.collections);\n };\n const result = await runMongo(driver, { ...spaceOptions, projectSchema });\n if (!result.ok) {\n return notOk<MultiSpaceRunnerFailure>({\n ...result.failure,\n failingSpace: spaceOptions.space,\n });\n }\n perSpaceResults.push({ space: spaceOptions.space, value: result.value });\n }\n return ok({ perSpaceResults });\n },\n };\n return runner;\n },\n contractToSchema(contract: Contract | null) {\n return contractToMongoSchemaIR(contract as MongoContract | null);\n },\n },\n create() {\n return { familyId: 'mongo' as const, targetId: 'mongo' as const };\n },\n};\n\n/**\n * Synthesise a {@link projectSchemaToSpace}-compatible member from a\n * per-space option entry. The projector only reads `spaceId` and\n * `contract()`; migration graph state is empty because the runner\n * consumes the destination contract directly.\n */\nfunction toSpaceMember(opts: MultiSpaceRunnerPerSpaceOptions<'mongo', 'mongo'>) {\n const contract = blindCast<Contract, 'destinationContract validated at aggregate boundary'>(\n opts.destinationContract,\n );\n return createContractSpaceMember({\n spaceId: opts.space,\n packages: [],\n refs: {},\n headRef: null,\n refsDir: '',\n resolveContract: () => contract,\n deserializeContract: (raw) =>\n blindCast<Contract, 'destinationContract validated at aggregate boundary'>(raw),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,0BAA0B;AAEhC,IAAe,oBAAf,cAAyC,aAA+C;CAMtF,qBAAmD;EACjD,OAAO,CAAC;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;EAAY,CAAC;CAChF;CAEA,SAAyB;EACvB,OAAO,OAAO,IAAI;CACpB;AACF;AAEA,SAAS,WAAW,MAA4C;CAC9D,OAAO,KAAK,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,EAAE,WAAW,EAAE,KAAK,IAAI;AAC/D;AAEA,IAAa,kBAAb,cAAqC,kBAAkB;CACrD,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CACA;CACA;CAEA,YACE,YACA,MACA,SACA;EACA,MAAM;EACN,KAAK,aAAa;EAClB,KAAK,OAAO;EACZ,KAAK,UAAU;EACf,KAAK,QAAQ,mBAAmB,WAAW,IAAI,WAAW,IAAI,EAAE;EAChE,KAAK,OAAO;C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AAK;EACd,UAAU,CAAC;EACX,MAAM,CAAC;EACP,SAAS;EACT,SAAS;EACT,uBAAuB;EACvB,sBAAsB,QACpB,UAA2E,GAAG;CAClF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,35 +1,35 @@
1
1
  {
2
2
  "name": "@prisma-next/target-mongo",
3
- "version": "0.11.0-dev.56",
3
+ "version": "0.11.0-dev.58",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "MongoDB target pack for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/adapter-mongo": "0.11.0-dev.56",
10
- "@prisma-next/contract": "0.11.0-dev.56",
11
- "@prisma-next/driver-mongo": "0.11.0-dev.56",
12
- "@prisma-next/errors": "0.11.0-dev.56",
13
- "@prisma-next/family-mongo": "0.11.0-dev.56",
14
- "@prisma-next/framework-components": "0.11.0-dev.56",
15
- "@prisma-next/migration-tools": "0.11.0-dev.56",
16
- "@prisma-next/ts-render": "0.11.0-dev.56",
17
- "@prisma-next/mongo-codec": "0.11.0-dev.56",
18
- "@prisma-next/mongo-contract": "0.11.0-dev.56",
19
- "@prisma-next/mongo-lowering": "0.11.0-dev.56",
20
- "@prisma-next/mongo-query-ast": "0.11.0-dev.56",
21
- "@prisma-next/mongo-schema-ir": "0.11.0-dev.56",
22
- "@prisma-next/mongo-value": "0.11.0-dev.56",
23
- "@prisma-next/utils": "0.11.0-dev.56",
9
+ "@prisma-next/adapter-mongo": "0.11.0-dev.58",
10
+ "@prisma-next/contract": "0.11.0-dev.58",
11
+ "@prisma-next/driver-mongo": "0.11.0-dev.58",
12
+ "@prisma-next/errors": "0.11.0-dev.58",
13
+ "@prisma-next/family-mongo": "0.11.0-dev.58",
14
+ "@prisma-next/framework-components": "0.11.0-dev.58",
15
+ "@prisma-next/migration-tools": "0.11.0-dev.58",
16
+ "@prisma-next/ts-render": "0.11.0-dev.58",
17
+ "@prisma-next/mongo-codec": "0.11.0-dev.58",
18
+ "@prisma-next/mongo-contract": "0.11.0-dev.58",
19
+ "@prisma-next/mongo-lowering": "0.11.0-dev.58",
20
+ "@prisma-next/mongo-query-ast": "0.11.0-dev.58",
21
+ "@prisma-next/mongo-schema-ir": "0.11.0-dev.58",
22
+ "@prisma-next/mongo-value": "0.11.0-dev.58",
23
+ "@prisma-next/utils": "0.11.0-dev.58",
24
24
  "arktype": "^2.2.0"
25
25
  },
26
26
  "devDependencies": {
27
27
  "mongodb": "^7.2.0",
28
- "@prisma-next/mongo-contract-psl": "0.11.0-dev.56",
29
- "@prisma-next/psl-parser": "0.11.0-dev.56",
30
- "@prisma-next/test-utils": "0.11.0-dev.56",
31
- "@prisma-next/tsconfig": "0.11.0-dev.56",
32
- "@prisma-next/tsdown": "0.11.0-dev.56",
28
+ "@prisma-next/mongo-contract-psl": "0.11.0-dev.58",
29
+ "@prisma-next/psl-parser": "0.11.0-dev.58",
30
+ "@prisma-next/test-utils": "0.11.0-dev.58",
31
+ "@prisma-next/tsconfig": "0.11.0-dev.58",
32
+ "@prisma-next/tsdown": "0.11.0-dev.58",
33
33
  "mongodb-memory-server": "11.1.0",
34
34
  "pathe": "^2.0.3",
35
35
  "tsdown": "0.22.0",
@@ -163,14 +163,17 @@ export const mongoTargetDescriptor: MongoControlTargetDescriptor<MongoTargetCont
163
163
  * consumes the destination contract directly.
164
164
  */
165
165
  function toSpaceMember(opts: MultiSpaceRunnerPerSpaceOptions<'mongo', 'mongo'>) {
166
+ const contract = blindCast<Contract, 'destinationContract validated at aggregate boundary'>(
167
+ opts.destinationContract,
168
+ );
166
169
  return createContractSpaceMember({
167
170
  spaceId: opts.space,
168
171
  packages: [],
169
172
  refs: {},
170
173
  headRef: null,
171
- resolveContract: () =>
172
- blindCast<Contract, 'destinationContract validated at aggregate boundary'>(
173
- opts.destinationContract,
174
- ),
174
+ refsDir: '',
175
+ resolveContract: () => contract,
176
+ deserializeContract: (raw) =>
177
+ blindCast<Contract, 'destinationContract validated at aggregate boundary'>(raw),
175
178
  });
176
179
  }