@prisma-next/family-mongo 0.7.0 → 0.8.0-dev.2

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 (37) hide show
  1. package/README.md +22 -9
  2. package/dist/control-adapter.d.mts +75 -0
  3. package/dist/control-adapter.d.mts.map +1 -0
  4. package/dist/control-adapter.mjs +1 -0
  5. package/dist/control.d.mts +60 -16
  6. package/dist/control.d.mts.map +1 -1
  7. package/dist/control.mjs +257 -276
  8. package/dist/control.mjs.map +1 -1
  9. package/dist/ir.d.mts +131 -0
  10. package/dist/ir.d.mts.map +1 -0
  11. package/dist/ir.mjs +54 -0
  12. package/dist/ir.mjs.map +1 -0
  13. package/dist/mongo-contract-serializer-Co3EaTVj.mjs +98 -0
  14. package/dist/mongo-contract-serializer-Co3EaTVj.mjs.map +1 -0
  15. package/dist/schema-verify.d.mts +22 -2
  16. package/dist/schema-verify.d.mts.map +1 -0
  17. package/dist/schema-verify.mjs +1 -1
  18. package/dist/verify-mongo-schema-BL7t9YTB.mjs +592 -0
  19. package/dist/verify-mongo-schema-BL7t9YTB.mjs.map +1 -0
  20. package/package.json +20 -22
  21. package/src/core/contract-to-schema.ts +84 -0
  22. package/src/core/control-adapter.ts +97 -0
  23. package/src/core/control-instance.ts +275 -272
  24. package/src/core/control-target-descriptor.ts +26 -0
  25. package/src/core/control-types.ts +6 -4
  26. package/src/core/ir/mongo-contract-serializer-base.ts +124 -0
  27. package/src/core/ir/mongo-contract-serializer.ts +18 -0
  28. package/src/core/ir/mongo-schema-verifier-base.ts +87 -0
  29. package/src/core/operation-preview.ts +131 -0
  30. package/src/core/schema-diff.ts +402 -0
  31. package/src/core/schema-verify/canonicalize-introspection.ts +389 -0
  32. package/src/core/schema-verify/verify-mongo-schema.ts +60 -0
  33. package/src/exports/control-adapter.ts +1 -0
  34. package/src/exports/control.ts +8 -1
  35. package/src/exports/ir.ts +3 -0
  36. package/src/exports/schema-verify.ts +4 -2
  37. package/src/core/mongo-target-descriptor.ts +0 -180
@@ -0,0 +1,592 @@
1
+ import { MongoSchemaCollection, MongoSchemaCollectionOptions, MongoSchemaIR, MongoSchemaIndex, MongoSchemaValidator, canonicalize, deepEqual } from "@prisma-next/mongo-schema-ir";
2
+ import { VERIFY_CODE_SCHEMA_FAILURE } from "@prisma-next/framework-components/control";
3
+ import { ifDefined } from "@prisma-next/utils/defined";
4
+ //#region src/core/contract-to-schema.ts
5
+ function stripIrKind(node) {
6
+ const { kind: _kind, ...rest } = node;
7
+ return rest;
8
+ }
9
+ function convertIndex(index) {
10
+ return new MongoSchemaIndex({
11
+ keys: index.keys,
12
+ unique: index.unique,
13
+ sparse: index.sparse,
14
+ expireAfterSeconds: index.expireAfterSeconds,
15
+ partialFilterExpression: index.partialFilterExpression,
16
+ wildcardProjection: index.wildcardProjection,
17
+ collation: index.collation,
18
+ weights: index.weights,
19
+ default_language: index.default_language,
20
+ language_override: index.language_override
21
+ });
22
+ }
23
+ function convertValidator(v) {
24
+ return new MongoSchemaValidator({
25
+ jsonSchema: v.jsonSchema,
26
+ validationLevel: v.validationLevel,
27
+ validationAction: v.validationAction
28
+ });
29
+ }
30
+ function convertOptions(o) {
31
+ return new MongoSchemaCollectionOptions({
32
+ ...o.capped !== void 0 && { capped: o.capped },
33
+ ...o.timeseries !== void 0 && { timeseries: {
34
+ timeField: o.timeseries.timeField,
35
+ ...o.timeseries.metaField !== void 0 && { metaField: o.timeseries.metaField },
36
+ ...o.timeseries.granularity !== void 0 && { granularity: o.timeseries.granularity }
37
+ } },
38
+ ...o.collation !== void 0 && { collation: stripIrKind(o.collation) },
39
+ ...o.changeStreamPreAndPostImages !== void 0 && { changeStreamPreAndPostImages: { enabled: o.changeStreamPreAndPostImages.enabled } },
40
+ ...o.clusteredIndex !== void 0 && { clusteredIndex: o.clusteredIndex }
41
+ });
42
+ }
43
+ function convertCollection(name, def) {
44
+ return new MongoSchemaCollection({
45
+ name,
46
+ indexes: (def.indexes ?? []).map(convertIndex),
47
+ ...def.validator != null && { validator: convertValidator(def.validator) },
48
+ ...def.options != null && { options: convertOptions(def.options) }
49
+ });
50
+ }
51
+ function contractToMongoSchemaIR(contract) {
52
+ if (!contract) return new MongoSchemaIR([]);
53
+ return new MongoSchemaIR(Object.entries(contract.storage.collections).map(([name, def]) => convertCollection(name, def)));
54
+ }
55
+ //#endregion
56
+ //#region src/core/schema-diff.ts
57
+ function diffMongoSchemas(live, expected, strict) {
58
+ const issues = [];
59
+ const collectionChildren = [];
60
+ let pass = 0;
61
+ let warn = 0;
62
+ let fail = 0;
63
+ const allNames = new Set([...live.collectionNames, ...expected.collectionNames]);
64
+ for (const name of [...allNames].sort()) {
65
+ const liveColl = live.collection(name);
66
+ const expectedColl = expected.collection(name);
67
+ if (!liveColl && expectedColl) {
68
+ issues.push({
69
+ kind: "missing_table",
70
+ table: name,
71
+ message: `Collection "${name}" is missing from the database`
72
+ });
73
+ collectionChildren.push({
74
+ status: "fail",
75
+ kind: "collection",
76
+ name,
77
+ contractPath: `storage.collections.${name}`,
78
+ code: "MISSING_COLLECTION",
79
+ message: `Collection "${name}" is missing`,
80
+ expected: name,
81
+ actual: null,
82
+ children: []
83
+ });
84
+ fail++;
85
+ continue;
86
+ }
87
+ if (liveColl && !expectedColl) {
88
+ const status = strict ? "fail" : "warn";
89
+ issues.push({
90
+ kind: "extra_table",
91
+ table: name,
92
+ message: `Extra collection "${name}" exists in the database but not in the contract`
93
+ });
94
+ collectionChildren.push({
95
+ status,
96
+ kind: "collection",
97
+ name,
98
+ contractPath: `storage.collections.${name}`,
99
+ code: "EXTRA_COLLECTION",
100
+ message: `Extra collection "${name}" found`,
101
+ expected: null,
102
+ actual: name,
103
+ children: []
104
+ });
105
+ if (status === "fail") fail++;
106
+ else warn++;
107
+ continue;
108
+ }
109
+ const lc = liveColl;
110
+ const ec = expectedColl;
111
+ const indexChildren = diffIndexes(name, lc, ec, strict, issues);
112
+ const validatorChildren = diffValidator(name, lc, ec, strict, issues);
113
+ const optionsChildren = diffOptions(name, lc, ec, strict, issues);
114
+ const children = [
115
+ ...indexChildren,
116
+ ...validatorChildren,
117
+ ...optionsChildren
118
+ ];
119
+ const worstStatus = children.reduce((s, c) => c.status === "fail" ? "fail" : c.status === "warn" && s !== "fail" ? "warn" : s, "pass");
120
+ for (const c of children) if (c.status === "pass") pass++;
121
+ else if (c.status === "warn") warn++;
122
+ else fail++;
123
+ if (children.length === 0) pass++;
124
+ collectionChildren.push({
125
+ status: worstStatus,
126
+ kind: "collection",
127
+ name,
128
+ contractPath: `storage.collections.${name}`,
129
+ code: worstStatus === "pass" ? "MATCH" : "DRIFT",
130
+ message: worstStatus === "pass" ? `Collection "${name}" matches` : `Collection "${name}" has drift`,
131
+ expected: name,
132
+ actual: name,
133
+ children
134
+ });
135
+ }
136
+ const rootStatus = fail > 0 ? "fail" : warn > 0 ? "warn" : "pass";
137
+ const totalNodes = pass + warn + fail + collectionChildren.length;
138
+ return {
139
+ root: {
140
+ status: rootStatus,
141
+ kind: "root",
142
+ name: "mongo-schema",
143
+ contractPath: "storage",
144
+ code: rootStatus === "pass" ? "MATCH" : "DRIFT",
145
+ message: rootStatus === "pass" ? "Schema matches" : "Schema has drift",
146
+ expected: null,
147
+ actual: null,
148
+ children: collectionChildren
149
+ },
150
+ issues,
151
+ counts: {
152
+ pass,
153
+ warn,
154
+ fail,
155
+ totalNodes
156
+ }
157
+ };
158
+ }
159
+ function buildIndexLookupKey(index) {
160
+ const keys = index.keys.map((k) => `${k.field}:${k.direction}`).join(",");
161
+ const opts = [
162
+ index.unique ? "unique" : "",
163
+ index.sparse ? "sparse" : "",
164
+ index.expireAfterSeconds != null ? `ttl:${index.expireAfterSeconds}` : "",
165
+ index.partialFilterExpression ? `pfe:${canonicalize(index.partialFilterExpression)}` : "",
166
+ index.wildcardProjection ? `wp:${canonicalize(index.wildcardProjection)}` : "",
167
+ index.collation ? `col:${canonicalize(index.collation)}` : "",
168
+ index.weights ? `wt:${canonicalize(index.weights)}` : "",
169
+ index.default_language ? `dl:${index.default_language}` : "",
170
+ index.language_override ? `lo:${index.language_override}` : ""
171
+ ].filter(Boolean).join(";");
172
+ return opts ? `${keys}|${opts}` : keys;
173
+ }
174
+ function formatIndexName(index) {
175
+ return index.keys.map((k) => `${k.field}:${k.direction}`).join(", ");
176
+ }
177
+ function diffIndexes(collName, live, expected, strict, issues) {
178
+ const nodes = [];
179
+ const liveLookup = /* @__PURE__ */ new Map();
180
+ for (const idx of live.indexes) liveLookup.set(buildIndexLookupKey(idx), idx);
181
+ const expectedLookup = /* @__PURE__ */ new Map();
182
+ for (const idx of expected.indexes) expectedLookup.set(buildIndexLookupKey(idx), idx);
183
+ for (const [key, idx] of expectedLookup) if (liveLookup.has(key)) nodes.push({
184
+ status: "pass",
185
+ kind: "index",
186
+ name: formatIndexName(idx),
187
+ contractPath: `storage.collections.${collName}.indexes`,
188
+ code: "MATCH",
189
+ message: `Index ${formatIndexName(idx)} matches`,
190
+ expected: key,
191
+ actual: key,
192
+ children: []
193
+ });
194
+ else {
195
+ issues.push({
196
+ kind: "index_mismatch",
197
+ table: collName,
198
+ indexOrConstraint: formatIndexName(idx),
199
+ message: `Index ${formatIndexName(idx)} missing on collection "${collName}"`
200
+ });
201
+ nodes.push({
202
+ status: "fail",
203
+ kind: "index",
204
+ name: formatIndexName(idx),
205
+ contractPath: `storage.collections.${collName}.indexes`,
206
+ code: "MISSING_INDEX",
207
+ message: `Index ${formatIndexName(idx)} missing`,
208
+ expected: key,
209
+ actual: null,
210
+ children: []
211
+ });
212
+ }
213
+ for (const [key, idx] of liveLookup) if (!expectedLookup.has(key)) {
214
+ const status = strict ? "fail" : "warn";
215
+ issues.push({
216
+ kind: "extra_index",
217
+ table: collName,
218
+ indexOrConstraint: formatIndexName(idx),
219
+ message: `Extra index ${formatIndexName(idx)} on collection "${collName}"`
220
+ });
221
+ nodes.push({
222
+ status,
223
+ kind: "index",
224
+ name: formatIndexName(idx),
225
+ contractPath: `storage.collections.${collName}.indexes`,
226
+ code: "EXTRA_INDEX",
227
+ message: `Extra index ${formatIndexName(idx)}`,
228
+ expected: null,
229
+ actual: key,
230
+ children: []
231
+ });
232
+ }
233
+ return nodes;
234
+ }
235
+ function diffValidator(collName, live, expected, strict, issues) {
236
+ if (!live.validator && !expected.validator) return [];
237
+ if (expected.validator && !live.validator) {
238
+ issues.push({
239
+ kind: "type_missing",
240
+ table: collName,
241
+ message: `Validator missing on collection "${collName}"`
242
+ });
243
+ return [{
244
+ status: "fail",
245
+ kind: "validator",
246
+ name: "validator",
247
+ contractPath: `storage.collections.${collName}.validator`,
248
+ code: "MISSING_VALIDATOR",
249
+ message: "Validator missing",
250
+ expected: canonicalize(expected.validator.jsonSchema),
251
+ actual: null,
252
+ children: []
253
+ }];
254
+ }
255
+ if (!expected.validator && live.validator) {
256
+ const status = strict ? "fail" : "warn";
257
+ issues.push({
258
+ kind: "extra_validator",
259
+ table: collName,
260
+ message: `Extra validator on collection "${collName}"`
261
+ });
262
+ return [{
263
+ status,
264
+ kind: "validator",
265
+ name: "validator",
266
+ contractPath: `storage.collections.${collName}.validator`,
267
+ code: "EXTRA_VALIDATOR",
268
+ message: "Extra validator found",
269
+ expected: null,
270
+ actual: canonicalize(live.validator.jsonSchema),
271
+ children: []
272
+ }];
273
+ }
274
+ const liveVal = live.validator;
275
+ const expectedVal = expected.validator;
276
+ const liveSchema = canonicalize(liveVal.jsonSchema);
277
+ const expectedSchema = canonicalize(expectedVal.jsonSchema);
278
+ if (liveSchema !== expectedSchema || liveVal.validationLevel !== expectedVal.validationLevel || liveVal.validationAction !== expectedVal.validationAction) {
279
+ issues.push({
280
+ kind: "type_mismatch",
281
+ table: collName,
282
+ expected: expectedSchema,
283
+ actual: liveSchema,
284
+ message: `Validator mismatch on collection "${collName}"`
285
+ });
286
+ return [{
287
+ status: "fail",
288
+ kind: "validator",
289
+ name: "validator",
290
+ contractPath: `storage.collections.${collName}.validator`,
291
+ code: "VALIDATOR_MISMATCH",
292
+ message: "Validator mismatch",
293
+ expected: {
294
+ jsonSchema: expectedVal.jsonSchema,
295
+ validationLevel: expectedVal.validationLevel,
296
+ validationAction: expectedVal.validationAction
297
+ },
298
+ actual: {
299
+ jsonSchema: liveVal.jsonSchema,
300
+ validationLevel: liveVal.validationLevel,
301
+ validationAction: liveVal.validationAction
302
+ },
303
+ children: []
304
+ }];
305
+ }
306
+ return [{
307
+ status: "pass",
308
+ kind: "validator",
309
+ name: "validator",
310
+ contractPath: `storage.collections.${collName}.validator`,
311
+ code: "MATCH",
312
+ message: "Validator matches",
313
+ expected: expectedSchema,
314
+ actual: liveSchema,
315
+ children: []
316
+ }];
317
+ }
318
+ function diffOptions(collName, live, expected, strict, issues) {
319
+ if (!live.options && !expected.options) return [];
320
+ if (!expected.options && live.options) {
321
+ const status = strict ? "fail" : "warn";
322
+ issues.push({
323
+ kind: "type_mismatch",
324
+ table: collName,
325
+ actual: canonicalize(live.options),
326
+ message: `Extra collection options on "${collName}"`
327
+ });
328
+ return [{
329
+ status,
330
+ kind: "options",
331
+ name: "options",
332
+ contractPath: `storage.collections.${collName}.options`,
333
+ code: "EXTRA_OPTIONS",
334
+ message: "Extra collection options found",
335
+ expected: null,
336
+ actual: live.options,
337
+ children: []
338
+ }];
339
+ }
340
+ if (deepEqual(live.options, expected.options)) return [{
341
+ status: "pass",
342
+ kind: "options",
343
+ name: "options",
344
+ contractPath: `storage.collections.${collName}.options`,
345
+ code: "MATCH",
346
+ message: "Collection options match",
347
+ expected: canonicalize(expected.options),
348
+ actual: canonicalize(live.options),
349
+ children: []
350
+ }];
351
+ issues.push({
352
+ kind: "type_mismatch",
353
+ table: collName,
354
+ expected: canonicalize(expected.options),
355
+ actual: canonicalize(live.options),
356
+ message: `Collection options mismatch on "${collName}"`
357
+ });
358
+ return [{
359
+ status: "fail",
360
+ kind: "options",
361
+ name: "options",
362
+ contractPath: `storage.collections.${collName}.options`,
363
+ code: "OPTIONS_MISMATCH",
364
+ message: "Collection options mismatch",
365
+ expected: expected.options,
366
+ actual: live.options,
367
+ children: []
368
+ }];
369
+ }
370
+ //#endregion
371
+ //#region src/core/schema-verify/canonicalize-introspection.ts
372
+ function canonicalizeSchemasForVerification(live, expected) {
373
+ const expectedByName = /* @__PURE__ */ new Map();
374
+ for (const c of expected.collections) expectedByName.set(c.name, c);
375
+ const liveByName = /* @__PURE__ */ new Map();
376
+ for (const c of live.collections) liveByName.set(c.name, c);
377
+ const canonicalLive = live.collections.map((c) => canonicalizeLiveCollection(c, expectedByName.get(c.name)));
378
+ const canonicalExpected = expected.collections.map((c) => canonicalizeExpectedCollection(c, liveByName.get(c.name)));
379
+ return {
380
+ live: new MongoSchemaIR(canonicalLive),
381
+ expected: new MongoSchemaIR(canonicalExpected)
382
+ };
383
+ }
384
+ function canonicalizeLiveCollection(liveColl, expectedColl) {
385
+ const expectedIndexes = expectedColl?.indexes ?? [];
386
+ const indexes = liveColl.indexes.map((idx) => canonicalizeLiveIndex(idx, findExpectedIndexCounterpart(idx, expectedIndexes)));
387
+ const options = liveColl.options ? canonicalizeLiveOptions(liveColl.options, expectedColl?.options) : void 0;
388
+ return new MongoSchemaCollection({
389
+ name: liveColl.name,
390
+ indexes,
391
+ ...ifDefined("validator", liveColl.validator),
392
+ ...ifDefined("options", options)
393
+ });
394
+ }
395
+ function canonicalizeExpectedCollection(expectedColl, liveColl) {
396
+ const indexes = expectedColl.indexes.map(canonicalizeTextIndexKeyOrder);
397
+ const options = expectedColl.options ? canonicalizeExpectedOptions(expectedColl.options, liveColl?.options) : void 0;
398
+ return new MongoSchemaCollection({
399
+ name: expectedColl.name,
400
+ indexes,
401
+ ...ifDefined("validator", expectedColl.validator),
402
+ ...ifDefined("options", options)
403
+ });
404
+ }
405
+ function canonicalizeTextIndexKeyOrder(index) {
406
+ if (!index.keys.some((k) => k.direction === "text")) return index;
407
+ return new MongoSchemaIndex({
408
+ keys: sortTextKeys(index.keys),
409
+ unique: index.unique,
410
+ ...ifDefined("sparse", index.sparse),
411
+ ...ifDefined("expireAfterSeconds", index.expireAfterSeconds),
412
+ ...ifDefined("partialFilterExpression", index.partialFilterExpression),
413
+ ...ifDefined("wildcardProjection", index.wildcardProjection),
414
+ ...ifDefined("collation", index.collation),
415
+ ...ifDefined("weights", index.weights),
416
+ ...ifDefined("default_language", index.default_language),
417
+ ...ifDefined("language_override", index.language_override)
418
+ });
419
+ }
420
+ /**
421
+ * Returns a copy of `keys` with text-direction entries sorted alphabetically
422
+ * while preserving the relative position of non-text entries. Compound text
423
+ * indexes (`{a: 1, _fts: 'text', _ftsx: 1, b: 1}`) keep their scalar
424
+ * prefix/suffix layout; only the contiguous text block is reordered.
425
+ */
426
+ function sortTextKeys(keys) {
427
+ const textEntries = keys.filter((k) => k.direction === "text");
428
+ if (textEntries.length <= 1) return keys;
429
+ const sortedText = [...textEntries].sort((a, b) => a.field.localeCompare(b.field));
430
+ let textIdx = 0;
431
+ return keys.map((k) => {
432
+ if (k.direction !== "text") return k;
433
+ const next = sortedText[textIdx++];
434
+ /* v8 ignore next 3 -- @preserve invariant guard: textIdx is always < sortedText.length here because we only consume sortedText for text-direction entries and sortedText is built from the same filter. */
435
+ if (next === void 0) throw new Error("sortTextKeys: text-key counts mismatched");
436
+ return next;
437
+ });
438
+ }
439
+ function canonicalizeLiveIndex(liveIndex, expectedIndex) {
440
+ const projectedKeys = sortTextKeys(projectTextIndexKeys(liveIndex));
441
+ const collation = liveIndex.collation ? stripUnspecifiedFields(liveIndex.collation, expectedIndex?.collation) : liveIndex.collation;
442
+ const weights = expectedIndex?.weights === void 0 && hasDefaultTextWeights(projectedKeys, liveIndex.weights) ? void 0 : liveIndex.weights;
443
+ const default_language = expectedIndex?.default_language === void 0 && liveIndex.default_language === "english" ? void 0 : liveIndex.default_language;
444
+ const language_override = expectedIndex?.language_override === void 0 && liveIndex.language_override === "language" ? void 0 : liveIndex.language_override;
445
+ return new MongoSchemaIndex({
446
+ keys: projectedKeys,
447
+ unique: liveIndex.unique,
448
+ ...ifDefined("sparse", liveIndex.sparse),
449
+ ...ifDefined("expireAfterSeconds", liveIndex.expireAfterSeconds),
450
+ ...ifDefined("partialFilterExpression", liveIndex.partialFilterExpression),
451
+ ...ifDefined("wildcardProjection", liveIndex.wildcardProjection),
452
+ ...ifDefined("collation", collation),
453
+ ...ifDefined("weights", weights),
454
+ ...ifDefined("default_language", default_language),
455
+ ...ifDefined("language_override", language_override)
456
+ });
457
+ }
458
+ /**
459
+ * Locate the contract-side index that corresponds to a live index for the
460
+ * purpose of contract-aware normalization. We deliberately match by the
461
+ * *projected* (contract-shaped) key list — so a live `_fts/_ftsx` index
462
+ * resolves to a contract `{title: 'text', body: 'text'}` index — and pick
463
+ * the first match. Contracts very rarely contain duplicate-key indexes; if
464
+ * we have no counterpart we fall back to no normalization for that index.
465
+ */
466
+ function findExpectedIndexCounterpart(liveIndex, expectedIndexes) {
467
+ const liveKeySig = sortTextKeys(projectTextIndexKeys(liveIndex)).map((k) => `${k.field}:${k.direction}`).join(",");
468
+ for (const expected of expectedIndexes) if (sortTextKeys(expected.keys).map((k) => `${k.field}:${k.direction}`).join(",") === liveKeySig) return expected;
469
+ }
470
+ /**
471
+ * MongoDB expands a contract-shaped text index like
472
+ * `[{title: 'text'}, {body: 'text'}]` into its internal weighted vector
473
+ * representation `[{_fts: 'text'}, {_ftsx: 1}]`. We project back to
474
+ * contract-shaped keys via `weights`, iterating in whatever order MongoDB
475
+ * returns them (alphabetical, in practice). `sortTextKeys` is applied
476
+ * downstream to canonicalize the order on both sides, so this projection
477
+ * does not depend on a specific iteration order.
478
+ */
479
+ function projectTextIndexKeys(liveIndex) {
480
+ if (!(liveIndex.keys.length >= 1 && liveIndex.keys.some((k) => k.field === "_fts" && k.direction === "text")) || !liveIndex.weights) return liveIndex.keys;
481
+ const textKeys = Object.keys(liveIndex.weights).map((field) => ({
482
+ field,
483
+ direction: "text"
484
+ }));
485
+ const projectedKeys = [];
486
+ for (const key of liveIndex.keys) {
487
+ if (key.field === "_ftsx") continue;
488
+ if (key.field === "_fts") {
489
+ projectedKeys.push(...textKeys);
490
+ continue;
491
+ }
492
+ projectedKeys.push(key);
493
+ }
494
+ return projectedKeys;
495
+ }
496
+ /**
497
+ * MongoDB's server-default `weights` for an authored-without-weights text
498
+ * index assigns `1` to every text-direction field. Returns `true` only when
499
+ * `liveWeights` is exactly that uniform shape (every projected text-direction
500
+ * key weighted at `1`) so the canonicalizer leaves non-default weights —
501
+ * including out-of-band relevance tweaks — visible to the verifier.
502
+ *
503
+ * `projectTextIndexKeys` derives text-direction keys from the live weights
504
+ * map, so the count is guaranteed to match; we only have to check the value
505
+ * shape.
506
+ */
507
+ function hasDefaultTextWeights(projectedKeys, liveWeights) {
508
+ if (liveWeights === void 0) return false;
509
+ return projectedKeys.filter((k) => k.direction === "text").map((k) => k.field).every((field) => liveWeights[field] === 1);
510
+ }
511
+ function canonicalizeLiveOptions(liveOptions, expectedOptions) {
512
+ const collation = liveOptions.collation ? stripUnspecifiedFields(liveOptions.collation, expectedOptions?.collation) : void 0;
513
+ const timeseries = liveOptions.timeseries ? stripUnspecifiedFields(liveOptions.timeseries, expectedOptions?.timeseries) : void 0;
514
+ const clusteredIndex = liveOptions.clusteredIndex ? stripUnspecifiedFields(liveOptions.clusteredIndex, expectedOptions?.clusteredIndex) : void 0;
515
+ const changeStreamPreAndPostImages = isDisabledChangeStream(liveOptions.changeStreamPreAndPostImages) ? void 0 : liveOptions.changeStreamPreAndPostImages;
516
+ if (!(liveOptions.capped || timeseries || collation || changeStreamPreAndPostImages || clusteredIndex)) return void 0;
517
+ return new MongoSchemaCollectionOptions({
518
+ ...ifDefined("capped", liveOptions.capped),
519
+ ...ifDefined("timeseries", timeseries),
520
+ ...ifDefined("collation", collation),
521
+ ...ifDefined("changeStreamPreAndPostImages", changeStreamPreAndPostImages),
522
+ ...ifDefined("clusteredIndex", clusteredIndex)
523
+ });
524
+ }
525
+ function canonicalizeExpectedOptions(expectedOptions, _liveOptions) {
526
+ const changeStreamPreAndPostImages = isDisabledChangeStream(expectedOptions.changeStreamPreAndPostImages) ? void 0 : expectedOptions.changeStreamPreAndPostImages;
527
+ if (!(expectedOptions.capped || expectedOptions.timeseries || expectedOptions.collation || changeStreamPreAndPostImages || expectedOptions.clusteredIndex)) return void 0;
528
+ return new MongoSchemaCollectionOptions({
529
+ ...ifDefined("capped", expectedOptions.capped),
530
+ ...ifDefined("timeseries", expectedOptions.timeseries),
531
+ ...ifDefined("collation", expectedOptions.collation),
532
+ ...ifDefined("changeStreamPreAndPostImages", changeStreamPreAndPostImages),
533
+ ...ifDefined("clusteredIndex", expectedOptions.clusteredIndex)
534
+ });
535
+ }
536
+ function isDisabledChangeStream(value) {
537
+ return value !== void 0 && value.enabled === false;
538
+ }
539
+ /**
540
+ * Returns a copy of `live` containing only the keys that `expected` defines.
541
+ * Used for option families whose individual sub-fields are server-extended
542
+ * with platform defaults (collation, timeseries, clusteredIndex), so the
543
+ * verifier should compare only what the contract actually authored.
544
+ *
545
+ * When `expected` is `undefined` — i.e. the contract authored nothing for
546
+ * this whole option family but the live IR has it — we return `live`
547
+ * unchanged so the verifier still sees the entire live block and can
548
+ * surface it as drift. (Returning `undefined` here would silently strip a
549
+ * server-attached collation/timeseries/clusteredIndex that the contract
550
+ * never asked for, hiding real drift.)
551
+ */
552
+ function stripUnspecifiedFields(live, expected) {
553
+ if (expected === void 0) return live;
554
+ const out = {};
555
+ for (const key of Object.keys(expected)) if (Object.hasOwn(live, key)) out[key] = live[key];
556
+ return out;
557
+ }
558
+ //#endregion
559
+ //#region src/core/schema-verify/verify-mongo-schema.ts
560
+ function verifyMongoSchema(options) {
561
+ const { contract, schema, strict, context } = options;
562
+ const startTime = Date.now();
563
+ const { live: canonicalLive, expected: canonicalExpected } = canonicalizeSchemasForVerification(schema, contractToMongoSchemaIR(contract));
564
+ const { root, issues, counts } = diffMongoSchemas(canonicalLive, canonicalExpected, strict);
565
+ const ok = counts.fail === 0;
566
+ const profileHash = typeof contract.profileHash === "string" ? contract.profileHash : "";
567
+ return {
568
+ ok,
569
+ ...ifDefined("code", ok ? void 0 : VERIFY_CODE_SCHEMA_FAILURE),
570
+ summary: ok ? "Schema matches contract" : `Schema verification found ${counts.fail} issue(s)`,
571
+ contract: {
572
+ storageHash: contract.storage.storageHash,
573
+ ...profileHash ? { profileHash } : {}
574
+ },
575
+ target: { expected: contract.target },
576
+ schema: {
577
+ issues,
578
+ root,
579
+ counts
580
+ },
581
+ meta: {
582
+ strict,
583
+ ...ifDefined("contractPath", context?.contractPath),
584
+ ...ifDefined("configPath", context?.configPath)
585
+ },
586
+ timings: { total: Date.now() - startTime }
587
+ };
588
+ }
589
+ //#endregion
590
+ export { contractToMongoSchemaIR as i, canonicalizeSchemasForVerification as n, diffMongoSchemas as r, verifyMongoSchema as t };
591
+
592
+ //# sourceMappingURL=verify-mongo-schema-BL7t9YTB.mjs.map