@prisma-next/target-mongo 0.7.0 → 0.8.0-dev.1

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