@prisma/orm-target-mongo 8.0.0-rc.23-dev.13 → 8.0.0-rc.23-dev.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/adapter.mjs +1 -1
  2. package/dist/adapter__control.mjs +1 -1
  3. package/dist/adapter__runtime.mjs +2 -2
  4. package/dist/{codecs-BbX2VMzN-Dm9db3Jz.mjs → codecs-Bl21z49D-Bj5erX9r.mjs} +3 -3
  5. package/dist/{codecs-BbX2VMzN-Dm9db3Jz.mjs.map → codecs-Bl21z49D-Bj5erX9r.mjs.map} +1 -1
  6. package/dist/{control-B77seMDK.mjs → control-BxslS3_F.mjs} +1452 -154
  7. package/dist/control-BxslS3_F.mjs.map +1 -0
  8. package/dist/{control-AjuXfVKk.mjs → control-DPih_MpI.mjs} +2 -2
  9. package/dist/{control-AjuXfVKk.mjs.map → control-DPih_MpI.mjs.map} +1 -1
  10. package/dist/{control-1-RnMe4V.d.mts → control-OiC131Dv.d.mts} +35 -5
  11. package/dist/control-OiC131Dv.d.mts.map +1 -0
  12. package/dist/{data-types-Cq1kg82y-Vk7z6rnW.mjs → data-types-B3SLjbqa-C1LmrfzH.mjs} +29 -5
  13. package/dist/{data-types-Cq1kg82y-Vk7z6rnW.mjs.map → data-types-B3SLjbqa-C1LmrfzH.mjs.map} +1 -1
  14. package/dist/{date-time-now-generators-fWUk_--7-BnCnC0d8.mjs → date-time-now-generators-Dhq1b2V8-TgMEfnbI.mjs} +3 -3
  15. package/dist/{date-time-now-generators-fWUk_--7-BnCnC0d8.mjs.map → date-time-now-generators-Dhq1b2V8-TgMEfnbI.mjs.map} +1 -1
  16. package/dist/{descriptor-meta-CFsOxO6g-Ca8valmZ.mjs → descriptor-meta-BXMz_uZd-B8WB2m7v.mjs} +5 -5
  17. package/dist/{descriptor-meta-CFsOxO6g-Ca8valmZ.mjs.map → descriptor-meta-BXMz_uZd-B8WB2m7v.mjs.map} +1 -1
  18. package/dist/{descriptor-meta-runtime-CBJIjp5R-DMQ9-3Hd.mjs → descriptor-meta-runtime-J4eVdBtZ-D1yRng4t.mjs} +4 -4
  19. package/dist/{descriptor-meta-runtime-CBJIjp5R-DMQ9-3Hd.mjs.map → descriptor-meta-runtime-J4eVdBtZ-D1yRng4t.mjs.map} +1 -1
  20. package/dist/driver.mjs +1 -1
  21. package/dist/driver__control.mjs +1 -1
  22. package/dist/driver__runtime.mjs +1 -1
  23. package/dist/driver__runtime.mjs.map +1 -1
  24. package/dist/migration-DASk9QNA.d.mts +5 -0
  25. package/dist/{migration-factories-oLRWgLGz-B9fWm8Wc.mjs → migration-factories-C5ktmt8c-BP8k9SnZ.mjs} +245 -17
  26. package/dist/migration-factories-C5ktmt8c-BP8k9SnZ.mjs.map +1 -0
  27. package/dist/{mongo-adapter-RJ_YOxiK-jlyFS6Wr.mjs → mongo-adapter-RJ_YOxiK-CCHpxwqy.mjs} +2 -2
  28. package/dist/{mongo-adapter-RJ_YOxiK-jlyFS6Wr.mjs.map → mongo-adapter-RJ_YOxiK-CCHpxwqy.mjs.map} +1 -1
  29. package/dist/{mongo-driver-Dtca4OAu-Cy1Lh7xi.mjs → mongo-driver-igrhXX_3-CWKp1Lw4.mjs} +3 -3
  30. package/dist/{mongo-driver-Dtca4OAu-Cy1Lh7xi.mjs.map → mongo-driver-igrhXX_3-CWKp1Lw4.mjs.map} +1 -1
  31. package/dist/op-factory-call-BCgwbVJe-DhcJRxAb.d.mts +248 -0
  32. package/dist/op-factory-call-BCgwbVJe-DhcJRxAb.d.mts.map +1 -0
  33. package/dist/{prisma6-binding-BjKPGVql.mjs → prisma6-binding-BXi_1e8c.mjs} +2 -2
  34. package/dist/{prisma6-binding-BjKPGVql.mjs.map → prisma6-binding-BXi_1e8c.mjs.map} +1 -1
  35. package/dist/{runtime-DyWNR1FZ.mjs → runtime-CkX-HAf5.mjs} +2 -2
  36. package/dist/{runtime-DyWNR1FZ.mjs.map → runtime-CkX-HAf5.mjs.map} +1 -1
  37. package/dist/target.d.mts +4 -4
  38. package/dist/target.mjs +8 -8
  39. package/dist/target__codecs.mjs +1 -1
  40. package/dist/target__control.d.mts +2 -2
  41. package/dist/target__control.mjs +1 -1
  42. package/dist/target__data-types.mjs +1 -1
  43. package/dist/target__migration.d.mts +3 -2
  44. package/dist/target__migration.mjs +3 -3
  45. package/dist/target__pack.mjs +1 -1
  46. package/dist/target__pack.mjs.map +1 -1
  47. package/dist/target__prisma6-binding.mjs +1 -1
  48. package/dist/target__runtime.mjs +2 -2
  49. package/package.json +10 -10
  50. package/dist/control-1-RnMe4V.d.mts.map +0 -1
  51. package/dist/control-B77seMDK.mjs.map +0 -1
  52. package/dist/migration-BMUh33vn.d.mts +0 -56
  53. package/dist/migration-BMUh33vn.d.mts.map +0 -1
  54. package/dist/migration-factories-oLRWgLGz-B9fWm8Wc.mjs.map +0 -1
  55. package/dist/op-factory-call-DzQ_ZxeZ-CukKyuhZ.d.mts +0 -115
  56. package/dist/op-factory-call-DzQ_ZxeZ-CukKyuhZ.d.mts.map +0 -1
  57. package/dist/{migration-C-jfTsGU.mjs → migration-psmPNv10.mjs} +1 -1
@@ -1,23 +1,27 @@
1
1
  import { t as mongoTargetError } from "./mongo-target-errors-Btf3ML1w-QOtEG7EX.mjs";
2
- import { t as mongoTargetDescriptorMeta } from "./descriptor-meta-CFsOxO6g-Ca8valmZ.mjs";
3
- import { a as dropCollection, c as renameField, d as unsetField, n as createCollection, o as dropIndex, r as createIndex, s as renameCollection, t as collMod, u as unrewritableFieldNameReason } from "./migration-factories-oLRWgLGz-B9fWm8Wc.mjs";
2
+ import { t as mongoTargetDescriptorMeta } from "./descriptor-meta-BXMz_uZd-B8WB2m7v.mjs";
3
+ import { a as createIndex, c as documentsNotOfType, d as fillField, f as isConvertTarget, g as renameField, h as renameCollection, i as createCollection, l as dropCollection, n as castsFrom, r as collMod, s as documentsMissingOrNull, t as castField, u as dropIndex, v as unrewritableFieldNameReason, y as unsetField } from "./migration-factories-C5ktmt8c-BP8k9SnZ.mjs";
4
+ import { assembleDataTypes } from "@prisma/orm-framework/components/codec";
5
+ import { bsonTypesOfCodec, temporaryValueOfCodec } from "@prisma/orm-family-mongo/contract/data-type";
4
6
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
5
7
  import { type } from "arktype";
6
8
  import { blindCast } from "@prisma/orm-framework/utils/casts";
7
9
  import { setFallbackTemporal } from "@prisma/orm-framework/type-implementations/temporal";
8
10
  import { NamespaceBase, UNBOUND_NAMESPACE_ID, elementCoordinates, freezeNode, hydrateNamespaceEntities } from "@prisma/orm-framework/components/ir";
9
- import { MongoCollection, MongoStorage, canonicalize, collectionControlPoliciesOf, collectionControlPolicyOf, collectionRootModelsOf, hasOwnFieldStoredAs, indexLookupKey, modelAndBasesOf, mongoModelsOf, ownEmbedStoredNamesOf, ownStoredNameOf, ownStoredNamesOf, validatorFieldNamesOf, validatorRootShapesOf } from "@prisma/orm-family-mongo/contract";
10
- import { CollModCommand, CreateCollectionCommand, CreateIndexCommand, DropCollectionCommand, DropIndexCommand, ListCollectionsCommand, ListIndexesCommand, MongoAndExpr, MongoExistsExpr, MongoFieldFilter, MongoNotExpr, MongoOrExpr, RenameCollectionCommand, isMongoDmlOperation } from "@prisma/orm-family-mongo/query-ast/control";
11
+ import { MongoCollection, MongoStorage, canonicalize, collectionControlPoliciesOf, collectionControlPolicyOf, collectionOfModel, defaultMongoIndexName, embeddingModelOf, hasOwnFieldStoredAs, indexLookupKey, modelAndBasesOf, modelFieldStoredAs, mongoModelsOf, otherModelsReached, ownEmbedStoredNamesOf, ownStoredNameOf, ownStoredNamesOf, propertyBsonTypesOf, validatorDocumentShapesOf, validatorFieldNamesOf, validatorRootShapesOf, variantFilterOf } from "@prisma/orm-family-mongo/contract";
12
+ import { CollModCommand, CreateCollectionCommand, CreateIndexCommand, DropCollectionCommand, DropIndexCommand, ListCollectionsCommand, ListIndexesCommand, MongoAndExpr, MongoExistsExpr, MongoFieldFilter, MongoNotExpr, MongoOrExpr, RenameCollectionCommand, isInspectionCheckSource, isMongoDmlOperation } from "@prisma/orm-family-mongo/query-ast/control";
11
13
  import { AggregateCommand, MongoAddFieldsStage, MongoLimitStage, MongoLookupStage, MongoMatchStage, MongoMergeStage, MongoProjectStage, MongoSortStage, RawAggregateCommand, RawDeleteManyCommand, RawDeleteOneCommand, RawFindOneAndDeleteCommand, RawFindOneAndUpdateCommand, RawInsertManyCommand, RawInsertOneCommand, RawUpdateManyCommand, RawUpdateOneCommand } from "@prisma/orm-family-mongo/query-ast/execution";
12
14
  import { canonicalizeSchemasForVerification, contractToMongoSchemaIR, diffMongoSchemas, fieldRewriteOf } from "@prisma/orm-family-mongo/family/control";
13
- import { APP_SPACE_ID, VERIFY_CODE_SCHEMA_FAILURE, contractSnapshotJsonSpecifier, contractSnapshotTypesSpecifier, describeMigrationStatement, expectAbsent, expectPresent, failedPostcheckWhy, failedPrecheckWhy, issueOutcome, migrationRunnerFailure, modelDisplayName, schemaCheckWhy, withDatabaseUnchanged, withFailingSpace } from "@prisma/orm-framework/components/control";
15
+ import { APP_SPACE_ID, VERIFY_CODE_SCHEMA_FAILURE, contractSnapshotJsonSpecifier, contractSnapshotTypesSpecifier, describeMigrationStatement, expectAbsent, expectPresent, extractCodecLookup, failedPostcheckWhy, failedPrecheckWhy, fieldStatementText, issueOutcome, migrationRunnerFailure, modelDisplayName, schemaCheckWhy, withDatabaseUnchanged, withFailingSpace } from "@prisma/orm-framework/components/control";
14
16
  import { notOk, ok } from "@prisma/orm-framework/utils/result";
15
17
  import { Temporal } from "temporal-polyfill/full/implementation";
16
18
  import { MongoContractSerializerBase, MongoSchemaVerifierBase } from "@prisma/orm-family-mongo/family/ir";
17
19
  import { composeMongoEntityKinds } from "@prisma/orm-family-mongo/contract/entity-kinds";
18
- import { asNamespaceId, governingControlPolicy } from "@prisma/orm-framework/contract/types";
20
+ import { asNamespaceId, governingControlPolicy, valueObjectAt, valueObjectsWithCoordinates } from "@prisma/orm-framework/contract/types";
19
21
  import { MongoSchemaCollection, MongoSchemaIR, deepEqual } from "@prisma/orm-family-mongo/schema-ir";
20
22
  import { InternalError } from "@prisma/orm-framework/utils/internal-error";
23
+ import { CliStructuredError } from "@prisma/orm-framework/errors/control";
24
+ import { errorUnfilledPlaceholder } from "@prisma/orm-framework/errors/migration";
21
25
  import { TsExpression, jsonToTsSource, renderImports } from "@prisma/orm-framework/ts-render";
22
26
  import { Migration } from "@prisma/orm-toolchain/migration-tools/migration";
23
27
  import { resolveRequirementSpecifiers } from "@prisma/orm-framework/components/emission";
@@ -149,6 +153,127 @@ var MongoTargetContractSerializer = class extends MongoContractSerializerBase {
149
153
  });
150
154
  }
151
155
  };
156
+ const SEPARATE_THE_MODELS = "move the models to separate collections, or carry out the change in a dataTransform operation of a migration.ts, with a filter that selects only their documents";
157
+ function sharedCollectionWhy(collection, others, change) {
158
+ const names = others.map((name) => JSON.stringify(name)).join(", ");
159
+ return `Collection ${JSON.stringify(collection)} stores several models and no discriminator tells their documents apart, so ${change} of ${names} too.`;
160
+ }
161
+ const TIME_SERIES_UPDATES = "MongoDB updates the documents of a time-series collection only through its metaField";
162
+ const WORDS = {
163
+ removal: {
164
+ conflictKind: "fieldRemovalRefused",
165
+ verb: "remove",
166
+ preposition: "from",
167
+ reaches: "holding",
168
+ timeSeries: "so the field cannot be removed from the documents that hold it. Keep the field in the contract, as an optional field if new documents leave it out, then run this command again.",
169
+ sharedChange: "removing the field would remove it from the documents",
170
+ sharedGoal: (_model, others) => `To keep it in ${others} documents only`
171
+ },
172
+ cast: {
173
+ conflictKind: "typeChangeRefused",
174
+ verb: "cast",
175
+ preposition: "in",
176
+ reaches: "holding",
177
+ timeSeries: "so the values of the field cannot be cast. Keep the field's type in the contract, then run this command again.",
178
+ sharedChange: "casting the field would cast it in the documents",
179
+ sharedGoal: (model) => `To change it in ${model} documents only`
180
+ },
181
+ conversion: {
182
+ conflictKind: "typeChangeRefused",
183
+ verb: "convert",
184
+ preposition: "in",
185
+ reaches: "holding",
186
+ timeSeries: "so a data transform cannot convert the values of the field. Keep the field's type in the contract, then run this command again.",
187
+ sharedChange: "the data transform would convert it in the documents",
188
+ sharedGoal: (model) => `To change it in ${model} documents only`
189
+ },
190
+ fill: {
191
+ conflictKind: "fieldFillRefused",
192
+ verb: "fill",
193
+ preposition: "in",
194
+ reaches: "selected",
195
+ timeSeries: "so the field cannot be filled in the documents. Make the field optional in the contract, then run this command again.",
196
+ sharedChange: "filling the field would add it to the documents",
197
+ sharedGoal: (model) => `To fill it in ${model} documents only`
198
+ },
199
+ backfill: {
200
+ conflictKind: "fieldFillRefused",
201
+ verb: "backfill",
202
+ preposition: "in",
203
+ reaches: "selected",
204
+ timeSeries: "so a data transform cannot fill the field. Make the field optional in the contract, then run this command again.",
205
+ sharedChange: "the data transform would fill it in the documents",
206
+ sharedGoal: (model) => `To fill it in ${model} documents only`
207
+ }
208
+ };
209
+ function quoted(names) {
210
+ return names.map((name) => JSON.stringify(name)).join(", ");
211
+ }
212
+ function timeSeriesRefusal(rewrite) {
213
+ const words = WORDS[rewrite.kind];
214
+ return {
215
+ kind: words.conflictKind,
216
+ summary: `Cannot ${words.verb} field ${JSON.stringify(rewrite.field)} ${words.preposition} collection ${JSON.stringify(rewrite.collection)}: it is a time-series collection`,
217
+ why: `${TIME_SERIES_UPDATES}, ${words.timeSeries}`
218
+ };
219
+ }
220
+ /**
221
+ * The refusal of a rewrite whose documents another model stored in the same collection shares:
222
+ * another root model when no discriminator value selects the rewrite's documents, or another root
223
+ * model's variant with the same discriminator field and value. A removal, cast or conversion reaches
224
+ * the models that hold the field; a fill or backfill reaches every model its filter selects. Without
225
+ * an origin contract, a cast in a collection whose validator describes several root models is
226
+ * refused, since nothing tells their documents apart.
227
+ */
228
+ function sharedCollectionRefusal(rewrite, contract, validator) {
229
+ const words = WORDS[rewrite.kind];
230
+ const { collection, field, model } = rewrite;
231
+ if (model === void 0) {
232
+ if (rewrite.kind === "removal" || validatorRootShapesOf(validator).length <= 1) return;
233
+ return {
234
+ kind: words.conflictKind,
235
+ summary: `Cannot ${words.verb} field ${JSON.stringify(field)} ${words.preposition} collection ${JSON.stringify(collection)}: the collection stores several root models`,
236
+ why: "No discriminator tells their documents apart, and without the origin contract the plan cannot tell which documents belong to the model that changed. Plan the change with migration plan --from <hash of the migration the database is at>."
237
+ };
238
+ }
239
+ const others = otherModelsReached(contract.domain, model, collection, rewrite.filter, words.reaches === "holding" ? field : void 0);
240
+ if (others.length === 0) return void 0;
241
+ const named = quoted(others);
242
+ const modelName = JSON.stringify(model.model);
243
+ return {
244
+ kind: words.conflictKind,
245
+ summary: `Cannot ${words.verb} field ${JSON.stringify(field)} of model ${modelName} ${words.preposition} collection ${JSON.stringify(collection)}: model ${named} ${words.reaches === "holding" ? "stores it" : "is stored"} in the same collection`,
246
+ why: `${sharedCollectionWhy(collection, others, words.sharedChange)} ${words.sharedGoal(modelName, named)}, ${SEPARATE_THE_MODELS}.`
247
+ };
248
+ }
249
+ /**
250
+ * Why the plan refuses a rewrite of its collection's documents: MongoDB does not let an update change
251
+ * a time-series collection's documents except through the metaField, and a rewrite must not change
252
+ * the documents of another model stored in the same collection. The planner refuses every rewrite it
253
+ * plans with these; the runner asks them before it names a statement that would plan one.
254
+ */
255
+ function rewriteRefusals(rewrite, contract, collection) {
256
+ const shared = sharedCollectionRefusal(rewrite, contract, collection.validator);
257
+ return [...collection.timeSeries ? [timeSeriesRefusal(rewrite)] : [], ...shared === void 0 ? [] : [shared]];
258
+ }
259
+ /**
260
+ * Mongo migration IR: one concrete `*Call` class per pure factory under
261
+ * `migration-factories.ts`, plus a shared `OpFactoryCallNode` abstract
262
+ * base. Every call class carries the literal arguments its backing
263
+ * factory would receive, computes a human-readable `label` in its
264
+ * constructor, and implements two polymorphic hooks:
265
+ *
266
+ * - `toOp()` — converts the IR node to a runtime
267
+ * `MongoMigrationPlanOperation` by delegating to the matching pure
268
+ * factory in `migration-factories.ts`.
269
+ * - `renderTypeScript()` / `importRequirements()` — inherited from
270
+ * `TsExpression`. Used by `renderCallsToTypeScript` to emit the call
271
+ * as a TypeScript expression inside the scaffolded `migration.ts`.
272
+ *
273
+ * The abstract base and all concrete classes are package-private.
274
+ * External consumers see only the framework-level `OpFactoryCall`
275
+ * interface and the `OpFactoryCall` union.
276
+ */
152
277
  /**
153
278
  * The single module a scaffolded Mongo `migration.ts` imports from: the
154
279
  * operation factories below, plus the `Migration` base and `MigrationCLI`
@@ -322,6 +447,115 @@ var UnsetFieldCall = class extends OpFactoryCallNode {
322
447
  return `unsetField(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.field)}${renderFilterOption(this.filter)})`;
323
448
  }
324
449
  };
450
+ var CastFieldCall = class extends OpFactoryCallNode {
451
+ factoryName = "castField";
452
+ collection;
453
+ field;
454
+ options;
455
+ operationClass;
456
+ label;
457
+ constructor(options) {
458
+ super();
459
+ this.collection = options.collection;
460
+ this.field = options.field;
461
+ this.options = options;
462
+ const op = this.toOp();
463
+ this.operationClass = op.operationClass;
464
+ this.label = op.label;
465
+ this.freeze();
466
+ }
467
+ toOp() {
468
+ return castField(this.options);
469
+ }
470
+ renderTypeScript() {
471
+ return `castField(${jsonToTsSource(this.options)})`;
472
+ }
473
+ };
474
+ /**
475
+ * A data transform the planner scaffolds for a field: its check and its run's filter select the
476
+ * documents still to change, and its update is a placeholder the user fills in `migration.ts`.
477
+ * Until then `toOp()` rejects with `MIGRATION.UNFILLED_PLACEHOLDER`, naming the operation it stands
478
+ * for, so the plan's other operations still list.
479
+ */
480
+ var DataTransformCall = class extends OpFactoryCallNode {
481
+ factoryName = "dataTransform";
482
+ operationClass = "data";
483
+ name;
484
+ collection;
485
+ filter;
486
+ label;
487
+ constructor(name, collection, filter) {
488
+ super();
489
+ this.name = name;
490
+ this.collection = collection;
491
+ this.filter = filter;
492
+ this.label = `Data transform: ${name}`;
493
+ this.freeze();
494
+ }
495
+ get slot() {
496
+ return `${this.name}:update`;
497
+ }
498
+ toOp() {
499
+ const unfilled = errorUnfilledPlaceholder(this.slot);
500
+ const operation = Promise.reject(new CliStructuredError(unfilled.code, unfilled.message, {
501
+ ...ifDefined("why", unfilled.why),
502
+ ...ifDefined("fix", unfilled.fix),
503
+ meta: {
504
+ slot: this.slot,
505
+ operation: {
506
+ id: `data_transform.${this.name}`,
507
+ label: this.label,
508
+ operationClass: this.operationClass
509
+ }
510
+ }
511
+ }));
512
+ operation.catch(() => void 0);
513
+ return operation;
514
+ }
515
+ renderTypeScript() {
516
+ const collection = jsonToTsSource(this.collection);
517
+ const filter = jsonToTsSource(this.filter);
518
+ return [
519
+ `dataTransform(${jsonToTsSource(this.name)}, {`,
520
+ ` check: { source: () => rawAggregate(${collection}, [{ $match: ${filter} }, { $limit: 1 }]) },`,
521
+ ` run: () => rawUpdateMany(${collection}, ${filter}, placeholder(${jsonToTsSource(this.slot)}), { bypassDocumentValidation: true }),`,
522
+ "})"
523
+ ].join("\n");
524
+ }
525
+ importRequirements() {
526
+ return [
527
+ "dataTransform",
528
+ "rawAggregate",
529
+ "rawUpdateMany",
530
+ "placeholder"
531
+ ].map((symbol) => ({
532
+ moduleSpecifier: TARGET_MIGRATION_MODULE,
533
+ symbol
534
+ }));
535
+ }
536
+ };
537
+ var FillFieldCall = class extends OpFactoryCallNode {
538
+ factoryName = "fillField";
539
+ operationClass = "widening";
540
+ collection;
541
+ field;
542
+ options;
543
+ label;
544
+ constructor(options) {
545
+ super();
546
+ this.collection = options.collection;
547
+ this.field = options.field;
548
+ this.options = options;
549
+ this.label = this.toOp().label;
550
+ this.freeze();
551
+ }
552
+ toOp() {
553
+ return fillField(this.options);
554
+ }
555
+ renderTypeScript() {
556
+ return `fillField(${jsonToTsSource(this.options)})`;
557
+ }
558
+ };
325
559
  var CollModCall = class extends OpFactoryCallNode {
326
560
  factoryName = "collMod";
327
561
  collection;
@@ -380,10 +614,15 @@ function schemaCollectionToCreateCollectionOptions(coll) {
380
614
  ...ifDefined("changeStreamPreAndPostImages", opts?.changeStreamPreAndPostImages)
381
615
  };
382
616
  }
383
- /** The collection a model stores its documents in; a model without `@@map` names it verbatim. */
384
- function collectionOf(contract, coordinate) {
385
- const collection = contract?.domain.namespaces[coordinate.namespaceId]?.models[coordinate.model]?.storage["collection"];
386
- return typeof collection === "string" ? collection : coordinate.model;
617
+ /** Why the plan does not rewrite the fields of the model at `coordinate`: its documents are embedded in another model's, if they are. */
618
+ function embeddedModelReason(contract, coordinate) {
619
+ const owner = embeddingModelOf(contract.domain, coordinate);
620
+ return owner === void 0 ? void 0 : `model "${modelDisplayName(coordinate)}" is embedded in the documents of model "${owner}"`;
621
+ }
622
+ const EMBEDDED_MODEL_WHY = "Fields of an embedded model are not rewritten in this release. Leave out this statement.";
623
+ /** Why a statement on `model` cannot be planned when no collection holds its documents. */
624
+ function noCollectionReason(model) {
625
+ return `model "${modelDisplayName(model)}" names no collection, and neither does a base or an owner`;
387
626
  }
388
627
  function modelAt(contract, coordinate) {
389
628
  const models = mongoModelsOf(contract.domain, coordinate.namespaceId);
@@ -400,21 +639,6 @@ function resolvedStoredNameAt(contract, coordinate) {
400
639
  if (storedName === void 0) throw new InternalError(`Field "${coordinate.model}.${coordinate.field}" a statement names has no stored name`);
401
640
  return storedName;
402
641
  }
403
- /**
404
- * The condition that selects a variant's documents in the collection it shares with its base: the
405
- * base's discriminator field holding the variant's value. A model that is not a variant has none.
406
- */
407
- function variantFilter(contract, coordinate) {
408
- const base = modelAt(contract, coordinate)?.base;
409
- if (base === void 0) return void 0;
410
- const baseModel = modelAt(contract, {
411
- namespaceId: asNamespaceId(base.namespace),
412
- model: base.model
413
- });
414
- const field = baseModel?.discriminator?.field;
415
- const value = Object.entries(baseModel?.variants ?? {}).find(([, variant]) => variant.namespace === coordinate.namespaceId && variant.model === coordinate.model)?.[0];
416
- return baseModel === void 0 || field === void 0 || value === void 0 ? void 0 : { [ownStoredNameOf(baseModel, field)]: value };
417
- }
418
642
  function declaredCollection(contract, collection) {
419
643
  return Object.values(contract.storage.namespaces).map((namespace) => namespace.entries["collection"]?.[collection]).find((entry) => entry instanceof MongoCollection);
420
644
  }
@@ -464,74 +688,6 @@ function refused(statement, label, reason, why) {
464
688
  };
465
689
  }
466
690
  const LEAVE_OUT = "Leave out this statement.";
467
- const SEPARATE_THE_MODELS = "move the models to separate collections, or carry out the change in a dataTransform operation of a migration.ts, with a filter that selects only their documents";
468
- /**
469
- * The discriminator field and value a variant's filter selects, or `undefined` for a filter that selects by anything else, or no filter.
470
- */
471
- function discriminatorValueOf(filter) {
472
- const entries = Object.entries(filter ?? {});
473
- if (entries.length !== 1) return void 0;
474
- const [entry] = entries;
475
- if (entry === void 0) return void 0;
476
- const [field, value] = entry;
477
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? {
478
- field,
479
- value
480
- } : void 0;
481
- }
482
- /**
483
- * The other models stored in `collection`, root models and their variants, whose documents a change of `storedName` with `filter` reaches, and which store the field themselves or through their base. No discriminator tells the documents of several root models apart, so without a filter, or with a base model's filter, every other root model's documents are reached. A variant's filter, one discriminator value, reaches a model only when its documents can hold that value: a variant of another root model with the same discriminator field and value, or a model that declares the discriminator field itself.
484
- */
485
- function otherModelsReached(contract, model, collection, filter, storedName) {
486
- const models = mongoModelsOf(contract.domain, model.namespaceId);
487
- const baseOf = (name) => {
488
- const base = models[name]?.base;
489
- return base === void 0 ? void 0 : models[base.model];
490
- };
491
- const storesOrInherits = (name, storedName) => modelAndBasesOf(models, name).some((each) => ownStores(each, storedName));
492
- const selected = discriminatorValueOf(filter);
493
- const canHold = (name) => {
494
- if (selected === void 0) return true;
495
- const base = baseOf(name);
496
- const discriminator = base?.discriminator?.field;
497
- if (base !== void 0 && discriminator !== void 0 && ownStoredNameOf(base, discriminator) === selected.field) return Object.entries(base.variants ?? {}).some(([value, variant]) => variant.model === name && value === selected.value);
498
- return storesOrInherits(name, selected.field);
499
- };
500
- const subjectRoot = modelAt(contract, model)?.base?.model ?? model.model;
501
- return (collectionRootModelsOf(models)[collection] ?? []).filter((name) => name !== subjectRoot).flatMap((name) => [name, ...Object.values(models[name]?.variants ?? {}).map((variant) => variant.model)]).filter((name) => canHold(name) && storesOrInherits(name, storedName));
502
- }
503
- function sharedCollectionWhy(collection, others, change) {
504
- const names = others.map((name) => JSON.stringify(name)).join(", ");
505
- return `Collection ${JSON.stringify(collection)} stores several models and no discriminator tells their documents apart, so ${change} of ${names} too.`;
506
- }
507
- /**
508
- * A removal the plan cannot carry out because another root model stored in the same collection still stores the field, and no discriminator selects the documents of the model that loses it.
509
- */
510
- function sharedCollectionRemovalRefusals(removals, contract) {
511
- return removals.flatMap((removal) => {
512
- const { subject, call } = removal;
513
- if (subject.kind !== "field") return [];
514
- const others = otherModelsReached(contract, subject, call.collection, call.filter, call.field);
515
- if (others.length === 0) return [];
516
- return [{
517
- kind: "fieldRemovalRefused",
518
- summary: `Cannot remove field ${JSON.stringify(call.field)} of model ${JSON.stringify(subject.model)} from collection ${JSON.stringify(call.collection)}: model ${others.map((name) => JSON.stringify(name)).join(", ")} stores it in the same collection`,
519
- why: `${sharedCollectionWhy(call.collection, others, "removing the field would remove it from the documents")} To keep it in ${others.map((name) => JSON.stringify(name)).join(", ")} documents only, ${SEPARATE_THE_MODELS}.`
520
- }];
521
- });
522
- }
523
- const TIME_SERIES_UPDATES = "MongoDB updates the documents of a time-series collection only through its metaField";
524
- /**
525
- * A removal the plan cannot carry out because its collection is a time-series collection, whose
526
- * documents MongoDB does not let an update change except through the metaField.
527
- */
528
- function timeSeriesRemovalRefusals(removals, schema) {
529
- return removals.filter((removal) => schema.collection(removal.call.collection)?.options?.timeseries !== void 0).map((removal) => ({
530
- kind: "fieldRemovalRefused",
531
- summary: `Cannot remove field ${JSON.stringify(removal.call.field)} from collection ${JSON.stringify(removal.call.collection)}: it is a time-series collection`,
532
- why: `${TIME_SERIES_UPDATES}, so the field cannot be removed from the documents that hold it. Keep the field in the contract, as an optional field if new documents leave it out, then run this command again.`
533
- }));
534
- }
535
691
  /**
536
692
  * Plans the rename each statement states, in order: a model statement whose collection changes renames the
537
693
  * collection in the schema the diff then starts from, and a field statement whose stored name
@@ -608,8 +764,8 @@ function controlPolicyRefusal(statement, label, contract, collection) {
608
764
  * documents keep the old value, which the new validator does not accept.
609
765
  */
610
766
  function discriminatorValueChange(statement, input) {
611
- const before = variantFilter(input.fromContract, statement.from);
612
- const after = variantFilter(input.contract, statement.to);
767
+ const before = variantFilterOf(input.fromContract.domain, statement.from);
768
+ const after = variantFilterOf(input.contract.domain, statement.to);
613
769
  const base = modelAt(input.contract, statement.to)?.base;
614
770
  if (before === void 0 || after === void 0 || base === void 0) return void 0;
615
771
  const [field, oldValue] = Object.entries(before)[0] ?? [];
@@ -620,13 +776,22 @@ function discriminatorValueChange(statement, input) {
620
776
  return [`its discriminator value changes from ${JSON.stringify(oldValue)} to ${JSON.stringify(newValue)}`, `The documents of "${fromName}" hold ${field} ${JSON.stringify(oldValue)}, and this release does not rewrite a discriminator value, so they would no longer match "${toName}" and would fail validation. Keep the value: declare "${toName}" with @@base(${base.model}, ${JSON.stringify(oldValue)}). A later release changes a stored value with --convert.`];
621
777
  }
622
778
  function planModelStatement(statement, label, schema, input) {
779
+ const embedded = embeddedModelReason(input.fromContract, statement.from) ?? embeddedModelReason(input.contract, statement.to);
780
+ if (embedded !== void 0) return {
781
+ kind: "refused",
782
+ conflict: refused(statement, label, embedded, `Embedded models are not renamed in this release. ${LEAVE_OUT}`)
783
+ };
623
784
  const discriminatorChange = discriminatorValueChange(statement, input);
624
785
  if (discriminatorChange !== void 0) return {
625
786
  kind: "refused",
626
787
  conflict: refused(statement, label, ...discriminatorChange)
627
788
  };
628
- const from = collectionOf(input.fromContract, statement.from);
629
- const to = collectionOf(input.contract, statement.to);
789
+ const from = collectionOfModel(input.fromContract.domain, statement.from);
790
+ const to = collectionOfModel(input.contract.domain, statement.to);
791
+ if (from === void 0 || to === void 0) return {
792
+ kind: "refused",
793
+ conflict: refused(statement, label, noCollectionReason(from === void 0 ? statement.from : statement.to), `A statement renames the documents of a model in its collection. Give the model a collection, then run this command again, or ${LEAVE_OUT.toLowerCase()}`)
794
+ };
630
795
  if (from === to) return { kind: "unchanged" };
631
796
  const policyRefusal = controlPolicyRefusal(statement, label, input.contract, to);
632
797
  if (policyRefusal !== void 0) return policyRefusal;
@@ -650,6 +815,8 @@ function planFieldStatement(statement, label, renamedCollections, schema, input)
650
815
  kind: "refused",
651
816
  conflict: refused(statement, label, reason, why)
652
817
  });
818
+ const embedded = embeddedModelReason(input.fromContract, statement.from) ?? embeddedModelReason(input.contract, statement.to);
819
+ if (embedded !== void 0) return refuse(embedded, EMBEDDED_MODEL_WHY);
653
820
  const fromField = storedField(modelAt(input.fromContract, statement.from), statement.from.field);
654
821
  const toField = storedField(modelAt(input.contract, statement.to), statement.to.field);
655
822
  if (fromField.kind === "embed" || toField.kind === "embed") return refuse("the field is an embedded relation", `Renaming an embedded relation is not supported in this release. ${LEAVE_OUT}`);
@@ -657,9 +824,10 @@ function planFieldStatement(statement, label, renamedCollections, schema, input)
657
824
  if (fromField.kind !== "field" || toField.kind !== "field") return refuse("the field is stored in documents on one side of the statement only", `A relation is not stored in documents, so a statement cannot rename a field to or from one. ${LEAVE_OUT}`);
658
825
  const fromStored = resolvedStoredNameAt(input.fromContract, statement.from);
659
826
  const toStored = resolvedStoredNameAt(input.contract, statement.to);
660
- const originCollection = collectionOf(input.fromContract, statement.from);
827
+ const originCollection = collectionOfModel(input.fromContract.domain, statement.from);
828
+ const destinationCollection = collectionOfModel(input.contract.domain, statement.to);
829
+ if (originCollection === void 0 || destinationCollection === void 0) return refuse(noCollectionReason(originCollection === void 0 ? statement.from : statement.to), `A statement renames a field in the documents of its model's collection. ${LEAVE_OUT}`);
661
830
  const collection = renamedCollections.get(originCollection) ?? originCollection;
662
- const destinationCollection = collectionOf(input.contract, statement.to);
663
831
  if (fromStored === toStored && collection === destinationCollection) return { kind: "unchanged" };
664
832
  if (fromStored === "_id" || toStored === "_id") return refuse("it renames _id", `MongoDB does not let a document change its _id. ${LEAVE_OUT}`);
665
833
  const unsafeFrom = unrewritableFieldNameReason(fromStored);
@@ -670,9 +838,9 @@ function planFieldStatement(statement, label, renamedCollections, schema, input)
670
838
  if (schema.collection(collection)?.options?.timeseries !== void 0) return refuse(`collection "${collection}" is a time-series collection`, `${TIME_SERIES_UPDATES}, so a statement cannot move the values of a field in them. Keep the stored name: store the field as ${JSON.stringify(fromStored)} (with @map(${JSON.stringify(fromStored)}) in PSL), then run this command again without this statement.`);
671
839
  const policyRefusal = controlPolicyRefusal(statement, label, input.contract, collection);
672
840
  if (policyRefusal !== void 0) return policyRefusal;
673
- const variant = variantFilter(input.fromContract, statement.from);
841
+ const variant = variantFilterOf(input.fromContract.domain, statement.from);
674
842
  const renamedTogether = new Set(input.statements.flatMap((other) => other.entity === "field" && other.from.namespaceId === statement.from.namespaceId && storedFieldNameAt(input.fromContract, other.from) === fromStored && storedFieldNameAt(input.contract, other.to) === toStored ? [other.from.model] : []));
675
- const others = otherModelsReached(input.fromContract, statement.from, originCollection, variant, fromStored).filter((name) => !renamedTogether.has(name));
843
+ const others = otherModelsReached(input.fromContract.domain, statement.from, originCollection, variant, fromStored).filter((name) => !renamedTogether.has(name));
676
844
  if (others.length > 0) return refuse(`model ${others.map((name) => JSON.stringify(name)).join(", ")} stores field ${JSON.stringify(fromStored)} in the same collection, ${JSON.stringify(collection)}`, `${sharedCollectionWhy(collection, others, "renaming the field would rename it in the documents")} To change it, ${SEPARATE_THE_MODELS}.`);
677
845
  return {
678
846
  kind: "renameField",
@@ -710,12 +878,33 @@ function destinationModelOf(origin, input) {
710
878
  const renamed = input.statements.find((statement) => statement.entity === "model" && sameModel(statement.from, origin));
711
879
  if (renamed !== void 0) return renamed.to;
712
880
  if (modelAt(input.contract, origin) !== void 0) return origin;
713
- const collection = input.collectionAfterRenames(collectionOf(input.fromContract, origin));
714
- const filter = JSON.stringify(variantFilter(input.fromContract, origin) ?? null);
715
- const stored = modelCoordinates(input.contract).filter((candidate) => collectionOf(input.contract, candidate) === collection && JSON.stringify(variantFilter(input.contract, candidate) ?? null) === filter);
881
+ if (embeddingModelOf(input.fromContract.domain, origin) !== void 0) return void 0;
882
+ const originCollection = collectionOfModel(input.fromContract.domain, origin);
883
+ if (originCollection === void 0) return void 0;
884
+ const collection = input.collectionAfterRenames(originCollection);
885
+ const filter = JSON.stringify(variantFilterOf(input.fromContract.domain, origin) ?? null);
886
+ const stored = modelCoordinates(input.contract).filter((candidate) => embeddingModelOf(input.contract.domain, candidate) === void 0 && collectionOfModel(input.contract.domain, candidate) === collection && JSON.stringify(variantFilterOf(input.contract.domain, candidate) ?? null) === filter);
716
887
  const [only] = stored;
717
888
  return stored.length === 1 ? only : void 0;
718
889
  }
890
+ /** The origin model a destination model was, by the rules of `destinationModelOf`, read the other way. */
891
+ function originModelOf(destination, input) {
892
+ return modelCoordinates(input.fromContract).find((origin) => {
893
+ const matched = destinationModelOf(origin, input);
894
+ return matched !== void 0 && sameModel(matched, destination);
895
+ });
896
+ }
897
+ function sameField$1(a, b) {
898
+ return sameModel(a, b) && a.field === b.field;
899
+ }
900
+ /** The name a field of the origin has in the destination: its rename statement's new name, else its own. */
901
+ function destinationFieldOf(origin, statements) {
902
+ return statements.find((statement) => statement.entity === "field" && sameField$1(statement.from, origin))?.to.field ?? origin.field;
903
+ }
904
+ /** The name a field of the destination had in the origin: its rename statement's old name, else its own. */
905
+ function originFieldOf(destination, statements) {
906
+ return statements.find((statement) => statement.entity === "field" && sameField$1(statement.to, destination))?.from.field ?? destination.field;
907
+ }
719
908
  function renamedByStatement(input, field) {
720
909
  return input.statements.some((statement) => statement.entity === "field" && sameModel(statement.from, field) && statement.from.field === field.field);
721
910
  }
@@ -756,14 +945,17 @@ function rootDocumentsLosing(contract, root, storedName) {
756
945
  */
757
946
  function planFieldRemovals(input) {
758
947
  return modelCoordinates(input.fromContract).flatMap((origin) => {
759
- const collection = input.collectionAfterRenames(collectionOf(input.fromContract, origin));
948
+ if (embeddingModelOf(input.fromContract.domain, origin) !== void 0) return [];
949
+ const originCollection = collectionOfModel(input.fromContract.domain, origin);
950
+ if (originCollection === void 0) return [];
951
+ const collection = input.collectionAfterRenames(originCollection);
760
952
  if (!input.keptCollections.has(collection)) return [];
761
953
  if (collectionControlPolicy(input.contract, collection) !== "managed") return [];
762
954
  const destination = destinationModelOf(origin, input);
763
955
  if (destination === void 0) return [];
764
956
  const model = modelAt(input.fromContract, origin);
765
957
  if (model === void 0) return [];
766
- const variant = variantFilter(input.fromContract, origin);
958
+ const variant = variantFilterOf(input.fromContract.domain, origin);
767
959
  const losing = (storedName) => {
768
960
  if (variant !== void 0) return storedFieldsOf(input.contract, destination).has(storedName) ? void 0 : { filter: variant };
769
961
  return rootDocumentsLosing(input.contract, destination, storedName);
@@ -803,6 +995,491 @@ function planValidatorFieldRemovals(input) {
803
995
  }));
804
996
  });
805
997
  }
998
+ function refuse(statement, reason, why, contracts) {
999
+ return {
1000
+ kind: "refused",
1001
+ conflict: {
1002
+ kind: "statementRefused",
1003
+ summary: `Cannot ${describeMigrationStatement(statement, contracts.fromContract, contracts.contract)}: ${reason}`,
1004
+ why,
1005
+ refusedStatement: statement
1006
+ }
1007
+ };
1008
+ }
1009
+ function withFilter(filter, condition) {
1010
+ return filter === void 0 ? condition : { $and: [filter, condition] };
1011
+ }
1012
+ /** Why the plan cannot rewrite a field of the destination contract, if it cannot. */
1013
+ function unrewritableReason(contract, field) {
1014
+ const model = modelAt(contract, field);
1015
+ if (model === void 0 || !Object.hasOwn(model.fields, field.field)) return void 0;
1016
+ const collection = collectionOfModel(contract.domain, field);
1017
+ if (collection === void 0) return noCollectionReason(field);
1018
+ const storedName = ownStoredNameOf(model, field.field);
1019
+ const nameReason = unrewritableFieldNameReason(storedName);
1020
+ if (nameReason !== void 0) return `its stored name ${JSON.stringify(storedName)} cannot be rewritten: ${nameReason}`;
1021
+ const policy = collectionControlPolicy(contract, collection);
1022
+ return policy === "managed" ? void 0 : `collection ${JSON.stringify(collection)} has control policy ${JSON.stringify(policy)}`;
1023
+ }
1024
+ /**
1025
+ * The data transform of `--convert`: its check and its run select the documents whose field holds
1026
+ * a type the new field does not allow, and the user writes the update.
1027
+ */
1028
+ function convertTransform(statement, change, contracts) {
1029
+ const embedded = embeddedModelReason(contracts.contract, statement.field);
1030
+ if (embedded !== void 0) return refuse(statement, embedded, EMBEDDED_MODEL_WHY, contracts);
1031
+ const unrewritable = unrewritableReason(contracts.contract, statement.field);
1032
+ if (unrewritable !== void 0) return refuse(statement, unrewritable, "Leave out this statement.", contracts);
1033
+ if (change === void 0) return refuse(statement, "its type does not change", "Leave out this statement.", contracts);
1034
+ const notOfType = documentsNotOfType(change.field, {
1035
+ types: change.to.list && !change.from.list ? ["array"] : change.to.types,
1036
+ list: change.to.list && change.from.list
1037
+ });
1038
+ return {
1039
+ kind: "transform",
1040
+ call: new DataTransformCall(fieldStatementText(contracts.contract, statement.field), change.collection, withFilter(change.filter, notOfType)),
1041
+ rewrite: {
1042
+ kind: "conversion",
1043
+ collection: change.collection,
1044
+ field: change.field,
1045
+ filter: change.filter,
1046
+ model: change.destination
1047
+ }
1048
+ };
1049
+ }
1050
+ /** Whether the origin already had the field and made it required. */
1051
+ function requiredInOrigin(input, collection, field, storedName) {
1052
+ if (input.match === void 0) {
1053
+ const declaring = validatorDocumentShapesOf(input.schema.collection(collection)?.validator?.jsonSchema).filter((shape) => Object.hasOwn(shape.properties, storedName));
1054
+ return declaring.length > 0 && declaring.every((shape) => shape.required.includes(storedName));
1055
+ }
1056
+ const origin = originModelOf(field, input.match);
1057
+ const model = origin === void 0 ? void 0 : modelAt(input.match.fromContract, origin);
1058
+ const originField = originFieldOf(field, input.match.statements);
1059
+ return model !== void 0 && Object.hasOwn(model.fields, originField) ? model.fields[originField]?.nullable === false : false;
1060
+ }
1061
+ /**
1062
+ * The data transform of `--backfill`: a required field that is new on an existing collection, or
1063
+ * was optional. Its check and its run select the documents where the field is missing or `null`,
1064
+ * and the user writes the update.
1065
+ */
1066
+ function backfillTransform(statement, input) {
1067
+ const contracts = {
1068
+ fromContract: input.match?.fromContract ?? input.contract,
1069
+ contract: input.contract
1070
+ };
1071
+ const model = modelAt(input.contract, statement.field);
1072
+ const definition = model?.fields[statement.field.field];
1073
+ if (model === void 0 || definition === void 0) return refuse(statement, "the destination has no such field", "Leave out this statement.", contracts);
1074
+ if (definition.nullable) return refuse(statement, "it is optional", "Only a required field needs a value in every document. Leave out this statement.", contracts);
1075
+ const embedded = embeddedModelReason(input.contract, statement.field);
1076
+ if (embedded !== void 0) return refuse(statement, embedded, EMBEDDED_MODEL_WHY, contracts);
1077
+ const unrewritable = unrewritableReason(input.contract, statement.field);
1078
+ if (unrewritable !== void 0) return refuse(statement, unrewritable, "Leave out this statement.", contracts);
1079
+ const collection = collectionOfModel(input.contract.domain, statement.field);
1080
+ if (collection === void 0) return refuse(statement, noCollectionReason(statement.field), "Leave out this statement.", contracts);
1081
+ if (input.schema.collection(collection) === void 0) return refuse(statement, `collection "${collection}" is new, so it has no documents to fill`, "Leave out this statement.", contracts);
1082
+ const storedName = ownStoredNameOf(model, statement.field.field);
1083
+ if (requiredInOrigin(input, collection, statement.field, storedName)) return refuse(statement, "it was already required", "Every document already has a value for it. Leave out this statement.", contracts);
1084
+ const variant = variantFilterOf(input.contract.domain, statement.field);
1085
+ return {
1086
+ kind: "transform",
1087
+ call: new DataTransformCall(fieldStatementText(input.contract, statement.field), collection, withFilter(variant, documentsMissingOrNull(storedName))),
1088
+ rewrite: {
1089
+ kind: "backfill",
1090
+ collection,
1091
+ field: storedName,
1092
+ filter: variant,
1093
+ model: statement.field
1094
+ }
1095
+ };
1096
+ }
1097
+ const NOT_A_STATEMENT = "No statement (--rename, --delete, --convert, --backfill) covers this change, so the plan does not rewrite the documents. Write a dataTransform in migration.ts, before the validator change, that rewrites them to fit; until they fit, the validator change checks the documents and fails the apply. With db update, plan the change with migration plan instead.";
1098
+ function warning(summary) {
1099
+ return {
1100
+ kind: "documentsNotRewritten",
1101
+ summary,
1102
+ why: NOT_A_STATEMENT
1103
+ };
1104
+ }
1105
+ function typeKey(field) {
1106
+ const { type } = field;
1107
+ const many = field.many !== void 0 && field.many !== false;
1108
+ if (type.kind === "scalar") return JSON.stringify([
1109
+ "scalar",
1110
+ type.codecId,
1111
+ many
1112
+ ]);
1113
+ if (type.kind === "valueObject") return JSON.stringify([
1114
+ "valueObject",
1115
+ type.namespaceId,
1116
+ type.entityName,
1117
+ many
1118
+ ]);
1119
+ return JSON.stringify(["union", many]);
1120
+ }
1121
+ function valueSetName(field) {
1122
+ return field.valueSet?.entityName;
1123
+ }
1124
+ function valueObjectName(field) {
1125
+ return field.type.kind === "valueObject" ? field.type.entityName : void 0;
1126
+ }
1127
+ /** What changes for a field kept by both contracts that the plan does not rewrite, in words. */
1128
+ function untouchedChange(name, before, after) {
1129
+ const enumBefore = valueSetName(before);
1130
+ const enumAfter = valueSetName(after);
1131
+ if (enumAfter !== void 0 && enumBefore === void 0) return `Field "${name}" gains enum "${enumAfter}"`;
1132
+ if (enumAfter !== void 0 && enumBefore !== void 0 && enumAfter !== enumBefore) return `Field "${name}" changes from enum "${enumBefore}" to enum "${enumAfter}"`;
1133
+ const objectBefore = valueObjectName(before);
1134
+ const objectAfter = valueObjectName(after);
1135
+ if (objectBefore !== void 0 && objectAfter !== void 0 && objectBefore !== objectAfter) return `Field "${name}" moves from value object "${objectBefore}" to value object "${objectAfter}"`;
1136
+ if (objectBefore === void 0 && objectAfter !== void 0 && before.type.kind === "scalar") return `Field "${name}" changes from a scalar to value object "${objectAfter}"`;
1137
+ if (objectBefore !== void 0 && objectAfter === void 0 && after.type.kind === "scalar") return `Field "${name}" changes from value object "${objectBefore}" to a scalar`;
1138
+ }
1139
+ /**
1140
+ * What changes for each field of an embedded model, whose documents the plan does not rewrite: a
1141
+ * field removed, a field whose type changes, and a required field that is new or was optional.
1142
+ */
1143
+ function embeddedModelChanges(fieldName, model, before, after) {
1144
+ const named = (field) => `Field "${fieldName(field)}" of embedded model "${model}"`;
1145
+ const kept = Object.entries(after.fields).flatMap(([field, definition]) => {
1146
+ const previous = Object.hasOwn(before.fields, field) ? before.fields[field] : void 0;
1147
+ if (previous === void 0) return definition.nullable ? [] : [`${named(field)} is new and required`];
1148
+ if (typeKey(previous) !== typeKey(definition)) return [`${named(field)} changes type`];
1149
+ return previous.nullable && !definition.nullable ? [`${named(field)} becomes required`] : [];
1150
+ });
1151
+ const removed = Object.keys(before.fields).filter((field) => !Object.hasOwn(after.fields, field)).map((field) => `${named(field)} is removed`);
1152
+ return [...kept, ...removed];
1153
+ }
1154
+ /**
1155
+ * The changes the plan does not rewrite the documents for, and that are not statements: a change to
1156
+ * a field of an embedded model, a field of a value object whose type changes, a field that moves to
1157
+ * another value object or between a scalar and a value object, and a field that gains an enum or
1158
+ * changes enum. Each is a warning that names the field; the validator change's document check then
1159
+ * fails the apply until the documents fit.
1160
+ */
1161
+ function documentsNotRewrittenWarnings(input) {
1162
+ const modelFields = modelCoordinates(input.contract).flatMap((model) => {
1163
+ const after = modelAt(input.contract, model);
1164
+ const origin = originModelOf(model, input);
1165
+ const before = origin === void 0 ? void 0 : modelAt(input.fromContract, origin);
1166
+ if (after === void 0 || before === void 0) return [];
1167
+ if (embeddedModelReason(input.contract, model) !== void 0) {
1168
+ const fieldName = (field) => fieldStatementText(input.contract, {
1169
+ ...model,
1170
+ field
1171
+ });
1172
+ return embeddedModelChanges(fieldName, model.model, before, after).map(warning);
1173
+ }
1174
+ return Object.entries(after.fields).flatMap(([field, definition]) => {
1175
+ const originField = originFieldOf({
1176
+ ...model,
1177
+ field
1178
+ }, input.statements);
1179
+ if (!Object.hasOwn(before.fields, originField)) return [];
1180
+ const previous = before.fields[originField];
1181
+ const change = previous === void 0 ? void 0 : untouchedChange(fieldStatementText(input.contract, {
1182
+ ...model,
1183
+ field
1184
+ }), previous, definition);
1185
+ return change === void 0 ? [] : [warning(change)];
1186
+ });
1187
+ });
1188
+ const valueObjectFields = valueObjectsWithCoordinates(input.contract.storage).flatMap(({ coordinate, valueObject }) => {
1189
+ const before = valueObjectAt(input.fromContract.storage, coordinate);
1190
+ if (before === void 0) return [];
1191
+ return Object.entries(valueObject.fields).flatMap(([field, definition]) => {
1192
+ const previous = Object.hasOwn(before.fields, field) ? before.fields[field] : void 0;
1193
+ if (previous === void 0) return [];
1194
+ const name = `${coordinate.entityName}.${field}`;
1195
+ const change = untouchedChange(name, previous, definition) ?? (typeKey(previous) === typeKey(definition) ? void 0 : `Field "${name}" of a value object changes type`);
1196
+ return change === void 0 ? [] : [warning(change)];
1197
+ });
1198
+ });
1199
+ return [...modelFields, ...valueObjectFields];
1200
+ }
1201
+ const EMPTY_LIST = {
1202
+ expression: [],
1203
+ text: "[]"
1204
+ };
1205
+ function temporaryValueOf(field, lookups) {
1206
+ if (field.many !== void 0 && field.many !== false) return EMPTY_LIST;
1207
+ if (field.type.kind !== "scalar" || field.valueSet !== void 0 || field.dict === true) return;
1208
+ return temporaryValueOfCodec(field.type.codecId, lookups);
1209
+ }
1210
+ function backfilled(statements, field) {
1211
+ return statements.some((statement) => statement.kind === "backfill" && statement.entity === "field" && statement.field.namespaceId === field.namespaceId && statement.field.model === field.model && statement.field.field === field.field);
1212
+ }
1213
+ /** Whether the origin stored the field: in the origin model, or, without an origin contract, in the origin validator. */
1214
+ function inOrigin(input, field, collection, storedName) {
1215
+ if (input.match === void 0) {
1216
+ const validator = input.schema.collection(collection)?.validator;
1217
+ return validator === void 0 || validatorFieldNamesOf(validator.jsonSchema).has(storedName);
1218
+ }
1219
+ const origin = originModelOf(field, input.match);
1220
+ const model = origin === void 0 ? void 0 : modelAt(input.match.fromContract, origin);
1221
+ return origin === void 0 || model === void 0 || Object.hasOwn(model.fields, originFieldOf(field, input.match.statements)) || storedFieldsOf(input.match.fromContract, origin).has(storedName);
1222
+ }
1223
+ /** Whether a unique index covers the field, so that one value in every document would break it. */
1224
+ function underUniqueIndex(destination, collection, storedName) {
1225
+ return (destination.collection(collection)?.indexes ?? []).some((index) => index.unique && index.keys.some((key) => key.field === storedName));
1226
+ }
1227
+ /**
1228
+ * Each required field of the destination that is new on a collection the plan keeps, with the
1229
+ * temporary value its type declares, unless a `--backfill` statement names it. A field whose type
1230
+ * declares none, or that a unique index covers, is left to the validator change's document check.
1231
+ */
1232
+ function planFieldFills(input) {
1233
+ return modelCoordinates(input.contract).flatMap((model) => {
1234
+ const definition = modelAt(input.contract, model);
1235
+ const collection = collectionOfModel(input.contract.domain, model);
1236
+ if (definition === void 0 || collection === void 0 || embeddedModelReason(input.contract, model) !== void 0) return [];
1237
+ if (input.schema.collection(collection) === void 0) return [];
1238
+ if (collectionControlPolicy(input.contract, collection) !== "managed") return [];
1239
+ return Object.entries(definition.fields).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).flatMap(([field, contractField]) => {
1240
+ const coordinate = {
1241
+ ...model,
1242
+ field
1243
+ };
1244
+ const storedName = ownStoredNameOf(definition, field);
1245
+ if (contractField.nullable || unrewritableFieldNameReason(storedName) !== void 0) return [];
1246
+ if (backfilled(input.statements, coordinate)) return [];
1247
+ if (inOrigin(input, coordinate, collection, storedName)) return [];
1248
+ if (underUniqueIndex(input.destination, collection, storedName)) return [];
1249
+ const value = temporaryValueOf(contractField, input.lookups);
1250
+ if (value === void 0) return [];
1251
+ const filter = variantFilterOf(input.contract.domain, model);
1252
+ return [{
1253
+ call: new FillFieldCall({
1254
+ collection,
1255
+ field: storedName,
1256
+ value: value.expression,
1257
+ ...filter === void 0 ? {} : { filter }
1258
+ }),
1259
+ subject: {
1260
+ kind: "field",
1261
+ ...coordinate
1262
+ },
1263
+ text: value.text
1264
+ }];
1265
+ });
1266
+ });
1267
+ }
1268
+ function withoutNull(types) {
1269
+ return types.filter((type) => type !== "null");
1270
+ }
1271
+ function fieldShapeOf(field, lookups) {
1272
+ if (field?.type.kind !== "scalar" || field.dict === true) return void 0;
1273
+ const types = bsonTypesOfCodec(field.type.codecId, lookups);
1274
+ return types === void 0 ? void 0 : {
1275
+ types: withoutNull(types),
1276
+ list: field.many !== void 0 && field.many !== false
1277
+ };
1278
+ }
1279
+ function isRecord$1(value) {
1280
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1281
+ }
1282
+ function bsonTypesOf(schema) {
1283
+ return withoutNull(propertyBsonTypesOf(schema));
1284
+ }
1285
+ function isObjectSchema(schema) {
1286
+ return [
1287
+ "properties",
1288
+ "oneOf",
1289
+ "anyOf"
1290
+ ].some((keyword) => Object.hasOwn(schema, keyword));
1291
+ }
1292
+ /** The shape a validator's property schema gives a field; `undefined` for an object, whose fields are not compared here. */
1293
+ function propertyShapeOf(schema) {
1294
+ if (!isRecord$1(schema) || isObjectSchema(schema)) return void 0;
1295
+ const types = bsonTypesOf(schema);
1296
+ const items = schema["items"];
1297
+ if (types.length === 1 && types[0] === "array" && isRecord$1(items)) return isObjectSchema(items) ? void 0 : {
1298
+ types: bsonTypesOf(items),
1299
+ list: true
1300
+ };
1301
+ return {
1302
+ types,
1303
+ list: false
1304
+ };
1305
+ }
1306
+ /** Whether a field of shape `to` takes every value a field of shape `from` holds. */
1307
+ function takesEveryValue(from, to) {
1308
+ if (to.types.length === 0 && !to.list) return true;
1309
+ if (from.list !== to.list) return false;
1310
+ if (to.types.length === 0) return true;
1311
+ return from.types.length > 0 && from.types.every((type) => to.types.includes(type));
1312
+ }
1313
+ function castOptions(from, to) {
1314
+ const [target, ...others] = to.types;
1315
+ if (from.types.length === 0) return void 0;
1316
+ if (from.list !== to.list || target === void 0 || others.length > 0) return void 0;
1317
+ if (!isConvertTarget(target) || !from.types.every((type) => castsFrom(type, target))) return;
1318
+ return {
1319
+ from: from.types,
1320
+ to: target,
1321
+ ...to.list ? { list: true } : {}
1322
+ };
1323
+ }
1324
+ function typeChange(input) {
1325
+ return {
1326
+ ...input,
1327
+ cast: castOptions(input.from, input.to)
1328
+ };
1329
+ }
1330
+ /** The `castField` call that carries out a type change, when it has a cast. */
1331
+ function castFieldCallOf(change) {
1332
+ return change.cast === void 0 ? void 0 : new CastFieldCall({
1333
+ collection: change.collection,
1334
+ field: change.field,
1335
+ ...change.cast,
1336
+ ...change.filter === void 0 ? {} : { filter: change.filter }
1337
+ });
1338
+ }
1339
+ /**
1340
+ * Each top-level field of a model or variant, in a collection the plan keeps, whose destination
1341
+ * type does not take every value its origin type holds, read from the BSON types of the two codecs.
1342
+ */
1343
+ function planFieldTypeChanges(input, lookups) {
1344
+ return modelCoordinates(input.fromContract).flatMap((origin) => {
1345
+ const model = modelAt(input.fromContract, origin);
1346
+ if (model === void 0 || embeddedModelReason(input.fromContract, origin) !== void 0) return [];
1347
+ const destination = destinationModelOf(origin, input);
1348
+ const destinationModel = destination === void 0 ? void 0 : modelAt(input.contract, destination);
1349
+ if (destination === void 0 || destinationModel === void 0) return [];
1350
+ const collection = collectionOfModel(input.contract.domain, destination);
1351
+ if (collection === void 0 || !input.keptCollections.has(collection)) return [];
1352
+ if (collectionControlPolicy(input.contract, collection) !== "managed") return [];
1353
+ return Object.keys(model.fields).sort().flatMap((field) => {
1354
+ const destinationField = destinationFieldOf({
1355
+ ...origin,
1356
+ field
1357
+ }, input.statements);
1358
+ if (!Object.hasOwn(destinationModel.fields, destinationField)) return [];
1359
+ const from = fieldShapeOf(model.fields[field], lookups);
1360
+ const to = fieldShapeOf(destinationModel.fields[destinationField], lookups);
1361
+ const storedName = ownStoredNameOf(destinationModel, destinationField);
1362
+ if (from === void 0 || to === void 0 || takesEveryValue(from, to)) return [];
1363
+ if (storedName === "_id") return [];
1364
+ return [typeChange({
1365
+ subject: {
1366
+ kind: "field",
1367
+ ...origin,
1368
+ field
1369
+ },
1370
+ destination: {
1371
+ ...destination,
1372
+ field: destinationField
1373
+ },
1374
+ collection,
1375
+ field: storedName,
1376
+ from,
1377
+ to,
1378
+ filter: variantFilterOf(input.contract.domain, destination)
1379
+ })];
1380
+ });
1381
+ });
1382
+ }
1383
+ /**
1384
+ * Without an origin contract, each field a root model of both validators declares whose new
1385
+ * property schema does not take every value the old one does, named by its storage name.
1386
+ */
1387
+ function planValidatorTypeChanges(input) {
1388
+ return input.origin.collections.flatMap((originCollection) => {
1389
+ const collection = originCollection.name;
1390
+ if (collectionControlPolicy(input.contract, collection) !== "managed") return [];
1391
+ const destination = input.destination.collection(collection);
1392
+ if (destination?.validator === void 0 || originCollection.validator === void 0) return [];
1393
+ const before = validatorDocumentShapesOf(originCollection.validator.jsonSchema);
1394
+ const changes = validatorDocumentShapesOf(destination.validator.jsonSchema).flatMap((after) => {
1395
+ const matched = before.find(({ key }) => key === after.key);
1396
+ if (matched === void 0) return [];
1397
+ return Object.keys(after.properties).filter((field) => field !== "_id" && Object.hasOwn(matched.properties, field)).flatMap((field) => {
1398
+ const from = propertyShapeOf(matched.properties[field]);
1399
+ const to = propertyShapeOf(after.properties[field]);
1400
+ if (from === void 0 || to === void 0 || takesEveryValue(from, to)) return [];
1401
+ return [{
1402
+ shape: after,
1403
+ field,
1404
+ from,
1405
+ to
1406
+ }];
1407
+ });
1408
+ });
1409
+ const sameEverywhere = (field, rootIndex) => {
1410
+ const shapes = validatorDocumentShapesOf(destination.validator?.jsonSchema).filter((shape) => shape.rootIndex === rootIndex);
1411
+ const found = changes.filter((change) => change.field === field && change.shape.rootIndex === rootIndex);
1412
+ return found.length === shapes.length && found.every((change) => JSON.stringify([change.from, change.to]) === JSON.stringify([found[0]?.from, found[0]?.to]));
1413
+ };
1414
+ const planned = /* @__PURE__ */ new Map();
1415
+ for (const { shape, field, from, to } of changes) {
1416
+ const filter = shape.discriminator === void 0 || sameEverywhere(field, shape.rootIndex) || shape.discriminator === void 0 ? void 0 : { [shape.discriminator.field]: shape.discriminator.value };
1417
+ const key = JSON.stringify([
1418
+ shape.rootIndex,
1419
+ field,
1420
+ filter ?? null
1421
+ ]);
1422
+ if (planned.has(key)) continue;
1423
+ planned.set(key, typeChange({
1424
+ subject: {
1425
+ kind: "storage",
1426
+ name: `${collection}.${field}`
1427
+ },
1428
+ destination: void 0,
1429
+ collection,
1430
+ field,
1431
+ from,
1432
+ to,
1433
+ filter
1434
+ }));
1435
+ }
1436
+ return [...planned.values()].sort((a, b) => a.field < b.field ? -1 : a.field > b.field ? 1 : 0);
1437
+ });
1438
+ }
1439
+ function shapeText(shape) {
1440
+ const types = shape.types.length === 0 ? "any value" : shape.types.join(", ");
1441
+ return shape.list ? `list of ${types}` : types;
1442
+ }
1443
+ function fieldText(change, contract) {
1444
+ return change.destination === void 0 ? change.subject.kind === "storage" ? change.subject.name : change.field : fieldStatementText(contract, change.destination);
1445
+ }
1446
+ /** A type change of a field whose stored name MongoDB reads as a path or an operator: neither a cast nor a conversion can rewrite it. */
1447
+ function unrewritableTypeChangeRefusals(changes, contract) {
1448
+ return changes.flatMap((change) => {
1449
+ const reason = unrewritableFieldNameReason(change.field);
1450
+ if (reason === void 0) return [];
1451
+ return [{
1452
+ kind: "typeChangeRefused",
1453
+ summary: `Cannot change the type of field "${fieldText(change, contract)}" in collection "${change.collection}": its stored name ${JSON.stringify(change.field)} cannot be rewritten: ${reason}`,
1454
+ why: "A cast or a conversion would have to rewrite the field. Keep its type, or store it under a name without \".\" that does not start with \"$\", then run this command again."
1455
+ }];
1456
+ });
1457
+ }
1458
+ /** A type change with no cast that keeps what the values mean: only a conversion the user writes keeps the field. */
1459
+ function noCastRefusals(changes, contract) {
1460
+ return changes.filter((change) => change.cast === void 0).map((change) => {
1461
+ const field = fieldText(change, contract);
1462
+ return {
1463
+ kind: "typeChangeRefused",
1464
+ summary: `Cannot change the type of field "${field}" in collection "${change.collection}" from ${shapeText(change.from)} to ${shapeText(change.to)}: MongoDB has no cast from ${shapeText(change.from)} to ${shapeText(change.to)} that keeps what the values mean`,
1465
+ why: change.destination === void 0 ? "Its values cannot be cast, so --delete cannot keep the field. Plan the change with migration plan --from <hash of the migration the database is at> and --convert, and write the conversion in migration.ts." : `Its values cannot be cast, so --delete cannot keep the field. Plan the change with migration plan and --convert ${field}, and write the conversion in migration.ts.`
1466
+ };
1467
+ });
1468
+ }
1469
+ function sameField(a, b) {
1470
+ return a.namespaceId === b.namespaceId && a.model === b.model && a.field === b.field;
1471
+ }
1472
+ /** The type change a convert statement names, if it names one. */
1473
+ function typeChangeConverted(statement, changes) {
1474
+ return changes.find((change) => change.destination !== void 0 && sameField(change.destination, statement.field));
1475
+ }
1476
+ /** The codecs and data types the composed components register, an extension's among them. */
1477
+ function mongoTypeLookupsOf(frameworkComponents) {
1478
+ return {
1479
+ codecLookup: extractCodecLookup(frameworkComponents),
1480
+ dataTypeLookup: assembleDataTypes(frameworkComponents).lookup
1481
+ };
1482
+ }
806
1483
  function renderOps(calls) {
807
1484
  return calls.map((call) => call.toOp());
808
1485
  }
@@ -969,10 +1646,10 @@ function validatorsEqual(a, b) {
969
1646
  function isPlainObject(v) {
970
1647
  return typeof v === "object" && v !== null && !Array.isArray(v);
971
1648
  }
972
- /** Each field a root model of the validator declares, with the distinct schemas the root models give it, in canonical form. */
1649
+ /** Each field a root model or variant of the validator declares, with the distinct schemas they give it, in canonical form. */
973
1650
  function propertiesOf(schema) {
974
1651
  const schemas = /* @__PURE__ */ new Map();
975
- for (const root of validatorRootShapesOf(schema)) for (const [field, fieldSchema] of Object.entries(root.properties)) schemas.set(field, (schemas.get(field) ?? /* @__PURE__ */ new Set()).add(canonicalize(fieldSchema)));
1652
+ for (const shape of validatorDocumentShapesOf(schema)) for (const [field, fieldSchema] of Object.entries(shape.properties)) schemas.set(field, (schemas.get(field) ?? /* @__PURE__ */ new Set()).add(canonicalize(fieldSchema)));
976
1653
  return Object.fromEntries([...schemas].map(([field, distinct]) => [field, [...distinct].sort().join("|")]));
977
1654
  }
978
1655
  /**
@@ -1036,14 +1713,14 @@ function modelStoredIn(fromContract, collection) {
1036
1713
  namespaceId: asNamespaceId(namespaceId),
1037
1714
  model
1038
1715
  };
1039
- return collectionOf(fromContract, coordinate) === collection ? [{
1716
+ return collectionOfModel(fromContract.domain, coordinate) === collection ? [{
1040
1717
  coordinate,
1041
1718
  isRoot: definition.base === void 0
1042
1719
  }] : [];
1043
1720
  }));
1044
1721
  return (storing.find(({ isRoot }) => isRoot) ?? storing[0])?.coordinate;
1045
1722
  }
1046
- /** A convert or backfill statement, which this release cannot carry out on MongoDB. */
1723
+ /** A convert or backfill statement this release cannot carry out on MongoDB. */
1047
1724
  function unsupportedStatementConflict(statement, fromContract, contract) {
1048
1725
  return {
1049
1726
  kind: "statementRefused",
@@ -1092,7 +1769,7 @@ function collectionDrops(calls, fromContract, contract, collections) {
1092
1769
  /** The collection the destination stores `model` in, when the destination still has that model. */
1093
1770
  function modelStoredInDestination(contract, model) {
1094
1771
  const namespace = contract.domain.namespaces[model.namespaceId];
1095
- return namespace !== void 0 && Object.hasOwn(namespace.models, model.model) ? collectionOf(contract, model) : void 0;
1772
+ return namespace !== void 0 && Object.hasOwn(namespace.models, model.model) ? collectionOfModel(contract.domain, model) : void 0;
1096
1773
  }
1097
1774
  function callsOf(diff) {
1098
1775
  return [
@@ -1253,7 +1930,7 @@ var MongoMigrationPlanner = class {
1253
1930
  const contract = blindCast(options.contract);
1254
1931
  const originIR = blindCast(options.schema);
1255
1932
  const fromContract = options.fromContract;
1256
- const unsupported = options.statements.find((statement) => statement.kind !== "rename");
1933
+ const unsupported = options.statements.find((statement) => statement.kind !== "rename" && !((statement.kind === "convert" || statement.kind === "backfill") && statement.entity === "field"));
1257
1934
  if (unsupported !== void 0) return {
1258
1935
  kind: "failure",
1259
1936
  conflicts: [unsupportedStatementConflict(unsupported, fromContract ?? contract, contract)]
@@ -1283,35 +1960,142 @@ var MongoMigrationPlanner = class {
1283
1960
  collectionAfterRenames: (collection) => renamedTo.get(collection) ?? collection,
1284
1961
  keptCollections: new Set(schema.collectionNames.filter((name) => destinationIR.collection(name) !== void 0))
1285
1962
  });
1286
- const removalRefusals = [...timeSeriesRemovalRefusals(removals, schema), ...sharedCollectionRemovalRefusals(removals, contract)];
1287
- if (removalRefusals.length > 0) return {
1963
+ const match = fromContract === null ? void 0 : {
1964
+ statements: renames,
1965
+ fromContract,
1966
+ contract,
1967
+ collectionAfterRenames: (collection) => renamedTo.get(collection) ?? collection
1968
+ };
1969
+ const lookups = mongoTypeLookupsOf(options.frameworkComponents);
1970
+ const typeChanges = fromContract === null ? planValidatorTypeChanges({
1971
+ origin: schema,
1972
+ destination: destinationIR,
1973
+ contract
1974
+ }) : planFieldTypeChanges({
1975
+ statements: renames,
1976
+ fromContract,
1977
+ contract,
1978
+ collectionAfterRenames: (collection) => renamedTo.get(collection) ?? collection,
1979
+ keptCollections: new Set(schema.collectionNames.filter((name) => destinationIR.collection(name) !== void 0))
1980
+ }, lookups);
1981
+ const contracts = {
1982
+ fromContract: fromContract ?? contract,
1983
+ contract
1984
+ };
1985
+ const converted = [];
1986
+ const transforms = options.statements.flatMap((statement) => {
1987
+ if (statement.kind === "convert" && statement.entity === "field") {
1988
+ const change = typeChangeConverted(statement, typeChanges);
1989
+ if (change !== void 0) converted.push(change);
1990
+ return [{
1991
+ statement,
1992
+ outcome: convertTransform(statement, change, contracts)
1993
+ }];
1994
+ }
1995
+ if (statement.kind === "backfill" && statement.entity === "field") return [{
1996
+ statement,
1997
+ outcome: backfillTransform(statement, {
1998
+ contract,
1999
+ schema,
2000
+ match
2001
+ })
2002
+ }];
2003
+ return [];
2004
+ });
2005
+ const unconverted = typeChanges.filter((change) => !converted.includes(change));
2006
+ const rewritable = unconverted.filter((change) => unrewritableFieldNameReason(change.field) === void 0);
2007
+ const casts = rewritable.flatMap((change) => {
2008
+ const call = castFieldCallOf(change);
2009
+ return call === void 0 ? [] : [{
2010
+ ...change,
2011
+ call
2012
+ }];
2013
+ });
2014
+ const fills = planFieldFills({
2015
+ match,
2016
+ contract,
2017
+ lookups,
2018
+ schema,
2019
+ destination: destinationIR,
2020
+ statements: options.statements
2021
+ });
2022
+ const rewrites = [
2023
+ ...removals.map(({ call, subject }) => ({
2024
+ kind: "removal",
2025
+ collection: call.collection,
2026
+ field: call.field,
2027
+ filter: call.filter,
2028
+ model: subject.kind === "field" ? subject : void 0
2029
+ })),
2030
+ ...casts.map((change) => ({
2031
+ kind: "cast",
2032
+ collection: change.collection,
2033
+ field: change.field,
2034
+ filter: change.filter,
2035
+ model: change.destination
2036
+ })),
2037
+ ...transforms.flatMap(({ outcome }) => outcome.kind === "transform" ? [outcome.rewrite] : []),
2038
+ ...fills.map(({ call, subject }) => ({
2039
+ kind: "fill",
2040
+ collection: call.options.collection,
2041
+ field: call.options.field,
2042
+ filter: call.options.filter,
2043
+ model: subject.kind === "field" ? subject : void 0
2044
+ }))
2045
+ ];
2046
+ const refusals = [
2047
+ ...transforms.flatMap(({ outcome }) => outcome.kind === "refused" ? [outcome.conflict] : []),
2048
+ ...unrewritableTypeChangeRefusals(unconverted, contract),
2049
+ ...noCastRefusals(rewritable, contract),
2050
+ ...rewrites.flatMap((rewrite) => rewriteRefusals(rewrite, contract, {
2051
+ timeSeries: schema.collection(rewrite.collection)?.options?.timeseries !== void 0,
2052
+ validator: schema.collection(rewrite.collection)?.validator?.jsonSchema
2053
+ }))
2054
+ ];
2055
+ if (refusals.length > 0) return {
1288
2056
  kind: "failure",
1289
- conflicts: removalRefusals
2057
+ conflicts: refusals
1290
2058
  };
2059
+ const castCalls = casts.map(({ call }) => call);
2060
+ const callOf = new Map([...renames.map((statement, index) => [statement, callOfStatement[index]]), ...transforms.map(({ statement, outcome }) => outcome.kind === "transform" ? [statement, outcome.call] : [statement, void 0])]);
2061
+ const transformCalls = (kind) => transforms.flatMap(({ statement, outcome }) => statement.kind === kind && outcome.kind === "transform" ? [outcome.call] : []);
1291
2062
  const result = this.planCalls({
1292
2063
  ...options,
1293
2064
  statementCalls: {
1294
2065
  schema,
1295
2066
  collectionRenames,
1296
- rewrites: [...fieldRenames, ...removals.map((removal) => removal.call)]
2067
+ rewrites: [
2068
+ ...fieldRenames,
2069
+ ...castCalls,
2070
+ ...transformCalls("convert"),
2071
+ ...fills.map((fill) => fill.call),
2072
+ ...transformCalls("backfill"),
2073
+ ...removals.map((removal) => removal.call)
2074
+ ]
1297
2075
  }
1298
2076
  });
1299
2077
  if (result.kind === "failure") return result;
1300
2078
  const { calls, warnings } = result;
1301
- const fieldLoss = removals.map((removal) => ({
2079
+ const allWarnings = [...warnings, ...match === void 0 ? [] : documentsNotRewrittenWarnings(match)];
2080
+ const fieldLoss = [...removals.map((removal) => ({
1302
2081
  operationIndex: calls.indexOf(removal.call),
1303
2082
  subject: removal.subject,
1304
2083
  loss: "drop",
1305
2084
  label: removal.call.label
1306
- }));
2085
+ })), ...casts.flatMap(({ call, subject }) => call.operationClass !== "destructive" ? [] : [{
2086
+ operationIndex: calls.indexOf(call),
2087
+ subject,
2088
+ loss: "typeChange",
2089
+ label: call.label
2090
+ }])];
1307
2091
  return {
1308
2092
  kind: "success",
1309
2093
  plan: new PlannerProducedMongoMigration(calls, {
1310
2094
  from: options.origin?.storageHash ?? null,
1311
2095
  to: contract.storage.storageHash
1312
2096
  }, options.snapshotsImportPath),
1313
- appliedStatements: options.statements.map((statement, index) => {
1314
- const call = callOfStatement[index];
2097
+ appliedStatements: options.statements.map((statement) => {
2098
+ const call = callOf.get(statement);
1315
2099
  return {
1316
2100
  statement,
1317
2101
  operationIndexes: call === void 0 ? [] : [calls.indexOf(call)]
@@ -1322,8 +2106,12 @@ var MongoMigrationPlanner = class {
1322
2106
  destination: destinationIR
1323
2107
  }), ...fieldLoss].sort((a, b) => a.operationIndex - b.operationIndex),
1324
2108
  accessChanges: [],
1325
- temporaryValues: [],
1326
- ...warnings.length > 0 ? { warnings } : {}
2109
+ temporaryValues: fills.map((fill) => ({
2110
+ operationIndex: calls.indexOf(fill.call),
2111
+ subject: fill.subject,
2112
+ value: fill.text
2113
+ })),
2114
+ ...allWarnings.length > 0 ? { warnings: allWarnings } : {}
1327
2115
  };
1328
2116
  }
1329
2117
  /**
@@ -1359,7 +2147,8 @@ function planValidatorDiffCall(collName, originValidator, destValidator) {
1359
2147
  }, {
1360
2148
  id: `validator.${collName}.${originValidator ? "update" : "add"}`,
1361
2149
  label: originValidator ? validatorUpdateLabel(collName, originValidator, destValidator) : `Add validator on ${collName}`,
1362
- operationClass: "widening"
2150
+ operationClass: "widening",
2151
+ checkDocuments: true
1363
2152
  });
1364
2153
  return new CollModCall(collName, {
1365
2154
  validator: {},
@@ -1643,10 +2432,21 @@ const StepJson = type({
1643
2432
  description: "string",
1644
2433
  command: "Record<string, unknown>"
1645
2434
  });
2435
+ const OperationMetaJson = type({ "rewrite?": type({
2436
+ kind: "\"cast\"",
2437
+ collection: "string",
2438
+ field: "string",
2439
+ to: "string"
2440
+ }).or({
2441
+ kind: "\"fill\"",
2442
+ collection: "string",
2443
+ field: "string"
2444
+ }) });
1646
2445
  const DdlOperationJson = type({
1647
2446
  id: "string",
1648
2447
  label: "string",
1649
2448
  operationClass: "\"additive\" | \"widening\" | \"destructive\"",
2449
+ "meta?": OperationMetaJson,
1650
2450
  precheck: "Record<string, unknown>[]",
1651
2451
  execute: "Record<string, unknown>[]",
1652
2452
  postcheck: "Record<string, unknown>[]"
@@ -1662,6 +2462,7 @@ const DmlOperationJson = type({
1662
2462
  label: "string",
1663
2463
  operationClass: "\"additive\" | \"widening\" | \"destructive\" | \"data\"",
1664
2464
  name: "string",
2465
+ "meta?": OperationMetaJson,
1665
2466
  precheck: "Record<string, unknown>[]",
1666
2467
  run: "Record<string, unknown>[]",
1667
2468
  postcheck: "Record<string, unknown>[]"
@@ -1930,11 +2731,15 @@ function deserializeInspectionCommand(json) {
1930
2731
  } });
1931
2732
  }
1932
2733
  }
2734
+ /** An inspection command has a `kind`, which its deserializer checks; a query plan has none. */
2735
+ function deserializeCheckSource(json) {
2736
+ return "kind" in json ? deserializeInspectionCommand(json) : deserializeMongoQueryPlan(json);
2737
+ }
1933
2738
  function deserializeCheck(json) {
1934
2739
  const data = validate(CheckJson, json, "migration check");
1935
2740
  return {
1936
2741
  description: data.description,
1937
- source: deserializeInspectionCommand(data.source),
2742
+ source: deserializeCheckSource(data.source),
1938
2743
  filter: deserializeFilterExpr(data.filter),
1939
2744
  expect: data.expect,
1940
2745
  ...ifDefined("object", data.object)
@@ -1956,6 +2761,7 @@ function deserializeDdlOp(json) {
1956
2761
  id: data.id,
1957
2762
  label: data.label,
1958
2763
  operationClass: data.operationClass,
2764
+ ...ifDefined("meta", data.meta),
1959
2765
  precheck: data.precheck.map(deserializeCheck),
1960
2766
  execute: data.execute.map(deserializeStep),
1961
2767
  postcheck: data.postcheck.map(deserializeCheck)
@@ -1977,6 +2783,7 @@ function deserializeDmlOp(json) {
1977
2783
  label: data.label,
1978
2784
  operationClass: data.operationClass,
1979
2785
  name: data.name,
2786
+ ...ifDefined("meta", data.meta),
1980
2787
  precheck: data.precheck.map(deserializeDmlCheck),
1981
2788
  run: data.run.map(deserializeMongoQueryPlan),
1982
2789
  postcheck: data.postcheck.map(deserializeDmlCheck)
@@ -1993,6 +2800,12 @@ function serializeMongoOps(ops) {
1993
2800
  return JSON.stringify(ops, null, 2);
1994
2801
  }
1995
2802
  const READ_ONLY_CHECK_COMMAND_KINDS = /* @__PURE__ */ new Set(["aggregate", "rawAggregate"]);
2803
+ const WRITING_STAGES = ["$out", "$merge"];
2804
+ /** The stage of an aggregate's pipeline that writes, `$out` or `$merge`, if it has one. */
2805
+ function writingStageOf(command) {
2806
+ if (command instanceof RawAggregateCommand) return command.pipeline.flatMap((stage) => WRITING_STAGES.filter((name) => Object.hasOwn(stage, name))).at(0);
2807
+ if (command instanceof AggregateCommand) return command.pipeline.map((stage) => `$${stage.kind}`).find((name) => WRITING_STAGES.includes(name));
2808
+ }
1996
2809
  const CHANGED_DOCUMENT_COUNTS = [
1997
2810
  "insertedCount",
1998
2811
  "modifiedCount",
@@ -2050,6 +2863,175 @@ function renameTargetExistsRefusal(op, failed) {
2050
2863
  meta: { operationId: op.id }
2051
2864
  });
2052
2865
  }
2866
+ function validatorSetBy(op) {
2867
+ const step = op.execute.find(({ command }) => command instanceof CollModCommand)?.command;
2868
+ return step instanceof CollModCommand && step.validator !== void 0 ? step : void 0;
2869
+ }
2870
+ /** The BSON types a property schema's `bsonType` allows, or `undefined` when it names none. */
2871
+ function allowedBsonTypes(schema) {
2872
+ const types = propertyBsonTypesOf(schema);
2873
+ return types.length === 0 ? void 0 : new Set(types);
2874
+ }
2875
+ /** The shape of a property schema that describes an embedded document, such as a value object. */
2876
+ function nestedShapeOf(schema) {
2877
+ if (typeof schema !== "object" || schema === null) return void 0;
2878
+ const properties = Reflect.get(schema, "properties");
2879
+ const required = Reflect.get(schema, "required");
2880
+ if (typeof properties !== "object" || properties === null || Array.isArray(properties)) return;
2881
+ return {
2882
+ properties: { ...properties },
2883
+ required: Array.isArray(required) ? required.filter((name) => typeof name === "string") : [],
2884
+ closed: Reflect.get(schema, "additionalProperties") === false
2885
+ };
2886
+ }
2887
+ function problemsAgainst(fields, shape, path) {
2888
+ const named = (field) => JSON.stringify(`${path}${field}`);
2889
+ const unreadable = (field) => field === "_id" ? void 0 : unrewritableFieldNameReason(field);
2890
+ const unchecked = [...fields.keys()].flatMap((field) => {
2891
+ const reason = unreadable(field);
2892
+ return reason === void 0 ? [] : [`has ${named(field)}, which the new validator cannot check: ${reason}`];
2893
+ });
2894
+ const missing = shape.required.filter((field) => !fields.has(field)).map((field) => `has no ${named(field)}`);
2895
+ const retyped = [...fields].flatMap(([field, { type }]) => {
2896
+ if (unreadable(field) !== void 0) return [];
2897
+ const allowed = allowedBsonTypes(shape.properties[field]);
2898
+ return allowed === void 0 || allowed.has(type) ? [] : [`holds a value of type ${type} in ${named(field)}, which the new validator does not allow there`];
2899
+ });
2900
+ const outsideEnum = [...fields].flatMap(([field, { value }]) => {
2901
+ const allowed = Reflect.get(Object(shape.properties[field]), "enum");
2902
+ return !Array.isArray(allowed) || allowed.some((member) => canonicalize(member) === canonicalize(value)) ? [] : [`holds ${mongoshValue(value)} in ${named(field)}, a value the new validator does not allow there`];
2903
+ });
2904
+ const undeclared = shape.closed ? [...fields.keys()].filter((field) => !Object.hasOwn(shape.properties, field) && unreadable(field) === void 0).map((field) => `has ${named(field)}, a field the new validator does not name`) : [];
2905
+ return [...unchecked.map((text) => ({
2906
+ text,
2907
+ uncheckable: true
2908
+ })), ...[
2909
+ ...missing,
2910
+ ...retyped,
2911
+ ...outsideEnum,
2912
+ ...undeclared
2913
+ ].map((text) => ({
2914
+ text,
2915
+ uncheckable: false
2916
+ }))];
2917
+ }
2918
+ /**
2919
+ * The root model or variant of a validator a document is read against: the variant whose
2920
+ * discriminator value the document holds, or else the one it fits best.
2921
+ */
2922
+ function shapeOfDocument(fields, shapes) {
2923
+ const selected = shapes.filter(({ discriminator }) => discriminator !== void 0 && canonicalize(fields.get(discriminator.field)?.value) === canonicalize(discriminator.value));
2924
+ return (selected.length > 0 ? selected : shapes).reduce((best, shape) => best === void 0 || problemsAgainst(fields, shape, "").length < problemsAgainst(fields, best, "").length ? shape : best, void 0);
2925
+ }
2926
+ function joinedList(items) {
2927
+ if (items.length <= 2) return items.join(" and ");
2928
+ return `${items.slice(0, -1).join(", ")}, and ${items.at(-1)}`;
2929
+ }
2930
+ /**
2931
+ * The `--backfill` statements that let the user choose values for the fields a change makes
2932
+ * required: one for each field the planner would accept the statement for, as its rewrite refusals
2933
+ * and stored name rules say.
2934
+ */
2935
+ function backfillAdvice(contract, collection, requires, rewriteCollection) {
2936
+ const accepted = backfillStatements(contract, collection, requires, rewriteCollection);
2937
+ if (accepted.length === 0) return [];
2938
+ return [`To give ${quotedList(accepted.map(({ stored }) => stored))} values you choose, plan the change with migration plan ${accepted.map(({ statement }) => `--backfill ${statement}`).join(" ")}.`];
2939
+ }
2940
+ /** The `--backfill` statement of each of `fields` the planner would accept it for, with the field's stored name. */
2941
+ function backfillStatements(contract, collection, fields, rewriteCollection) {
2942
+ return fields.flatMap((stored) => {
2943
+ if (unrewritableFieldNameReason(stored) !== void 0) return [];
2944
+ const field = fieldStoredAt(contract, collection, stored);
2945
+ if (field.kind !== "field") return [];
2946
+ const model = {
2947
+ namespaceId: field.namespaceId,
2948
+ model: field.model
2949
+ };
2950
+ return rewriteRefusals({
2951
+ kind: "backfill",
2952
+ collection,
2953
+ field: stored,
2954
+ filter: variantFilterOf(contract.domain, model),
2955
+ model
2956
+ }, contract, rewriteCollection).length === 0 ? [{
2957
+ stored,
2958
+ statement: fieldStatementText(contract, field)
2959
+ }] : [];
2960
+ });
2961
+ }
2962
+ /** How to change documents by hand while the old validator, which may reject their new shape, is in place. */
2963
+ function byHandAdvice(collection) {
2964
+ return `The old validator may reject a document changed to the new shape, so the update that fixes one can skip document validation: change them with a dataTransform in migration.ts, or in mongosh with an update command that sets bypassDocumentValidation: true, such as db.runCommand({ update: ${JSON.stringify(collection)}, updates: [{ q: { _id: <id> }, u: { $set: { <field>: <value> } } }], bypassDocumentValidation: true }).`;
2965
+ }
2966
+ function bsonTypeOf(value) {
2967
+ return Reflect.get(value, "_bsontype");
2968
+ }
2969
+ function uuidText(bytes) {
2970
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
2971
+ return [
2972
+ hex.slice(0, 8),
2973
+ hex.slice(8, 12),
2974
+ hex.slice(12, 16),
2975
+ hex.slice(16, 20),
2976
+ hex.slice(20)
2977
+ ].join("-");
2978
+ }
2979
+ /** A value as `mongosh` writes it: `ObjectId("…")`, `ISODate("…")`, `UUID("…")`, anything else as JSON. */
2980
+ function mongoshValue(value) {
2981
+ if (value instanceof Date) return `ISODate(${JSON.stringify(value.toISOString())})`;
2982
+ if (typeof value === "object" && value !== null) {
2983
+ if (bsonTypeOf(value) === "ObjectId") return `ObjectId(${JSON.stringify(String(value))})`;
2984
+ const bytes = Reflect.get(value, "buffer");
2985
+ if (bsonTypeOf(value) === "Binary" && Reflect.get(value, "sub_type") === 4 && bytes instanceof Uint8Array && bytes.length === 16) return `UUID(${JSON.stringify(uuidText(bytes))})`;
2986
+ }
2987
+ return JSON.stringify(value) ?? String(value);
2988
+ }
2989
+ function documentShapes(jsonSchema) {
2990
+ return validatorDocumentShapesOf(jsonSchema).map((shape) => ({
2991
+ key: shape.key,
2992
+ required: new Set(shape.required),
2993
+ properties: new Map(Object.entries(shape.properties).map(([field, schema]) => [field, canonicalize(schema)]))
2994
+ }));
2995
+ }
2996
+ const ANY_VALUE = canonicalize({});
2997
+ const NO_SHAPE = {
2998
+ key: "",
2999
+ required: /* @__PURE__ */ new Set(),
3000
+ properties: /* @__PURE__ */ new Map()
3001
+ };
3002
+ /**
3003
+ * The fields a validator change makes required, and those whose accepted values it changes, each
3004
+ * kind of document compared with the same kind under the validator the collection has. A kind the
3005
+ * collection's validator does not describe is not compared; with no validator, every field it
3006
+ * requires is new.
3007
+ */
3008
+ function fieldsTouched(before, after) {
3009
+ const shapesBefore = documentShapes(before);
3010
+ const requires = /* @__PURE__ */ new Set();
3011
+ const retypes = /* @__PURE__ */ new Set();
3012
+ for (const shape of documentShapes(after)) {
3013
+ const previous = shapesBefore.length === 0 ? NO_SHAPE : shapesBefore.find(({ key }) => key === shape.key);
3014
+ if (previous === void 0) continue;
3015
+ for (const field of shape.required) if (field !== "_id" && !previous.required.has(field)) requires.add(field);
3016
+ for (const [field, schema] of shape.properties) {
3017
+ const schemaBefore = previous.properties.get(field);
3018
+ if (schemaBefore !== void 0 && schemaBefore !== schema && schema !== ANY_VALUE) retypes.add(field);
3019
+ }
3020
+ }
3021
+ return {
3022
+ requires: [...requires].sort(),
3023
+ retypes: [...retypes].filter((field) => !requires.has(field)).sort()
3024
+ };
3025
+ }
3026
+ function quotedList(fields) {
3027
+ const quoted = fields.map((field) => JSON.stringify(field));
3028
+ return quoted.length <= 1 ? quoted.join("") : `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`;
3029
+ }
3030
+ /** What a validator change touches, in words: `This validator change makes "plan" required.` */
3031
+ function touchedSentence(touched) {
3032
+ const parts = [...touched.requires.length === 0 ? [] : [`makes ${quotedList(touched.requires)} required`], ...touched.retypes.length === 0 ? [] : [`changes what ${quotedList(touched.retypes)} ${touched.retypes.length === 1 ? "accepts" : "accept"}`]];
3033
+ return parts.length === 0 ? "" : `This validator change ${parts.join(" and ")}. `;
3034
+ }
2053
3035
  const MONGO_UNAUTHORIZED = 13;
2054
3036
  /**
2055
3037
  * The failure for a rewrite that skips validation when the database user lacks the
@@ -2061,7 +3043,7 @@ function bypassValidationRefusal(op, plan, error) {
2061
3043
  if (Reflect.get(error, "code") !== MONGO_UNAUTHORIZED) return void 0;
2062
3044
  const codeName = Reflect.get(error, "codeName");
2063
3045
  return runnerFailure("MIGRATION.EXECUTION_FAILED", `Operation ${op.id} failed: the database user may not skip document validation`, {
2064
- why: `Renaming or removing a field rewrites documents with bypassDocumentValidation, because the old validator requires the old field. MongoDB refused it with error ${MONGO_UNAUTHORIZED} (${String(codeName)}). Grant the user the bypassDocumentValidation action on the database, for example with the dbAdmin or restore role, then run the command again; operations that already ran are skipped.`,
3046
+ why: `Rewriting documents to fit the new schema skips document validation, because the old validator rejects the new shape. MongoDB refused it with error ${MONGO_UNAUTHORIZED} (${String(codeName)}). Grant the user the bypassDocumentValidation action on the database, for example with the dbAdmin or restore role, then run the command again; operations that already ran are skipped.`,
2065
3047
  meta: {
2066
3048
  operationId: op.id,
2067
3049
  mongoCode: MONGO_UNAUTHORIZED,
@@ -2069,6 +3051,124 @@ function bypassValidationRefusal(op, plan, error) {
2069
3051
  }
2070
3052
  });
2071
3053
  }
3054
+ const MONGO_CONVERSION_FAILURE = 241;
3055
+ /** The innermost cause MongoDB gives in an error's message, without its closing period. */
3056
+ function mongoErrorText(error) {
3057
+ const message = String(Reflect.get(error, "message"));
3058
+ return (message.split(" :: caused by :: ").at(-1) ?? message).replace(/\.+$/, "");
3059
+ }
3060
+ /** The field of the destination contract a collection stores under `storedName`, or the storage name when no model declares it. */
3061
+ function fieldStoredAt(contract, collection, storedName) {
3062
+ const field = modelFieldStoredAs(contract.domain, collection, storedName);
3063
+ return field === void 0 ? {
3064
+ kind: "storage",
3065
+ name: `${collection}.${storedName}`
3066
+ } : {
3067
+ kind: "field",
3068
+ ...field,
3069
+ namespaceId: asNamespaceId(field.namespaceId)
3070
+ };
3071
+ }
3072
+ const MONGO_DUPLICATE_KEY = 11e3;
3073
+ /** What a user can do about a MongoDB error that stopped a rewrite, when the error says. */
3074
+ function rewriteErrorFix(mongoCode, reason) {
3075
+ if (mongoCode !== MONGO_DUPLICATE_KEY) return void 0;
3076
+ const index = /index: (\S+)/.exec(reason)?.[1];
3077
+ return `The rewrite would give two documents the same value under ${index === void 0 ? "a unique index" : `unique index ${JSON.stringify(index)}`}. Change or remove the documents that would collide, then run the command again; operations that already ran are skipped.`;
3078
+ }
3079
+ /**
3080
+ * The failure when MongoDB cannot build a unique index because two documents hold the same value
3081
+ * of its keys, as documents without the field all hold `null`. The build changes nothing.
3082
+ */
3083
+ /** The fields of a duplicate key MongoDB reports, when every one of them is `null` or missing. */
3084
+ function nullKeyFields(error) {
3085
+ const keyValue = Reflect.get(error, "keyValue");
3086
+ if (typeof keyValue !== "object" || keyValue === null) return [];
3087
+ const entries = Object.entries(keyValue);
3088
+ return entries.length > 0 && entries.every(([, value]) => value === null) ? entries.map(([field]) => field) : [];
3089
+ }
3090
+ function isDuplicateKeyError(error) {
3091
+ return typeof error === "object" && error !== null && Reflect.get(error, "code") === MONGO_DUPLICATE_KEY;
3092
+ }
3093
+ function indexBuildFailure(op, command, error, backfill) {
3094
+ const reason = mongoErrorText(error);
3095
+ const duplicate = /dup key: (\{.*\})/.exec(reason)?.[1];
3096
+ const index = command.name ?? defaultMongoIndexName(command.keys);
3097
+ const lacking = nullKeyFields(error);
3098
+ const statements = backfill(lacking);
3099
+ const why = [
3100
+ lacking.length === 0 ? "A document without the field counts as holding null." : `The documents that collide lack ${quotedList(lacking)} or hold null in ${lacking.length === 1 ? "it" : "them"}, and a document without the field counts as holding null.`,
3101
+ "Give each document its own value of the indexed fields, or remove the duplicates, then run the command again; operations that already ran are skipped.",
3102
+ ...statements.length === 0 ? [] : [`Under migration plan, ${statements.join(" ")} writes a slot to give each document its own value.`]
3103
+ ].join(" ");
3104
+ return runnerFailure("MIGRATION.EXECUTION_FAILED", `Operation ${op.id} failed: the unique index ${index} cannot be built, because two documents in collection ${command.collection} hold the same value${duplicate === void 0 ? "" : ` ${duplicate}`}`, {
3105
+ why,
3106
+ meta: {
3107
+ operationId: op.id,
3108
+ mongoCode: MONGO_DUPLICATE_KEY,
3109
+ index,
3110
+ collection: command.collection,
3111
+ ...duplicate === void 0 ? {} : { duplicateKey: duplicate }
3112
+ }
3113
+ });
3114
+ }
3115
+ /**
3116
+ * The failure when a rewrite fails after MongoDB began it: documents it reached may already be
3117
+ * rewritten. A planner cast that meets a value `$convert` cannot cast names the field, which the
3118
+ * advice reads to offer `--convert`. A data transform's update is the user's own, so its failure
3119
+ * never names a type change.
3120
+ */
3121
+ function rewriteFailure(op, error, position) {
3122
+ if (typeof error !== "object" || error === null) return void 0;
3123
+ const mongoCode = Reflect.get(error, "code");
3124
+ if (typeof mongoCode !== "number") return void 0;
3125
+ const codeName = Reflect.get(error, "codeName");
3126
+ const mongoError = typeof codeName === "string" ? `${mongoCode} (${codeName})` : `${mongoCode}`;
3127
+ const reason = mongoErrorText(error);
3128
+ if (op.operationClass === "data") return mongoCode === MONGO_CONVERSION_FAILURE ? runnerFailure("MIGRATION.EXECUTION_FAILED", `Operation ${op.id} failed: its update met a value MongoDB cannot convert`, {
3129
+ why: `MongoDB stopped the data transform's update: ${reason}. Documents it updated before that value stay updated. Until a re-run finishes, a document the update already changed may no longer fit the collection's current validator, so updates to it fail. Fix the update in the migration's migration.ts, run the file with node, then run the command again.`,
3130
+ meta: {
3131
+ operationId: op.id,
3132
+ mongoCode
3133
+ }
3134
+ }) : runnerFailure("MIGRATION.EXECUTION_FAILED", `Operation ${op.id} failed: MongoDB error ${mongoError}: ${reason}`, {
3135
+ why: "Documents the update changed before the error stay changed. Until a re-run finishes, a document the update already changed may no longer fit the collection's current validator, so updates to it fail. Fix what MongoDB names; when it comes from the update, change the update in the migration's migration.ts so its filter and update work on a re-run, and run the file with node. Then run the command again.",
3136
+ meta: {
3137
+ operationId: op.id,
3138
+ mongoCode,
3139
+ ...typeof codeName === "string" ? { codeName } : {}
3140
+ }
3141
+ });
3142
+ const rewrite = fieldRewriteOf(op);
3143
+ if (rewrite === void 0) return void 0;
3144
+ const cast = op.meta?.rewrite?.kind === "cast" ? op.meta.rewrite : void 0;
3145
+ if (mongoCode !== MONGO_CONVERSION_FAILURE || cast === void 0) {
3146
+ const fix = rewriteErrorFix(mongoCode, reason);
3147
+ return runnerFailure("MIGRATION.EXECUTION_FAILED", `Operation ${op.id} failed: MongoDB error ${mongoError}: ${reason}`, {
3148
+ why: ["Documents the rewrite changed before the error stay changed.", ...fix === void 0 ? [] : [fix]].join(" "),
3149
+ meta: {
3150
+ operationId: op.id,
3151
+ mongoCode,
3152
+ ...typeof codeName === "string" ? { codeName } : {}
3153
+ }
3154
+ });
3155
+ }
3156
+ const field = fieldStoredAt(position.contract, rewrite.collection, rewrite.field);
3157
+ const named = field.kind === "field" ? fieldStatementText(position.contract, field) : rewrite.field;
3158
+ return runnerFailure("MIGRATION.EXECUTION_FAILED", `Operation ${op.id} failed: a value of field "${named}" in collection ${cast.collection} cannot be cast to ${cast.to}`, {
3159
+ why: `MongoDB's $convert met a value of field "${named}" it cannot cast to ${cast.to}: ${reason}. Documents cast before that value stay cast, and a re-run casts the rest. Until it does, a document already cast holds a type the collection's current validator does not allow, so updates to it fail.`,
3160
+ meta: {
3161
+ operationId: op.id,
3162
+ mongoCode,
3163
+ failedTypeChange: {
3164
+ field,
3165
+ by: "cast",
3166
+ reason: "value",
3167
+ operationIndex: position.operationIndex
3168
+ }
3169
+ }
3170
+ });
3171
+ }
2072
3172
  var MongoMigrationRunner = class {
2073
3173
  deps;
2074
3174
  constructor(deps) {
@@ -2100,11 +3200,14 @@ var MongoMigrationRunner = class {
2100
3200
  const runIdempotency = checks?.idempotencyChecks !== false;
2101
3201
  const filterEvaluator = new FilterEvaluator();
2102
3202
  let operationsExecuted = 0;
2103
- for (const operation of operations) {
3203
+ for (const [operationIndex, operation] of operations.entries()) {
2104
3204
  options.callbacks?.onOperationStart?.(operation);
2105
3205
  try {
2106
3206
  if (isMongoDmlOperation(operation)) {
2107
- const result = await this.executeDmlOperation(operation, adapter, driver, filterEvaluator, runIdempotency, runPrechecks, runPostchecks, wrote);
3207
+ const result = await this.executeDmlOperation(operation, adapter, driver, filterEvaluator, runIdempotency, runPrechecks, runPostchecks, wrote, {
3208
+ operationIndex,
3209
+ contract: options.destinationContract
3210
+ });
2108
3211
  if (result.failure) return result.failure;
2109
3212
  if (result.executed) operationsExecuted += 1;
2110
3213
  continue;
@@ -2116,14 +3219,21 @@ var MongoMigrationRunner = class {
2116
3219
  const failing = await this.firstFailingCheck(operation.precheck, inspectionExecutor, filterEvaluator);
2117
3220
  if (failing !== void 0) {
2118
3221
  const failedCheck = failedCheckOf(operation.id, "precheck", failing);
2119
- return renameTargetExistsRefusal(operation, failing) ?? runnerFailure("MIGRATION.PRECHECK_FAILED", `Operation ${operation.id} failed during precheck: ${failing.description}`, {
3222
+ return renameTargetExistsRefusal(operation, failing) ?? await this.documentsFailingValidatorRefusal(operation, failing, options.destinationContract) ?? runnerFailure("MIGRATION.PRECHECK_FAILED", `Operation ${operation.id} failed during precheck: ${failing.description}`, {
2120
3223
  why: failedPrecheckWhy(failedCheck),
2121
3224
  meta: { failedCheck }
2122
3225
  });
2123
3226
  }
2124
3227
  }
2125
3228
  for (const step of operation.execute) {
2126
- await executeDdl(step.command);
3229
+ try {
3230
+ await executeDdl(step.command);
3231
+ } catch (error) {
3232
+ const { command } = step;
3233
+ if (!(command instanceof CreateIndexCommand) || !isDuplicateKeyError(error)) throw error;
3234
+ const inPlace = await this.collectionInPlace(command.collection);
3235
+ return indexBuildFailure(operation, command, error, (fields) => backfillStatements(options.destinationContract, command.collection, fields, inPlace.rewrite).map(({ statement }) => `--backfill ${statement}`));
3236
+ }
2127
3237
  wrote();
2128
3238
  }
2129
3239
  if (runPostchecks) {
@@ -2210,12 +3320,12 @@ var MongoMigrationRunner = class {
2210
3320
  });
2211
3321
  }
2212
3322
  }
2213
- async executeDmlOperation(op, adapter, driver, filterEvaluator, runIdempotency, runPrechecks, runPostchecks, wrote) {
3323
+ async executeDmlOperation(op, adapter, driver, filterEvaluator, runIdempotency, runPrechecks, runPostchecks, wrote, position) {
2214
3324
  if (runPostchecks && runIdempotency && op.postcheck.length > 0) {
2215
- if (await this.evaluateDmlChecks(op.postcheck, adapter, driver, filterEvaluator)) return { executed: false };
3325
+ if (await this.evaluateDmlChecks(op.postcheck, filterEvaluator)) return { executed: false };
2216
3326
  }
2217
3327
  if (runPrechecks && op.precheck.length > 0) {
2218
- if (!await this.evaluateDmlChecks(op.precheck, adapter, driver, filterEvaluator)) return {
3328
+ if (!await this.evaluateDmlChecks(op.precheck, filterEvaluator)) return {
2219
3329
  executed: false,
2220
3330
  failure: renameOverwriteRefusal(op) ?? runnerFailure("MIGRATION.PRECHECK_FAILED", `Operation ${op.id} failed during precheck`, { meta: {
2221
3331
  operationId: op.id,
@@ -2233,17 +3343,23 @@ var MongoMigrationRunner = class {
2233
3343
  if (reportedChange || !reportedNoChange) wrote();
2234
3344
  } catch (error) {
2235
3345
  const refusal = bypassValidationRefusal(op, plan, error);
2236
- if (refusal === void 0) throw error;
2237
- return {
3346
+ if (refusal !== void 0) return {
2238
3347
  executed: false,
2239
3348
  failure: refusal
2240
3349
  };
3350
+ const failure = rewriteFailure(op, error, position);
3351
+ if (failure === void 0) throw error;
3352
+ wrote();
3353
+ return {
3354
+ executed: false,
3355
+ failure
3356
+ };
2241
3357
  }
2242
3358
  }
2243
3359
  if (runPostchecks && op.postcheck.length > 0) {
2244
- if (!await this.evaluateDmlChecks(op.postcheck, adapter, driver, filterEvaluator)) return {
3360
+ if (!await this.evaluateDmlChecks(op.postcheck, filterEvaluator)) return {
2245
3361
  executed: false,
2246
- failure: runnerFailure("MIGRATION.POSTCHECK_FAILED", `Operation ${op.id} failed during postcheck`, { meta: {
3362
+ failure: await this.documentsStillMatchingFailure(op) ?? runnerFailure("MIGRATION.POSTCHECK_FAILED", `Operation ${op.id} failed during postcheck`, { meta: {
2247
3363
  operationId: op.id,
2248
3364
  name: op.name
2249
3365
  } })
@@ -2251,34 +3367,216 @@ var MongoMigrationRunner = class {
2251
3367
  }
2252
3368
  return { executed: true };
2253
3369
  }
2254
- async evaluateDmlChecks(checks, adapter, driver, filterEvaluator) {
2255
- for (const check of checks) {
2256
- const commandKind = check.source.command.kind;
2257
- if (!READ_ONLY_CHECK_COMMAND_KINDS.has(commandKind)) throw mongoTargetError("MIGRATION.DATA_TRANSFORM_CHECK_NOT_READ_ONLY", `Data-transform check rejected: command kind "${commandKind}" is not read-only`, {
2258
- why: "Data-transform checks must use aggregate or rawAggregate commands so the pre/postcheck path cannot mutate the database.",
2259
- fix: "Author the check.source as an aggregate pipeline (or rawAggregate) rather than a DML write command.",
2260
- meta: {
2261
- checkDescription: check.description,
2262
- commandKind,
2263
- collection: check.source.collection
3370
+ /**
3371
+ * The failure when a validator change's precheck finds documents the new validator rejects: how
3372
+ * many, one `_id`, and the query that finds them all.
3373
+ */
3374
+ async documentsFailingValidatorRefusal(op, failed, contract) {
3375
+ if (isInspectionCheckSource(failed.source)) return void 0;
3376
+ const collMod = validatorSetBy(op);
3377
+ if (collMod?.validator === void 0) return void 0;
3378
+ const { collection, validator } = collMod;
3379
+ const failing = { $nor: [validator] };
3380
+ const counted = await this.firstRow({
3381
+ ...failed.source,
3382
+ command: new RawAggregateCommand(collection, [{ $match: failing }, { $group: {
3383
+ _id: null,
3384
+ documents: { $sum: 1 },
3385
+ documentId: { $first: "$_id" }
3386
+ } }])
3387
+ });
3388
+ const documents = Number(counted?.["documents"] ?? 0);
3389
+ if (documents === 0) return void 0;
3390
+ const documentId = mongoshValue(counted?.["documentId"]);
3391
+ const query = `db.getCollection(${JSON.stringify(collection)}).find(${JSON.stringify(failing)})`;
3392
+ const inPlace = await this.collectionInPlace(collection);
3393
+ const validatorBefore = inPlace.validator;
3394
+ const touched = fieldsTouched(Reflect.get(validatorBefore ?? {}, "$jsonSchema"), Reflect.get(validator, "$jsonSchema"));
3395
+ const one = documents === 1;
3396
+ const documentObjectId = counted?.["documentId"];
3397
+ const fields = await this.fieldsOfDocument(failed.source, collection, documentObjectId, "$$ROOT");
3398
+ const shape = fields.size === 0 ? void 0 : shapeOfDocument(fields, validatorDocumentShapesOf(Reflect.get(validator, "$jsonSchema")));
3399
+ const problems = shape === void 0 ? [] : await this.documentProblems({
3400
+ source: failed.source,
3401
+ collection,
3402
+ id: documentObjectId
3403
+ }, fields, shape, "");
3404
+ const hadValidator = typeof validatorBefore === "object" && validatorBefore !== null;
3405
+ const found = [
3406
+ `${touchedSentence(touched)}${one ? "It has" : "One of them has"} _id ${documentId}.`,
3407
+ ...problems.length === 0 ? [] : [`That document ${joinedList(problems.map(({ text }) => text))}.`],
3408
+ `Find them all with ${query} in mongosh.`
3409
+ ];
3410
+ const uncheckable = problems.length > 0 && problems.every((problem) => problem.uncheckable);
3411
+ const advice = uncheckable ? ["A document that holds such a field can never fit the validator, so changing the documents does not help: store the field under a name without \".\" that does not start with \"$\"."] : hadValidator ? [...backfillAdvice(contract, collection, await this.fieldsSomeDocumentLacks(failed.source, collection, failing, touched.requires), inPlace.rewrite), byHandAdvice(collection)] : ["Change them with a dataTransform in migration.ts, or with an update in mongosh."];
3412
+ const why = [
3413
+ ...found,
3414
+ ...advice,
3415
+ `Under db migrate you can instead apply the validator over them: set checkDocuments to false on this operation in that migration.ts, run the file with node, and run db migrate again. db update writes no migration.ts, so there ${uncheckable ? "store the field under another name" : "fix the documents"} first.`,
3416
+ "This operation did not change the validator.",
3417
+ `${uncheckable ? "Then run the command again" : "Once the documents are fixed, run the command again"}; operations that already ran are skipped.`
3418
+ ].join(" ");
3419
+ return runnerFailure("MIGRATION.PRECHECK_FAILED", `Operation ${op.id} stopped: ${documents} ${one ? "document" : "documents"} in collection ${collection} ${one ? "does" : "do"} not fit the new validator`, {
3420
+ why,
3421
+ meta: {
3422
+ operationId: op.id,
3423
+ documentsFailingValidator: {
3424
+ collection,
3425
+ documents,
3426
+ documentId,
3427
+ query,
3428
+ requires: touched.requires,
3429
+ retypes: touched.retypes
2264
3430
  }
2265
- });
2266
- const wireCommand = await adapter.lower(check.source, {});
2267
- let matchFound = false;
2268
- for await (const row of driver.execute(wireCommand)) if (filterEvaluator.evaluate(check.filter, row)) {
2269
- matchFound = true;
2270
- break;
2271
3431
  }
3432
+ });
3433
+ }
3434
+ /**
3435
+ * The failure when a rewrite's check still finds documents after its update: how many, one `_id`,
3436
+ * and the query that finds them all. Only a data transform's update is the user's to change.
3437
+ */
3438
+ async documentsStillMatchingFailure(op) {
3439
+ const [check] = op.postcheck;
3440
+ const command = check?.source.command;
3441
+ if (check?.expect !== "notExists" || !(command instanceof RawAggregateCommand)) return void 0;
3442
+ const match = Reflect.get(command.pipeline[0] ?? {}, "$match");
3443
+ if (typeof match !== "object" || match === null) return void 0;
3444
+ const counted = await this.firstRow({
3445
+ ...check.source,
3446
+ command: new RawAggregateCommand(command.collection, [{ $match: match }, { $group: {
3447
+ _id: null,
3448
+ documents: { $sum: 1 },
3449
+ documentId: { $first: "$_id" }
3450
+ } }])
3451
+ });
3452
+ const documents = Number(counted?.["documents"] ?? 0);
3453
+ if (documents === 0) return void 0;
3454
+ const one = documents === 1;
3455
+ const documentId = mongoshValue(counted?.["documentId"]);
3456
+ const query = `db.getCollection(${JSON.stringify(command.collection)}).find(${JSON.stringify(match)})`;
3457
+ return runnerFailure("MIGRATION.POSTCHECK_FAILED", `Operation ${op.id} failed: after its update, ${documents} ${one ? "document" : "documents"} in collection ${command.collection} still ${one ? "matches" : "match"} its check`, {
3458
+ why: [`${one ? "It has" : "One of them has"} _id ${documentId}. Find them all with ${query} in mongosh.`, op.operationClass === "data" ? "Change the update in the migration's migration.ts so it changes them too, run the file with node, then run the command again; operations that already ran are skipped." : "The update this operation runs did not change them: another client may have written them during the apply, or the value it writes does not pass its own check. Run the command again; operations that already ran are skipped. If they are still found, change them by hand."].join(" "),
3459
+ meta: {
3460
+ operationId: op.id,
3461
+ name: op.name,
3462
+ documentsStillMatching: {
3463
+ collection: command.collection,
3464
+ documents,
3465
+ documentId,
3466
+ query
3467
+ }
3468
+ }
3469
+ });
3470
+ }
3471
+ /**
3472
+ * Why a document does not fit a validator, against `shape`: the required fields it lacks, the
3473
+ * fields whose type the validator does not allow, the fields a closed validator does not name, and
3474
+ * the same inside each embedded document the validator describes, such as a value object.
3475
+ */
3476
+ async documentProblems(document, fields, shape, path) {
3477
+ const nested = await Promise.all([...fields].map(async ([field, { type }]) => {
3478
+ const nestedShape = type === "object" ? nestedShapeOf(shape.properties[field]) : void 0;
3479
+ if (nestedShape === void 0) return [];
3480
+ const nestedPath = `${path}${field}`;
3481
+ const nestedFields = await this.fieldsOfDocument(document.source, document.collection, document.id, `$${nestedPath}`);
3482
+ return this.documentProblems(document, nestedFields, nestedShape, `${nestedPath}.`);
3483
+ }));
3484
+ return [...problemsAgainst(fields, shape, path), ...nested.flat()];
3485
+ }
3486
+ /**
3487
+ * The collection as the database has it now: its validator, and what a rewrite's refusals read of
3488
+ * it, whether it is a time-series collection and its validator's `$jsonSchema`.
3489
+ */
3490
+ async collectionInPlace(collection) {
3491
+ const [current] = (await this.deps.inspectionExecutor.listCollections(new ListCollectionsCommand())).filter((info) => info["name"] === collection);
3492
+ const options = current?.["options"];
3493
+ const readable = typeof options === "object" && options !== null;
3494
+ const validator = readable ? Reflect.get(options, "validator") : void 0;
3495
+ return {
3496
+ validator,
3497
+ rewrite: {
3498
+ timeSeries: readable && Reflect.get(options, "timeseries") !== void 0,
3499
+ validator: Reflect.get(validator ?? {}, "$jsonSchema")
3500
+ }
3501
+ };
3502
+ }
3503
+ /** Each of `fields` that a document matching `failing` lacks or holds as `null`. */
3504
+ async fieldsSomeDocumentLacks(source, collection, failing, fields) {
3505
+ return (await Promise.all(fields.map(async (field) => unrewritableFieldNameReason(field) === void 0 && await this.firstRow({
3506
+ ...source,
3507
+ command: new RawAggregateCommand(collection, [{ $match: { $and: [failing, { [field]: null }] } }, { $limit: 1 }])
3508
+ }) !== void 0 ? [field] : []))).flat();
3509
+ }
3510
+ /**
3511
+ * Each field of the document with `_id`, at `input`, `$$ROOT` or the path of an embedded document:
3512
+ * its BSON type, read with `$type`, and its value.
3513
+ */
3514
+ async fieldsOfDocument(source, collection, id, input) {
3515
+ const fields = (await this.firstRow({
3516
+ ...source,
3517
+ command: new RawAggregateCommand(collection, [
3518
+ { $match: { _id: id } },
3519
+ { $limit: 1 },
3520
+ { $project: {
3521
+ _id: 0,
3522
+ fields: { $map: {
3523
+ input: { $objectToArray: input },
3524
+ in: [
3525
+ "$$this.k",
3526
+ { $type: "$$this.v" },
3527
+ "$$this.v"
3528
+ ]
3529
+ } }
3530
+ } }
3531
+ ])
3532
+ }))?.["fields"];
3533
+ return new Map((Array.isArray(fields) ? fields : []).flatMap((entry) => Array.isArray(entry) && typeof entry[0] === "string" && typeof entry[1] === "string" ? [[entry[0], {
3534
+ type: entry[1],
3535
+ value: entry[2]
3536
+ }]] : []));
3537
+ }
3538
+ async firstRow(plan) {
3539
+ const wireCommand = await this.deps.adapter.lower(plan, {});
3540
+ for await (const row of this.deps.driver.execute(wireCommand)) return row;
3541
+ }
3542
+ async evaluateDmlChecks(checks, filterEvaluator) {
3543
+ for (const check of checks) {
3544
+ const matchFound = await this.documentsMatch(check, check.source, filterEvaluator);
2272
3545
  if (!(check.expect === "exists" ? matchFound : !matchFound)) return false;
2273
3546
  }
2274
3547
  return true;
2275
3548
  }
3549
+ async documentsMatch(check, source, filterEvaluator) {
3550
+ const commandKind = source.command.kind;
3551
+ if (!READ_ONLY_CHECK_COMMAND_KINDS.has(commandKind)) throw mongoTargetError("MIGRATION.DATA_TRANSFORM_CHECK_NOT_READ_ONLY", `Migration check rejected: command kind "${commandKind}" is not read-only`, {
3552
+ why: "A migration check must read with an aggregate or rawAggregate command, so that running it cannot change the database.",
3553
+ fix: "Write the check's source as an aggregate or rawAggregate pipeline, not a command that writes.",
3554
+ meta: {
3555
+ checkDescription: check.description,
3556
+ commandKind,
3557
+ collection: source.collection
3558
+ }
3559
+ });
3560
+ const stage = writingStageOf(source.command);
3561
+ if (stage !== void 0) throw mongoTargetError("MIGRATION.DATA_TRANSFORM_CHECK_NOT_READ_ONLY", `Migration check rejected: stage "${stage}" is not read-only`, {
3562
+ why: `A migration check must only read, so that running it cannot change the database; the ${stage} stage of its pipeline writes its results to a collection.`,
3563
+ fix: `Remove the ${stage} stage from the check's pipeline.`,
3564
+ meta: {
3565
+ checkDescription: check.description,
3566
+ stage,
3567
+ collection: source.collection
3568
+ }
3569
+ });
3570
+ const wireCommand = await this.deps.adapter.lower(source, {});
3571
+ for await (const row of this.deps.driver.execute(wireCommand)) if (filterEvaluator.evaluate(check.filter, row)) return true;
3572
+ return false;
3573
+ }
2276
3574
  async evaluateChecks(checks, inspectionExecutor, filterEvaluator) {
2277
3575
  return await this.firstFailingCheck(checks, inspectionExecutor, filterEvaluator) === void 0;
2278
3576
  }
2279
3577
  async firstFailingCheck(checks, inspectionExecutor, filterEvaluator) {
2280
3578
  for (const check of checks) {
2281
- const matchFound = (await check.source.accept(inspectionExecutor)).some((doc) => filterEvaluator.evaluate(check.filter, doc));
3579
+ const matchFound = isInspectionCheckSource(check.source) ? (await check.source.accept(inspectionExecutor)).some((doc) => filterEvaluator.evaluate(check.filter, doc)) : await this.documentsMatch(check, check.source, filterEvaluator);
2282
3580
  if (!(check.expect === "exists" ? matchFound : !matchFound)) return check;
2283
3581
  }
2284
3582
  }
@@ -2457,4 +3755,4 @@ const mongoTargetDescriptor = {
2457
3755
  //#endregion
2458
3756
  export { schemaIndexToCreateIndexOptions as C, schemaCollectionToCreateCollectionOptions as S, deserializeMongoOp as _, DropIndexCall as a, renderCallsToTypeScript as b, MongoMigrationRunner as c, MongoTargetSchemaVerifier as d, MongoTargetUnboundDatabase as f, UnsetFieldCall as g, RenameFieldCall as h, DropCollectionCall as i, MongoTargetContractSerializer as l, RenameCollectionCall as m, CreateCollectionCall as n, FilterEvaluator as o, PlannerProducedMongoMigration as p, CreateIndexCall as r, MongoMigrationPlanner as s, CollModCall as t, MongoTargetDatabase as u, deserializeMongoOps as v, serializeMongoOps as w, renderOps as x, mongoTargetDescriptor as y };
2459
3757
 
2460
- //# sourceMappingURL=control-B77seMDK.mjs.map
3758
+ //# sourceMappingURL=control-BxslS3_F.mjs.map