@prisma-next/mongo-contract-psl 0.14.0-dev.34 → 0.14.0-dev.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/exports/provider.mjs +1 -1
- package/dist/index.d.mts +12 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{interpreter-CDnf61pR.mjs → interpreter-WfZjKUyx.mjs} +44 -15
- package/dist/interpreter-WfZjKUyx.mjs.map +1 -0
- package/package.json +12 -11
- package/src/derive-json-schema.ts +19 -12
- package/src/exports/index.ts +5 -1
- package/src/interpreter.ts +56 -7
- package/dist/interpreter-CDnf61pR.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as interpretPslDocumentToMongoContract } from "../interpreter-
|
|
1
|
+
import { t as interpretPslDocumentToMongoContract } from "../interpreter-WfZjKUyx.mjs";
|
|
2
2
|
import { buildSymbolTable, rangeToPslSpan } from "@prisma-next/psl-parser";
|
|
3
3
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
4
4
|
import { notOk, ok } from "@prisma-next/utils/result";
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MongoValidator } from "@prisma-next/mongo-contract";
|
|
2
|
-
import { Contract,
|
|
2
|
+
import { Contract, ContractField, ContractValueObject, JsonValue } from "@prisma-next/contract/types";
|
|
3
3
|
import { AuthoringContributions } from "@prisma-next/framework-components/authoring";
|
|
4
4
|
import { SymbolTable } from "@prisma-next/psl-parser";
|
|
5
5
|
import { Result } from "@prisma-next/utils/result";
|
|
@@ -8,12 +8,20 @@ import { CodecLookup } from "@prisma-next/framework-components/codec";
|
|
|
8
8
|
import { ContractSourceDiagnostic, ContractSourceDiagnostics } from "@prisma-next/config/config-types";
|
|
9
9
|
|
|
10
10
|
//#region src/derive-json-schema.d.ts
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* The permitted values a field's value set restricts it to, keyed by the value set's name — the
|
|
13
|
+
* storage `entries.valueSet` slot. The validator's `enum` keyword is sourced from these, not from
|
|
14
|
+
* `domain.enum`.
|
|
15
|
+
*/
|
|
16
|
+
type FieldValueSets = Record<string, {
|
|
17
|
+
readonly values: readonly JsonValue[];
|
|
18
|
+
}>;
|
|
19
|
+
declare function deriveJsonSchema(fields: Record<string, ContractField>, valueObjects?: Record<string, ContractValueObject>, codecLookup?: CodecLookup, valueSets?: FieldValueSets): MongoValidator;
|
|
12
20
|
interface PolymorphicVariant {
|
|
13
21
|
readonly discriminatorValue: string;
|
|
14
22
|
readonly fields: Record<string, ContractField>;
|
|
15
23
|
}
|
|
16
|
-
declare function derivePolymorphicJsonSchema(baseFields: Record<string, ContractField>, discriminatorField: string, variants: readonly PolymorphicVariant[], valueObjects?: Record<string, ContractValueObject>, codecLookup?: CodecLookup,
|
|
24
|
+
declare function derivePolymorphicJsonSchema(baseFields: Record<string, ContractField>, discriminatorField: string, variants: readonly PolymorphicVariant[], valueObjects?: Record<string, ContractValueObject>, codecLookup?: CodecLookup, valueSets?: FieldValueSets): MongoValidator;
|
|
17
25
|
//#endregion
|
|
18
26
|
//#region src/interpreter.d.ts
|
|
19
27
|
interface InterpretPslDocumentToMongoContractInput {
|
|
@@ -27,5 +35,5 @@ interface InterpretPslDocumentToMongoContractInput {
|
|
|
27
35
|
}
|
|
28
36
|
declare function interpretPslDocumentToMongoContract(input: InterpretPslDocumentToMongoContractInput): Result<Contract, ContractSourceDiagnostics>;
|
|
29
37
|
//#endregion
|
|
30
|
-
export { type InterpretPslDocumentToMongoContractInput, deriveJsonSchema, derivePolymorphicJsonSchema, interpretPslDocumentToMongoContract };
|
|
38
|
+
export { type FieldValueSets, type InterpretPslDocumentToMongoContractInput, deriveJsonSchema, derivePolymorphicJsonSchema, interpretPslDocumentToMongoContract };
|
|
31
39
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/derive-json-schema.ts","../src/interpreter.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/derive-json-schema.ts","../src/interpreter.ts"],"mappings":";;;;;;;;;;;;;;;KASY,cAAA,GAAiB,MAAM;EAAA,SAAoB,MAAA,WAAiB,SAAA;AAAA;AAAA,iBA2FxD,gBAAA,CACd,MAAA,EAAQ,MAAA,SAAe,aAAA,GACvB,YAAA,GAAe,MAAA,SAAe,mBAAA,GAC9B,WAAA,GAAc,WAAA,EACd,SAAA,GAAY,cAAA,GACX,cAAA;AAAA,UAQc,kBAAA;EAAA,SACN,kBAAA;EAAA,SACA,MAAA,EAAQ,MAAM,SAAS,aAAA;AAAA;AAAA,iBAGlB,2BAAA,CACd,UAAA,EAAY,MAAA,SAAe,aAAA,GAC3B,kBAAA,UACA,QAAA,WAAmB,kBAAA,IACnB,YAAA,GAAe,MAAA,SAAe,mBAAA,GAC9B,WAAA,GAAc,WAAA,EACd,SAAA,GAAY,cAAA,GACX,cAAA;;;UC3Cc,wCAAA;EAAA,SACN,WAAA,EAAa,WAAA;EAAA,SACb,UAAA,EAAY,UAAA;EAAA,SACZ,QAAA;EAAA,SACA,qBAAA,EAAuB,WAAA;EAAA,SACvB,WAAA,GAAc,WAAA;EAAA,SACd,eAAA,YAA2B,wBAAA;EAAA,SAC3B,sBAAA,GAAyB,sBAAA;AAAA;AAAA,iBA41BpB,mCAAA,CACd,KAAA,EAAO,wCAAA,GACN,MAAA,CAAO,QAAA,EAAU,yBAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as deriveJsonSchema, r as derivePolymorphicJsonSchema, t as interpretPslDocumentToMongoContract } from "./interpreter-
|
|
1
|
+
import { n as deriveJsonSchema, r as derivePolymorphicJsonSchema, t as interpretPslDocumentToMongoContract } from "./interpreter-WfZjKUyx.mjs";
|
|
2
2
|
export { deriveJsonSchema, derivePolymorphicJsonSchema, interpretPslDocumentToMongoContract };
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { MongoIndex, MongoStorage, MongoValidator, applyPolymorphicScopeToMongoIndex, buildMongoNamespace } from "@prisma-next/mongo-contract";
|
|
2
2
|
import { computeProfileHash, computeStorageHash } from "@prisma-next/contract/hashing";
|
|
3
3
|
import { crossRef } from "@prisma-next/contract/types";
|
|
4
|
+
import { errorEnumCodecNotInPackStack } from "@prisma-next/errors/control";
|
|
4
5
|
import { instantiateAuthoringEntityType, isAuthoringEntityTypeDescriptor } from "@prisma-next/framework-components/authoring";
|
|
5
6
|
import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
|
|
6
7
|
import { mongoContractCanonicalizationHooks } from "@prisma-next/mongo-contract/canonicalization-hooks";
|
|
7
8
|
import { nodePslSpan, parseQuotedStringLiteral } from "@prisma-next/psl-parser";
|
|
9
|
+
import { assertDefined } from "@prisma-next/utils/assertions";
|
|
8
10
|
import { blindCast } from "@prisma-next/utils/casts";
|
|
9
11
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
10
12
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -12,11 +14,11 @@ import { notOk, ok } from "@prisma-next/utils/result";
|
|
|
12
14
|
function resolveBsonType(codecId, codecLookup) {
|
|
13
15
|
return codecLookup?.targetTypesFor(codecId)?.[0];
|
|
14
16
|
}
|
|
15
|
-
function fieldToBsonSchema(field, valueObjects, codecLookup,
|
|
17
|
+
function fieldToBsonSchema(field, valueObjects, codecLookup, valueSets) {
|
|
16
18
|
if (field.type.kind === "scalar") {
|
|
17
19
|
const bsonType = resolveBsonType(field.type.codecId, codecLookup);
|
|
18
20
|
if (!bsonType) return void 0;
|
|
19
|
-
const enumValues = field.valueSet
|
|
21
|
+
const enumValues = field.valueSet !== void 0 ? valueSets?.[field.valueSet.entityName]?.values ?? null : null;
|
|
20
22
|
if ("many" in field && field.many) {
|
|
21
23
|
const items = { bsonType };
|
|
22
24
|
if (enumValues) items["enum"] = enumValues;
|
|
@@ -37,7 +39,7 @@ function fieldToBsonSchema(field, valueObjects, codecLookup, enums) {
|
|
|
37
39
|
if (field.type.kind === "valueObject") {
|
|
38
40
|
const vo = valueObjects?.[field.type.name];
|
|
39
41
|
if (!vo) return void 0;
|
|
40
|
-
const voSchema = deriveObjectSchema(vo.fields, valueObjects, codecLookup,
|
|
42
|
+
const voSchema = deriveObjectSchema(vo.fields, valueObjects, codecLookup, valueSets);
|
|
41
43
|
if ("many" in field && field.many) return {
|
|
42
44
|
bsonType: "array",
|
|
43
45
|
items: voSchema
|
|
@@ -46,11 +48,11 @@ function fieldToBsonSchema(field, valueObjects, codecLookup, enums) {
|
|
|
46
48
|
return voSchema;
|
|
47
49
|
}
|
|
48
50
|
}
|
|
49
|
-
function deriveObjectSchema(fields, valueObjects, codecLookup,
|
|
51
|
+
function deriveObjectSchema(fields, valueObjects, codecLookup, valueSets) {
|
|
50
52
|
const properties = {};
|
|
51
53
|
const required = [];
|
|
52
54
|
for (const [fieldName, field] of Object.entries(fields)) {
|
|
53
|
-
const schema = fieldToBsonSchema(field, valueObjects, codecLookup,
|
|
55
|
+
const schema = fieldToBsonSchema(field, valueObjects, codecLookup, valueSets);
|
|
54
56
|
if (schema) {
|
|
55
57
|
properties[fieldName] = schema;
|
|
56
58
|
if (!field.nullable) required.push(fieldName);
|
|
@@ -67,15 +69,15 @@ function deriveObjectSchema(fields, valueObjects, codecLookup, enums) {
|
|
|
67
69
|
function isRecord(value) {
|
|
68
70
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
69
71
|
}
|
|
70
|
-
function deriveJsonSchema(fields, valueObjects, codecLookup,
|
|
72
|
+
function deriveJsonSchema(fields, valueObjects, codecLookup, valueSets) {
|
|
71
73
|
return new MongoValidator({
|
|
72
|
-
jsonSchema: deriveObjectSchema(fields, valueObjects, codecLookup,
|
|
74
|
+
jsonSchema: deriveObjectSchema(fields, valueObjects, codecLookup, valueSets),
|
|
73
75
|
validationLevel: "strict",
|
|
74
76
|
validationAction: "error"
|
|
75
77
|
});
|
|
76
78
|
}
|
|
77
|
-
function derivePolymorphicJsonSchema(baseFields, discriminatorField, variants, valueObjects, codecLookup,
|
|
78
|
-
const baseSchema = deriveObjectSchema(baseFields, valueObjects, codecLookup,
|
|
79
|
+
function derivePolymorphicJsonSchema(baseFields, discriminatorField, variants, valueObjects, codecLookup, valueSets) {
|
|
80
|
+
const baseSchema = deriveObjectSchema(baseFields, valueObjects, codecLookup, valueSets);
|
|
79
81
|
const baseProperties = isRecord(baseSchema["properties"]) ? baseSchema["properties"] : {};
|
|
80
82
|
const oneOf = [];
|
|
81
83
|
for (const variant of variants) {
|
|
@@ -84,7 +86,7 @@ function derivePolymorphicJsonSchema(baseFields, discriminatorField, variants, v
|
|
|
84
86
|
const variantProperties = {};
|
|
85
87
|
const variantRequired = [discriminatorField];
|
|
86
88
|
for (const [name, field] of Object.entries(variantOnlyFields)) {
|
|
87
|
-
const schema = fieldToBsonSchema(field, valueObjects, codecLookup,
|
|
89
|
+
const schema = fieldToBsonSchema(field, valueObjects, codecLookup, valueSets);
|
|
88
90
|
if (schema) {
|
|
89
91
|
variantProperties[name] = schema;
|
|
90
92
|
if (!field.nullable) variantRequired.push(name);
|
|
@@ -201,6 +203,18 @@ function stripQuotes(value) {
|
|
|
201
203
|
//#endregion
|
|
202
204
|
//#region src/interpreter.ts
|
|
203
205
|
/**
|
|
206
|
+
* Encode an authored enum value to its codec-encoded JSON form via the codec resolved by id from the
|
|
207
|
+
* contract's codec lookup, so a non-identity `encodeJson` (permitted by the `mongoCodec` factory) is
|
|
208
|
+
* respected. Matches the TS builder's `encodeEnumValue`: the lookup is always threaded in production,
|
|
209
|
+
* and a codecId the lookup cannot resolve is a hard error — the enum uses a codec that is not part of
|
|
210
|
+
* the contract's pack stack.
|
|
211
|
+
*/
|
|
212
|
+
function encodeEnumValue(value, codecId, codecLookup) {
|
|
213
|
+
const codec = codecLookup.get(codecId);
|
|
214
|
+
if (!codec) throw errorEnumCodecNotInPackStack({ codecId });
|
|
215
|
+
return codec.encodeJson(value);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
204
218
|
* Mongo's PSL surface binds the database from the connection string, so every
|
|
205
219
|
* explicit namespace block is invalid, including `namespace unbound { … }`.
|
|
206
220
|
*/
|
|
@@ -998,6 +1012,15 @@ function interpretPslDocumentToMongoContract(input) {
|
|
|
998
1012
|
});
|
|
999
1013
|
const resolvedModels = polyResult.models;
|
|
1000
1014
|
const resolvedCollections = polyResult.collections;
|
|
1015
|
+
const storageValueSets = {};
|
|
1016
|
+
const enumEntries = Object.entries(builtEnums);
|
|
1017
|
+
if (enumEntries.length > 0) {
|
|
1018
|
+
assertDefined(codecLookup, "Mongo PSL interpretation requires a codec lookup to encode enum values");
|
|
1019
|
+
for (const [enumName, builtEnum] of enumEntries) storageValueSets[enumName] = {
|
|
1020
|
+
kind: "valueSet",
|
|
1021
|
+
values: builtEnum.members.map((m) => encodeEnumValue(m.value, builtEnum.codecId, codecLookup))
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1001
1024
|
for (const [, modelEntry] of Object.entries(resolvedModels)) {
|
|
1002
1025
|
if (modelEntry.base) continue;
|
|
1003
1026
|
const coll = resolvedCollections[modelEntry.storage.collection];
|
|
@@ -1007,8 +1030,8 @@ function interpretPslDocumentToMongoContract(input) {
|
|
|
1007
1030
|
discriminatorValue: value,
|
|
1008
1031
|
fields: resolvedModels[variantName]?.fields ?? {}
|
|
1009
1032
|
}));
|
|
1010
|
-
coll["validator"] = derivePolymorphicJsonSchema(modelEntry.fields, modelEntry.discriminator.field, variantEntries, valueObjects, codecLookup,
|
|
1011
|
-
} else coll["validator"] = deriveJsonSchema(modelEntry.fields, valueObjects, codecLookup,
|
|
1033
|
+
coll["validator"] = derivePolymorphicJsonSchema(modelEntry.fields, modelEntry.discriminator.field, variantEntries, valueObjects, codecLookup, storageValueSets);
|
|
1034
|
+
} else coll["validator"] = deriveJsonSchema(modelEntry.fields, valueObjects, codecLookup, storageValueSets);
|
|
1012
1035
|
}
|
|
1013
1036
|
const target = "mongo";
|
|
1014
1037
|
const targetFamily = "mongo";
|
|
@@ -1022,7 +1045,10 @@ function interpretPslDocumentToMongoContract(input) {
|
|
|
1022
1045
|
}
|
|
1023
1046
|
const unboundNamespace = buildMongoNamespace({
|
|
1024
1047
|
id: UNBOUND_NAMESPACE_ID,
|
|
1025
|
-
entries: {
|
|
1048
|
+
entries: {
|
|
1049
|
+
collection: collectionInputs,
|
|
1050
|
+
...Object.keys(storageValueSets).length > 0 ? { valueSet: storageValueSets } : {}
|
|
1051
|
+
}
|
|
1026
1052
|
});
|
|
1027
1053
|
const storage = new MongoStorage({
|
|
1028
1054
|
storageHash: computeStorageHash({
|
|
@@ -1030,7 +1056,10 @@ function interpretPslDocumentToMongoContract(input) {
|
|
|
1030
1056
|
targetFamily,
|
|
1031
1057
|
storage: { namespaces: { [UNBOUND_NAMESPACE_ID]: {
|
|
1032
1058
|
id: UNBOUND_NAMESPACE_ID,
|
|
1033
|
-
entries: {
|
|
1059
|
+
entries: {
|
|
1060
|
+
collection: unboundNamespace.entries.collection,
|
|
1061
|
+
...unboundNamespace.entries.valueSet !== void 0 ? { valueSet: unboundNamespace.entries.valueSet } : {}
|
|
1062
|
+
}
|
|
1034
1063
|
} } },
|
|
1035
1064
|
...mongoContractCanonicalizationHooks
|
|
1036
1065
|
}),
|
|
@@ -1061,4 +1090,4 @@ function interpretPslDocumentToMongoContract(input) {
|
|
|
1061
1090
|
//#endregion
|
|
1062
1091
|
export { deriveJsonSchema as n, derivePolymorphicJsonSchema as r, interpretPslDocumentToMongoContract as t };
|
|
1063
1092
|
|
|
1064
|
-
//# sourceMappingURL=interpreter-
|
|
1093
|
+
//# sourceMappingURL=interpreter-WfZjKUyx.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interpreter-WfZjKUyx.mjs","names":[],"sources":["../src/derive-json-schema.ts","../src/psl-helpers.ts","../src/interpreter.ts"],"sourcesContent":["import type { ContractField, ContractValueObject, JsonValue } from '@prisma-next/contract/types';\nimport type { CodecLookup } from '@prisma-next/framework-components/codec';\nimport { MongoValidator } from '@prisma-next/mongo-contract';\n\n/**\n * The permitted values a field's value set restricts it to, keyed by the value set's name — the\n * storage `entries.valueSet` slot. The validator's `enum` keyword is sourced from these, not from\n * `domain.enum`.\n */\nexport type FieldValueSets = Record<string, { readonly values: readonly JsonValue[] }>;\n\nfunction resolveBsonType(\n codecId: string,\n codecLookup: CodecLookup | undefined,\n): string | undefined {\n return codecLookup?.targetTypesFor(codecId)?.[0];\n}\n\nfunction fieldToBsonSchema(\n field: ContractField,\n valueObjects: Record<string, ContractValueObject> | undefined,\n codecLookup: CodecLookup | undefined,\n valueSets: FieldValueSets | undefined,\n): Record<string, unknown> | undefined {\n if (field.type.kind === 'scalar') {\n const bsonType = resolveBsonType(field.type.codecId, codecLookup);\n if (!bsonType) return undefined;\n\n const enumValues =\n field.valueSet !== undefined\n ? (valueSets?.[field.valueSet.entityName]?.values ?? null)\n : null;\n\n if ('many' in field && field.many) {\n const items: Record<string, unknown> = { bsonType };\n if (enumValues) items['enum'] = enumValues;\n return { bsonType: 'array', items };\n }\n\n if (field.nullable) {\n const s: Record<string, unknown> = { bsonType: ['null', bsonType] };\n if (enumValues) s['enum'] = [...enumValues, null];\n return s;\n }\n\n const s: Record<string, unknown> = { bsonType };\n if (enumValues) s['enum'] = enumValues;\n return s;\n }\n\n if (field.type.kind === 'valueObject') {\n const vo = valueObjects?.[field.type.name];\n if (!vo) return undefined;\n const voSchema = deriveObjectSchema(vo.fields, valueObjects, codecLookup, valueSets);\n if ('many' in field && field.many) {\n return { bsonType: 'array', items: voSchema };\n }\n if (field.nullable) {\n return { oneOf: [{ bsonType: 'null' }, voSchema] };\n }\n return voSchema;\n }\n\n return undefined;\n}\n\nfunction deriveObjectSchema(\n fields: Record<string, ContractField>,\n valueObjects: Record<string, ContractValueObject> | undefined,\n codecLookup: CodecLookup | undefined,\n valueSets: FieldValueSets | undefined,\n): Record<string, unknown> {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [fieldName, field] of Object.entries(fields)) {\n const schema = fieldToBsonSchema(field, valueObjects, codecLookup, valueSets);\n if (schema) {\n properties[fieldName] = schema;\n if (!field.nullable) {\n required.push(fieldName);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n bsonType: 'object',\n properties,\n additionalProperties: false,\n };\n if (required.length > 0) {\n result['required'] = required.sort();\n }\n return result;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function deriveJsonSchema(\n fields: Record<string, ContractField>,\n valueObjects?: Record<string, ContractValueObject>,\n codecLookup?: CodecLookup,\n valueSets?: FieldValueSets,\n): MongoValidator {\n return new MongoValidator({\n jsonSchema: deriveObjectSchema(fields, valueObjects, codecLookup, valueSets),\n validationLevel: 'strict',\n validationAction: 'error',\n });\n}\n\nexport interface PolymorphicVariant {\n readonly discriminatorValue: string;\n readonly fields: Record<string, ContractField>;\n}\n\nexport function derivePolymorphicJsonSchema(\n baseFields: Record<string, ContractField>,\n discriminatorField: string,\n variants: readonly PolymorphicVariant[],\n valueObjects?: Record<string, ContractValueObject>,\n codecLookup?: CodecLookup,\n valueSets?: FieldValueSets,\n): MongoValidator {\n const baseSchema = deriveObjectSchema(baseFields, valueObjects, codecLookup, valueSets);\n const baseProperties = isRecord(baseSchema['properties']) ? baseSchema['properties'] : {};\n\n const oneOf: Record<string, unknown>[] = [];\n for (const variant of variants) {\n const variantOnlyFields: Record<string, ContractField> = {};\n for (const [name, field] of Object.entries(variant.fields)) {\n if (!(name in baseFields)) {\n variantOnlyFields[name] = field;\n }\n }\n\n const variantProperties: Record<string, unknown> = {};\n const variantRequired: string[] = [discriminatorField];\n for (const [name, field] of Object.entries(variantOnlyFields)) {\n const schema = fieldToBsonSchema(field, valueObjects, codecLookup, valueSets);\n if (schema) {\n variantProperties[name] = schema;\n if (!field.nullable) {\n variantRequired.push(name);\n }\n }\n }\n\n const entry: Record<string, unknown> = {\n properties: {\n ...baseProperties,\n [discriminatorField]: { enum: [variant.discriminatorValue] },\n ...variantProperties,\n },\n required: variantRequired.sort(),\n additionalProperties: false,\n };\n\n oneOf.push(entry);\n }\n\n const jsonSchema = { ...baseSchema };\n delete jsonSchema['additionalProperties'];\n if (oneOf.length > 0) {\n jsonSchema['oneOf'] = oneOf;\n }\n\n return new MongoValidator({\n jsonSchema,\n validationLevel: 'strict',\n validationAction: 'error',\n });\n}\n","import type { ResolvedAttribute, ResolvedAttributeArg } from '@prisma-next/psl-parser';\nimport { parseQuotedStringLiteral } from '@prisma-next/psl-parser';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\nexport { parseQuotedStringLiteral };\n\nexport function getPositionalArgument(attr: ResolvedAttribute, index = 0): string | undefined {\n return attr.args.filter((arg) => arg.kind === 'positional')[index]?.value;\n}\n\nexport function getNamedArgument(attr: ResolvedAttribute, name: string): string | undefined {\n const arg = attr.args.find((a) => a.kind === 'named' && a.name === name);\n return arg?.value;\n}\n\nexport function parseFieldList(value: string): readonly string[] {\n const inner = value.replace(/^\\[/, '').replace(/\\]$/, '').trim();\n if (inner.length === 0) return [];\n return splitTopLevel(inner).map((s) => s.trim());\n}\n\nexport interface ParsedIndexField {\n readonly name: string;\n readonly isWildcard: boolean;\n readonly direction?: number;\n}\n\nexport function parseIndexFieldList(value: string): readonly ParsedIndexField[] {\n const segments = parseFieldList(value);\n return segments.map(parseIndexFieldSegment);\n}\n\nfunction parseIndexFieldSegment(segment: string): ParsedIndexField {\n const wildcardMatch = segment.match(/^wildcard\\(\\s*(.*?)\\s*\\)$/);\n if (wildcardMatch) {\n const scope = wildcardMatch[1] ?? '';\n return {\n name: scope.length > 0 ? `${scope}.$**` : '$**',\n isWildcard: true,\n };\n }\n\n const modifierMatch = segment.match(/^(\\w+)\\(\\s*sort:\\s*(\\w+)\\s*\\)$/);\n if (modifierMatch) {\n const fieldName = modifierMatch[1] ?? segment;\n const sortValue = modifierMatch[2];\n return {\n name: fieldName,\n isWildcard: false,\n direction: sortValue === 'Desc' ? -1 : 1,\n };\n }\n\n return { name: segment, isWildcard: false };\n}\n\nfunction splitTopLevel(input: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n if (ch === '(' || ch === '[' || ch === '{') depth++;\n else if (ch === ')' || ch === ']' || ch === '}') depth = Math.max(0, depth - 1);\n else if (ch === ',' && depth === 0) {\n parts.push(input.slice(start, i));\n start = i + 1;\n }\n }\n parts.push(input.slice(start));\n return parts;\n}\n\nexport function lowerFirst(value: string): string {\n if (value.length === 0) return value;\n return value[0]?.toLowerCase() + value.slice(1);\n}\n\nexport function getAttribute(\n attributes: readonly ResolvedAttribute[],\n name: string,\n): ResolvedAttribute | undefined {\n return attributes.find((attr) => attr.name === name);\n}\n\nexport function getMapName(attributes: readonly ResolvedAttribute[]): string | undefined {\n const mapAttr = getAttribute(attributes, 'map');\n if (!mapAttr) return undefined;\n const arg = mapAttr.args[0];\n if (!arg) return undefined;\n return stripQuotes(arg.value);\n}\n\nexport interface ParsedRelationAttribute {\n readonly relationName?: string;\n readonly fields?: readonly string[];\n readonly references?: readonly string[];\n}\n\nexport function parseRelationAttribute(\n attributes: readonly ResolvedAttribute[],\n): ParsedRelationAttribute | undefined {\n const relationAttr = getAttribute(attributes, 'relation');\n if (!relationAttr) return undefined;\n\n let relationName: string | undefined;\n let fieldsArg: ResolvedAttributeArg | undefined;\n let referencesArg: ResolvedAttributeArg | undefined;\n\n for (const arg of relationAttr.args) {\n if (arg.kind === 'positional') {\n relationName = stripQuotes(arg.value);\n } else if (arg.name === 'name') {\n relationName = stripQuotes(arg.value);\n } else if (arg.name === 'fields') {\n fieldsArg = arg;\n } else if (arg.name === 'references') {\n referencesArg = arg;\n }\n }\n\n const fields = fieldsArg ? parseFieldList(fieldsArg.value) : undefined;\n const references = referencesArg ? parseFieldList(referencesArg.value) : undefined;\n\n return {\n ...ifDefined('relationName', relationName),\n ...ifDefined('fields', fields),\n ...ifDefined('references', references),\n };\n}\n\nfunction stripQuotes(value: string): string {\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return value.slice(1, -1);\n }\n return value;\n}\n","import type {\n ContractSourceDiagnostic,\n ContractSourceDiagnostics,\n} from '@prisma-next/config/config-types';\nimport { computeProfileHash, computeStorageHash } from '@prisma-next/contract/hashing';\nimport {\n type Contract,\n type ContractEnum,\n type ContractField,\n type ContractReferenceRelation,\n type ContractValueObject,\n type CrossReference,\n crossRef,\n type JsonValue,\n type ValueSetRef,\n} from '@prisma-next/contract/types';\nimport type { EnumTypeHandle } from '@prisma-next/contract-authoring';\nimport { errorEnumCodecNotInPackStack } from '@prisma-next/errors/control';\nimport type {\n AuthoringContributions,\n AuthoringEntityContext,\n} from '@prisma-next/framework-components/authoring';\nimport {\n instantiateAuthoringEntityType,\n isAuthoringEntityTypeDescriptor,\n} from '@prisma-next/framework-components/authoring';\nimport type { CodecLookup } from '@prisma-next/framework-components/codec';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n applyPolymorphicScopeToMongoIndex,\n buildMongoNamespace,\n type MongoCollectionInput,\n MongoIndex,\n type MongoIndexKeyDirection,\n MongoStorage,\n type MongoValueSetInput,\n} from '@prisma-next/mongo-contract';\nimport { mongoContractCanonicalizationHooks } from '@prisma-next/mongo-contract/canonicalization-hooks';\nimport type { CollationOptions } from '@prisma-next/mongo-value/mongodb-types';\nimport type {\n CompositeTypeSymbol,\n FieldSymbol,\n ModelSymbol,\n NamespaceSymbol,\n PslExtensionBlock,\n PslSpan,\n ResolvedAttribute,\n SymbolTable,\n} from '@prisma-next/psl-parser';\nimport { nodePslSpan } from '@prisma-next/psl-parser';\nimport type { SourceFile } from '@prisma-next/psl-parser/syntax';\nimport { assertDefined } from '@prisma-next/utils/assertions';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { deriveJsonSchema, derivePolymorphicJsonSchema } from './derive-json-schema';\nimport {\n getAttribute,\n getMapName,\n getNamedArgument,\n getPositionalArgument,\n lowerFirst,\n parseIndexFieldList,\n parseQuotedStringLiteral,\n parseRelationAttribute,\n} from './psl-helpers';\n\n/**\n * Encode an authored enum value to its codec-encoded JSON form via the codec resolved by id from the\n * contract's codec lookup, so a non-identity `encodeJson` (permitted by the `mongoCodec` factory) is\n * respected. Matches the TS builder's `encodeEnumValue`: the lookup is always threaded in production,\n * and a codecId the lookup cannot resolve is a hard error — the enum uses a codec that is not part of\n * the contract's pack stack.\n */\nfunction encodeEnumValue(value: unknown, codecId: string, codecLookup: CodecLookup): JsonValue {\n const codec = codecLookup.get(codecId);\n if (!codec) {\n throw errorEnumCodecNotInPackStack({ codecId });\n }\n return codec.encodeJson(value);\n}\n\nexport interface InterpretPslDocumentToMongoContractInput {\n readonly symbolTable: SymbolTable;\n readonly sourceFile: SourceFile;\n readonly sourceId: string;\n readonly scalarTypeDescriptors: ReadonlyMap<string, string>;\n readonly codecLookup?: CodecLookup;\n readonly seedDiagnostics?: readonly ContractSourceDiagnostic[];\n readonly authoringContributions?: AuthoringContributions;\n}\n\n/**\n * Mongo's PSL surface binds the database from the connection string, so every\n * explicit namespace block is invalid, including `namespace unbound { … }`.\n */\nfunction validateNamespaceBlocksForMongoTarget(input: {\n readonly namespaces: readonly NamespaceSymbol[];\n readonly sourceId: string;\n readonly sourceFile: SourceFile;\n readonly diagnostics: ContractSourceDiagnostic[];\n}): void {\n for (const namespace of input.namespaces) {\n input.diagnostics.push({\n code: 'PSL_UNSUPPORTED_NAMESPACE_BLOCK',\n message: `Mongo does not support \\`namespace ${namespace.name} { … }\\` blocks (the database is bound by the connection string; declare models at the document top level instead).`,\n sourceId: input.sourceId,\n span: nodePslSpan(namespace.node.syntax, input.sourceFile),\n });\n }\n}\n\ninterface FieldMappings {\n readonly pslNameToMapped: Map<string, string>;\n}\n\ninterface FkRelation {\n readonly declaringModel: string;\n readonly fieldName: string;\n readonly targetModel: string;\n readonly relationName?: string;\n readonly localFields: readonly string[];\n readonly targetFields: readonly string[];\n}\n\nfunction fkRelationPairKey(declaringModel: string, targetModel: string): string {\n return `${declaringModel}::${targetModel}`;\n}\n\nfunction resolveFieldMappings(model: ModelSymbol): FieldMappings {\n const pslNameToMapped = new Map<string, string>();\n for (const field of Object.values(model.fields)) {\n const mapped = getMapName(field.attributes) ?? field.name;\n pslNameToMapped.set(field.name, mapped);\n }\n return { pslNameToMapped };\n}\n\nfunction resolveCollectionName(model: ModelSymbol): string {\n return getMapName(model.attributes) ?? lowerFirst(model.name);\n}\n\ninterface MongoModelEntry {\n readonly fields: Record<string, ContractField>;\n readonly relations: Record<string, ContractReferenceRelation>;\n readonly storage: { readonly collection: string };\n readonly discriminator?: { readonly field: string };\n readonly variants?: Record<string, { readonly value: string }>;\n readonly base?: CrossReference;\n}\n\ntype DiscriminatorDeclaration = { readonly fieldName: string; readonly span: PslSpan };\ntype BaseDeclaration = {\n readonly baseName: string;\n readonly value: string;\n readonly collectionName: string;\n readonly span: PslSpan;\n};\n\nfunction mongoCrossRef(modelName: string): CrossReference {\n return crossRef(modelName, UNBOUND_NAMESPACE_ID);\n}\n\nfunction collectPolymorphismDeclarations(\n models: readonly ModelSymbol[],\n sourceId: string,\n diagnostics: ContractSourceDiagnostic[],\n): {\n discriminatorDeclarations: Map<string, DiscriminatorDeclaration>;\n baseDeclarations: Map<string, BaseDeclaration>;\n} {\n const discriminatorDeclarations = new Map<string, DiscriminatorDeclaration>();\n const baseDeclarations = new Map<string, BaseDeclaration>();\n\n for (const model of models) {\n for (const attr of model.attributes) {\n if (attr.name === 'discriminator') {\n const fieldName = getPositionalArgument(attr);\n if (!fieldName) {\n diagnostics.push({\n code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',\n message: `Model \"${model.name}\" @@discriminator requires a field name argument`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n const discField = model.fields[fieldName];\n if (discField && discField.typeName !== 'String') {\n diagnostics.push({\n code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',\n message: `Discriminator field \"${fieldName}\" on model \"${model.name}\" must be of type String, but is \"${discField.typeName}\"`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n discriminatorDeclarations.set(model.name, { fieldName, span: attr.span });\n }\n if (attr.name === 'base') {\n const baseName = getPositionalArgument(attr, 0);\n const rawValue = getPositionalArgument(attr, 1);\n if (!baseName || !rawValue) {\n diagnostics.push({\n code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',\n message: `Model \"${model.name}\" @@base requires two arguments: base model name and discriminator value`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n const value = parseQuotedStringLiteral(rawValue);\n if (value === undefined) {\n diagnostics.push({\n code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',\n message: `Model \"${model.name}\" @@base discriminator value must be a quoted string literal`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n const collectionName = resolveCollectionName(model);\n baseDeclarations.set(model.name, { baseName, value, collectionName, span: attr.span });\n }\n }\n }\n\n return { discriminatorDeclarations, baseDeclarations };\n}\n\nfunction resolvePolymorphism(input: {\n models: Record<string, MongoModelEntry>;\n roots: Record<string, CrossReference>;\n collections: Record<string, Record<string, unknown>>;\n allModels: readonly ModelSymbol[];\n discriminatorDeclarations: Map<string, DiscriminatorDeclaration>;\n baseDeclarations: Map<string, BaseDeclaration>;\n modelNames: ReadonlySet<string>;\n indexSpans: Map<MongoIndex, PslSpan>;\n modelIndexesByName: Map<string, readonly MongoIndex[]>;\n sourceId: string;\n}): {\n models: Record<string, MongoModelEntry>;\n roots: Record<string, CrossReference>;\n collections: Record<string, Record<string, unknown>>;\n diagnostics: ContractSourceDiagnostic[];\n} {\n const {\n discriminatorDeclarations,\n baseDeclarations,\n modelNames,\n sourceId,\n allModels: allModelViews,\n indexSpans,\n modelIndexesByName,\n } = input;\n let patched = input.models;\n let roots = input.roots;\n let collections = input.collections;\n const diagnostics: ContractSourceDiagnostic[] = [];\n\n for (const [modelName, decl] of discriminatorDeclarations) {\n if (baseDeclarations.has(modelName)) {\n diagnostics.push({\n code: 'PSL_DISCRIMINATOR_AND_BASE',\n message: `Model \"${modelName}\" cannot have both @@discriminator and @@base`,\n sourceId,\n span: decl.span,\n });\n continue;\n }\n\n const model = patched[modelName];\n if (!model) continue;\n\n const modelView = allModelViews.find((m) => m.name === modelName);\n const mappedDiscriminatorField = modelView\n ? (resolveFieldMappings(modelView).pslNameToMapped.get(decl.fieldName) ?? decl.fieldName)\n : decl.fieldName;\n\n if (!Object.hasOwn(model.fields, mappedDiscriminatorField)) {\n diagnostics.push({\n code: 'PSL_DISCRIMINATOR_FIELD_NOT_FOUND',\n message: `Discriminator field \"${decl.fieldName}\" is not a field on model \"${modelName}\"`,\n sourceId,\n span: decl.span,\n });\n continue;\n }\n\n const variants: Record<string, { readonly value: string }> = {};\n for (const [variantName, baseDecl] of baseDeclarations) {\n if (baseDecl.baseName !== modelName) continue;\n variants[variantName] = { value: baseDecl.value };\n }\n\n if (Object.keys(variants).length === 0) {\n diagnostics.push({\n code: 'PSL_ORPHANED_DISCRIMINATOR',\n message: `Model \"${modelName}\" has @@discriminator but no variant models declare @@base(${modelName}, ...)`,\n sourceId,\n span: decl.span,\n });\n continue;\n }\n\n patched = {\n ...patched,\n [modelName]: { ...model, discriminator: { field: mappedDiscriminatorField }, variants },\n };\n }\n\n for (const [variantName, baseDecl] of baseDeclarations) {\n if (!modelNames.has(baseDecl.baseName)) {\n diagnostics.push({\n code: 'PSL_BASE_TARGET_NOT_FOUND',\n message: `Model \"${variantName}\" @@base references non-existent model \"${baseDecl.baseName}\"`,\n sourceId,\n span: baseDecl.span,\n });\n continue;\n }\n\n if (!discriminatorDeclarations.has(baseDecl.baseName)) {\n diagnostics.push({\n code: 'PSL_ORPHANED_BASE',\n message: `Model \"${variantName}\" declares @@base(${baseDecl.baseName}, ...) but \"${baseDecl.baseName}\" has no @@discriminator`,\n sourceId,\n span: baseDecl.span,\n });\n continue;\n }\n\n if (discriminatorDeclarations.has(variantName)) {\n continue;\n }\n\n const baseModel = patched[baseDecl.baseName];\n const variantModelView = allModelViews.find((m) => m.name === variantName);\n if (!variantModelView) continue;\n const hasExplicitMap = getMapName(variantModelView.attributes) !== undefined;\n\n if (hasExplicitMap && baseModel && baseDecl.collectionName !== baseModel.storage.collection) {\n diagnostics.push({\n code: 'PSL_MONGO_VARIANT_SEPARATE_COLLECTION',\n message: `Mongo variant \"${variantName}\" cannot use a different collection than its base \"${baseDecl.baseName}\". Mongo only supports single-collection polymorphism.`,\n sourceId,\n span: baseDecl.span,\n });\n continue;\n }\n\n const baseCollection = baseModel?.storage.collection ?? baseDecl.collectionName;\n const variantModel = patched[variantName];\n if (variantModel) {\n patched = {\n ...patched,\n [variantName]: {\n ...variantModel,\n base: mongoCrossRef(baseDecl.baseName),\n storage: { collection: baseCollection },\n },\n };\n }\n\n const variantCollectionName = resolveCollectionName(variantModelView);\n if (roots[variantCollectionName]?.model === variantName) {\n if (variantCollectionName === baseCollection && baseModel) {\n roots = { ...roots, [variantCollectionName]: mongoCrossRef(baseDecl.baseName) };\n } else {\n roots = Object.fromEntries(\n Object.entries(roots).filter(([key]) => key !== variantCollectionName),\n );\n }\n }\n\n const variantOwnIndexes = modelIndexesByName.get(variantName) ?? [];\n const baseColl = collections[baseCollection];\n\n const baseModelEntry = patched[baseDecl.baseName];\n const discriminatorField = baseModelEntry?.discriminator?.field;\n const scopedVariantIndexes: MongoIndex[] = [];\n if (discriminatorField) {\n for (const idx of variantOwnIndexes) {\n const result = applyPolymorphicScopeToMongoIndex(idx, {\n discriminatorField,\n discriminatorValue: baseDecl.value,\n });\n if (result.kind === 'conflict') {\n const span = indexSpans.get(idx) ?? baseDecl.span;\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: `Variant \"${variantName}\" index conflicts with discriminator scope: ${result.reason}`,\n sourceId,\n span,\n });\n continue;\n }\n if (result.index !== idx) {\n indexSpans.set(result.index, indexSpans.get(idx) ?? baseDecl.span);\n }\n scopedVariantIndexes.push(result.index);\n }\n } else {\n scopedVariantIndexes.push(...variantOwnIndexes);\n }\n\n if (variantCollectionName !== baseCollection) {\n const filtered = Object.fromEntries(\n Object.entries(collections).filter(([key]) => key !== variantCollectionName),\n );\n if (scopedVariantIndexes.length > 0 && baseColl) {\n const baseIndexes = (baseColl['indexes'] ?? []) as MongoIndex[];\n collections = {\n ...filtered,\n [baseCollection]: {\n ...baseColl,\n indexes: [...baseIndexes, ...scopedVariantIndexes],\n },\n };\n } else {\n collections = filtered;\n }\n } else if (baseColl) {\n const existingIndexes = (baseColl['indexes'] ?? []) as MongoIndex[];\n const variantIndexSet = new Set<MongoIndex>(variantOwnIndexes);\n const withoutUnscopedVariants = existingIndexes.filter((idx) => !variantIndexSet.has(idx));\n const mergedIndexes = [...withoutUnscopedVariants];\n for (const idx of scopedVariantIndexes) {\n const idxKey = canonicalJson(idx);\n const isDuplicate = withoutUnscopedVariants.some(\n (existing) => canonicalJson(existing) === idxKey,\n );\n if (!isDuplicate) {\n mergedIndexes.push(idx);\n }\n }\n if (\n mergedIndexes.length !== existingIndexes.length ||\n mergedIndexes.some((idx, i) => idx !== existingIndexes[i])\n ) {\n const next: Record<string, unknown> = { ...baseColl };\n if (mergedIndexes.length > 0) {\n next['indexes'] = mergedIndexes;\n } else {\n delete next['indexes'];\n }\n collections = { ...collections, [baseCollection]: next };\n }\n }\n }\n\n return { models: patched, roots, collections, diagnostics };\n}\n\n// Property-order-stable serialization for structural equality of plain\n// JSON-compatible values. Used for comparing MongoIndex shapes in\n// the variant-merge dedup path where a future change to the spread order\n// would otherwise produce JSON-stringify mismatches even though the\n// indexes are structurally identical.\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(',')}]`;\n }\n if (value && typeof value === 'object') {\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)\n .join(',')}}`;\n }\n return JSON.stringify(value);\n}\n\nfunction parseIndexDirection(raw: string | undefined): MongoIndexKeyDirection {\n if (!raw) return 1;\n const stripped = raw.replace(/^[\"']/, '').replace(/[\"']$/, '');\n const num = Number(stripped);\n if (num === 1 || num === -1) return num;\n if (['text', '2dsphere', '2d', 'hashed'].includes(stripped))\n return stripped as MongoIndexKeyDirection;\n return 1;\n}\n\nfunction parseNumericArg(raw: string | undefined): number | undefined {\n if (!raw) return undefined;\n const n = Number(raw);\n return Number.isFinite(n) ? n : undefined;\n}\n\nfunction parseBooleanArg(raw: string | undefined): boolean | undefined {\n if (raw === 'true') return true;\n if (raw === 'false') return false;\n return undefined;\n}\n\nfunction parseJsonArg(raw: string | undefined): Record<string, unknown> | undefined {\n if (!raw) return undefined;\n const stripped = raw.replace(/^[\"']/, '').replace(/[\"']$/, '').replace(/\\\\\"/g, '\"');\n try {\n const parsed = JSON.parse(stripped);\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // not valid JSON\n }\n return undefined;\n}\n\nfunction parseCollation(attr: ResolvedAttribute): CollationOptions | null | undefined {\n const locale = stripQuotesHelper(getNamedArgument(attr, 'collationLocale'));\n if (!locale) {\n const hasAnyCollationArg =\n getNamedArgument(attr, 'collationStrength') != null ||\n getNamedArgument(attr, 'collationCaseLevel') != null ||\n getNamedArgument(attr, 'collationCaseFirst') != null ||\n getNamedArgument(attr, 'collationNumericOrdering') != null ||\n getNamedArgument(attr, 'collationAlternate') != null ||\n getNamedArgument(attr, 'collationMaxVariable') != null ||\n getNamedArgument(attr, 'collationBackwards') != null ||\n getNamedArgument(attr, 'collationNormalization') != null;\n return hasAnyCollationArg ? null : undefined;\n }\n\n const collation: CollationOptions = { locale };\n const strength = parseNumericArg(getNamedArgument(attr, 'collationStrength'));\n if (strength != null) collation.strength = strength;\n const caseLevel = parseBooleanArg(getNamedArgument(attr, 'collationCaseLevel'));\n if (caseLevel != null) collation.caseLevel = caseLevel;\n const caseFirst = stripQuotesHelper(getNamedArgument(attr, 'collationCaseFirst'));\n if (caseFirst != null) collation.caseFirst = caseFirst;\n const numericOrdering = parseBooleanArg(getNamedArgument(attr, 'collationNumericOrdering'));\n if (numericOrdering != null) collation.numericOrdering = numericOrdering;\n const alternate = stripQuotesHelper(getNamedArgument(attr, 'collationAlternate'));\n if (alternate != null) collation.alternate = alternate;\n const maxVariable = stripQuotesHelper(getNamedArgument(attr, 'collationMaxVariable'));\n if (maxVariable != null) collation.maxVariable = maxVariable;\n const backwards = parseBooleanArg(getNamedArgument(attr, 'collationBackwards'));\n if (backwards != null) collation.backwards = backwards;\n const normalization = parseBooleanArg(getNamedArgument(attr, 'collationNormalization'));\n if (normalization != null) collation.normalization = normalization;\n return collation;\n}\n\nfunction stripQuotesHelper(raw: string | undefined): string | undefined {\n if (!raw) return undefined;\n return raw.replace(/^[\"']/, '').replace(/[\"']$/, '');\n}\n\nfunction parseProjectionList(\n raw: string | undefined,\n value: 0 | 1,\n): Record<string, 0 | 1> | undefined {\n if (!raw) return undefined;\n const stripped = raw.replace(/^[\"']/, '').replace(/[\"']$/, '');\n const inner = stripped.replace(/^\\[/, '').replace(/\\]$/, '').trim();\n if (inner.length === 0) return undefined;\n const fields = inner\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n const result: Record<string, 0 | 1> = {};\n for (const f of fields) {\n result[f] = value;\n }\n return result;\n}\n\nfunction collectIndexes(\n pslModel: ModelSymbol,\n fieldMappings: FieldMappings,\n modelNames: ReadonlySet<string>,\n sourceId: string,\n diagnostics: ContractSourceDiagnostic[],\n indexSpans: Map<MongoIndex, PslSpan>,\n): MongoIndex[] {\n const indexes: MongoIndex[] = [];\n let textIndexCount = 0;\n\n // Storage-indexable PSL field names — i.e. all declared fields except\n // relation fields (which don't materialize a column on this model). The\n // index field-existence check (PSL_INDEX_FIELD_NOT_FOUND) consults this\n // rather than fieldMappings.pslNameToMapped because the latter contains\n // every PSL field including relation fields.\n const indexableFieldNames = new Set<string>();\n for (const f of Object.values(pslModel.fields)) {\n if (modelNames.has(f.typeName)) continue;\n indexableFieldNames.add(f.name);\n }\n\n for (const field of Object.values(pslModel.fields)) {\n if (modelNames.has(field.typeName)) continue;\n const uniqueAttr = getAttribute(field.attributes, 'unique');\n if (!uniqueAttr) continue;\n const mappedName = fieldMappings.pslNameToMapped.get(field.name) ?? field.name;\n const fieldUniqueIndex = new MongoIndex({\n keys: [{ field: mappedName, direction: 1 }],\n unique: true,\n });\n indexes.push(fieldUniqueIndex);\n indexSpans.set(fieldUniqueIndex, uniqueAttr.span);\n }\n\n for (const attr of pslModel.attributes) {\n const isIndex = attr.name === 'index';\n const isUnique = attr.name === 'unique';\n const isTextIndex = attr.name === 'textIndex';\n if (!isIndex && !isUnique && !isTextIndex) continue;\n\n const fieldsArg = getPositionalArgument(attr, 0);\n if (!fieldsArg) continue;\n const parsedFields = parseIndexFieldList(fieldsArg);\n if (parsedFields.length === 0) continue;\n\n const hasWildcard = parsedFields.some((f) => f.isWildcard);\n const wildcardCount = parsedFields.filter((f) => f.isWildcard).length;\n\n if (wildcardCount > 1) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'An index can contain at most one wildcard() field',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if (isUnique && hasWildcard) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'Unique indexes cannot use wildcard() fields',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if (isTextIndex) {\n textIndexCount++;\n if (textIndexCount > 1) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: `Only one @@textIndex is allowed per collection (model \"${pslModel.name}\")`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if (hasWildcard) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message:\n 'wildcard() fields cannot be combined with type: hashed/2dsphere/2d or @@textIndex',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n }\n\n const typeArg = getNamedArgument(attr, 'type');\n const defaultDirection: MongoIndexKeyDirection = isTextIndex\n ? 'text'\n : parseIndexDirection(typeArg);\n\n if (\n hasWildcard &&\n typeof defaultDirection === 'string' &&\n ['hashed', '2dsphere', '2d'].includes(defaultDirection)\n ) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: `wildcard() fields cannot be combined with type: ${defaultDirection}`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if (defaultDirection === 'hashed' && parsedFields.length > 1) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'Hashed indexes must have exactly one field',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n let missingField: string | undefined;\n for (const pf of parsedFields) {\n let fieldNameForLookup: string | undefined;\n if (pf.isWildcard) {\n const wildcardMatch = pf.name.match(/^(.+)\\.\\$\\*\\*$/);\n fieldNameForLookup = wildcardMatch ? wildcardMatch[1] : undefined;\n } else {\n fieldNameForLookup = pf.name;\n }\n if (fieldNameForLookup === undefined || fieldNameForLookup.length === 0) continue;\n if (!indexableFieldNames.has(fieldNameForLookup)) {\n missingField = fieldNameForLookup;\n break;\n }\n }\n if (missingField !== undefined) {\n diagnostics.push({\n code: 'PSL_INDEX_FIELD_NOT_FOUND',\n message: `Index on model \"${pslModel.name}\" references unknown field \"${missingField}\"`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n const keys = parsedFields.map((pf) => {\n const mappedName = pf.isWildcard\n ? pf.name.replace(/^(.+)\\.\\$\\*\\*$/, (_, prefix: string) => {\n const mapped = fieldMappings.pslNameToMapped.get(prefix);\n return mapped ? `${mapped}.$**` : `${prefix}.$**`;\n })\n : (fieldMappings.pslNameToMapped.get(pf.name) ?? pf.name);\n const direction: MongoIndexKeyDirection =\n pf.direction != null ? (pf.direction as MongoIndexKeyDirection) : defaultDirection;\n return { field: mappedName, direction };\n });\n\n const unique = isUnique ? true : undefined;\n const sparse = isTextIndex ? undefined : parseBooleanArg(getNamedArgument(attr, 'sparse'));\n const expireAfterSeconds = isTextIndex\n ? undefined\n : parseNumericArg(getNamedArgument(attr, 'expireAfterSeconds'));\n\n if (hasWildcard && expireAfterSeconds != null) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'expireAfterSeconds cannot be combined with wildcard() fields',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n const partialFilterExpression = parseJsonArg(getNamedArgument(attr, 'filter'));\n\n const includeArg = getNamedArgument(attr, 'include');\n const excludeArg = getNamedArgument(attr, 'exclude');\n\n if (includeArg != null && excludeArg != null) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'Cannot specify both include and exclude on the same index',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if ((includeArg != null || excludeArg != null) && !hasWildcard) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message:\n 'include/exclude options are only valid when the index contains a wildcard() field',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n const wildcardProjection =\n includeArg != null\n ? parseProjectionList(includeArg, 1)\n : excludeArg != null\n ? parseProjectionList(excludeArg, 0)\n : undefined;\n\n const collation = parseCollation(attr);\n if (collation === null) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'collationLocale is required when using collation options',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n const rawWeights = parseJsonArg(getNamedArgument(attr, 'weights'));\n let weights: Record<string, number> | undefined;\n if (rawWeights) {\n weights = {};\n for (const [k, v] of Object.entries(rawWeights)) {\n if (typeof v === 'number') weights[k] = v;\n }\n }\n\n const rawDefaultLang = isTextIndex\n ? getNamedArgument(attr, 'language')\n : getNamedArgument(attr, 'default_language');\n const default_language = stripQuotesHelper(rawDefaultLang);\n\n const rawLangOverride = getNamedArgument(attr, 'languageOverride');\n const language_override = stripQuotesHelper(rawLangOverride);\n\n const index = new MongoIndex({\n keys,\n ...(unique != null && { unique }),\n ...(sparse != null && { sparse }),\n ...(expireAfterSeconds != null && { expireAfterSeconds }),\n ...(partialFilterExpression != null && { partialFilterExpression }),\n ...(wildcardProjection != null && { wildcardProjection }),\n ...(collation != null && { collation }),\n ...(weights != null && { weights }),\n ...(default_language != null && { default_language }),\n ...(language_override != null && { language_override }),\n });\n\n indexes.push(index);\n indexSpans.set(index, attr.span);\n }\n\n return indexes;\n}\n\nfunction isRelationField(field: FieldSymbol, modelNames: ReadonlySet<string>): boolean {\n return modelNames.has(field.typeName);\n}\n\n// PSL scalar type name whose codec is mandated for a Mongo model's `_id`.\nconst MONGO_OBJECT_ID_PSL_TYPE = 'ObjectId';\n\nfunction resolveFieldCodecId(\n field: FieldSymbol,\n scalarTypeDescriptors: ReadonlyMap<string, string>,\n): string | undefined {\n return scalarTypeDescriptors.get(field.typeName);\n}\n\nfunction resolveNonRelationField(\n field: FieldSymbol,\n ownerName: string,\n compositeTypeNames: ReadonlySet<string>,\n scalarTypeDescriptors: ReadonlyMap<string, string>,\n codecIdByEnumName: ReadonlyMap<string, string>,\n sourceId: string,\n diagnostics: ContractSourceDiagnostic[],\n): ContractField | undefined {\n if (compositeTypeNames.has(field.typeName)) {\n const result: ContractField = {\n type: { kind: 'valueObject', name: field.typeName },\n nullable: field.optional,\n };\n return field.list ? { ...result, many: true } : result;\n }\n\n // If this field's declared type is a known enum name, treat the field as a scalar\n // with that enum's codec and stamp the domain valueSet ref.\n const enumCodecId = codecIdByEnumName.get(field.typeName);\n if (enumCodecId !== undefined) {\n const valueSet: ValueSetRef = {\n plane: 'domain',\n entityKind: 'enum',\n namespaceId: UNBOUND_NAMESPACE_ID,\n entityName: field.typeName,\n };\n const result: ContractField = {\n type: { kind: 'scalar', codecId: enumCodecId },\n nullable: field.optional,\n valueSet,\n };\n return field.list ? { ...result, many: true } : result;\n }\n\n // Avoid cascading unsupported-type diagnostics after invalid qualification.\n if (field.malformedType) {\n return undefined;\n }\n\n const codecId = resolveFieldCodecId(field, scalarTypeDescriptors);\n if (!codecId) {\n diagnostics.push({\n code: 'PSL_UNSUPPORTED_FIELD_TYPE',\n message: `Field \"${ownerName}.${field.name}\" type \"${field.typeName}\" is not supported in Mongo PSL interpreter`,\n sourceId,\n span: field.span,\n });\n return undefined;\n }\n\n const result: ContractField = {\n type: { kind: 'scalar', codecId },\n nullable: field.optional,\n };\n return field.list ? { ...result, many: true } : result;\n}\n\nfunction processEnumDeclarations(input: {\n readonly enumBlocks: readonly PslExtensionBlock[];\n readonly sourceId: string;\n readonly authoringContributions: AuthoringContributions | undefined;\n readonly entityContext: AuthoringEntityContext;\n readonly diagnostics: ContractSourceDiagnostic[];\n}): Record<string, ContractEnum> {\n const builtEnums: Record<string, ContractEnum> = {};\n\n if (input.enumBlocks.length === 0) return builtEnums;\n\n const enumDescriptor =\n input.authoringContributions?.entityTypes?.['enum'] !== undefined &&\n isAuthoringEntityTypeDescriptor(input.authoringContributions.entityTypes['enum'])\n ? input.authoringContributions.entityTypes['enum']\n : undefined;\n\n if (!enumDescriptor) {\n for (const decl of input.enumBlocks) {\n input.diagnostics.push({\n code: 'PSL_ENUM_MISSING_FACTORY',\n message: `enum \"${decl.name}\" requires an \"enum\" entityType factory in the active authoring contributions`,\n sourceId: input.sourceId,\n span: decl.span,\n });\n }\n return builtEnums;\n }\n\n for (const decl of input.enumBlocks) {\n const handle = instantiateAuthoringEntityType<EnumTypeHandle | undefined>(\n 'enum',\n enumDescriptor,\n [decl],\n input.entityContext,\n );\n\n if (handle === undefined || handle === null) continue;\n\n builtEnums[decl.name] = {\n codecId: handle.codecId,\n members: handle.enumMembers.map((m) => ({\n name: m.name,\n value: blindCast<JsonValue, 'factory-validated enum members are JsonValue-compatible'>(\n m.value,\n ),\n })),\n };\n }\n\n return builtEnums;\n}\n\nexport function interpretPslDocumentToMongoContract(\n input: InterpretPslDocumentToMongoContractInput,\n): Result<Contract, ContractSourceDiagnostics> {\n const { symbolTable, sourceFile, scalarTypeDescriptors, codecLookup } = input;\n const sourceId = input.sourceId;\n const diagnostics: ContractSourceDiagnostic[] = [...(input.seedDiagnostics ?? [])];\n const topLevel = symbolTable.topLevel;\n validateNamespaceBlocksForMongoTarget({\n namespaces: Object.values(topLevel.namespaces),\n sourceId,\n sourceFile,\n diagnostics,\n });\n const allModels: ModelSymbol[] = Object.values(topLevel.models);\n const allCompositeTypes: CompositeTypeSymbol[] = Object.values(topLevel.compositeTypes);\n const modelNames = new Set(allModels.map((m) => m.name));\n const compositeTypeNames = new Set(allCompositeTypes.map((ct) => ct.name));\n\n const topLevelEnumBlocks = Object.values(topLevel.blocks)\n .filter((b) => b.keyword === 'enum')\n .map((b) => b.block);\n\n const builtEnums = processEnumDeclarations({\n enumBlocks: topLevelEnumBlocks,\n sourceId,\n authoringContributions: input.authoringContributions,\n entityContext: {\n family: 'mongo',\n target: 'mongo',\n ...ifDefined('codecLookup', codecLookup),\n sourceId,\n diagnostics: {\n push: (d) => {\n diagnostics.push(\n blindCast<ContractSourceDiagnostic, 'sink diagnostics are span-compatible'>(d),\n );\n },\n },\n },\n diagnostics,\n });\n\n const codecIdByEnumName: Map<string, string> = new Map(\n Object.entries(builtEnums).map(([name, e]) => [name, e.codecId]),\n );\n\n const models: Record<string, MongoModelEntry> = {};\n const collections: Record<string, Record<string, unknown>> = {};\n const roots: Record<string, CrossReference> = {};\n const allFkRelations: FkRelation[] = [];\n const indexSpans = new Map<MongoIndex, PslSpan>();\n const modelIndexesByName = new Map<string, readonly MongoIndex[]>();\n\n interface BackrelationCandidate {\n readonly modelName: string;\n readonly fieldName: string;\n readonly targetModelName: string;\n readonly relationName?: string;\n readonly cardinality: '1:1' | '1:N';\n readonly field: FieldSymbol;\n }\n const backrelationCandidates: BackrelationCandidate[] = [];\n\n for (const pslModel of allModels) {\n const collectionName = resolveCollectionName(pslModel);\n const fieldMappings = resolveFieldMappings(pslModel);\n\n const fields: Record<string, ContractField> = {};\n const relations: Record<string, ContractReferenceRelation> = {};\n\n for (const field of Object.values(pslModel.fields)) {\n if (isRelationField(field, modelNames)) {\n const relation = parseRelationAttribute(field.attributes);\n\n if (field.list || !(relation?.fields && relation?.references)) {\n backrelationCandidates.push({\n modelName: pslModel.name,\n fieldName: field.name,\n targetModelName: field.typeName,\n ...ifDefined('relationName', relation?.relationName),\n cardinality: field.list ? '1:N' : '1:1',\n field,\n });\n continue;\n }\n\n if (relation?.fields && relation?.references) {\n const localMapped = relation.fields.map((f) => fieldMappings.pslNameToMapped.get(f) ?? f);\n\n const targetModel = allModels.find((m) => m.name === field.typeName);\n const targetFieldMappings = targetModel ? resolveFieldMappings(targetModel) : undefined;\n const targetMapped = relation.references.map(\n (f) => targetFieldMappings?.pslNameToMapped.get(f) ?? f,\n );\n\n relations[field.name] = {\n to: mongoCrossRef(field.typeName),\n cardinality: 'N:1' as const,\n on: {\n localFields: localMapped,\n targetFields: targetMapped,\n },\n };\n\n allFkRelations.push({\n declaringModel: pslModel.name,\n fieldName: field.name,\n targetModel: field.typeName,\n ...ifDefined('relationName', relation.relationName),\n localFields: localMapped,\n targetFields: targetMapped,\n });\n }\n continue;\n }\n\n const resolved = resolveNonRelationField(\n field,\n pslModel.name,\n compositeTypeNames,\n scalarTypeDescriptors,\n codecIdByEnumName,\n sourceId,\n diagnostics,\n );\n if (!resolved) continue;\n\n const mappedName = fieldMappings.pslNameToMapped.get(field.name) ?? field.name;\n fields[mappedName] = resolved;\n }\n\n const isVariantModel = pslModel.attributes.some((attr) => attr.name === 'base');\n const hasIdField = Object.values(pslModel.fields).some(\n (f) => getAttribute(f.attributes, 'id') !== undefined,\n );\n // Variant models inherit the base's identity and are validated through their base.\n if (!isVariantModel) {\n if (!hasIdField) {\n diagnostics.push({\n code: 'PSL_MISSING_ID_FIELD',\n message: `Model \"${pslModel.name}\" has no field with @id attribute. Every model must have exactly one @id field.`,\n sourceId,\n });\n } else {\n // The resulting document must carry an `_id` of BSON type objectId. We\n // assert on the emitted shape (the mapped-name-keyed field record), not\n // on how the user spelled it — `id ObjectId @id @map(\"_id\")` and a field\n // literally named `_id` both satisfy it; a non-objectId or unmapped id\n // does not.\n const objectIdCodecId = scalarTypeDescriptors.get(MONGO_OBJECT_ID_PSL_TYPE);\n const idField = fields['_id'];\n const idIsObjectId =\n idField !== undefined &&\n idField.type.kind === 'scalar' &&\n objectIdCodecId !== undefined &&\n idField.type.codecId === objectIdCodecId;\n if (!idIsObjectId) {\n diagnostics.push({\n code: 'PSL_MONGO_ID_REQUIRED',\n message: `Model \"${pslModel.name}\" must declare an _id field of type ObjectId (e.g. \\`id ObjectId @id @map(\"_id\")\\`).`,\n sourceId,\n });\n }\n }\n }\n\n models[pslModel.name] = { fields, relations, storage: { collection: collectionName } };\n const modelIndexes = collectIndexes(\n pslModel,\n fieldMappings,\n modelNames,\n sourceId,\n diagnostics,\n indexSpans,\n );\n modelIndexesByName.set(pslModel.name, modelIndexes);\n const existingColl = collections[collectionName];\n if (existingColl && modelIndexes.length > 0) {\n const existingIndexes = (existingColl['indexes'] ?? []) as MongoIndex[];\n collections[collectionName] = { indexes: [...existingIndexes, ...modelIndexes] };\n } else if (!existingColl) {\n collections[collectionName] = modelIndexes.length > 0 ? { indexes: modelIndexes } : {};\n }\n roots[collectionName] = mongoCrossRef(pslModel.name);\n }\n\n const valueObjects: Record<string, ContractValueObject> = {};\n for (const compositeType of allCompositeTypes) {\n const fields: Record<string, ContractField> = {};\n for (const field of Object.values(compositeType.fields)) {\n const resolved = resolveNonRelationField(\n field,\n compositeType.name,\n compositeTypeNames,\n scalarTypeDescriptors,\n codecIdByEnumName,\n sourceId,\n diagnostics,\n );\n if (!resolved) continue;\n fields[field.name] = resolved;\n }\n valueObjects[compositeType.name] = { fields };\n }\n\n const fkRelationsByPair = new Map<string, FkRelation[]>();\n for (const fk of allFkRelations) {\n const key = fkRelationPairKey(fk.declaringModel, fk.targetModel);\n const existing = fkRelationsByPair.get(key);\n if (existing) {\n existing.push(fk);\n } else {\n fkRelationsByPair.set(key, [fk]);\n }\n }\n\n for (const candidate of backrelationCandidates) {\n const pairKey = fkRelationPairKey(candidate.targetModelName, candidate.modelName);\n const pairMatches = fkRelationsByPair.get(pairKey) ?? [];\n const matches = candidate.relationName\n ? pairMatches.filter((r) => r.relationName === candidate.relationName)\n : [...pairMatches];\n\n if (matches.length === 0) {\n diagnostics.push({\n code: 'PSL_ORPHANED_BACKRELATION',\n message: `Backrelation list field \"${candidate.modelName}.${candidate.fieldName}\" has no matching FK-side relation on model \"${candidate.targetModelName}\". Add @relation(fields: [...], references: [...]) on the FK-side relation or use an explicit join model for many-to-many.`,\n sourceId,\n span: candidate.field.span,\n });\n continue;\n }\n if (matches.length > 1) {\n diagnostics.push({\n code: 'PSL_AMBIGUOUS_BACKRELATION',\n message: `Backrelation list field \"${candidate.modelName}.${candidate.fieldName}\" matches multiple FK-side relations on model \"${candidate.targetModelName}\". Add @relation(\"...\") to both sides to disambiguate.`,\n sourceId,\n span: candidate.field.span,\n });\n continue;\n }\n\n const fk = matches[0];\n if (!fk) continue;\n const modelEntry = models[candidate.modelName];\n if (!modelEntry) continue;\n modelEntry.relations[candidate.fieldName] = {\n to: mongoCrossRef(candidate.targetModelName),\n cardinality: candidate.cardinality,\n on: {\n localFields: fk.targetFields,\n targetFields: fk.localFields,\n },\n };\n }\n\n const { discriminatorDeclarations, baseDeclarations } = collectPolymorphismDeclarations(\n allModels,\n sourceId,\n diagnostics,\n );\n const polyResult = resolvePolymorphism({\n models,\n roots,\n collections,\n allModels,\n discriminatorDeclarations,\n baseDeclarations,\n modelNames,\n indexSpans,\n modelIndexesByName,\n sourceId,\n });\n\n if (diagnostics.length > 0 || polyResult.diagnostics.length > 0) {\n return notOk({\n summary: 'PSL to Mongo contract interpretation failed',\n diagnostics: [...diagnostics, ...polyResult.diagnostics],\n });\n }\n\n const resolvedModels = polyResult.models;\n const resolvedCollections = polyResult.collections;\n\n // The storage value set is the source of truth for both the emit typing and the validator's\n // `enum` keyword. Built once, ahead of validator derivation, from each enum's codec-encoded member\n // values (mirroring SQL's build-contract). Encoding needs the codec lookup; production always\n // threads it (the CLI control stack supplies it), so its absence when enums exist is a wiring bug,\n // not a runtime input to tolerate.\n const storageValueSets: Record<string, MongoValueSetInput> = {};\n const enumEntries = Object.entries(builtEnums);\n if (enumEntries.length > 0) {\n assertDefined(\n codecLookup,\n 'Mongo PSL interpretation requires a codec lookup to encode enum values',\n );\n for (const [enumName, builtEnum] of enumEntries) {\n storageValueSets[enumName] = {\n kind: 'valueSet',\n values: builtEnum.members.map((m) =>\n encodeEnumValue(m.value, builtEnum.codecId, codecLookup),\n ),\n };\n }\n }\n\n for (const [, modelEntry] of Object.entries(resolvedModels)) {\n if (modelEntry.base) continue;\n\n const collectionName = modelEntry.storage.collection;\n const coll = resolvedCollections[collectionName];\n if (!coll) continue;\n\n if (modelEntry.discriminator && modelEntry.variants) {\n const variantEntries = Object.entries(modelEntry.variants).map(\n ([variantName, { value }]) => ({\n discriminatorValue: value,\n fields: resolvedModels[variantName]?.fields ?? {},\n }),\n );\n coll['validator'] = derivePolymorphicJsonSchema(\n modelEntry.fields,\n modelEntry.discriminator.field,\n variantEntries,\n valueObjects,\n codecLookup,\n storageValueSets,\n );\n } else {\n coll['validator'] = deriveJsonSchema(\n modelEntry.fields,\n valueObjects,\n codecLookup,\n storageValueSets,\n );\n }\n }\n\n const target = 'mongo';\n const targetFamily = 'mongo';\n const collectionInputs: Record<string, MongoCollectionInput> = {};\n for (const [name, coll] of Object.entries(resolvedCollections)) {\n const raw: Record<string, unknown> = {};\n if (coll['indexes'] != null) raw['indexes'] = coll['indexes'];\n if (coll['validator'] != null) raw['validator'] = coll['validator'];\n if (coll['options'] != null) raw['options'] = coll['options'];\n collectionInputs[name] = blindCast<\n MongoCollectionInput,\n 'arktype-validated JSON shapes satisfy MongoCollectionInput by construction'\n >(raw);\n }\n const hasValueSets = Object.keys(storageValueSets).length > 0;\n\n const unboundNamespace = buildMongoNamespace({\n id: UNBOUND_NAMESPACE_ID,\n entries: {\n collection: collectionInputs,\n ...(hasValueSets ? { valueSet: storageValueSets } : {}),\n },\n });\n // Hash the constructed (normalized) entries, not the raw input literals —\n // persisted storageHash values were computed over the constructed form.\n const storageWithoutHash = {\n namespaces: {\n [UNBOUND_NAMESPACE_ID]: {\n id: UNBOUND_NAMESPACE_ID,\n entries: {\n collection: unboundNamespace.entries.collection,\n ...(unboundNamespace.entries.valueSet !== undefined\n ? { valueSet: unboundNamespace.entries.valueSet }\n : {}),\n },\n },\n },\n };\n const storageHash = computeStorageHash({\n target,\n targetFamily,\n storage: storageWithoutHash,\n ...mongoContractCanonicalizationHooks,\n });\n const storage = new MongoStorage({\n storageHash,\n namespaces: {\n [UNBOUND_NAMESPACE_ID]: unboundNamespace,\n },\n }) as Contract['storage'];\n const capabilities: Record<string, Record<string, boolean>> = {};\n\n const hasEnums = Object.keys(builtEnums).length > 0;\n\n return ok({\n targetFamily,\n target,\n roots: polyResult.roots,\n domain: {\n namespaces: {\n [UNBOUND_NAMESPACE_ID]: {\n models: polyResult.models,\n ...(Object.keys(valueObjects).length > 0 ? { valueObjects } : {}),\n ...(hasEnums ? { enum: builtEnums } : {}),\n },\n },\n },\n storage,\n extensionPacks: {},\n capabilities,\n profileHash: computeProfileHash({ target, targetFamily, capabilities }),\n meta: {},\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAWA,SAAS,gBACP,SACA,aACoB;CACpB,OAAO,aAAa,eAAe,OAAO,CAAC,GAAG;AAChD;AAEA,SAAS,kBACP,OACA,cACA,aACA,WACqC;CACrC,IAAI,MAAM,KAAK,SAAS,UAAU;EAChC,MAAM,WAAW,gBAAgB,MAAM,KAAK,SAAS,WAAW;EAChE,IAAI,CAAC,UAAU,OAAO,KAAA;EAEtB,MAAM,aACJ,MAAM,aAAa,KAAA,IACd,YAAY,MAAM,SAAS,WAAW,EAAE,UAAU,OACnD;EAEN,IAAI,UAAU,SAAS,MAAM,MAAM;GACjC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AY,iBAAiB,QAAQ;KACrC,GAAI,iBAAiB,QAAQ,aAAa,KAAA,IACtC,EAAE,UAAU,iBAAiB,QAAQ,SAAS,IAC9C,CAAC;IACP;GACF,EACF,EAK0B;GAC1B,GAAG;EACL,CAEY;EACV,YAAY,GACT,uBAAuB,iBAC1B;CACF,CAAC;CACD,MAAM,eAAwD,CAAC;CAE/D,MAAM,WAAW,OAAO,KAAK,UAAU,CAAC,CAAC,SAAS;CAElD,OAAO,GAAG;EACR;EACA;EACA,OAAO,WAAW;EAClB,QAAQ,EACN,YAAY,GACT,uBAAuB;GACtB,QAAQ,WAAW;GACnB,GAAI,OAAO,KAAK,YAAY,CAAC,CAAC,SAAS,IAAI,EAAE,aAAa,IAAI,CAAC;GAC/D,GAAI,WAAW,EAAE,MAAM,WAAW,IAAI,CAAC;EACzC,EACF,EACF;EACA;EACA,gBAAgB,CAAC;EACjB;EACA,aAAa,mBAAmB;GAAE;GAAQ;GAAc;EAAa,CAAC;EACtE,MAAM,CAAC;CACT,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,25 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/mongo-contract-psl",
|
|
3
|
-
"version": "0.14.0-dev.
|
|
3
|
+
"version": "0.14.0-dev.35",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "PSL-to-Mongo ContractIR interpreter for Prisma Next",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@prisma-next/config": "0.14.0-dev.
|
|
10
|
-
"@prisma-next/contract": "0.14.0-dev.
|
|
11
|
-
"@prisma-next/contract-authoring": "0.14.0-dev.
|
|
12
|
-
"@prisma-next/
|
|
13
|
-
"@prisma-next/
|
|
14
|
-
"@prisma-next/mongo-
|
|
15
|
-
"@prisma-next/
|
|
16
|
-
"@prisma-next/
|
|
9
|
+
"@prisma-next/config": "0.14.0-dev.35",
|
|
10
|
+
"@prisma-next/contract": "0.14.0-dev.35",
|
|
11
|
+
"@prisma-next/contract-authoring": "0.14.0-dev.35",
|
|
12
|
+
"@prisma-next/errors": "0.14.0-dev.35",
|
|
13
|
+
"@prisma-next/framework-components": "0.14.0-dev.35",
|
|
14
|
+
"@prisma-next/mongo-contract": "0.14.0-dev.35",
|
|
15
|
+
"@prisma-next/mongo-value": "0.14.0-dev.35",
|
|
16
|
+
"@prisma-next/psl-parser": "0.14.0-dev.35",
|
|
17
|
+
"@prisma-next/utils": "0.14.0-dev.35",
|
|
17
18
|
"mongodb": "^7.2.0",
|
|
18
19
|
"pathe": "^2.0.3"
|
|
19
20
|
},
|
|
20
21
|
"devDependencies": {
|
|
21
|
-
"@prisma-next/tsconfig": "0.14.0-dev.
|
|
22
|
-
"@prisma-next/tsdown": "0.14.0-dev.
|
|
22
|
+
"@prisma-next/tsconfig": "0.14.0-dev.35",
|
|
23
|
+
"@prisma-next/tsdown": "0.14.0-dev.35",
|
|
23
24
|
"tsdown": "0.22.1",
|
|
24
25
|
"typescript": "5.9.3",
|
|
25
26
|
"vitest": "4.1.8"
|
|
@@ -1,7 +1,14 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ContractField, ContractValueObject, JsonValue } from '@prisma-next/contract/types';
|
|
2
2
|
import type { CodecLookup } from '@prisma-next/framework-components/codec';
|
|
3
3
|
import { MongoValidator } from '@prisma-next/mongo-contract';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* The permitted values a field's value set restricts it to, keyed by the value set's name — the
|
|
7
|
+
* storage `entries.valueSet` slot. The validator's `enum` keyword is sourced from these, not from
|
|
8
|
+
* `domain.enum`.
|
|
9
|
+
*/
|
|
10
|
+
export type FieldValueSets = Record<string, { readonly values: readonly JsonValue[] }>;
|
|
11
|
+
|
|
5
12
|
function resolveBsonType(
|
|
6
13
|
codecId: string,
|
|
7
14
|
codecLookup: CodecLookup | undefined,
|
|
@@ -13,15 +20,15 @@ function fieldToBsonSchema(
|
|
|
13
20
|
field: ContractField,
|
|
14
21
|
valueObjects: Record<string, ContractValueObject> | undefined,
|
|
15
22
|
codecLookup: CodecLookup | undefined,
|
|
16
|
-
|
|
23
|
+
valueSets: FieldValueSets | undefined,
|
|
17
24
|
): Record<string, unknown> | undefined {
|
|
18
25
|
if (field.type.kind === 'scalar') {
|
|
19
26
|
const bsonType = resolveBsonType(field.type.codecId, codecLookup);
|
|
20
27
|
if (!bsonType) return undefined;
|
|
21
28
|
|
|
22
29
|
const enumValues =
|
|
23
|
-
field.valueSet
|
|
24
|
-
? (
|
|
30
|
+
field.valueSet !== undefined
|
|
31
|
+
? (valueSets?.[field.valueSet.entityName]?.values ?? null)
|
|
25
32
|
: null;
|
|
26
33
|
|
|
27
34
|
if ('many' in field && field.many) {
|
|
@@ -44,7 +51,7 @@ function fieldToBsonSchema(
|
|
|
44
51
|
if (field.type.kind === 'valueObject') {
|
|
45
52
|
const vo = valueObjects?.[field.type.name];
|
|
46
53
|
if (!vo) return undefined;
|
|
47
|
-
const voSchema = deriveObjectSchema(vo.fields, valueObjects, codecLookup,
|
|
54
|
+
const voSchema = deriveObjectSchema(vo.fields, valueObjects, codecLookup, valueSets);
|
|
48
55
|
if ('many' in field && field.many) {
|
|
49
56
|
return { bsonType: 'array', items: voSchema };
|
|
50
57
|
}
|
|
@@ -61,13 +68,13 @@ function deriveObjectSchema(
|
|
|
61
68
|
fields: Record<string, ContractField>,
|
|
62
69
|
valueObjects: Record<string, ContractValueObject> | undefined,
|
|
63
70
|
codecLookup: CodecLookup | undefined,
|
|
64
|
-
|
|
71
|
+
valueSets: FieldValueSets | undefined,
|
|
65
72
|
): Record<string, unknown> {
|
|
66
73
|
const properties: Record<string, unknown> = {};
|
|
67
74
|
const required: string[] = [];
|
|
68
75
|
|
|
69
76
|
for (const [fieldName, field] of Object.entries(fields)) {
|
|
70
|
-
const schema = fieldToBsonSchema(field, valueObjects, codecLookup,
|
|
77
|
+
const schema = fieldToBsonSchema(field, valueObjects, codecLookup, valueSets);
|
|
71
78
|
if (schema) {
|
|
72
79
|
properties[fieldName] = schema;
|
|
73
80
|
if (!field.nullable) {
|
|
@@ -95,10 +102,10 @@ export function deriveJsonSchema(
|
|
|
95
102
|
fields: Record<string, ContractField>,
|
|
96
103
|
valueObjects?: Record<string, ContractValueObject>,
|
|
97
104
|
codecLookup?: CodecLookup,
|
|
98
|
-
|
|
105
|
+
valueSets?: FieldValueSets,
|
|
99
106
|
): MongoValidator {
|
|
100
107
|
return new MongoValidator({
|
|
101
|
-
jsonSchema: deriveObjectSchema(fields, valueObjects, codecLookup,
|
|
108
|
+
jsonSchema: deriveObjectSchema(fields, valueObjects, codecLookup, valueSets),
|
|
102
109
|
validationLevel: 'strict',
|
|
103
110
|
validationAction: 'error',
|
|
104
111
|
});
|
|
@@ -115,9 +122,9 @@ export function derivePolymorphicJsonSchema(
|
|
|
115
122
|
variants: readonly PolymorphicVariant[],
|
|
116
123
|
valueObjects?: Record<string, ContractValueObject>,
|
|
117
124
|
codecLookup?: CodecLookup,
|
|
118
|
-
|
|
125
|
+
valueSets?: FieldValueSets,
|
|
119
126
|
): MongoValidator {
|
|
120
|
-
const baseSchema = deriveObjectSchema(baseFields, valueObjects, codecLookup,
|
|
127
|
+
const baseSchema = deriveObjectSchema(baseFields, valueObjects, codecLookup, valueSets);
|
|
121
128
|
const baseProperties = isRecord(baseSchema['properties']) ? baseSchema['properties'] : {};
|
|
122
129
|
|
|
123
130
|
const oneOf: Record<string, unknown>[] = [];
|
|
@@ -132,7 +139,7 @@ export function derivePolymorphicJsonSchema(
|
|
|
132
139
|
const variantProperties: Record<string, unknown> = {};
|
|
133
140
|
const variantRequired: string[] = [discriminatorField];
|
|
134
141
|
for (const [name, field] of Object.entries(variantOnlyFields)) {
|
|
135
|
-
const schema = fieldToBsonSchema(field, valueObjects, codecLookup,
|
|
142
|
+
const schema = fieldToBsonSchema(field, valueObjects, codecLookup, valueSets);
|
|
136
143
|
if (schema) {
|
|
137
144
|
variantProperties[name] = schema;
|
|
138
145
|
if (!field.nullable) {
|
package/src/exports/index.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {
|
|
2
|
+
deriveJsonSchema,
|
|
3
|
+
derivePolymorphicJsonSchema,
|
|
4
|
+
type FieldValueSets,
|
|
5
|
+
} from '../derive-json-schema';
|
|
2
6
|
export {
|
|
3
7
|
type InterpretPslDocumentToMongoContractInput,
|
|
4
8
|
interpretPslDocumentToMongoContract,
|
package/src/interpreter.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
type ValueSetRef,
|
|
16
16
|
} from '@prisma-next/contract/types';
|
|
17
17
|
import type { EnumTypeHandle } from '@prisma-next/contract-authoring';
|
|
18
|
+
import { errorEnumCodecNotInPackStack } from '@prisma-next/errors/control';
|
|
18
19
|
import type {
|
|
19
20
|
AuthoringContributions,
|
|
20
21
|
AuthoringEntityContext,
|
|
@@ -32,6 +33,7 @@ import {
|
|
|
32
33
|
MongoIndex,
|
|
33
34
|
type MongoIndexKeyDirection,
|
|
34
35
|
MongoStorage,
|
|
36
|
+
type MongoValueSetInput,
|
|
35
37
|
} from '@prisma-next/mongo-contract';
|
|
36
38
|
import { mongoContractCanonicalizationHooks } from '@prisma-next/mongo-contract/canonicalization-hooks';
|
|
37
39
|
import type { CollationOptions } from '@prisma-next/mongo-value/mongodb-types';
|
|
@@ -47,6 +49,7 @@ import type {
|
|
|
47
49
|
} from '@prisma-next/psl-parser';
|
|
48
50
|
import { nodePslSpan } from '@prisma-next/psl-parser';
|
|
49
51
|
import type { SourceFile } from '@prisma-next/psl-parser/syntax';
|
|
52
|
+
import { assertDefined } from '@prisma-next/utils/assertions';
|
|
50
53
|
import { blindCast } from '@prisma-next/utils/casts';
|
|
51
54
|
import { ifDefined } from '@prisma-next/utils/defined';
|
|
52
55
|
import { notOk, ok, type Result } from '@prisma-next/utils/result';
|
|
@@ -62,6 +65,21 @@ import {
|
|
|
62
65
|
parseRelationAttribute,
|
|
63
66
|
} from './psl-helpers';
|
|
64
67
|
|
|
68
|
+
/**
|
|
69
|
+
* Encode an authored enum value to its codec-encoded JSON form via the codec resolved by id from the
|
|
70
|
+
* contract's codec lookup, so a non-identity `encodeJson` (permitted by the `mongoCodec` factory) is
|
|
71
|
+
* respected. Matches the TS builder's `encodeEnumValue`: the lookup is always threaded in production,
|
|
72
|
+
* and a codecId the lookup cannot resolve is a hard error — the enum uses a codec that is not part of
|
|
73
|
+
* the contract's pack stack.
|
|
74
|
+
*/
|
|
75
|
+
function encodeEnumValue(value: unknown, codecId: string, codecLookup: CodecLookup): JsonValue {
|
|
76
|
+
const codec = codecLookup.get(codecId);
|
|
77
|
+
if (!codec) {
|
|
78
|
+
throw errorEnumCodecNotInPackStack({ codecId });
|
|
79
|
+
}
|
|
80
|
+
return codec.encodeJson(value);
|
|
81
|
+
}
|
|
82
|
+
|
|
65
83
|
export interface InterpretPslDocumentToMongoContractInput {
|
|
66
84
|
readonly symbolTable: SymbolTable;
|
|
67
85
|
readonly sourceFile: SourceFile;
|
|
@@ -1213,6 +1231,28 @@ export function interpretPslDocumentToMongoContract(
|
|
|
1213
1231
|
const resolvedModels = polyResult.models;
|
|
1214
1232
|
const resolvedCollections = polyResult.collections;
|
|
1215
1233
|
|
|
1234
|
+
// The storage value set is the source of truth for both the emit typing and the validator's
|
|
1235
|
+
// `enum` keyword. Built once, ahead of validator derivation, from each enum's codec-encoded member
|
|
1236
|
+
// values (mirroring SQL's build-contract). Encoding needs the codec lookup; production always
|
|
1237
|
+
// threads it (the CLI control stack supplies it), so its absence when enums exist is a wiring bug,
|
|
1238
|
+
// not a runtime input to tolerate.
|
|
1239
|
+
const storageValueSets: Record<string, MongoValueSetInput> = {};
|
|
1240
|
+
const enumEntries = Object.entries(builtEnums);
|
|
1241
|
+
if (enumEntries.length > 0) {
|
|
1242
|
+
assertDefined(
|
|
1243
|
+
codecLookup,
|
|
1244
|
+
'Mongo PSL interpretation requires a codec lookup to encode enum values',
|
|
1245
|
+
);
|
|
1246
|
+
for (const [enumName, builtEnum] of enumEntries) {
|
|
1247
|
+
storageValueSets[enumName] = {
|
|
1248
|
+
kind: 'valueSet',
|
|
1249
|
+
values: builtEnum.members.map((m) =>
|
|
1250
|
+
encodeEnumValue(m.value, builtEnum.codecId, codecLookup),
|
|
1251
|
+
),
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1216
1256
|
for (const [, modelEntry] of Object.entries(resolvedModels)) {
|
|
1217
1257
|
if (modelEntry.base) continue;
|
|
1218
1258
|
|
|
@@ -1233,14 +1273,14 @@ export function interpretPslDocumentToMongoContract(
|
|
|
1233
1273
|
variantEntries,
|
|
1234
1274
|
valueObjects,
|
|
1235
1275
|
codecLookup,
|
|
1236
|
-
|
|
1276
|
+
storageValueSets,
|
|
1237
1277
|
);
|
|
1238
1278
|
} else {
|
|
1239
1279
|
coll['validator'] = deriveJsonSchema(
|
|
1240
1280
|
modelEntry.fields,
|
|
1241
1281
|
valueObjects,
|
|
1242
1282
|
codecLookup,
|
|
1243
|
-
|
|
1283
|
+
storageValueSets,
|
|
1244
1284
|
);
|
|
1245
1285
|
}
|
|
1246
1286
|
}
|
|
@@ -1258,18 +1298,27 @@ export function interpretPslDocumentToMongoContract(
|
|
|
1258
1298
|
'arktype-validated JSON shapes satisfy MongoCollectionInput by construction'
|
|
1259
1299
|
>(raw);
|
|
1260
1300
|
}
|
|
1301
|
+
const hasValueSets = Object.keys(storageValueSets).length > 0;
|
|
1302
|
+
|
|
1261
1303
|
const unboundNamespace = buildMongoNamespace({
|
|
1262
1304
|
id: UNBOUND_NAMESPACE_ID,
|
|
1263
|
-
entries: {
|
|
1305
|
+
entries: {
|
|
1306
|
+
collection: collectionInputs,
|
|
1307
|
+
...(hasValueSets ? { valueSet: storageValueSets } : {}),
|
|
1308
|
+
},
|
|
1264
1309
|
});
|
|
1265
|
-
// Hash the constructed (normalized)
|
|
1266
|
-
//
|
|
1267
|
-
// constructed form.
|
|
1310
|
+
// Hash the constructed (normalized) entries, not the raw input literals —
|
|
1311
|
+
// persisted storageHash values were computed over the constructed form.
|
|
1268
1312
|
const storageWithoutHash = {
|
|
1269
1313
|
namespaces: {
|
|
1270
1314
|
[UNBOUND_NAMESPACE_ID]: {
|
|
1271
1315
|
id: UNBOUND_NAMESPACE_ID,
|
|
1272
|
-
entries: {
|
|
1316
|
+
entries: {
|
|
1317
|
+
collection: unboundNamespace.entries.collection,
|
|
1318
|
+
...(unboundNamespace.entries.valueSet !== undefined
|
|
1319
|
+
? { valueSet: unboundNamespace.entries.valueSet }
|
|
1320
|
+
: {}),
|
|
1321
|
+
},
|
|
1273
1322
|
},
|
|
1274
1323
|
},
|
|
1275
1324
|
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"interpreter-CDnf61pR.mjs","names":[],"sources":["../src/derive-json-schema.ts","../src/psl-helpers.ts","../src/interpreter.ts"],"sourcesContent":["import type { ContractEnum, ContractField, ContractValueObject } from '@prisma-next/contract/types';\nimport type { CodecLookup } from '@prisma-next/framework-components/codec';\nimport { MongoValidator } from '@prisma-next/mongo-contract';\n\nfunction resolveBsonType(\n codecId: string,\n codecLookup: CodecLookup | undefined,\n): string | undefined {\n return codecLookup?.targetTypesFor(codecId)?.[0];\n}\n\nfunction fieldToBsonSchema(\n field: ContractField,\n valueObjects: Record<string, ContractValueObject> | undefined,\n codecLookup: CodecLookup | undefined,\n enums: Record<string, ContractEnum> | undefined,\n): Record<string, unknown> | undefined {\n if (field.type.kind === 'scalar') {\n const bsonType = resolveBsonType(field.type.codecId, codecLookup);\n if (!bsonType) return undefined;\n\n const enumValues =\n field.valueSet?.entityKind === 'enum'\n ? (enums?.[field.valueSet.entityName]?.members.map((m) => m.value) ?? null)\n : null;\n\n if ('many' in field && field.many) {\n const items: Record<string, unknown> = { bsonType };\n if (enumValues) items['enum'] = enumValues;\n return { bsonType: 'array', items };\n }\n\n if (field.nullable) {\n const s: Record<string, unknown> = { bsonType: ['null', bsonType] };\n if (enumValues) s['enum'] = [...enumValues, null];\n return s;\n }\n\n const s: Record<string, unknown> = { bsonType };\n if (enumValues) s['enum'] = enumValues;\n return s;\n }\n\n if (field.type.kind === 'valueObject') {\n const vo = valueObjects?.[field.type.name];\n if (!vo) return undefined;\n const voSchema = deriveObjectSchema(vo.fields, valueObjects, codecLookup, enums);\n if ('many' in field && field.many) {\n return { bsonType: 'array', items: voSchema };\n }\n if (field.nullable) {\n return { oneOf: [{ bsonType: 'null' }, voSchema] };\n }\n return voSchema;\n }\n\n return undefined;\n}\n\nfunction deriveObjectSchema(\n fields: Record<string, ContractField>,\n valueObjects: Record<string, ContractValueObject> | undefined,\n codecLookup: CodecLookup | undefined,\n enums: Record<string, ContractEnum> | undefined,\n): Record<string, unknown> {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [fieldName, field] of Object.entries(fields)) {\n const schema = fieldToBsonSchema(field, valueObjects, codecLookup, enums);\n if (schema) {\n properties[fieldName] = schema;\n if (!field.nullable) {\n required.push(fieldName);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n bsonType: 'object',\n properties,\n additionalProperties: false,\n };\n if (required.length > 0) {\n result['required'] = required.sort();\n }\n return result;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function deriveJsonSchema(\n fields: Record<string, ContractField>,\n valueObjects?: Record<string, ContractValueObject>,\n codecLookup?: CodecLookup,\n enums?: Record<string, ContractEnum>,\n): MongoValidator {\n return new MongoValidator({\n jsonSchema: deriveObjectSchema(fields, valueObjects, codecLookup, enums),\n validationLevel: 'strict',\n validationAction: 'error',\n });\n}\n\nexport interface PolymorphicVariant {\n readonly discriminatorValue: string;\n readonly fields: Record<string, ContractField>;\n}\n\nexport function derivePolymorphicJsonSchema(\n baseFields: Record<string, ContractField>,\n discriminatorField: string,\n variants: readonly PolymorphicVariant[],\n valueObjects?: Record<string, ContractValueObject>,\n codecLookup?: CodecLookup,\n enums?: Record<string, ContractEnum>,\n): MongoValidator {\n const baseSchema = deriveObjectSchema(baseFields, valueObjects, codecLookup, enums);\n const baseProperties = isRecord(baseSchema['properties']) ? baseSchema['properties'] : {};\n\n const oneOf: Record<string, unknown>[] = [];\n for (const variant of variants) {\n const variantOnlyFields: Record<string, ContractField> = {};\n for (const [name, field] of Object.entries(variant.fields)) {\n if (!(name in baseFields)) {\n variantOnlyFields[name] = field;\n }\n }\n\n const variantProperties: Record<string, unknown> = {};\n const variantRequired: string[] = [discriminatorField];\n for (const [name, field] of Object.entries(variantOnlyFields)) {\n const schema = fieldToBsonSchema(field, valueObjects, codecLookup, enums);\n if (schema) {\n variantProperties[name] = schema;\n if (!field.nullable) {\n variantRequired.push(name);\n }\n }\n }\n\n const entry: Record<string, unknown> = {\n properties: {\n ...baseProperties,\n [discriminatorField]: { enum: [variant.discriminatorValue] },\n ...variantProperties,\n },\n required: variantRequired.sort(),\n additionalProperties: false,\n };\n\n oneOf.push(entry);\n }\n\n const jsonSchema = { ...baseSchema };\n delete jsonSchema['additionalProperties'];\n if (oneOf.length > 0) {\n jsonSchema['oneOf'] = oneOf;\n }\n\n return new MongoValidator({\n jsonSchema,\n validationLevel: 'strict',\n validationAction: 'error',\n });\n}\n","import type { ResolvedAttribute, ResolvedAttributeArg } from '@prisma-next/psl-parser';\nimport { parseQuotedStringLiteral } from '@prisma-next/psl-parser';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\nexport { parseQuotedStringLiteral };\n\nexport function getPositionalArgument(attr: ResolvedAttribute, index = 0): string | undefined {\n return attr.args.filter((arg) => arg.kind === 'positional')[index]?.value;\n}\n\nexport function getNamedArgument(attr: ResolvedAttribute, name: string): string | undefined {\n const arg = attr.args.find((a) => a.kind === 'named' && a.name === name);\n return arg?.value;\n}\n\nexport function parseFieldList(value: string): readonly string[] {\n const inner = value.replace(/^\\[/, '').replace(/\\]$/, '').trim();\n if (inner.length === 0) return [];\n return splitTopLevel(inner).map((s) => s.trim());\n}\n\nexport interface ParsedIndexField {\n readonly name: string;\n readonly isWildcard: boolean;\n readonly direction?: number;\n}\n\nexport function parseIndexFieldList(value: string): readonly ParsedIndexField[] {\n const segments = parseFieldList(value);\n return segments.map(parseIndexFieldSegment);\n}\n\nfunction parseIndexFieldSegment(segment: string): ParsedIndexField {\n const wildcardMatch = segment.match(/^wildcard\\(\\s*(.*?)\\s*\\)$/);\n if (wildcardMatch) {\n const scope = wildcardMatch[1] ?? '';\n return {\n name: scope.length > 0 ? `${scope}.$**` : '$**',\n isWildcard: true,\n };\n }\n\n const modifierMatch = segment.match(/^(\\w+)\\(\\s*sort:\\s*(\\w+)\\s*\\)$/);\n if (modifierMatch) {\n const fieldName = modifierMatch[1] ?? segment;\n const sortValue = modifierMatch[2];\n return {\n name: fieldName,\n isWildcard: false,\n direction: sortValue === 'Desc' ? -1 : 1,\n };\n }\n\n return { name: segment, isWildcard: false };\n}\n\nfunction splitTopLevel(input: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n if (ch === '(' || ch === '[' || ch === '{') depth++;\n else if (ch === ')' || ch === ']' || ch === '}') depth = Math.max(0, depth - 1);\n else if (ch === ',' && depth === 0) {\n parts.push(input.slice(start, i));\n start = i + 1;\n }\n }\n parts.push(input.slice(start));\n return parts;\n}\n\nexport function lowerFirst(value: string): string {\n if (value.length === 0) return value;\n return value[0]?.toLowerCase() + value.slice(1);\n}\n\nexport function getAttribute(\n attributes: readonly ResolvedAttribute[],\n name: string,\n): ResolvedAttribute | undefined {\n return attributes.find((attr) => attr.name === name);\n}\n\nexport function getMapName(attributes: readonly ResolvedAttribute[]): string | undefined {\n const mapAttr = getAttribute(attributes, 'map');\n if (!mapAttr) return undefined;\n const arg = mapAttr.args[0];\n if (!arg) return undefined;\n return stripQuotes(arg.value);\n}\n\nexport interface ParsedRelationAttribute {\n readonly relationName?: string;\n readonly fields?: readonly string[];\n readonly references?: readonly string[];\n}\n\nexport function parseRelationAttribute(\n attributes: readonly ResolvedAttribute[],\n): ParsedRelationAttribute | undefined {\n const relationAttr = getAttribute(attributes, 'relation');\n if (!relationAttr) return undefined;\n\n let relationName: string | undefined;\n let fieldsArg: ResolvedAttributeArg | undefined;\n let referencesArg: ResolvedAttributeArg | undefined;\n\n for (const arg of relationAttr.args) {\n if (arg.kind === 'positional') {\n relationName = stripQuotes(arg.value);\n } else if (arg.name === 'name') {\n relationName = stripQuotes(arg.value);\n } else if (arg.name === 'fields') {\n fieldsArg = arg;\n } else if (arg.name === 'references') {\n referencesArg = arg;\n }\n }\n\n const fields = fieldsArg ? parseFieldList(fieldsArg.value) : undefined;\n const references = referencesArg ? parseFieldList(referencesArg.value) : undefined;\n\n return {\n ...ifDefined('relationName', relationName),\n ...ifDefined('fields', fields),\n ...ifDefined('references', references),\n };\n}\n\nfunction stripQuotes(value: string): string {\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return value.slice(1, -1);\n }\n return value;\n}\n","import type {\n ContractSourceDiagnostic,\n ContractSourceDiagnostics,\n} from '@prisma-next/config/config-types';\nimport { computeProfileHash, computeStorageHash } from '@prisma-next/contract/hashing';\nimport {\n type Contract,\n type ContractEnum,\n type ContractField,\n type ContractReferenceRelation,\n type ContractValueObject,\n type CrossReference,\n crossRef,\n type JsonValue,\n type ValueSetRef,\n} from '@prisma-next/contract/types';\nimport type { EnumTypeHandle } from '@prisma-next/contract-authoring';\nimport type {\n AuthoringContributions,\n AuthoringEntityContext,\n} from '@prisma-next/framework-components/authoring';\nimport {\n instantiateAuthoringEntityType,\n isAuthoringEntityTypeDescriptor,\n} from '@prisma-next/framework-components/authoring';\nimport type { CodecLookup } from '@prisma-next/framework-components/codec';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n applyPolymorphicScopeToMongoIndex,\n buildMongoNamespace,\n type MongoCollectionInput,\n MongoIndex,\n type MongoIndexKeyDirection,\n MongoStorage,\n} from '@prisma-next/mongo-contract';\nimport { mongoContractCanonicalizationHooks } from '@prisma-next/mongo-contract/canonicalization-hooks';\nimport type { CollationOptions } from '@prisma-next/mongo-value/mongodb-types';\nimport type {\n CompositeTypeSymbol,\n FieldSymbol,\n ModelSymbol,\n NamespaceSymbol,\n PslExtensionBlock,\n PslSpan,\n ResolvedAttribute,\n SymbolTable,\n} from '@prisma-next/psl-parser';\nimport { nodePslSpan } from '@prisma-next/psl-parser';\nimport type { SourceFile } from '@prisma-next/psl-parser/syntax';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { deriveJsonSchema, derivePolymorphicJsonSchema } from './derive-json-schema';\nimport {\n getAttribute,\n getMapName,\n getNamedArgument,\n getPositionalArgument,\n lowerFirst,\n parseIndexFieldList,\n parseQuotedStringLiteral,\n parseRelationAttribute,\n} from './psl-helpers';\n\nexport interface InterpretPslDocumentToMongoContractInput {\n readonly symbolTable: SymbolTable;\n readonly sourceFile: SourceFile;\n readonly sourceId: string;\n readonly scalarTypeDescriptors: ReadonlyMap<string, string>;\n readonly codecLookup?: CodecLookup;\n readonly seedDiagnostics?: readonly ContractSourceDiagnostic[];\n readonly authoringContributions?: AuthoringContributions;\n}\n\n/**\n * Mongo's PSL surface binds the database from the connection string, so every\n * explicit namespace block is invalid, including `namespace unbound { … }`.\n */\nfunction validateNamespaceBlocksForMongoTarget(input: {\n readonly namespaces: readonly NamespaceSymbol[];\n readonly sourceId: string;\n readonly sourceFile: SourceFile;\n readonly diagnostics: ContractSourceDiagnostic[];\n}): void {\n for (const namespace of input.namespaces) {\n input.diagnostics.push({\n code: 'PSL_UNSUPPORTED_NAMESPACE_BLOCK',\n message: `Mongo does not support \\`namespace ${namespace.name} { … }\\` blocks (the database is bound by the connection string; declare models at the document top level instead).`,\n sourceId: input.sourceId,\n span: nodePslSpan(namespace.node.syntax, input.sourceFile),\n });\n }\n}\n\ninterface FieldMappings {\n readonly pslNameToMapped: Map<string, string>;\n}\n\ninterface FkRelation {\n readonly declaringModel: string;\n readonly fieldName: string;\n readonly targetModel: string;\n readonly relationName?: string;\n readonly localFields: readonly string[];\n readonly targetFields: readonly string[];\n}\n\nfunction fkRelationPairKey(declaringModel: string, targetModel: string): string {\n return `${declaringModel}::${targetModel}`;\n}\n\nfunction resolveFieldMappings(model: ModelSymbol): FieldMappings {\n const pslNameToMapped = new Map<string, string>();\n for (const field of Object.values(model.fields)) {\n const mapped = getMapName(field.attributes) ?? field.name;\n pslNameToMapped.set(field.name, mapped);\n }\n return { pslNameToMapped };\n}\n\nfunction resolveCollectionName(model: ModelSymbol): string {\n return getMapName(model.attributes) ?? lowerFirst(model.name);\n}\n\ninterface MongoModelEntry {\n readonly fields: Record<string, ContractField>;\n readonly relations: Record<string, ContractReferenceRelation>;\n readonly storage: { readonly collection: string };\n readonly discriminator?: { readonly field: string };\n readonly variants?: Record<string, { readonly value: string }>;\n readonly base?: CrossReference;\n}\n\ntype DiscriminatorDeclaration = { readonly fieldName: string; readonly span: PslSpan };\ntype BaseDeclaration = {\n readonly baseName: string;\n readonly value: string;\n readonly collectionName: string;\n readonly span: PslSpan;\n};\n\nfunction mongoCrossRef(modelName: string): CrossReference {\n return crossRef(modelName, UNBOUND_NAMESPACE_ID);\n}\n\nfunction collectPolymorphismDeclarations(\n models: readonly ModelSymbol[],\n sourceId: string,\n diagnostics: ContractSourceDiagnostic[],\n): {\n discriminatorDeclarations: Map<string, DiscriminatorDeclaration>;\n baseDeclarations: Map<string, BaseDeclaration>;\n} {\n const discriminatorDeclarations = new Map<string, DiscriminatorDeclaration>();\n const baseDeclarations = new Map<string, BaseDeclaration>();\n\n for (const model of models) {\n for (const attr of model.attributes) {\n if (attr.name === 'discriminator') {\n const fieldName = getPositionalArgument(attr);\n if (!fieldName) {\n diagnostics.push({\n code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',\n message: `Model \"${model.name}\" @@discriminator requires a field name argument`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n const discField = model.fields[fieldName];\n if (discField && discField.typeName !== 'String') {\n diagnostics.push({\n code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',\n message: `Discriminator field \"${fieldName}\" on model \"${model.name}\" must be of type String, but is \"${discField.typeName}\"`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n discriminatorDeclarations.set(model.name, { fieldName, span: attr.span });\n }\n if (attr.name === 'base') {\n const baseName = getPositionalArgument(attr, 0);\n const rawValue = getPositionalArgument(attr, 1);\n if (!baseName || !rawValue) {\n diagnostics.push({\n code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',\n message: `Model \"${model.name}\" @@base requires two arguments: base model name and discriminator value`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n const value = parseQuotedStringLiteral(rawValue);\n if (value === undefined) {\n diagnostics.push({\n code: 'PSL_INVALID_ATTRIBUTE_ARGUMENT',\n message: `Model \"${model.name}\" @@base discriminator value must be a quoted string literal`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n const collectionName = resolveCollectionName(model);\n baseDeclarations.set(model.name, { baseName, value, collectionName, span: attr.span });\n }\n }\n }\n\n return { discriminatorDeclarations, baseDeclarations };\n}\n\nfunction resolvePolymorphism(input: {\n models: Record<string, MongoModelEntry>;\n roots: Record<string, CrossReference>;\n collections: Record<string, Record<string, unknown>>;\n allModels: readonly ModelSymbol[];\n discriminatorDeclarations: Map<string, DiscriminatorDeclaration>;\n baseDeclarations: Map<string, BaseDeclaration>;\n modelNames: ReadonlySet<string>;\n indexSpans: Map<MongoIndex, PslSpan>;\n modelIndexesByName: Map<string, readonly MongoIndex[]>;\n sourceId: string;\n}): {\n models: Record<string, MongoModelEntry>;\n roots: Record<string, CrossReference>;\n collections: Record<string, Record<string, unknown>>;\n diagnostics: ContractSourceDiagnostic[];\n} {\n const {\n discriminatorDeclarations,\n baseDeclarations,\n modelNames,\n sourceId,\n allModels: allModelViews,\n indexSpans,\n modelIndexesByName,\n } = input;\n let patched = input.models;\n let roots = input.roots;\n let collections = input.collections;\n const diagnostics: ContractSourceDiagnostic[] = [];\n\n for (const [modelName, decl] of discriminatorDeclarations) {\n if (baseDeclarations.has(modelName)) {\n diagnostics.push({\n code: 'PSL_DISCRIMINATOR_AND_BASE',\n message: `Model \"${modelName}\" cannot have both @@discriminator and @@base`,\n sourceId,\n span: decl.span,\n });\n continue;\n }\n\n const model = patched[modelName];\n if (!model) continue;\n\n const modelView = allModelViews.find((m) => m.name === modelName);\n const mappedDiscriminatorField = modelView\n ? (resolveFieldMappings(modelView).pslNameToMapped.get(decl.fieldName) ?? decl.fieldName)\n : decl.fieldName;\n\n if (!Object.hasOwn(model.fields, mappedDiscriminatorField)) {\n diagnostics.push({\n code: 'PSL_DISCRIMINATOR_FIELD_NOT_FOUND',\n message: `Discriminator field \"${decl.fieldName}\" is not a field on model \"${modelName}\"`,\n sourceId,\n span: decl.span,\n });\n continue;\n }\n\n const variants: Record<string, { readonly value: string }> = {};\n for (const [variantName, baseDecl] of baseDeclarations) {\n if (baseDecl.baseName !== modelName) continue;\n variants[variantName] = { value: baseDecl.value };\n }\n\n if (Object.keys(variants).length === 0) {\n diagnostics.push({\n code: 'PSL_ORPHANED_DISCRIMINATOR',\n message: `Model \"${modelName}\" has @@discriminator but no variant models declare @@base(${modelName}, ...)`,\n sourceId,\n span: decl.span,\n });\n continue;\n }\n\n patched = {\n ...patched,\n [modelName]: { ...model, discriminator: { field: mappedDiscriminatorField }, variants },\n };\n }\n\n for (const [variantName, baseDecl] of baseDeclarations) {\n if (!modelNames.has(baseDecl.baseName)) {\n diagnostics.push({\n code: 'PSL_BASE_TARGET_NOT_FOUND',\n message: `Model \"${variantName}\" @@base references non-existent model \"${baseDecl.baseName}\"`,\n sourceId,\n span: baseDecl.span,\n });\n continue;\n }\n\n if (!discriminatorDeclarations.has(baseDecl.baseName)) {\n diagnostics.push({\n code: 'PSL_ORPHANED_BASE',\n message: `Model \"${variantName}\" declares @@base(${baseDecl.baseName}, ...) but \"${baseDecl.baseName}\" has no @@discriminator`,\n sourceId,\n span: baseDecl.span,\n });\n continue;\n }\n\n if (discriminatorDeclarations.has(variantName)) {\n continue;\n }\n\n const baseModel = patched[baseDecl.baseName];\n const variantModelView = allModelViews.find((m) => m.name === variantName);\n if (!variantModelView) continue;\n const hasExplicitMap = getMapName(variantModelView.attributes) !== undefined;\n\n if (hasExplicitMap && baseModel && baseDecl.collectionName !== baseModel.storage.collection) {\n diagnostics.push({\n code: 'PSL_MONGO_VARIANT_SEPARATE_COLLECTION',\n message: `Mongo variant \"${variantName}\" cannot use a different collection than its base \"${baseDecl.baseName}\". Mongo only supports single-collection polymorphism.`,\n sourceId,\n span: baseDecl.span,\n });\n continue;\n }\n\n const baseCollection = baseModel?.storage.collection ?? baseDecl.collectionName;\n const variantModel = patched[variantName];\n if (variantModel) {\n patched = {\n ...patched,\n [variantName]: {\n ...variantModel,\n base: mongoCrossRef(baseDecl.baseName),\n storage: { collection: baseCollection },\n },\n };\n }\n\n const variantCollectionName = resolveCollectionName(variantModelView);\n if (roots[variantCollectionName]?.model === variantName) {\n if (variantCollectionName === baseCollection && baseModel) {\n roots = { ...roots, [variantCollectionName]: mongoCrossRef(baseDecl.baseName) };\n } else {\n roots = Object.fromEntries(\n Object.entries(roots).filter(([key]) => key !== variantCollectionName),\n );\n }\n }\n\n const variantOwnIndexes = modelIndexesByName.get(variantName) ?? [];\n const baseColl = collections[baseCollection];\n\n const baseModelEntry = patched[baseDecl.baseName];\n const discriminatorField = baseModelEntry?.discriminator?.field;\n const scopedVariantIndexes: MongoIndex[] = [];\n if (discriminatorField) {\n for (const idx of variantOwnIndexes) {\n const result = applyPolymorphicScopeToMongoIndex(idx, {\n discriminatorField,\n discriminatorValue: baseDecl.value,\n });\n if (result.kind === 'conflict') {\n const span = indexSpans.get(idx) ?? baseDecl.span;\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: `Variant \"${variantName}\" index conflicts with discriminator scope: ${result.reason}`,\n sourceId,\n span,\n });\n continue;\n }\n if (result.index !== idx) {\n indexSpans.set(result.index, indexSpans.get(idx) ?? baseDecl.span);\n }\n scopedVariantIndexes.push(result.index);\n }\n } else {\n scopedVariantIndexes.push(...variantOwnIndexes);\n }\n\n if (variantCollectionName !== baseCollection) {\n const filtered = Object.fromEntries(\n Object.entries(collections).filter(([key]) => key !== variantCollectionName),\n );\n if (scopedVariantIndexes.length > 0 && baseColl) {\n const baseIndexes = (baseColl['indexes'] ?? []) as MongoIndex[];\n collections = {\n ...filtered,\n [baseCollection]: {\n ...baseColl,\n indexes: [...baseIndexes, ...scopedVariantIndexes],\n },\n };\n } else {\n collections = filtered;\n }\n } else if (baseColl) {\n const existingIndexes = (baseColl['indexes'] ?? []) as MongoIndex[];\n const variantIndexSet = new Set<MongoIndex>(variantOwnIndexes);\n const withoutUnscopedVariants = existingIndexes.filter((idx) => !variantIndexSet.has(idx));\n const mergedIndexes = [...withoutUnscopedVariants];\n for (const idx of scopedVariantIndexes) {\n const idxKey = canonicalJson(idx);\n const isDuplicate = withoutUnscopedVariants.some(\n (existing) => canonicalJson(existing) === idxKey,\n );\n if (!isDuplicate) {\n mergedIndexes.push(idx);\n }\n }\n if (\n mergedIndexes.length !== existingIndexes.length ||\n mergedIndexes.some((idx, i) => idx !== existingIndexes[i])\n ) {\n const next: Record<string, unknown> = { ...baseColl };\n if (mergedIndexes.length > 0) {\n next['indexes'] = mergedIndexes;\n } else {\n delete next['indexes'];\n }\n collections = { ...collections, [baseCollection]: next };\n }\n }\n }\n\n return { models: patched, roots, collections, diagnostics };\n}\n\n// Property-order-stable serialization for structural equality of plain\n// JSON-compatible values. Used for comparing MongoIndex shapes in\n// the variant-merge dedup path where a future change to the spread order\n// would otherwise produce JSON-stringify mismatches even though the\n// indexes are structurally identical.\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(',')}]`;\n }\n if (value && typeof value === 'object') {\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)\n .join(',')}}`;\n }\n return JSON.stringify(value);\n}\n\nfunction parseIndexDirection(raw: string | undefined): MongoIndexKeyDirection {\n if (!raw) return 1;\n const stripped = raw.replace(/^[\"']/, '').replace(/[\"']$/, '');\n const num = Number(stripped);\n if (num === 1 || num === -1) return num;\n if (['text', '2dsphere', '2d', 'hashed'].includes(stripped))\n return stripped as MongoIndexKeyDirection;\n return 1;\n}\n\nfunction parseNumericArg(raw: string | undefined): number | undefined {\n if (!raw) return undefined;\n const n = Number(raw);\n return Number.isFinite(n) ? n : undefined;\n}\n\nfunction parseBooleanArg(raw: string | undefined): boolean | undefined {\n if (raw === 'true') return true;\n if (raw === 'false') return false;\n return undefined;\n}\n\nfunction parseJsonArg(raw: string | undefined): Record<string, unknown> | undefined {\n if (!raw) return undefined;\n const stripped = raw.replace(/^[\"']/, '').replace(/[\"']$/, '').replace(/\\\\\"/g, '\"');\n try {\n const parsed = JSON.parse(stripped);\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // not valid JSON\n }\n return undefined;\n}\n\nfunction parseCollation(attr: ResolvedAttribute): CollationOptions | null | undefined {\n const locale = stripQuotesHelper(getNamedArgument(attr, 'collationLocale'));\n if (!locale) {\n const hasAnyCollationArg =\n getNamedArgument(attr, 'collationStrength') != null ||\n getNamedArgument(attr, 'collationCaseLevel') != null ||\n getNamedArgument(attr, 'collationCaseFirst') != null ||\n getNamedArgument(attr, 'collationNumericOrdering') != null ||\n getNamedArgument(attr, 'collationAlternate') != null ||\n getNamedArgument(attr, 'collationMaxVariable') != null ||\n getNamedArgument(attr, 'collationBackwards') != null ||\n getNamedArgument(attr, 'collationNormalization') != null;\n return hasAnyCollationArg ? null : undefined;\n }\n\n const collation: CollationOptions = { locale };\n const strength = parseNumericArg(getNamedArgument(attr, 'collationStrength'));\n if (strength != null) collation.strength = strength;\n const caseLevel = parseBooleanArg(getNamedArgument(attr, 'collationCaseLevel'));\n if (caseLevel != null) collation.caseLevel = caseLevel;\n const caseFirst = stripQuotesHelper(getNamedArgument(attr, 'collationCaseFirst'));\n if (caseFirst != null) collation.caseFirst = caseFirst;\n const numericOrdering = parseBooleanArg(getNamedArgument(attr, 'collationNumericOrdering'));\n if (numericOrdering != null) collation.numericOrdering = numericOrdering;\n const alternate = stripQuotesHelper(getNamedArgument(attr, 'collationAlternate'));\n if (alternate != null) collation.alternate = alternate;\n const maxVariable = stripQuotesHelper(getNamedArgument(attr, 'collationMaxVariable'));\n if (maxVariable != null) collation.maxVariable = maxVariable;\n const backwards = parseBooleanArg(getNamedArgument(attr, 'collationBackwards'));\n if (backwards != null) collation.backwards = backwards;\n const normalization = parseBooleanArg(getNamedArgument(attr, 'collationNormalization'));\n if (normalization != null) collation.normalization = normalization;\n return collation;\n}\n\nfunction stripQuotesHelper(raw: string | undefined): string | undefined {\n if (!raw) return undefined;\n return raw.replace(/^[\"']/, '').replace(/[\"']$/, '');\n}\n\nfunction parseProjectionList(\n raw: string | undefined,\n value: 0 | 1,\n): Record<string, 0 | 1> | undefined {\n if (!raw) return undefined;\n const stripped = raw.replace(/^[\"']/, '').replace(/[\"']$/, '');\n const inner = stripped.replace(/^\\[/, '').replace(/\\]$/, '').trim();\n if (inner.length === 0) return undefined;\n const fields = inner\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n const result: Record<string, 0 | 1> = {};\n for (const f of fields) {\n result[f] = value;\n }\n return result;\n}\n\nfunction collectIndexes(\n pslModel: ModelSymbol,\n fieldMappings: FieldMappings,\n modelNames: ReadonlySet<string>,\n sourceId: string,\n diagnostics: ContractSourceDiagnostic[],\n indexSpans: Map<MongoIndex, PslSpan>,\n): MongoIndex[] {\n const indexes: MongoIndex[] = [];\n let textIndexCount = 0;\n\n // Storage-indexable PSL field names — i.e. all declared fields except\n // relation fields (which don't materialize a column on this model). The\n // index field-existence check (PSL_INDEX_FIELD_NOT_FOUND) consults this\n // rather than fieldMappings.pslNameToMapped because the latter contains\n // every PSL field including relation fields.\n const indexableFieldNames = new Set<string>();\n for (const f of Object.values(pslModel.fields)) {\n if (modelNames.has(f.typeName)) continue;\n indexableFieldNames.add(f.name);\n }\n\n for (const field of Object.values(pslModel.fields)) {\n if (modelNames.has(field.typeName)) continue;\n const uniqueAttr = getAttribute(field.attributes, 'unique');\n if (!uniqueAttr) continue;\n const mappedName = fieldMappings.pslNameToMapped.get(field.name) ?? field.name;\n const fieldUniqueIndex = new MongoIndex({\n keys: [{ field: mappedName, direction: 1 }],\n unique: true,\n });\n indexes.push(fieldUniqueIndex);\n indexSpans.set(fieldUniqueIndex, uniqueAttr.span);\n }\n\n for (const attr of pslModel.attributes) {\n const isIndex = attr.name === 'index';\n const isUnique = attr.name === 'unique';\n const isTextIndex = attr.name === 'textIndex';\n if (!isIndex && !isUnique && !isTextIndex) continue;\n\n const fieldsArg = getPositionalArgument(attr, 0);\n if (!fieldsArg) continue;\n const parsedFields = parseIndexFieldList(fieldsArg);\n if (parsedFields.length === 0) continue;\n\n const hasWildcard = parsedFields.some((f) => f.isWildcard);\n const wildcardCount = parsedFields.filter((f) => f.isWildcard).length;\n\n if (wildcardCount > 1) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'An index can contain at most one wildcard() field',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if (isUnique && hasWildcard) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'Unique indexes cannot use wildcard() fields',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if (isTextIndex) {\n textIndexCount++;\n if (textIndexCount > 1) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: `Only one @@textIndex is allowed per collection (model \"${pslModel.name}\")`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if (hasWildcard) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message:\n 'wildcard() fields cannot be combined with type: hashed/2dsphere/2d or @@textIndex',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n }\n\n const typeArg = getNamedArgument(attr, 'type');\n const defaultDirection: MongoIndexKeyDirection = isTextIndex\n ? 'text'\n : parseIndexDirection(typeArg);\n\n if (\n hasWildcard &&\n typeof defaultDirection === 'string' &&\n ['hashed', '2dsphere', '2d'].includes(defaultDirection)\n ) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: `wildcard() fields cannot be combined with type: ${defaultDirection}`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if (defaultDirection === 'hashed' && parsedFields.length > 1) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'Hashed indexes must have exactly one field',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n let missingField: string | undefined;\n for (const pf of parsedFields) {\n let fieldNameForLookup: string | undefined;\n if (pf.isWildcard) {\n const wildcardMatch = pf.name.match(/^(.+)\\.\\$\\*\\*$/);\n fieldNameForLookup = wildcardMatch ? wildcardMatch[1] : undefined;\n } else {\n fieldNameForLookup = pf.name;\n }\n if (fieldNameForLookup === undefined || fieldNameForLookup.length === 0) continue;\n if (!indexableFieldNames.has(fieldNameForLookup)) {\n missingField = fieldNameForLookup;\n break;\n }\n }\n if (missingField !== undefined) {\n diagnostics.push({\n code: 'PSL_INDEX_FIELD_NOT_FOUND',\n message: `Index on model \"${pslModel.name}\" references unknown field \"${missingField}\"`,\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n const keys = parsedFields.map((pf) => {\n const mappedName = pf.isWildcard\n ? pf.name.replace(/^(.+)\\.\\$\\*\\*$/, (_, prefix: string) => {\n const mapped = fieldMappings.pslNameToMapped.get(prefix);\n return mapped ? `${mapped}.$**` : `${prefix}.$**`;\n })\n : (fieldMappings.pslNameToMapped.get(pf.name) ?? pf.name);\n const direction: MongoIndexKeyDirection =\n pf.direction != null ? (pf.direction as MongoIndexKeyDirection) : defaultDirection;\n return { field: mappedName, direction };\n });\n\n const unique = isUnique ? true : undefined;\n const sparse = isTextIndex ? undefined : parseBooleanArg(getNamedArgument(attr, 'sparse'));\n const expireAfterSeconds = isTextIndex\n ? undefined\n : parseNumericArg(getNamedArgument(attr, 'expireAfterSeconds'));\n\n if (hasWildcard && expireAfterSeconds != null) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'expireAfterSeconds cannot be combined with wildcard() fields',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n const partialFilterExpression = parseJsonArg(getNamedArgument(attr, 'filter'));\n\n const includeArg = getNamedArgument(attr, 'include');\n const excludeArg = getNamedArgument(attr, 'exclude');\n\n if (includeArg != null && excludeArg != null) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'Cannot specify both include and exclude on the same index',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n if ((includeArg != null || excludeArg != null) && !hasWildcard) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message:\n 'include/exclude options are only valid when the index contains a wildcard() field',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n const wildcardProjection =\n includeArg != null\n ? parseProjectionList(includeArg, 1)\n : excludeArg != null\n ? parseProjectionList(excludeArg, 0)\n : undefined;\n\n const collation = parseCollation(attr);\n if (collation === null) {\n diagnostics.push({\n code: 'PSL_INVALID_INDEX',\n message: 'collationLocale is required when using collation options',\n sourceId,\n span: attr.span,\n });\n continue;\n }\n\n const rawWeights = parseJsonArg(getNamedArgument(attr, 'weights'));\n let weights: Record<string, number> | undefined;\n if (rawWeights) {\n weights = {};\n for (const [k, v] of Object.entries(rawWeights)) {\n if (typeof v === 'number') weights[k] = v;\n }\n }\n\n const rawDefaultLang = isTextIndex\n ? getNamedArgument(attr, 'language')\n : getNamedArgument(attr, 'default_language');\n const default_language = stripQuotesHelper(rawDefaultLang);\n\n const rawLangOverride = getNamedArgument(attr, 'languageOverride');\n const language_override = stripQuotesHelper(rawLangOverride);\n\n const index = new MongoIndex({\n keys,\n ...(unique != null && { unique }),\n ...(sparse != null && { sparse }),\n ...(expireAfterSeconds != null && { expireAfterSeconds }),\n ...(partialFilterExpression != null && { partialFilterExpression }),\n ...(wildcardProjection != null && { wildcardProjection }),\n ...(collation != null && { collation }),\n ...(weights != null && { weights }),\n ...(default_language != null && { default_language }),\n ...(language_override != null && { language_override }),\n });\n\n indexes.push(index);\n indexSpans.set(index, attr.span);\n }\n\n return indexes;\n}\n\nfunction isRelationField(field: FieldSymbol, modelNames: ReadonlySet<string>): boolean {\n return modelNames.has(field.typeName);\n}\n\n// PSL scalar type name whose codec is mandated for a Mongo model's `_id`.\nconst MONGO_OBJECT_ID_PSL_TYPE = 'ObjectId';\n\nfunction resolveFieldCodecId(\n field: FieldSymbol,\n scalarTypeDescriptors: ReadonlyMap<string, string>,\n): string | undefined {\n return scalarTypeDescriptors.get(field.typeName);\n}\n\nfunction resolveNonRelationField(\n field: FieldSymbol,\n ownerName: string,\n compositeTypeNames: ReadonlySet<string>,\n scalarTypeDescriptors: ReadonlyMap<string, string>,\n codecIdByEnumName: ReadonlyMap<string, string>,\n sourceId: string,\n diagnostics: ContractSourceDiagnostic[],\n): ContractField | undefined {\n if (compositeTypeNames.has(field.typeName)) {\n const result: ContractField = {\n type: { kind: 'valueObject', name: field.typeName },\n nullable: field.optional,\n };\n return field.list ? { ...result, many: true } : result;\n }\n\n // If this field's declared type is a known enum name, treat the field as a scalar\n // with that enum's codec and stamp the domain valueSet ref.\n const enumCodecId = codecIdByEnumName.get(field.typeName);\n if (enumCodecId !== undefined) {\n const valueSet: ValueSetRef = {\n plane: 'domain',\n entityKind: 'enum',\n namespaceId: UNBOUND_NAMESPACE_ID,\n entityName: field.typeName,\n };\n const result: ContractField = {\n type: { kind: 'scalar', codecId: enumCodecId },\n nullable: field.optional,\n valueSet,\n };\n return field.list ? { ...result, many: true } : result;\n }\n\n // Avoid cascading unsupported-type diagnostics after invalid qualification.\n if (field.malformedType) {\n return undefined;\n }\n\n const codecId = resolveFieldCodecId(field, scalarTypeDescriptors);\n if (!codecId) {\n diagnostics.push({\n code: 'PSL_UNSUPPORTED_FIELD_TYPE',\n message: `Field \"${ownerName}.${field.name}\" type \"${field.typeName}\" is not supported in Mongo PSL interpreter`,\n sourceId,\n span: field.span,\n });\n return undefined;\n }\n\n const result: ContractField = {\n type: { kind: 'scalar', codecId },\n nullable: field.optional,\n };\n return field.list ? { ...result, many: true } : result;\n}\n\nfunction processEnumDeclarations(input: {\n readonly enumBlocks: readonly PslExtensionBlock[];\n readonly sourceId: string;\n readonly authoringContributions: AuthoringContributions | undefined;\n readonly entityContext: AuthoringEntityContext;\n readonly diagnostics: ContractSourceDiagnostic[];\n}): Record<string, ContractEnum> {\n const builtEnums: Record<string, ContractEnum> = {};\n\n if (input.enumBlocks.length === 0) return builtEnums;\n\n const enumDescriptor =\n input.authoringContributions?.entityTypes?.['enum'] !== undefined &&\n isAuthoringEntityTypeDescriptor(input.authoringContributions.entityTypes['enum'])\n ? input.authoringContributions.entityTypes['enum']\n : undefined;\n\n if (!enumDescriptor) {\n for (const decl of input.enumBlocks) {\n input.diagnostics.push({\n code: 'PSL_ENUM_MISSING_FACTORY',\n message: `enum \"${decl.name}\" requires an \"enum\" entityType factory in the active authoring contributions`,\n sourceId: input.sourceId,\n span: decl.span,\n });\n }\n return builtEnums;\n }\n\n for (const decl of input.enumBlocks) {\n const handle = instantiateAuthoringEntityType<EnumTypeHandle | undefined>(\n 'enum',\n enumDescriptor,\n [decl],\n input.entityContext,\n );\n\n if (handle === undefined || handle === null) continue;\n\n builtEnums[decl.name] = {\n codecId: handle.codecId,\n members: handle.enumMembers.map((m) => ({\n name: m.name,\n value: blindCast<JsonValue, 'factory-validated enum members are JsonValue-compatible'>(\n m.value,\n ),\n })),\n };\n }\n\n return builtEnums;\n}\n\nexport function interpretPslDocumentToMongoContract(\n input: InterpretPslDocumentToMongoContractInput,\n): Result<Contract, ContractSourceDiagnostics> {\n const { symbolTable, sourceFile, scalarTypeDescriptors, codecLookup } = input;\n const sourceId = input.sourceId;\n const diagnostics: ContractSourceDiagnostic[] = [...(input.seedDiagnostics ?? [])];\n const topLevel = symbolTable.topLevel;\n validateNamespaceBlocksForMongoTarget({\n namespaces: Object.values(topLevel.namespaces),\n sourceId,\n sourceFile,\n diagnostics,\n });\n const allModels: ModelSymbol[] = Object.values(topLevel.models);\n const allCompositeTypes: CompositeTypeSymbol[] = Object.values(topLevel.compositeTypes);\n const modelNames = new Set(allModels.map((m) => m.name));\n const compositeTypeNames = new Set(allCompositeTypes.map((ct) => ct.name));\n\n const topLevelEnumBlocks = Object.values(topLevel.blocks)\n .filter((b) => b.keyword === 'enum')\n .map((b) => b.block);\n\n const builtEnums = processEnumDeclarations({\n enumBlocks: topLevelEnumBlocks,\n sourceId,\n authoringContributions: input.authoringContributions,\n entityContext: {\n family: 'mongo',\n target: 'mongo',\n ...ifDefined('codecLookup', codecLookup),\n sourceId,\n diagnostics: {\n push: (d) => {\n diagnostics.push(\n blindCast<ContractSourceDiagnostic, 'sink diagnostics are span-compatible'>(d),\n );\n },\n },\n },\n diagnostics,\n });\n\n const codecIdByEnumName: Map<string, string> = new Map(\n Object.entries(builtEnums).map(([name, e]) => [name, e.codecId]),\n );\n\n const models: Record<string, MongoModelEntry> = {};\n const collections: Record<string, Record<string, unknown>> = {};\n const roots: Record<string, CrossReference> = {};\n const allFkRelations: FkRelation[] = [];\n const indexSpans = new Map<MongoIndex, PslSpan>();\n const modelIndexesByName = new Map<string, readonly MongoIndex[]>();\n\n interface BackrelationCandidate {\n readonly modelName: string;\n readonly fieldName: string;\n readonly targetModelName: string;\n readonly relationName?: string;\n readonly cardinality: '1:1' | '1:N';\n readonly field: FieldSymbol;\n }\n const backrelationCandidates: BackrelationCandidate[] = [];\n\n for (const pslModel of allModels) {\n const collectionName = resolveCollectionName(pslModel);\n const fieldMappings = resolveFieldMappings(pslModel);\n\n const fields: Record<string, ContractField> = {};\n const relations: Record<string, ContractReferenceRelation> = {};\n\n for (const field of Object.values(pslModel.fields)) {\n if (isRelationField(field, modelNames)) {\n const relation = parseRelationAttribute(field.attributes);\n\n if (field.list || !(relation?.fields && relation?.references)) {\n backrelationCandidates.push({\n modelName: pslModel.name,\n fieldName: field.name,\n targetModelName: field.typeName,\n ...ifDefined('relationName', relation?.relationName),\n cardinality: field.list ? '1:N' : '1:1',\n field,\n });\n continue;\n }\n\n if (relation?.fields && relation?.references) {\n const localMapped = relation.fields.map((f) => fieldMappings.pslNameToMapped.get(f) ?? f);\n\n const targetModel = allModels.find((m) => m.name === field.typeName);\n const targetFieldMappings = targetModel ? resolveFieldMappings(targetModel) : undefined;\n const targetMapped = relation.references.map(\n (f) => targetFieldMappings?.pslNameToMapped.get(f) ?? f,\n );\n\n relations[field.name] = {\n to: mongoCrossRef(field.typeName),\n cardinality: 'N:1' as const,\n on: {\n localFields: localMapped,\n targetFields: targetMapped,\n },\n };\n\n allFkRelations.push({\n declaringModel: pslModel.name,\n fieldName: field.name,\n targetModel: field.typeName,\n ...ifDefined('relationName', relation.relationName),\n localFields: localMapped,\n targetFields: targetMapped,\n });\n }\n continue;\n }\n\n const resolved = resolveNonRelationField(\n field,\n pslModel.name,\n compositeTypeNames,\n scalarTypeDescriptors,\n codecIdByEnumName,\n sourceId,\n diagnostics,\n );\n if (!resolved) continue;\n\n const mappedName = fieldMappings.pslNameToMapped.get(field.name) ?? field.name;\n fields[mappedName] = resolved;\n }\n\n const isVariantModel = pslModel.attributes.some((attr) => attr.name === 'base');\n const hasIdField = Object.values(pslModel.fields).some(\n (f) => getAttribute(f.attributes, 'id') !== undefined,\n );\n // Variant models inherit the base's identity and are validated through their base.\n if (!isVariantModel) {\n if (!hasIdField) {\n diagnostics.push({\n code: 'PSL_MISSING_ID_FIELD',\n message: `Model \"${pslModel.name}\" has no field with @id attribute. Every model must have exactly one @id field.`,\n sourceId,\n });\n } else {\n // The resulting document must carry an `_id` of BSON type objectId. We\n // assert on the emitted shape (the mapped-name-keyed field record), not\n // on how the user spelled it — `id ObjectId @id @map(\"_id\")` and a field\n // literally named `_id` both satisfy it; a non-objectId or unmapped id\n // does not.\n const objectIdCodecId = scalarTypeDescriptors.get(MONGO_OBJECT_ID_PSL_TYPE);\n const idField = fields['_id'];\n const idIsObjectId =\n idField !== undefined &&\n idField.type.kind === 'scalar' &&\n objectIdCodecId !== undefined &&\n idField.type.codecId === objectIdCodecId;\n if (!idIsObjectId) {\n diagnostics.push({\n code: 'PSL_MONGO_ID_REQUIRED',\n message: `Model \"${pslModel.name}\" must declare an _id field of type ObjectId (e.g. \\`id ObjectId @id @map(\"_id\")\\`).`,\n sourceId,\n });\n }\n }\n }\n\n models[pslModel.name] = { fields, relations, storage: { collection: collectionName } };\n const modelIndexes = collectIndexes(\n pslModel,\n fieldMappings,\n modelNames,\n sourceId,\n diagnostics,\n indexSpans,\n );\n modelIndexesByName.set(pslModel.name, modelIndexes);\n const existingColl = collections[collectionName];\n if (existingColl && modelIndexes.length > 0) {\n const existingIndexes = (existingColl['indexes'] ?? []) as MongoIndex[];\n collections[collectionName] = { indexes: [...existingIndexes, ...modelIndexes] };\n } else if (!existingColl) {\n collections[collectionName] = modelIndexes.length > 0 ? { indexes: modelIndexes } : {};\n }\n roots[collectionName] = mongoCrossRef(pslModel.name);\n }\n\n const valueObjects: Record<string, ContractValueObject> = {};\n for (const compositeType of allCompositeTypes) {\n const fields: Record<string, ContractField> = {};\n for (const field of Object.values(compositeType.fields)) {\n const resolved = resolveNonRelationField(\n field,\n compositeType.name,\n compositeTypeNames,\n scalarTypeDescriptors,\n codecIdByEnumName,\n sourceId,\n diagnostics,\n );\n if (!resolved) continue;\n fields[field.name] = resolved;\n }\n valueObjects[compositeType.name] = { fields };\n }\n\n const fkRelationsByPair = new Map<string, FkRelation[]>();\n for (const fk of allFkRelations) {\n const key = fkRelationPairKey(fk.declaringModel, fk.targetModel);\n const existing = fkRelationsByPair.get(key);\n if (existing) {\n existing.push(fk);\n } else {\n fkRelationsByPair.set(key, [fk]);\n }\n }\n\n for (const candidate of backrelationCandidates) {\n const pairKey = fkRelationPairKey(candidate.targetModelName, candidate.modelName);\n const pairMatches = fkRelationsByPair.get(pairKey) ?? [];\n const matches = candidate.relationName\n ? pairMatches.filter((r) => r.relationName === candidate.relationName)\n : [...pairMatches];\n\n if (matches.length === 0) {\n diagnostics.push({\n code: 'PSL_ORPHANED_BACKRELATION',\n message: `Backrelation list field \"${candidate.modelName}.${candidate.fieldName}\" has no matching FK-side relation on model \"${candidate.targetModelName}\". Add @relation(fields: [...], references: [...]) on the FK-side relation or use an explicit join model for many-to-many.`,\n sourceId,\n span: candidate.field.span,\n });\n continue;\n }\n if (matches.length > 1) {\n diagnostics.push({\n code: 'PSL_AMBIGUOUS_BACKRELATION',\n message: `Backrelation list field \"${candidate.modelName}.${candidate.fieldName}\" matches multiple FK-side relations on model \"${candidate.targetModelName}\". Add @relation(\"...\") to both sides to disambiguate.`,\n sourceId,\n span: candidate.field.span,\n });\n continue;\n }\n\n const fk = matches[0];\n if (!fk) continue;\n const modelEntry = models[candidate.modelName];\n if (!modelEntry) continue;\n modelEntry.relations[candidate.fieldName] = {\n to: mongoCrossRef(candidate.targetModelName),\n cardinality: candidate.cardinality,\n on: {\n localFields: fk.targetFields,\n targetFields: fk.localFields,\n },\n };\n }\n\n const { discriminatorDeclarations, baseDeclarations } = collectPolymorphismDeclarations(\n allModels,\n sourceId,\n diagnostics,\n );\n const polyResult = resolvePolymorphism({\n models,\n roots,\n collections,\n allModels,\n discriminatorDeclarations,\n baseDeclarations,\n modelNames,\n indexSpans,\n modelIndexesByName,\n sourceId,\n });\n\n if (diagnostics.length > 0 || polyResult.diagnostics.length > 0) {\n return notOk({\n summary: 'PSL to Mongo contract interpretation failed',\n diagnostics: [...diagnostics, ...polyResult.diagnostics],\n });\n }\n\n const resolvedModels = polyResult.models;\n const resolvedCollections = polyResult.collections;\n\n for (const [, modelEntry] of Object.entries(resolvedModels)) {\n if (modelEntry.base) continue;\n\n const collectionName = modelEntry.storage.collection;\n const coll = resolvedCollections[collectionName];\n if (!coll) continue;\n\n if (modelEntry.discriminator && modelEntry.variants) {\n const variantEntries = Object.entries(modelEntry.variants).map(\n ([variantName, { value }]) => ({\n discriminatorValue: value,\n fields: resolvedModels[variantName]?.fields ?? {},\n }),\n );\n coll['validator'] = derivePolymorphicJsonSchema(\n modelEntry.fields,\n modelEntry.discriminator.field,\n variantEntries,\n valueObjects,\n codecLookup,\n builtEnums,\n );\n } else {\n coll['validator'] = deriveJsonSchema(\n modelEntry.fields,\n valueObjects,\n codecLookup,\n builtEnums,\n );\n }\n }\n\n const target = 'mongo';\n const targetFamily = 'mongo';\n const collectionInputs: Record<string, MongoCollectionInput> = {};\n for (const [name, coll] of Object.entries(resolvedCollections)) {\n const raw: Record<string, unknown> = {};\n if (coll['indexes'] != null) raw['indexes'] = coll['indexes'];\n if (coll['validator'] != null) raw['validator'] = coll['validator'];\n if (coll['options'] != null) raw['options'] = coll['options'];\n collectionInputs[name] = blindCast<\n MongoCollectionInput,\n 'arktype-validated JSON shapes satisfy MongoCollectionInput by construction'\n >(raw);\n }\n const unboundNamespace = buildMongoNamespace({\n id: UNBOUND_NAMESPACE_ID,\n entries: { collection: collectionInputs },\n });\n // Hash the constructed (normalized) collection map, not the raw input\n // literals — persisted storageHash values were computed over the\n // constructed form.\n const storageWithoutHash = {\n namespaces: {\n [UNBOUND_NAMESPACE_ID]: {\n id: UNBOUND_NAMESPACE_ID,\n entries: { collection: unboundNamespace.entries.collection },\n },\n },\n };\n const storageHash = computeStorageHash({\n target,\n targetFamily,\n storage: storageWithoutHash,\n ...mongoContractCanonicalizationHooks,\n });\n const storage = new MongoStorage({\n storageHash,\n namespaces: {\n [UNBOUND_NAMESPACE_ID]: unboundNamespace,\n },\n }) as Contract['storage'];\n const capabilities: Record<string, Record<string, boolean>> = {};\n\n const hasEnums = Object.keys(builtEnums).length > 0;\n\n return ok({\n targetFamily,\n target,\n roots: polyResult.roots,\n domain: {\n namespaces: {\n [UNBOUND_NAMESPACE_ID]: {\n models: polyResult.models,\n ...(Object.keys(valueObjects).length > 0 ? { valueObjects } : {}),\n ...(hasEnums ? { enum: builtEnums } : {}),\n },\n },\n },\n storage,\n extensionPacks: {},\n capabilities,\n profileHash: computeProfileHash({ target, targetFamily, capabilities }),\n meta: {},\n });\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAS,gBACP,SACA,aACoB;CACpB,OAAO,aAAa,eAAe,OAAO,CAAC,GAAG;AAChD;AAEA,SAAS,kBACP,OACA,cACA,aACA,OACqC;CACrC,IAAI,MAAM,KAAK,SAAS,UAAU;EAChC,MAAM,WAAW,gBAAgB,MAAM,KAAK,SAAS,WAAW;EAChE,IAAI,CAAC,UAAU,OAAO,KAAA;EAEtB,MAAM,aACJ,MAAM,UAAU,eAAe,SAC1B,QAAQ,MAAM,SAAS,WAAW,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,KAAK,OACpE;EAEN,IAAI,UAAU,SAAS,MAAM,MAAM;GACjC,MAAM,QAAiC,EAAE,SAAS;GAClD,IAAI,YAAY,MAAM,UAAU;GAChC,OAAO;IAAE,UAAU;IAAS;GAAM;EACpC;EAEA,IAAI,MAAM,UAAU;GAClB,MAAM,IAA6B,EAAE,UAAU,CAAC,QAAQ,QAAQ,EAAE;GAClE,IAAI,YAAY,EAAE,UAAU,CAAC,GAAG,YAAY,IAAI;GAChD,OAAO;EACT;EAEA,MAAM,IAA6B,EAAE,SAAS;EAC9C,IAAI,YAAY,EAAE,UAAU;EAC5B,OAAO;CACT;CAEA,IAAI,MAAM,KAAK,SAAS,eAAe;EACrC,MAAM,KAAK,eAAe,MAAM,KAAK;EACrC,IAAI,CAAC,IAAI,OAAO,KAAA;EAChB,MAAM,WAAW,mBAAmB,GAAG,QAAQ,cAAc,aAAa,KAAK;EAC/E,IAAI,UAAU,SAAS,MAAM,MAC3B,OAAO;GAAE,UAAU;GAAS,OAAO;EAAS;EA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