@prisma-next/mongo-contract 0.11.0 → 0.12.0
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/canonicalization-hooks.d.mts +9 -0
- package/dist/canonicalization-hooks.d.mts.map +1 -0
- package/dist/canonicalization-hooks.mjs +20 -0
- package/dist/canonicalization-hooks.mjs.map +1 -0
- package/dist/index.d.mts +20 -13
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +120 -96
- package/dist/index.mjs.map +1 -1
- package/package.json +20 -8
- package/src/canonicalization-hooks.ts +27 -0
- package/src/contract-schema.ts +16 -10
- package/src/contract-types.ts +15 -7
- package/src/exports/canonicalization-hooks.ts +1 -0
- package/src/exports/index.ts +3 -0
- package/src/ir/build-mongo-namespace.ts +80 -0
- package/src/ir/mongo-storage.ts +7 -67
- package/src/validate-storage.ts +52 -45
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/contract-schema.ts","../src/ir/mongo-change-stream-pre-and-post-images-options.ts","../src/ir/mongo-clustered-collection-options.ts","../src/ir/mongo-collation-options.ts","../src/ir/mongo-index-option-defaults.ts","../src/ir/mongo-time-series-collection-options.ts","../src/ir/mongo-collection-options.ts","../src/ir/mongo-index.ts","../src/ir/mongo-validator.ts","../src/ir/mongo-collection.ts","../src/ir/mongo-index-options.ts","../src/ir/mongo-unbound-namespace.ts","../src/ir/mongo-storage.ts","../src/polymorphic-index-scope.ts","../src/validate-storage.ts"],"sourcesContent":["import { type Type, type } from 'arktype';\nimport type { MongoJsonObject, MongoJsonPrimitive, MongoJsonValue } from './contract-types';\n\nconst ScalarFieldTypeSchema = type({\n '+': 'reject',\n kind: \"'scalar'\",\n codecId: 'string',\n 'typeParams?': 'Record<string, unknown>',\n});\n\nconst ValueObjectFieldTypeSchema = type({\n '+': 'reject',\n kind: \"'valueObject'\",\n name: 'string',\n});\n\nconst UnionFieldTypeSchema = type({\n '+': 'reject',\n kind: \"'union'\",\n members: ScalarFieldTypeSchema.or(ValueObjectFieldTypeSchema).array(),\n});\n\nconst FieldTypeSchema = ScalarFieldTypeSchema.or(ValueObjectFieldTypeSchema).or(\n UnionFieldTypeSchema,\n);\n\nconst RawFieldSchema = type({\n '+': 'reject',\n type: FieldTypeSchema,\n 'nullable?': 'boolean',\n 'many?': 'boolean',\n 'dict?': 'boolean',\n});\n\nconst FieldSchema = RawFieldSchema.pipe((field) => ({\n ...field,\n nullable: field.nullable ?? false,\n}));\n\nconst RelationOnSchema = type({\n '+': 'reject',\n localFields: 'string[]',\n targetFields: 'string[]',\n});\n\nconst RelationSchema = type({\n '+': 'reject',\n to: 'string',\n cardinality: \"'1:1' | '1:N' | 'N:1'\",\n 'on?': RelationOnSchema,\n});\n\nconst StorageRelationEntrySchema = type({\n '+': 'reject',\n field: 'string',\n});\n\nconst MongoJsonPrimitiveSchema = type\n .declare<MongoJsonPrimitive>()\n .type('string | number | boolean | null');\n\nfunction isMongoJsonRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction withUnseenReference(value: object, seen: WeakSet<object>, visit: () => boolean): boolean {\n if (seen.has(value)) {\n return false;\n }\n\n seen.add(value);\n const result = visit();\n seen.delete(value);\n return result;\n}\n\nfunction isMongoJsonObject(value: unknown, seen: WeakSet<object>): value is MongoJsonObject {\n return (\n isMongoJsonRecord(value) &&\n withUnseenReference(value, seen, () =>\n Object.values(value).every((entry) => isMongoJsonValue(entry, seen)),\n )\n );\n}\n\nfunction isMongoJsonValue(value: unknown, seen = new WeakSet<object>()): value is MongoJsonValue {\n if (MongoJsonPrimitiveSchema.allows(value)) {\n return true;\n }\n if (Array.isArray(value)) {\n return withUnseenReference(value, seen, () =>\n value.every((entry) => isMongoJsonValue(entry, seen)),\n );\n }\n return isMongoJsonObject(value, seen);\n}\n\nconst MongoJsonValueSchema = type('unknown').narrow((value, ctx) =>\n isMongoJsonValue(value) ? true : ctx.mustBe('a JSON-serializable MongoJsonValue'),\n);\n\nconst MongoJsonObjectSchema = type({ '[string]': 'unknown' }).narrow((value, ctx) =>\n isMongoJsonRecord(value) &&\n Object.values(value).every((entry) => MongoJsonValueSchema.allows(entry))\n ? true\n : ctx.mustBe('a JSON object with MongoJsonValue entries'),\n);\n\nconst NumberRecordSchema = type({ '[string]': 'number' });\n\nconst IndexFieldsSchema = type({\n '+': 'reject',\n '[string]': '1 | -1 | \"text\" | \"2dsphere\" | \"2d\" | \"hashed\"',\n}).narrow((fields, ctx) =>\n Object.keys(fields).length > 0 ? true : ctx.mustBe('an index field map with at least one entry'),\n);\n\nconst CollationSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-collation-options'\",\n locale: 'string',\n 'caseLevel?': 'boolean',\n 'caseFirst?': '\"off\" | \"upper\" | \"lower\"',\n 'strength?': '1 | 2 | 3 | 4 | 5',\n 'numericOrdering?': 'boolean',\n 'alternate?': '\"non-ignorable\" | \"shifted\"',\n 'maxVariable?': '\"punct\" | \"space\"',\n 'backwards?': 'boolean',\n 'normalization?': 'boolean',\n});\n\nconst IndexOptionDefaultsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-index-option-defaults'\",\n 'storageEngine?': MongoJsonObjectSchema,\n});\n\nconst TimeSeriesCollectionOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-time-series-collection-options'\",\n timeField: 'string',\n 'metaField?': 'string',\n 'granularity?': '\"seconds\" | \"minutes\" | \"hours\"',\n 'bucketMaxSpanSeconds?': 'number',\n 'bucketRoundingSeconds?': 'number',\n});\n\nconst ClusteredCollectionKeySchema = type({\n '+': 'reject',\n '[string]': '1',\n}).narrow((key, ctx) =>\n Object.keys(key).length > 0\n ? true\n : ctx.mustBe('a clustered index key map with at least one entry'),\n);\n\nconst ClusteredCollectionOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-clustered-collection-options'\",\n 'name?': 'string',\n key: ClusteredCollectionKeySchema,\n unique: 'boolean',\n});\n\nconst ChangeStreamPreAndPostImagesSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-change-stream-pre-and-post-images-options'\",\n enabled: 'boolean',\n});\n\nconst CollectionOptionsSchema = type({\n '+': 'reject',\n 'capped?': 'boolean',\n 'size?': 'number',\n 'max?': 'number',\n 'storageEngine?': MongoJsonObjectSchema,\n 'indexOptionDefaults?': IndexOptionDefaultsSchema,\n 'collation?': CollationSchema,\n 'timeseries?': TimeSeriesCollectionOptionsSchema,\n 'clusteredIndex?': ClusteredCollectionOptionsSchema,\n 'expireAfterSeconds?': 'number',\n 'changeStreamPreAndPostImages?': ChangeStreamPreAndPostImagesSchema,\n});\n\nconst ModelStorageSchema = type({\n '+': 'reject',\n 'collection?': 'string',\n 'relations?': type({ '[string]': StorageRelationEntrySchema }),\n});\n\nconst DiscriminatorSchema = type({\n '+': 'reject',\n field: 'string',\n});\n\nconst VariantEntrySchema = type({\n '+': 'reject',\n value: 'string',\n});\n\nconst ModelDefinitionSchema = type({\n '+': 'reject',\n fields: type({ '[string]': FieldSchema }),\n storage: ModelStorageSchema,\n 'relations?': type({ '[string]': RelationSchema }),\n 'discriminator?': DiscriminatorSchema,\n 'variants?': type({ '[string]': VariantEntrySchema }),\n 'base?': 'string',\n 'owner?': 'string',\n});\n\nconst WildcardProjectionSchema = type({\n '+': 'reject',\n '[string]': '0 | 1',\n});\n\nconst IndexOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-index-options'\",\n 'unique?': 'boolean',\n 'name?': 'string',\n 'partialFilterExpression?': MongoJsonObjectSchema,\n 'sparse?': 'boolean',\n 'expireAfterSeconds?': 'number',\n 'weights?': NumberRecordSchema,\n 'default_language?': 'string',\n 'language_override?': 'string',\n 'textIndexVersion?': 'number',\n '2dsphereIndexVersion?': 'number',\n 'bits?': 'number',\n 'min?': 'number',\n 'max?': 'number',\n 'bucketSize?': 'number',\n 'hidden?': 'boolean',\n 'collation?': CollationSchema,\n 'wildcardProjection?': WildcardProjectionSchema,\n});\n\nconst IndexSchema = type({\n '+': 'reject',\n fields: IndexFieldsSchema,\n 'options?': IndexOptionsSchema,\n});\n\nconst MongoIndexKeySchema = type({\n '+': 'reject',\n field: 'string',\n direction: '1 | -1 | \"text\" | \"2dsphere\" | \"2d\" | \"hashed\"',\n});\n\nconst MongoStorageIndexSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-index'\",\n keys: MongoIndexKeySchema.array().atLeastLength(1),\n 'unique?': 'boolean',\n 'sparse?': 'boolean',\n 'expireAfterSeconds?': 'number',\n 'partialFilterExpression?': 'Record<string, unknown>',\n 'wildcardProjection?': 'Record<string, 0 | 1>',\n 'collation?': 'Record<string, unknown>',\n 'weights?': 'Record<string, number>',\n 'default_language?': 'string',\n 'language_override?': 'string',\n});\n\nconst MongoStorageValidatorSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-validator'\",\n jsonSchema: 'Record<string, unknown>',\n validationLevel: \"'strict' | 'moderate'\",\n validationAction: \"'error' | 'warn'\",\n});\n\nconst CappedOptionsSchema = type({\n '+': 'reject',\n size: 'number',\n 'max?': 'number',\n});\n\nconst TimeseriesOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-time-series-collection-options'\",\n timeField: 'string',\n 'metaField?': 'string',\n 'granularity?': \"'seconds' | 'minutes' | 'hours'\",\n 'bucketMaxSpanSeconds?': 'number',\n 'bucketRoundingSeconds?': 'number',\n});\n\nconst ClusteredIndexSchema = type({\n '+': 'reject',\n 'name?': 'string',\n});\n\nconst MongoCollectionOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-collection-options'\",\n 'capped?': CappedOptionsSchema,\n 'storageEngine?': MongoJsonObjectSchema,\n 'indexOptionDefaults?': IndexOptionDefaultsSchema,\n 'timeseries?': TimeseriesOptionsSchema,\n 'collation?': 'Record<string, unknown>',\n 'expireAfterSeconds?': 'number',\n 'changeStreamPreAndPostImages?': ChangeStreamPreAndPostImagesSchema,\n 'clusteredIndex?': ClusteredIndexSchema,\n});\n\nconst StorageCollectionSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-collection'\",\n 'indexes?': MongoStorageIndexSchema.array(),\n 'validator?': MongoStorageValidatorSchema,\n 'options?': MongoCollectionOptionsSchema,\n});\n\nfunction collectionEntrySchema(fragments?: ReadonlyMap<string, Type<unknown>>): Type<unknown> {\n if (fragments === undefined || fragments.size === 0) {\n return StorageCollectionSchema;\n }\n return type('unknown').narrow((entry, ctx) => {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {\n return ctx.mustBe('an object');\n }\n const kind = (entry as { kind?: unknown }).kind;\n if (typeof kind === 'string') {\n const fragment = fragments.get(kind);\n if (fragment !== undefined) {\n const parsed = fragment(entry);\n if (parsed instanceof type.errors) {\n return ctx.reject({ expected: parsed.summary });\n }\n return true;\n }\n }\n const parsed = StorageCollectionSchema(entry);\n if (parsed instanceof type.errors) {\n return ctx.reject({ expected: parsed.summary });\n }\n return true;\n });\n}\n\n/**\n * Builds the per-namespace envelope schema for Mongo storage. Pack\n * contributions are keyed by the descriptor's `discriminator` and\n * validate each entry by matching the entry's `kind` field. Mongo today\n * has no pack contributions; the composition surface exists for symmetry\n * with SQL and as the substrate for future entity kinds.\n *\n * `'kind?': 'string'` because `kind` is non-enumerable on\n * `MongoNamespacePayload` and therefore absent from the wire shape; the\n * type-side narrowing is enforced by the IR class, not by this validator.\n */\nexport function createMongoNamespaceEnvelopeSchema(\n fragments?: ReadonlyMap<string, Type<unknown>>,\n): Type<unknown> {\n return type({\n '+': 'reject',\n id: 'string',\n 'kind?': 'string',\n 'collections?': type({ '[string]': collectionEntrySchema(fragments) }),\n }) as Type<unknown>;\n}\n\n/**\n * Builds the full Mongo contract schema. The per-namespace entry\n * threading happens through {@link createMongoNamespaceEnvelopeSchema};\n * the rest of the envelope is family-shared.\n */\nexport function createMongoContractSchema(\n fragments?: ReadonlyMap<string, Type<unknown>>,\n): Type<unknown> {\n const namespaceEnvelope = createMongoNamespaceEnvelopeSchema(fragments);\n return type({\n '+': 'reject',\n targetFamily: \"'mongo'\",\n 'schemaVersion?': 'string',\n 'target?': 'string',\n 'storageHash?': 'string',\n 'profileHash?': 'string',\n roots: 'Record<string, string>',\n 'capabilities?': 'Record<string, unknown>',\n 'extensionPacks?': 'Record<string, unknown>',\n 'meta?': 'Record<string, unknown>',\n 'sources?': 'Record<string, unknown>',\n '_generated?': 'Record<string, unknown>',\n 'domain?': 'unknown',\n storage: type({\n '+': 'reject',\n namespaces: type({ '[string]': namespaceEnvelope }),\n 'storageHash?': 'string',\n }),\n models: type({ '[string]': ModelDefinitionSchema }),\n 'valueObjects?': type({\n '[string]': type({ '+': 'reject', fields: type({ '[string]': FieldSchema }) }),\n }),\n }) as Type<unknown>;\n}\n\nexport const MongoContractSchema = createMongoContractSchema();\n\nexport {\n CollationSchema,\n CollectionOptionsSchema,\n IndexFieldsSchema,\n IndexOptionsSchema,\n IndexSchema,\n MongoIndexKeySchema,\n MongoStorageIndexSchema,\n NumberRecordSchema,\n WildcardProjectionSchema,\n};\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport interface MongoChangeStreamPreAndPostImagesOptionsInput {\n readonly enabled: boolean;\n}\n\n/**\n * Change-stream pre-and-post-images collection option. Lifted from a\n * `type =` data shape to an AST class extending `IRNodeBase` per\n * FR18. Single-field shape; the class exists for AST-pattern\n * consistency (every nested data shape inside `MongoCollectionOptions`\n * is an AST node so the verifier can walk uniformly).\n */\nexport class MongoChangeStreamPreAndPostImagesOptions extends IRNodeBase {\n readonly kind = 'mongo-change-stream-pre-and-post-images-options' as const;\n readonly enabled: boolean;\n\n constructor(options: MongoChangeStreamPreAndPostImagesOptionsInput) {\n super();\n this.enabled = options.enabled;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport type MongoClusteredCollectionKey = Readonly<Record<string, 1>>;\n\nexport interface MongoClusteredCollectionOptionsInput {\n readonly name?: string;\n readonly key: MongoClusteredCollectionKey;\n readonly unique: boolean;\n}\n\n/**\n * Clustered-collection options (the `clusteredIndex` collection-creation\n * field). Lifted from a `type =` data shape to an AST class extending\n * `IRNodeBase` per FR18.\n *\n * MongoDB requires `key` and `unique` for any clustered collection; the\n * constructor enforces presence by type signature.\n */\nexport class MongoClusteredCollectionOptions extends IRNodeBase {\n readonly kind = 'mongo-clustered-collection-options' as const;\n declare readonly name?: string;\n readonly key: MongoClusteredCollectionKey;\n readonly unique: boolean;\n\n constructor(options: MongoClusteredCollectionOptionsInput) {\n super();\n if (options.name !== undefined) this.name = options.name;\n this.key = options.key;\n this.unique = options.unique;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport type MongoCollationCaseFirst = 'off' | 'upper' | 'lower';\nexport type MongoCollationStrength = 1 | 2 | 3 | 4 | 5;\nexport type MongoCollationAlternate = 'non-ignorable' | 'shifted';\nexport type MongoCollationMaxVariable = 'punct' | 'space';\n\n/**\n * Authoring / hydration input shape for {@link MongoCollationOptions}. Carries\n * the canonical data without the IR-class `kind` discriminator; the class\n * fabricates `kind` so the authoring DSL and the SPI hydration walker can\n * pass plain data literals through the constructor without forcing every\n * call site to spell out `kind: 'mongo-collation-options'`.\n */\nexport interface MongoCollationOptionsInput {\n readonly locale: string;\n readonly caseLevel?: boolean;\n readonly caseFirst?: MongoCollationCaseFirst;\n readonly strength?: MongoCollationStrength;\n readonly numericOrdering?: boolean;\n readonly alternate?: MongoCollationAlternate;\n readonly maxVariable?: MongoCollationMaxVariable;\n readonly backwards?: boolean;\n readonly normalization?: boolean;\n}\n\n/**\n * Mongo Contract IR leaf for collection / index collation options.\n *\n * Lifted from a `type =` data shape to an AST class extending\n * `IRNodeBase` per FR18 (\"Mongo's Contract IR is fully unified under\n * the AST-class pattern, layered family / target\"). Single concrete class\n * (no target subclass): collation options carry no target-specific\n * variation at this layer — both Atlas and self-hosted Mongo consume the\n * same option vocabulary.\n *\n * Undefined optional fields are not assigned, so `JSON.stringify` omits\n * them from the canonical JSON output (matches the pre-lift data shape's\n * round-trip behaviour, modulo the new `kind` discriminator).\n */\nexport class MongoCollationOptions extends IRNodeBase {\n readonly kind = 'mongo-collation-options' as const;\n readonly locale: string;\n declare readonly caseLevel?: boolean;\n declare readonly caseFirst?: MongoCollationCaseFirst;\n declare readonly strength?: MongoCollationStrength;\n declare readonly numericOrdering?: boolean;\n declare readonly alternate?: MongoCollationAlternate;\n declare readonly maxVariable?: MongoCollationMaxVariable;\n declare readonly backwards?: boolean;\n declare readonly normalization?: boolean;\n\n constructor(options: MongoCollationOptionsInput) {\n super();\n this.locale = options.locale;\n if (options.caseLevel !== undefined) this.caseLevel = options.caseLevel;\n if (options.caseFirst !== undefined) this.caseFirst = options.caseFirst;\n if (options.strength !== undefined) this.strength = options.strength;\n if (options.numericOrdering !== undefined) this.numericOrdering = options.numericOrdering;\n if (options.alternate !== undefined) this.alternate = options.alternate;\n if (options.maxVariable !== undefined) this.maxVariable = options.maxVariable;\n if (options.backwards !== undefined) this.backwards = options.backwards;\n if (options.normalization !== undefined) this.normalization = options.normalization;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport type { MongoJsonObject } from '../contract-types';\n\nexport interface MongoIndexOptionDefaultsInput {\n readonly storageEngine?: MongoJsonObject;\n}\n\n/**\n * Collection-level default index options (the `indexOptionDefaults`\n * collection-creation field on Mongo's `createCollection`). Lifted from\n * a `type =` data shape to an AST class extending `IRNodeBase` per\n * FR18 (Mongo Contract IR fully unified under the AST-class pattern).\n *\n * Carries `storageEngine` only — the underlying MongoDB option set is\n * intentionally narrow at this layer; per-engine richer option vocabularies\n * are out of scope for this project.\n */\nexport class MongoIndexOptionDefaults extends IRNodeBase {\n readonly kind = 'mongo-index-option-defaults' as const;\n declare readonly storageEngine?: MongoJsonObject;\n\n constructor(options: MongoIndexOptionDefaultsInput = {}) {\n super();\n if (options.storageEngine !== undefined) this.storageEngine = options.storageEngine;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport type MongoTimeSeriesGranularity = 'seconds' | 'minutes' | 'hours';\n\nexport interface MongoTimeSeriesCollectionOptionsInput {\n readonly timeField: string;\n readonly metaField?: string;\n readonly granularity?: MongoTimeSeriesGranularity;\n readonly bucketMaxSpanSeconds?: number;\n readonly bucketRoundingSeconds?: number;\n}\n\n/**\n * Time-series collection options. Lifted from a `type =` data shape to\n * an AST class extending `IRNodeBase` per FR18.\n *\n * MongoDB requires `timeField` for any time-series collection; the\n * constructor enforces presence by type signature (`timeField: string`\n * is required on the input).\n */\nexport class MongoTimeSeriesCollectionOptions extends IRNodeBase {\n readonly kind = 'mongo-time-series-collection-options' as const;\n readonly timeField: string;\n declare readonly metaField?: string;\n declare readonly granularity?: MongoTimeSeriesGranularity;\n declare readonly bucketMaxSpanSeconds?: number;\n declare readonly bucketRoundingSeconds?: number;\n\n constructor(options: MongoTimeSeriesCollectionOptionsInput) {\n super();\n this.timeField = options.timeField;\n if (options.metaField !== undefined) this.metaField = options.metaField;\n if (options.granularity !== undefined) this.granularity = options.granularity;\n if (options.bucketMaxSpanSeconds !== undefined)\n this.bucketMaxSpanSeconds = options.bucketMaxSpanSeconds;\n if (options.bucketRoundingSeconds !== undefined)\n this.bucketRoundingSeconds = options.bucketRoundingSeconds;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport type { MongoJsonObject } from '../contract-types';\nimport {\n MongoChangeStreamPreAndPostImagesOptions,\n type MongoChangeStreamPreAndPostImagesOptionsInput,\n} from './mongo-change-stream-pre-and-post-images-options';\nimport type {\n MongoClusteredCollectionOptions,\n MongoClusteredCollectionOptionsInput,\n} from './mongo-clustered-collection-options';\nimport { MongoCollationOptions, type MongoCollationOptionsInput } from './mongo-collation-options';\nimport {\n MongoIndexOptionDefaults,\n type MongoIndexOptionDefaultsInput,\n} from './mongo-index-option-defaults';\nimport {\n MongoTimeSeriesCollectionOptions,\n type MongoTimeSeriesCollectionOptionsInput,\n} from './mongo-time-series-collection-options';\n\n/**\n * Storage-shape sub-shape: only `name` is persisted on the storage\n * `clusteredIndex` field. The richer authoring vocabulary\n * (`MongoClusteredCollectionOptions.key`, `…unique`) is intentionally\n * not round-tripped through the on-disk JSON envelope — those fields\n * are application-side configuration that informs collection creation\n * but does not survive into the persisted collection options.\n */\nexport interface MongoStorageClusteredIndexShape {\n readonly name?: string;\n}\n\n/**\n * Storage-shape sub-shape: `capped` collections persist `size` (required)\n * and optionally `max` document count. The authoring DSL surface uses a\n * flat `capped: boolean` + separate `size` / `max` fields; builders\n * translate that authoring vocabulary into this nested storage form\n * before constructing {@link MongoCollectionOptions}.\n */\nexport interface MongoStorageCappedShape {\n readonly size: number;\n readonly max?: number;\n}\n\n/**\n * Hydration / construction input shape for {@link MongoCollectionOptions}.\n * Mirrors the on-disk storage JSON envelope exactly (nested `capped`,\n * `clusteredIndex`, …) so the family-base serializer's hydration walker\n * can hand an arktype-validated object literal straight to `new`.\n * Nested IR-class fields may be supplied as either plain data literals\n * (typical for JSON-derived input) or already-constructed class\n * instances (typical when re-wrapping during a partial walk).\n */\nexport interface MongoCollectionOptionsInput {\n readonly capped?: MongoStorageCappedShape;\n readonly storageEngine?: MongoJsonObject;\n readonly indexOptionDefaults?: MongoIndexOptionDefaults | MongoIndexOptionDefaultsInput;\n readonly collation?: MongoCollationOptions | MongoCollationOptionsInput;\n readonly timeseries?: MongoTimeSeriesCollectionOptions | MongoTimeSeriesCollectionOptionsInput;\n readonly clusteredIndex?: MongoStorageClusteredIndexShape;\n readonly expireAfterSeconds?: number;\n readonly changeStreamPreAndPostImages?:\n | MongoChangeStreamPreAndPostImagesOptions\n | MongoChangeStreamPreAndPostImagesOptionsInput;\n}\n\n/**\n * Authoring-side flat vocabulary accepted by the contract-ts builder\n * DSL (e.g. `capped: boolean` + separate `size` / `max` scalars). The\n * builder translates this surface into a {@link MongoCollectionOptionsInput}\n * before constructing {@link MongoCollectionOptions}. Kept as a\n * standalone type so authoring DSL ergonomics do not leak into the\n * storage IR construction contract.\n */\nexport interface MongoCollectionOptionsAuthoringInput {\n readonly capped?: boolean;\n readonly size?: number;\n readonly max?: number;\n readonly storageEngine?: MongoJsonObject;\n readonly indexOptionDefaults?: MongoIndexOptionDefaults | MongoIndexOptionDefaultsInput;\n readonly collation?: MongoCollationOptions | MongoCollationOptionsInput;\n readonly timeseries?: MongoTimeSeriesCollectionOptions | MongoTimeSeriesCollectionOptionsInput;\n readonly clusteredIndex?: MongoClusteredCollectionOptions | MongoClusteredCollectionOptionsInput;\n readonly expireAfterSeconds?: number;\n readonly changeStreamPreAndPostImages?:\n | MongoChangeStreamPreAndPostImagesOptions\n | MongoChangeStreamPreAndPostImagesOptionsInput;\n}\n\n/**\n * Mongo Contract IR node for collection-level creation options (the\n * second argument to `db.createCollection(name, options)`). Lifted from\n * the pre-M2R2 `MongoStorageCollectionOptions` storage interface to a\n * class extending `IRNodeBase` per FR18.\n *\n * Single concrete family-layer class (no target subclass). The\n * constructor accepts the storage JSON envelope shape ({@link\n * MongoCollectionOptionsInput}) so the family-base hydration walker\n * can pass arktype-validated objects directly to `new`. Authoring\n * vocabulary is translated to this shape upstream in the contract-ts\n * builder.\n *\n * Nested IR sub-shapes (collation, timeseries, …) are normalised to\n * their respective IR class instances inside the constructor so\n * downstream walks see a uniform AST regardless of whether the input\n * was a JSON literal or an already-constructed class.\n */\nexport class MongoCollectionOptions extends IRNodeBase {\n readonly kind = 'mongo-collection-options' as const;\n declare readonly capped?: MongoStorageCappedShape;\n declare readonly storageEngine?: MongoJsonObject;\n declare readonly indexOptionDefaults?: MongoIndexOptionDefaults;\n declare readonly collation?: MongoCollationOptions;\n declare readonly timeseries?: MongoTimeSeriesCollectionOptions;\n declare readonly clusteredIndex?: MongoStorageClusteredIndexShape;\n declare readonly expireAfterSeconds?: number;\n declare readonly changeStreamPreAndPostImages?: MongoChangeStreamPreAndPostImagesOptions;\n\n constructor(input: MongoCollectionOptionsInput = {}) {\n super();\n if (input.capped !== undefined) {\n this.capped = {\n size: input.capped.size,\n ...(input.capped.max != null && { max: input.capped.max }),\n };\n }\n if (input.storageEngine !== undefined) this.storageEngine = input.storageEngine;\n if (input.indexOptionDefaults !== undefined) {\n this.indexOptionDefaults =\n input.indexOptionDefaults instanceof MongoIndexOptionDefaults\n ? input.indexOptionDefaults\n : new MongoIndexOptionDefaults(input.indexOptionDefaults);\n }\n if (input.collation !== undefined) {\n this.collation =\n input.collation instanceof MongoCollationOptions\n ? input.collation\n : new MongoCollationOptions(input.collation);\n }\n if (input.timeseries !== undefined) {\n this.timeseries =\n input.timeseries instanceof MongoTimeSeriesCollectionOptions\n ? input.timeseries\n : new MongoTimeSeriesCollectionOptions(input.timeseries);\n }\n if (input.clusteredIndex !== undefined) {\n this.clusteredIndex =\n input.clusteredIndex.name !== undefined ? { name: input.clusteredIndex.name } : {};\n }\n if (input.expireAfterSeconds !== undefined) this.expireAfterSeconds = input.expireAfterSeconds;\n if (input.changeStreamPreAndPostImages !== undefined) {\n this.changeStreamPreAndPostImages =\n input.changeStreamPreAndPostImages instanceof MongoChangeStreamPreAndPostImagesOptions\n ? input.changeStreamPreAndPostImages\n : new MongoChangeStreamPreAndPostImagesOptions(input.changeStreamPreAndPostImages);\n }\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport type { MongoIndexKey } from '../contract-types';\n\n/**\n * Hydration / construction input shape for {@link MongoIndex}. Mirrors\n * the on-disk storage JSON envelope exactly so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`.\n */\nexport interface MongoIndexInput {\n readonly keys: ReadonlyArray<MongoIndexKey>;\n readonly unique?: boolean;\n readonly sparse?: boolean;\n readonly expireAfterSeconds?: number;\n readonly partialFilterExpression?: Record<string, unknown>;\n readonly wildcardProjection?: Record<string, 0 | 1>;\n readonly collation?: Record<string, unknown>;\n readonly weights?: Record<string, number>;\n readonly default_language?: string;\n readonly language_override?: string;\n}\n\n/**\n * Mongo Contract IR node for a single collection index entry (one\n * element of `MongoCollection.indexes`). Lifted from the\n * pre-M2R2 `MongoStorageIndex` storage interface to a class extending\n * `IRNodeBase` per FR18.\n *\n * Single concrete family-layer class (no target subclass). The spec's\n * `MongoTargetIndex extends MongoIndex` pattern remains additive — a\n * future Mongo target with target-specific index extensions is free to\n * subclass; for the single Mongo target shipped today a concrete\n * family-layer class is enough and avoids a target-import layering\n * violation from the contract-ts builder.\n */\nexport class MongoIndex extends IRNodeBase {\n readonly kind = 'mongo-index' as const;\n readonly keys: ReadonlyArray<MongoIndexKey>;\n declare readonly unique?: boolean;\n declare readonly sparse?: boolean;\n declare readonly expireAfterSeconds?: number;\n declare readonly partialFilterExpression?: Record<string, unknown>;\n declare readonly wildcardProjection?: Record<string, 0 | 1>;\n declare readonly collation?: Record<string, unknown>;\n declare readonly weights?: Record<string, number>;\n declare readonly default_language?: string;\n declare readonly language_override?: string;\n\n constructor(input: MongoIndexInput) {\n super();\n this.keys = input.keys;\n if (input.unique !== undefined) this.unique = input.unique;\n if (input.sparse !== undefined) this.sparse = input.sparse;\n if (input.expireAfterSeconds !== undefined) this.expireAfterSeconds = input.expireAfterSeconds;\n if (input.partialFilterExpression !== undefined)\n this.partialFilterExpression = input.partialFilterExpression;\n if (input.wildcardProjection !== undefined) this.wildcardProjection = input.wildcardProjection;\n if (input.collation !== undefined) this.collation = input.collation;\n if (input.weights !== undefined) this.weights = input.weights;\n if (input.default_language !== undefined) this.default_language = input.default_language;\n if (input.language_override !== undefined) this.language_override = input.language_override;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport type MongoValidatorValidationLevel = 'strict' | 'moderate';\nexport type MongoValidatorValidationAction = 'error' | 'warn';\n\nexport interface MongoValidatorInput {\n readonly jsonSchema: Record<string, unknown>;\n readonly validationLevel: MongoValidatorValidationLevel;\n readonly validationAction: MongoValidatorValidationAction;\n}\n\n/**\n * Mongo Contract IR node for collection-level document validators (the\n * `validator` field on Mongo's `createCollection`). Lifted from the\n * pre-M2R2 `MongoStorageValidator` storage interface to a class extending\n * `IRNodeBase` per FR18.\n *\n * Concrete at the family layer (no target subclass). The spec's\n * abstract-family + target-concrete pattern (`MongoTargetValidator\n * extends MongoValidator`) becomes meaningful when a second Mongo target\n * introduces target-specific validator extensions (Atlas search rules,\n * DocumentDB-specific levels, …); for the single Mongo target shipped\n * today, a concrete family-layer class lets the PSL JSON-Schema deriver\n * and the contract-ts builder construct instances directly without a\n * target-import layering violation. Target subclassing remains additive\n * — a future `MongoTargetValidator extends MongoValidator` is an\n * additive change, not a breaking one.\n */\nexport class MongoValidator extends IRNodeBase {\n readonly kind = 'mongo-validator' as const;\n readonly jsonSchema: Record<string, unknown>;\n readonly validationLevel: MongoValidatorValidationLevel;\n readonly validationAction: MongoValidatorValidationAction;\n\n constructor(input: MongoValidatorInput) {\n super();\n this.jsonSchema = input.jsonSchema;\n this.validationLevel = input.validationLevel;\n this.validationAction = input.validationAction;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport {\n MongoCollectionOptions,\n type MongoCollectionOptionsInput,\n} from './mongo-collection-options';\nimport { MongoIndex, type MongoIndexInput } from './mongo-index';\nimport { MongoValidator, type MongoValidatorInput } from './mongo-validator';\n\n/**\n * Hydration / construction input shape for {@link MongoCollection}.\n * Mirrors the on-disk storage JSON envelope exactly (the value held at\n * `contract.storage.namespaces[<namespaceId>].collections[<name>]`) so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`. Nested IR-class fields may be supplied as either\n * plain data literals (typical for JSON-derived input) or\n * already-constructed class instances.\n */\nexport interface MongoCollectionInput {\n readonly indexes?: ReadonlyArray<MongoIndex | MongoIndexInput>;\n readonly validator?: MongoValidator | MongoValidatorInput;\n readonly options?: MongoCollectionOptions | MongoCollectionOptionsInput;\n}\n\n/**\n * Mongo Contract IR node for a single collection entry in a namespace's\n * `collections` map. Lifted from the pre-M2R2\n * `MongoStorageCollection` storage interface to a class extending\n * `IRNodeBase` per FR18.\n *\n * Concrete at the family layer (no target subclass). The spec's\n * `MongoTargetCollection extends MongoCollection` pattern remains\n * additive: a future Mongo target with target-specific extensions is\n * free to subclass without breaking the family-layer construction\n * sites.\n *\n * The unprefixed name `MongoCollection` is now the contract IR class.\n * Note that `@prisma-next/mongo-orm` also exports a (different)\n * `MongoCollection<TContract, ModelName>` generic for the user-facing\n * ORM query builder; the two live in separate packages and are\n * resolved by import path. A source file that needs both should alias\n * one (e.g. `import { MongoCollection as MongoContractCollection }\n * from '@prisma-next/mongo-contract'`).\n */\nexport class MongoCollection extends IRNodeBase {\n readonly kind = 'mongo-collection' as const;\n declare readonly indexes?: ReadonlyArray<MongoIndex>;\n declare readonly validator?: MongoValidator;\n declare readonly options?: MongoCollectionOptions;\n\n constructor(input: MongoCollectionInput = {}) {\n super();\n if (input.indexes !== undefined) {\n this.indexes = input.indexes.map((idx) =>\n idx instanceof MongoIndex ? idx : new MongoIndex(idx),\n );\n }\n if (input.validator !== undefined) {\n this.validator =\n input.validator instanceof MongoValidator\n ? input.validator\n : new MongoValidator(input.validator);\n }\n if (input.options !== undefined) {\n this.options =\n input.options instanceof MongoCollectionOptions\n ? input.options\n : new MongoCollectionOptions(input.options);\n }\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport type { MongoJsonObject, MongoWildcardProjection } from '../contract-types';\nimport { MongoCollationOptions, type MongoCollationOptionsInput } from './mongo-collation-options';\n\n/**\n * Authoring / hydration input shape for {@link MongoIndexOptions}. Carries\n * the index option vocabulary as plain data without the IR-class `kind`\n * discriminator. `collation` accepts either a class instance or its own\n * input shape — the constructor normalises to the class form internally.\n */\nexport interface MongoIndexOptionsInput {\n readonly unique?: boolean;\n readonly name?: string;\n readonly partialFilterExpression?: MongoJsonObject;\n readonly sparse?: boolean;\n readonly expireAfterSeconds?: number;\n readonly weights?: Readonly<Record<string, number>>;\n readonly default_language?: string;\n readonly language_override?: string;\n readonly textIndexVersion?: number;\n readonly '2dsphereIndexVersion'?: number;\n readonly bits?: number;\n readonly min?: number;\n readonly max?: number;\n readonly bucketSize?: number;\n readonly hidden?: boolean;\n readonly collation?: MongoCollationOptions | MongoCollationOptionsInput;\n readonly wildcardProjection?: MongoWildcardProjection;\n}\n\n/**\n * Mongo Contract IR node for the per-index option vocabulary (the second\n * argument to `db.collection.createIndex(keys, options)` minus the keys\n * themselves). Lifted from a `type =` data shape to an AST class\n * extending `IRNodeBase` per FR18.\n *\n * Nested `collation` is itself an IR class (`MongoCollationOptions`); the\n * constructor accepts either a class instance or a data literal and\n * normalises to the class form so downstream walks see a uniform IR tree.\n */\nexport class MongoIndexOptions extends IRNodeBase {\n readonly kind = 'mongo-index-options' as const;\n declare readonly unique?: boolean;\n declare readonly name?: string;\n declare readonly partialFilterExpression?: MongoJsonObject;\n declare readonly sparse?: boolean;\n declare readonly expireAfterSeconds?: number;\n declare readonly weights?: Readonly<Record<string, number>>;\n declare readonly default_language?: string;\n declare readonly language_override?: string;\n declare readonly textIndexVersion?: number;\n declare readonly '2dsphereIndexVersion'?: number;\n declare readonly bits?: number;\n declare readonly min?: number;\n declare readonly max?: number;\n declare readonly bucketSize?: number;\n declare readonly hidden?: boolean;\n declare readonly collation?: MongoCollationOptions;\n declare readonly wildcardProjection?: MongoWildcardProjection;\n\n constructor(options: MongoIndexOptionsInput = {}) {\n super();\n if (options.unique !== undefined) this.unique = options.unique;\n if (options.name !== undefined) this.name = options.name;\n if (options.partialFilterExpression !== undefined)\n this.partialFilterExpression = options.partialFilterExpression;\n if (options.sparse !== undefined) this.sparse = options.sparse;\n if (options.expireAfterSeconds !== undefined)\n this.expireAfterSeconds = options.expireAfterSeconds;\n if (options.weights !== undefined) this.weights = options.weights;\n if (options.default_language !== undefined) this.default_language = options.default_language;\n if (options.language_override !== undefined) this.language_override = options.language_override;\n if (options.textIndexVersion !== undefined) this.textIndexVersion = options.textIndexVersion;\n if (options['2dsphereIndexVersion'] !== undefined)\n this['2dsphereIndexVersion'] = options['2dsphereIndexVersion'];\n if (options.bits !== undefined) this.bits = options.bits;\n if (options.min !== undefined) this.min = options.min;\n if (options.max !== undefined) this.max = options.max;\n if (options.bucketSize !== undefined) this.bucketSize = options.bucketSize;\n if (options.hidden !== undefined) this.hidden = options.hidden;\n if (options.collation !== undefined) {\n this.collation =\n options.collation instanceof MongoCollationOptions\n ? options.collation\n : new MongoCollationOptions(options.collation);\n }\n if (options.wildcardProjection !== undefined)\n this.wildcardProjection = options.wildcardProjection;\n freezeNode(this);\n }\n}\n","import {\n freezeNode,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport type { MongoCollection } from './mongo-collection';\n\nexport class MongoUnboundNamespace extends NamespaceBase {\n static readonly instance: MongoUnboundNamespace = new MongoUnboundNamespace();\n\n readonly id = UNBOUND_NAMESPACE_ID;\n readonly collections: Readonly<Record<string, MongoCollection>> = Object.freeze({});\n declare readonly kind: string;\n\n private constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'mongo-namespace',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n}\n","import type { StorageHashBase } from '@prisma-next/contract/types';\nimport {\n freezeNode,\n IRNodeBase,\n type Namespace,\n NamespaceBase,\n type Storage,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { MongoCollection, type MongoCollectionInput } from './mongo-collection';\nimport { MongoUnboundNamespace } from './mongo-unbound-namespace';\n\nexport interface MongoNamespaceCollectionsInput {\n readonly id: string;\n readonly collections?: Record<string, MongoCollection | MongoCollectionInput>;\n}\n\nexport interface MongoStorageInput<THash extends string = string> {\n readonly storageHash: StorageHashBase<THash>;\n readonly namespaces?: Readonly<Record<string, Namespace | MongoNamespaceCollectionsInput>>;\n}\n\nconst DEFAULT_NAMESPACES: Readonly<Record<string, Namespace>> = Object.freeze({\n [UNBOUND_NAMESPACE_ID]: MongoUnboundNamespace.instance,\n});\n\nclass MongoNamespacePayload extends NamespaceBase {\n declare readonly kind: string;\n\n readonly id: string;\n readonly collections: Readonly<Record<string, MongoCollection>>;\n\n constructor(input: MongoNamespaceCollectionsInput) {\n super();\n this.id = input.id;\n this.collections = Object.freeze(\n Object.fromEntries(\n Object.entries(input.collections ?? {}).map(([name, c]) => [\n name,\n c instanceof MongoCollection ? c : new MongoCollection(c),\n ]),\n ),\n );\n Object.defineProperty(this, 'kind', {\n value: 'mongo-namespace',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n}\n\nfunction normaliseNamespaceEntry(\n nsKey: string,\n ns: Namespace | MongoNamespaceCollectionsInput,\n): Namespace {\n if (ns instanceof NamespaceBase) {\n return ns;\n }\n // The framework `Namespace` interface only promises `id`; the remaining\n // arm of this union — plain-object inputs accepted by `MongoStorageInput`\n // — is `MongoNamespaceCollectionsInput`. The `instanceof` guard above\n // discriminates the two; TypeScript can't narrow further without a hint.\n const input = ns as MongoNamespaceCollectionsInput;\n const collectionCount = Object.keys(input.collections ?? {}).length;\n if (nsKey === UNBOUND_NAMESPACE_ID && collectionCount === 0) {\n return MongoUnboundNamespace.instance;\n }\n return new MongoNamespacePayload(input);\n}\n\n// Mongo concretions always store `MongoCollection` instances in\n// `collections` (Mongo idiom — distinct from the SQL family's `tables`).\n// Narrowing the namespace map here lets target/family-level consumers\n// iterate `namespaces[*].collections[*]` and recover the concrete\n// collection type without the framework's wider `Namespace` tripping\n// them up.\nexport type MongoNamespace = Namespace & {\n readonly collections: Readonly<Record<string, MongoCollection>>;\n};\n\nexport class MongoStorage<THash extends string = string> extends IRNodeBase implements Storage {\n declare readonly kind: 'mongo-storage';\n readonly storageHash: StorageHashBase<THash>;\n readonly namespaces: Readonly<Record<string, MongoNamespace>>;\n\n constructor(input: MongoStorageInput<THash>) {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'mongo-storage',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n this.storageHash = input.storageHash;\n this.namespaces = Object.freeze(\n Object.fromEntries(\n Object.entries(input.namespaces ?? DEFAULT_NAMESPACES).map(([nsKey, ns]) => [\n nsKey,\n normaliseNamespaceEntry(nsKey, ns) as MongoNamespace,\n ]),\n ),\n );\n freezeNode(this);\n }\n}\n","import { MongoIndex, type MongoIndexInput } from './ir/mongo-index';\n\nexport type PolymorphicIndexScope = {\n readonly discriminatorField: string;\n readonly discriminatorValue: string | number | boolean;\n};\n\nexport type ApplyScopeResult =\n | { readonly kind: 'ok'; readonly index: MongoIndex }\n | { readonly kind: 'conflict'; readonly reason: string };\n\nfunction isScalarDiscriminatorValue(value: unknown): value is string | number | boolean {\n const t = typeof value;\n return t === 'string' || t === 'number' || t === 'boolean';\n}\n\nfunction formatValue(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value);\n if (value === null) return 'null';\n if (Array.isArray(value)) return JSON.stringify(value);\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n\nexport function applyPolymorphicScopeToMongoIndex(\n index: MongoIndex,\n scope: PolymorphicIndexScope,\n): ApplyScopeResult {\n if (!isScalarDiscriminatorValue(scope.discriminatorValue)) {\n return {\n kind: 'conflict',\n reason: `Variant-scoped indexes require a scalar (string, number, or boolean) discriminator value for field \"${scope.discriminatorField}\", but received ${formatValue(scope.discriminatorValue)}.`,\n };\n }\n\n const existing = index.partialFilterExpression;\n if (existing && Object.hasOwn(existing, scope.discriminatorField)) {\n const existingValue = existing[scope.discriminatorField];\n if (existingValue === scope.discriminatorValue) {\n return { kind: 'ok', index };\n }\n return {\n kind: 'conflict',\n reason: `Index partialFilterExpression sets \"${scope.discriminatorField}\" to ${formatValue(existingValue)}, which conflicts with the variant's discriminator value ${formatValue(scope.discriminatorValue)}.`,\n };\n }\n\n const merged: Record<string, unknown> = {\n ...(existing ?? {}),\n [scope.discriminatorField]: scope.discriminatorValue,\n };\n\n const cloned: MongoIndexInput = {\n keys: index.keys,\n ...(index.unique !== undefined && { unique: index.unique }),\n ...(index.sparse !== undefined && { sparse: index.sparse }),\n ...(index.expireAfterSeconds !== undefined && { expireAfterSeconds: index.expireAfterSeconds }),\n partialFilterExpression: merged,\n ...(index.wildcardProjection !== undefined && { wildcardProjection: index.wildcardProjection }),\n ...(index.collation !== undefined && { collation: index.collation }),\n ...(index.weights !== undefined && { weights: index.weights }),\n ...(index.default_language !== undefined && { default_language: index.default_language }),\n ...(index.language_override !== undefined && { language_override: index.language_override }),\n };\n\n return { kind: 'ok', index: new MongoIndex(cloned) };\n}\n","import type { MongoContract } from './contract-types';\n\nfunction storageDeclaresCollection(\n storage: MongoContract['storage'],\n collectionName: string,\n): boolean {\n for (const ns of Object.values(storage.namespaces)) {\n if (Object.hasOwn(ns.collections, collectionName)) {\n return true;\n }\n }\n return false;\n}\n\nexport function validateMongoStorage(contract: MongoContract): void {\n const errors: string[] = [];\n\n for (const [modelName, model] of Object.entries(contract.models)) {\n if (\n model.storage.collection &&\n !storageDeclaresCollection(contract.storage, model.storage.collection)\n ) {\n errors.push(\n `Model \"${modelName}\" references collection \"${model.storage.collection}\" which is not declared under any namespace's collections map`,\n );\n }\n\n // Mongo does not support multi-table inheritance (ADR 2): all variants of a base\n // must share the same collection (single-table inheritance only).\n if (model.base) {\n const baseModel = contract.models[model.base];\n if (baseModel) {\n const variantCollection = model.storage.collection;\n const baseCollection = baseModel.storage.collection;\n if (variantCollection !== baseCollection) {\n errors.push(\n `Mongo does not support multi-table inheritance; variant \"${modelName}\" must share its base's collection (\"${baseCollection ?? '(none)'}\"), but has \"${variantCollection ?? '(none)'}\"`,\n );\n }\n }\n }\n\n for (const [relName, relation] of Object.entries(model.relations ?? {})) {\n const targetModel = contract.models[relation.to];\n\n if (targetModel?.owner) {\n if (targetModel.owner !== modelName) {\n errors.push(\n `Embed relation \"${relName}\" targets \"${relation.to}\" which is owned by \"${targetModel.owner}\", not \"${modelName}\"`,\n );\n }\n if (targetModel.storage.collection) {\n errors.push(\n `Embed relation \"${relName}\" targets \"${relation.to}\" which must not have a collection`,\n );\n }\n } else if ('on' in relation && relation.on) {\n for (const localField of relation.on.localFields) {\n if (!(localField in model.fields)) {\n errors.push(\n `Reference relation \"${relName}\": localField \"${localField}\" is not a field on model \"${modelName}\"`,\n );\n }\n }\n\n if (targetModel) {\n for (const targetField of relation.on.targetFields) {\n if (!(targetField in targetModel.fields)) {\n errors.push(\n `Reference relation \"${relName}\": targetField \"${targetField}\" is not a field on model \"${relation.to}\"`,\n );\n }\n }\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new Error(`Contract storage validation failed:\\n- ${errors.join('\\n- ')}`);\n }\n}\n"],"mappings":";;;AAGA,MAAM,wBAAwB,KAAK;CACjC,KAAK;CACL,MAAM;CACN,SAAS;CACT,eAAe;CAChB,CAAC;AAEF,MAAM,6BAA6B,KAAK;CACtC,KAAK;CACL,MAAM;CACN,MAAM;CACP,CAAC;AAEF,MAAM,uBAAuB,KAAK;CAChC,KAAK;CACL,MAAM;CACN,SAAS,sBAAsB,GAAG,2BAA2B,CAAC,OAAO;CACtE,CAAC;AAcF,MAAM,cARiB,KAAK;CAC1B,KAAK;CACL,MANsB,sBAAsB,GAAG,2BAA2B,CAAC,GAC3E,qBAKqB;CACrB,aAAa;CACb,SAAS;CACT,SAAS;CACV,CAEiC,CAAC,MAAM,WAAW;CAClD,GAAG;CACH,UAAU,MAAM,YAAY;CAC7B,EAAE;AAQH,MAAM,iBAAiB,KAAK;CAC1B,KAAK;CACL,IAAI;CACJ,aAAa;CACb,OAVuB,KAAK;EAC5B,KAAK;EACL,aAAa;EACb,cAAc;EACf,CAMwB;CACxB,CAAC;AAEF,MAAM,6BAA6B,KAAK;CACtC,KAAK;CACL,OAAO;CACR,CAAC;AAEF,MA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oB,MAAM,QAAQ;IACxC,MAAM,iBAAiB,UAAU,QAAQ;IACzC,IAAI,sBAAsB,gBACxB,OAAO,KACL,4DAA4D,UAAU,uCAAuC,kBAAkB,SAAS,eAAe,qBAAqB,SAAS,GACtL;;;EAKP,KAAK,MAAM,CAAC,SAAS,aAAa,OAAO,QAAQ,MAAM,aAAa,EAAE,CAAC,EAAE;GACvE,MAAM,cAAc,SAAS,OAAO,SAAS;GAE7C,IAAI,aAAa,OAAO;IACtB,IAAI,YAAY,UAAU,WACxB,OAAO,KACL,mBAAmB,QAAQ,aAAa,SAAS,GAAG,uBAAuB,YAAY,MAAM,UAAU,UAAU,GAClH;IAEH,IAAI,YAAY,QAAQ,YACtB,OAAO,KACL,mBAAmB,QAAQ,aAAa,SAAS,GAAG,oCACrD;UAEE,IAAI,QAAQ,YAAY,SAAS,IAAI;IAC1C,KAAK,MAAM,cAAc,SAAS,GAAG,aACnC,IAAI,EAAE,cAAc,MAAM,SACxB,OAAO,KACL,uBAAuB,QAAQ,iBAAiB,WAAW,6BAA6B,UAAU,GACnG;IAIL,IAAI;UACG,MAAM,eAAe,SAAS,GAAG,cACpC,IAAI,EAAE,eAAe,YAAY,SAC/B,OAAO,KACL,uBAAuB,QAAQ,kBAAkB,YAAY,6BAA6B,SAAS,GAAG,GACvG;;;;;CAQb,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MAAM,0CAA0C,OAAO,KAAK,OAAO,GAAG"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/contract-schema.ts","../src/ir/mongo-change-stream-pre-and-post-images-options.ts","../src/ir/mongo-collation-options.ts","../src/ir/mongo-index-option-defaults.ts","../src/ir/mongo-time-series-collection-options.ts","../src/ir/mongo-collection-options.ts","../src/ir/mongo-index.ts","../src/ir/mongo-validator.ts","../src/ir/mongo-collection.ts","../src/ir/mongo-unbound-namespace.ts","../src/ir/build-mongo-namespace.ts","../src/ir/mongo-clustered-collection-options.ts","../src/ir/mongo-index-options.ts","../src/ir/mongo-storage.ts","../src/polymorphic-index-scope.ts","../src/validate-storage.ts"],"sourcesContent":["import { CrossReferenceSchema } from '@prisma-next/contract/types';\nimport { type Type, type } from 'arktype';\nimport type { MongoJsonObject, MongoJsonPrimitive, MongoJsonValue } from './contract-types';\n\nconst ScalarFieldTypeSchema = type({\n '+': 'reject',\n kind: \"'scalar'\",\n codecId: 'string',\n 'typeParams?': 'Record<string, unknown>',\n});\n\nconst ValueObjectFieldTypeSchema = type({\n '+': 'reject',\n kind: \"'valueObject'\",\n name: 'string',\n});\n\nconst UnionFieldTypeSchema = type({\n '+': 'reject',\n kind: \"'union'\",\n members: ScalarFieldTypeSchema.or(ValueObjectFieldTypeSchema).array(),\n});\n\nconst FieldTypeSchema = ScalarFieldTypeSchema.or(ValueObjectFieldTypeSchema).or(\n UnionFieldTypeSchema,\n);\n\nconst RawFieldSchema = type({\n '+': 'reject',\n type: FieldTypeSchema,\n 'nullable?': 'boolean',\n 'many?': 'boolean',\n 'dict?': 'boolean',\n});\n\nconst FieldSchema = RawFieldSchema.pipe((field) => ({\n ...field,\n nullable: field.nullable ?? false,\n}));\n\nconst RelationOnSchema = type({\n '+': 'reject',\n localFields: 'string[]',\n targetFields: 'string[]',\n});\n\nconst RelationSchema = type({\n '+': 'reject',\n to: CrossReferenceSchema,\n cardinality: \"'1:1' | '1:N' | 'N:1'\",\n 'on?': RelationOnSchema,\n});\n\nconst StorageRelationEntrySchema = type({\n '+': 'reject',\n field: 'string',\n});\n\nconst MongoJsonPrimitiveSchema = type\n .declare<MongoJsonPrimitive>()\n .type('string | number | boolean | null');\n\nfunction isMongoJsonRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction withUnseenReference(value: object, seen: WeakSet<object>, visit: () => boolean): boolean {\n if (seen.has(value)) {\n return false;\n }\n\n seen.add(value);\n const result = visit();\n seen.delete(value);\n return result;\n}\n\nfunction isMongoJsonObject(value: unknown, seen: WeakSet<object>): value is MongoJsonObject {\n return (\n isMongoJsonRecord(value) &&\n withUnseenReference(value, seen, () =>\n Object.values(value).every((entry) => isMongoJsonValue(entry, seen)),\n )\n );\n}\n\nfunction isMongoJsonValue(value: unknown, seen = new WeakSet<object>()): value is MongoJsonValue {\n if (MongoJsonPrimitiveSchema.allows(value)) {\n return true;\n }\n if (Array.isArray(value)) {\n return withUnseenReference(value, seen, () =>\n value.every((entry) => isMongoJsonValue(entry, seen)),\n );\n }\n return isMongoJsonObject(value, seen);\n}\n\nconst MongoJsonValueSchema = type('unknown').narrow((value, ctx) =>\n isMongoJsonValue(value) ? true : ctx.mustBe('a JSON-serializable MongoJsonValue'),\n);\n\nconst MongoJsonObjectSchema = type({ '[string]': 'unknown' }).narrow((value, ctx) =>\n isMongoJsonRecord(value) &&\n Object.values(value).every((entry) => MongoJsonValueSchema.allows(entry))\n ? true\n : ctx.mustBe('a JSON object with MongoJsonValue entries'),\n);\n\nconst NumberRecordSchema = type({ '[string]': 'number' });\n\nconst IndexFieldsSchema = type({\n '+': 'reject',\n '[string]': '1 | -1 | \"text\" | \"2dsphere\" | \"2d\" | \"hashed\"',\n}).narrow((fields, ctx) =>\n Object.keys(fields).length > 0 ? true : ctx.mustBe('an index field map with at least one entry'),\n);\n\nconst CollationSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-collation-options'\",\n locale: 'string',\n 'caseLevel?': 'boolean',\n 'caseFirst?': '\"off\" | \"upper\" | \"lower\"',\n 'strength?': '1 | 2 | 3 | 4 | 5',\n 'numericOrdering?': 'boolean',\n 'alternate?': '\"non-ignorable\" | \"shifted\"',\n 'maxVariable?': '\"punct\" | \"space\"',\n 'backwards?': 'boolean',\n 'normalization?': 'boolean',\n});\n\nconst IndexOptionDefaultsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-index-option-defaults'\",\n 'storageEngine?': MongoJsonObjectSchema,\n});\n\nconst TimeSeriesCollectionOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-time-series-collection-options'\",\n timeField: 'string',\n 'metaField?': 'string',\n 'granularity?': '\"seconds\" | \"minutes\" | \"hours\"',\n 'bucketMaxSpanSeconds?': 'number',\n 'bucketRoundingSeconds?': 'number',\n});\n\nconst ClusteredCollectionKeySchema = type({\n '+': 'reject',\n '[string]': '1',\n}).narrow((key, ctx) =>\n Object.keys(key).length > 0\n ? true\n : ctx.mustBe('a clustered index key map with at least one entry'),\n);\n\nconst ClusteredCollectionOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-clustered-collection-options'\",\n 'name?': 'string',\n key: ClusteredCollectionKeySchema,\n unique: 'boolean',\n});\n\nconst ChangeStreamPreAndPostImagesSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-change-stream-pre-and-post-images-options'\",\n enabled: 'boolean',\n});\n\nconst CollectionOptionsSchema = type({\n '+': 'reject',\n 'capped?': 'boolean',\n 'size?': 'number',\n 'max?': 'number',\n 'storageEngine?': MongoJsonObjectSchema,\n 'indexOptionDefaults?': IndexOptionDefaultsSchema,\n 'collation?': CollationSchema,\n 'timeseries?': TimeSeriesCollectionOptionsSchema,\n 'clusteredIndex?': ClusteredCollectionOptionsSchema,\n 'expireAfterSeconds?': 'number',\n 'changeStreamPreAndPostImages?': ChangeStreamPreAndPostImagesSchema,\n});\n\nconst ModelStorageSchema = type({\n '+': 'reject',\n 'collection?': 'string',\n 'relations?': type({ '[string]': StorageRelationEntrySchema }),\n});\n\nconst DiscriminatorSchema = type({\n '+': 'reject',\n field: 'string',\n});\n\nconst VariantEntrySchema = type({\n '+': 'reject',\n value: 'string',\n});\n\nconst ModelDefinitionSchema = type({\n '+': 'reject',\n fields: type({ '[string]': FieldSchema }),\n storage: ModelStorageSchema,\n 'relations?': type({ '[string]': RelationSchema }),\n 'discriminator?': DiscriminatorSchema,\n 'variants?': type({ '[string]': VariantEntrySchema }),\n 'base?': CrossReferenceSchema,\n 'owner?': 'string',\n});\n\nconst WildcardProjectionSchema = type({\n '+': 'reject',\n '[string]': '0 | 1',\n});\n\nconst IndexOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-index-options'\",\n 'unique?': 'boolean',\n 'name?': 'string',\n 'partialFilterExpression?': MongoJsonObjectSchema,\n 'sparse?': 'boolean',\n 'expireAfterSeconds?': 'number',\n 'weights?': NumberRecordSchema,\n 'default_language?': 'string',\n 'language_override?': 'string',\n 'textIndexVersion?': 'number',\n '2dsphereIndexVersion?': 'number',\n 'bits?': 'number',\n 'min?': 'number',\n 'max?': 'number',\n 'bucketSize?': 'number',\n 'hidden?': 'boolean',\n 'collation?': CollationSchema,\n 'wildcardProjection?': WildcardProjectionSchema,\n});\n\nconst IndexSchema = type({\n '+': 'reject',\n fields: IndexFieldsSchema,\n 'options?': IndexOptionsSchema,\n});\n\nconst MongoIndexKeySchema = type({\n '+': 'reject',\n field: 'string',\n direction: '1 | -1 | \"text\" | \"2dsphere\" | \"2d\" | \"hashed\"',\n});\n\nconst MongoStorageIndexSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-index'\",\n keys: MongoIndexKeySchema.array().atLeastLength(1),\n 'unique?': 'boolean',\n 'sparse?': 'boolean',\n 'expireAfterSeconds?': 'number',\n 'partialFilterExpression?': 'Record<string, unknown>',\n 'wildcardProjection?': 'Record<string, 0 | 1>',\n 'collation?': 'Record<string, unknown>',\n 'weights?': 'Record<string, number>',\n 'default_language?': 'string',\n 'language_override?': 'string',\n});\n\nconst MongoStorageValidatorSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-validator'\",\n jsonSchema: 'Record<string, unknown>',\n validationLevel: \"'strict' | 'moderate'\",\n validationAction: \"'error' | 'warn'\",\n});\n\nconst CappedOptionsSchema = type({\n '+': 'reject',\n size: 'number',\n 'max?': 'number',\n});\n\nconst TimeseriesOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-time-series-collection-options'\",\n timeField: 'string',\n 'metaField?': 'string',\n 'granularity?': \"'seconds' | 'minutes' | 'hours'\",\n 'bucketMaxSpanSeconds?': 'number',\n 'bucketRoundingSeconds?': 'number',\n});\n\nconst ClusteredIndexSchema = type({\n '+': 'reject',\n 'name?': 'string',\n});\n\nconst MongoCollectionOptionsSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-collection-options'\",\n 'capped?': CappedOptionsSchema,\n 'storageEngine?': MongoJsonObjectSchema,\n 'indexOptionDefaults?': IndexOptionDefaultsSchema,\n 'timeseries?': TimeseriesOptionsSchema,\n 'collation?': 'Record<string, unknown>',\n 'expireAfterSeconds?': 'number',\n 'changeStreamPreAndPostImages?': ChangeStreamPreAndPostImagesSchema,\n 'clusteredIndex?': ClusteredIndexSchema,\n});\n\nconst StorageCollectionSchema = type({\n '+': 'reject',\n 'kind?': \"'mongo-collection'\",\n 'indexes?': MongoStorageIndexSchema.array(),\n 'validator?': MongoStorageValidatorSchema,\n 'options?': MongoCollectionOptionsSchema,\n});\n\nfunction collectionEntrySchema(fragments?: ReadonlyMap<string, Type<unknown>>): Type<unknown> {\n if (fragments === undefined || fragments.size === 0) {\n return StorageCollectionSchema;\n }\n return type('unknown').narrow((entry, ctx) => {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {\n return ctx.mustBe('an object');\n }\n const kind = (entry as { kind?: unknown }).kind;\n if (typeof kind === 'string') {\n const fragment = fragments.get(kind);\n if (fragment !== undefined) {\n const parsed = fragment(entry);\n if (parsed instanceof type.errors) {\n return ctx.reject({ expected: parsed.summary });\n }\n return true;\n }\n }\n const parsed = StorageCollectionSchema(entry);\n if (parsed instanceof type.errors) {\n return ctx.reject({ expected: parsed.summary });\n }\n return true;\n });\n}\n\n/**\n * Builds the per-namespace envelope schema for Mongo storage. Pack\n * contributions are keyed by the descriptor's `discriminator` and\n * validate each entry by matching the entry's `kind` field. Mongo today\n * has no pack contributions; the composition surface exists for symmetry\n * with SQL and as the substrate for future entity kinds.\n *\n * `'kind?': 'string'` because `kind` is non-enumerable on built\n * Mongo namespace IR classes and therefore absent from the wire shape; the\n * type-side narrowing is enforced by the IR class, not by this validator.\n */\nexport function createMongoNamespaceEnvelopeSchema(\n fragments?: ReadonlyMap<string, Type<unknown>>,\n): Type<unknown> {\n return type({\n '+': 'reject',\n id: 'string',\n 'kind?': 'string',\n 'collections?': type({ '[string]': collectionEntrySchema(fragments) }),\n }) as Type<unknown>;\n}\n\n/**\n * Builds the full Mongo contract schema. The per-namespace entry\n * threading happens through {@link createMongoNamespaceEnvelopeSchema};\n * the rest of the envelope is family-shared.\n */\nexport function createMongoContractSchema(\n fragments?: ReadonlyMap<string, Type<unknown>>,\n): Type<unknown> {\n const namespaceEnvelope = createMongoNamespaceEnvelopeSchema(fragments);\n return type({\n '+': 'reject',\n targetFamily: \"'mongo'\",\n 'schemaVersion?': 'string',\n 'target?': 'string',\n 'storageHash?': 'string',\n 'profileHash?': 'string',\n roots: type({ '[string]': CrossReferenceSchema }),\n 'capabilities?': 'Record<string, unknown>',\n 'extensionPacks?': 'Record<string, unknown>',\n 'meta?': 'Record<string, unknown>',\n 'sources?': 'Record<string, unknown>',\n '_generated?': 'Record<string, unknown>',\n domain: type({\n namespaces: type({\n '[string]': type({\n models: type({ '[string]': ModelDefinitionSchema }),\n 'valueObjects?': type({\n '[string]': type({ '+': 'reject', fields: type({ '[string]': FieldSchema }) }),\n }),\n }),\n }),\n }),\n storage: type({\n '+': 'reject',\n namespaces: type({ '[string]': namespaceEnvelope }),\n 'storageHash?': 'string',\n }),\n }) as Type<unknown>;\n}\n\nexport const MongoContractSchema = createMongoContractSchema();\n\nexport {\n CollationSchema,\n CollectionOptionsSchema,\n IndexFieldsSchema,\n IndexOptionsSchema,\n IndexSchema,\n MongoIndexKeySchema,\n MongoStorageIndexSchema,\n NumberRecordSchema,\n WildcardProjectionSchema,\n};\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport interface MongoChangeStreamPreAndPostImagesOptionsInput {\n readonly enabled: boolean;\n}\n\n/**\n * Change-stream pre-and-post-images collection option. Lifted from a\n * `type =` data shape to an AST class extending `IRNodeBase` per\n * FR18. Single-field shape; the class exists for AST-pattern\n * consistency (every nested data shape inside `MongoCollectionOptions`\n * is an AST node so the verifier can walk uniformly).\n */\nexport class MongoChangeStreamPreAndPostImagesOptions extends IRNodeBase {\n readonly kind = 'mongo-change-stream-pre-and-post-images-options' as const;\n readonly enabled: boolean;\n\n constructor(options: MongoChangeStreamPreAndPostImagesOptionsInput) {\n super();\n this.enabled = options.enabled;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport type MongoCollationCaseFirst = 'off' | 'upper' | 'lower';\nexport type MongoCollationStrength = 1 | 2 | 3 | 4 | 5;\nexport type MongoCollationAlternate = 'non-ignorable' | 'shifted';\nexport type MongoCollationMaxVariable = 'punct' | 'space';\n\n/**\n * Authoring / hydration input shape for {@link MongoCollationOptions}. Carries\n * the canonical data without the IR-class `kind` discriminator; the class\n * fabricates `kind` so the authoring DSL and the SPI hydration walker can\n * pass plain data literals through the constructor without forcing every\n * call site to spell out `kind: 'mongo-collation-options'`.\n */\nexport interface MongoCollationOptionsInput {\n readonly locale: string;\n readonly caseLevel?: boolean;\n readonly caseFirst?: MongoCollationCaseFirst;\n readonly strength?: MongoCollationStrength;\n readonly numericOrdering?: boolean;\n readonly alternate?: MongoCollationAlternate;\n readonly maxVariable?: MongoCollationMaxVariable;\n readonly backwards?: boolean;\n readonly normalization?: boolean;\n}\n\n/**\n * Mongo Contract IR leaf for collection / index collation options.\n *\n * Lifted from a `type =` data shape to an AST class extending\n * `IRNodeBase` per FR18 (\"Mongo's Contract IR is fully unified under\n * the AST-class pattern, layered family / target\"). Single concrete class\n * (no target subclass): collation options carry no target-specific\n * variation at this layer — both Atlas and self-hosted Mongo consume the\n * same option vocabulary.\n *\n * Undefined optional fields are not assigned, so `JSON.stringify` omits\n * them from the canonical JSON output (matches the pre-lift data shape's\n * round-trip behaviour, modulo the new `kind` discriminator).\n */\nexport class MongoCollationOptions extends IRNodeBase {\n readonly kind = 'mongo-collation-options' as const;\n readonly locale: string;\n declare readonly caseLevel?: boolean;\n declare readonly caseFirst?: MongoCollationCaseFirst;\n declare readonly strength?: MongoCollationStrength;\n declare readonly numericOrdering?: boolean;\n declare readonly alternate?: MongoCollationAlternate;\n declare readonly maxVariable?: MongoCollationMaxVariable;\n declare readonly backwards?: boolean;\n declare readonly normalization?: boolean;\n\n constructor(options: MongoCollationOptionsInput) {\n super();\n this.locale = options.locale;\n if (options.caseLevel !== undefined) this.caseLevel = options.caseLevel;\n if (options.caseFirst !== undefined) this.caseFirst = options.caseFirst;\n if (options.strength !== undefined) this.strength = options.strength;\n if (options.numericOrdering !== undefined) this.numericOrdering = options.numericOrdering;\n if (options.alternate !== undefined) this.alternate = options.alternate;\n if (options.maxVariable !== undefined) this.maxVariable = options.maxVariable;\n if (options.backwards !== undefined) this.backwards = options.backwards;\n if (options.normalization !== undefined) this.normalization = options.normalization;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport type { MongoJsonObject } from '../contract-types';\n\nexport interface MongoIndexOptionDefaultsInput {\n readonly storageEngine?: MongoJsonObject;\n}\n\n/**\n * Collection-level default index options (the `indexOptionDefaults`\n * collection-creation field on Mongo's `createCollection`). Lifted from\n * a `type =` data shape to an AST class extending `IRNodeBase` per\n * FR18 (Mongo Contract IR fully unified under the AST-class pattern).\n *\n * Carries `storageEngine` only — the underlying MongoDB option set is\n * intentionally narrow at this layer; per-engine richer option vocabularies\n * are out of scope for this project.\n */\nexport class MongoIndexOptionDefaults extends IRNodeBase {\n readonly kind = 'mongo-index-option-defaults' as const;\n declare readonly storageEngine?: MongoJsonObject;\n\n constructor(options: MongoIndexOptionDefaultsInput = {}) {\n super();\n if (options.storageEngine !== undefined) this.storageEngine = options.storageEngine;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport type MongoTimeSeriesGranularity = 'seconds' | 'minutes' | 'hours';\n\nexport interface MongoTimeSeriesCollectionOptionsInput {\n readonly timeField: string;\n readonly metaField?: string;\n readonly granularity?: MongoTimeSeriesGranularity;\n readonly bucketMaxSpanSeconds?: number;\n readonly bucketRoundingSeconds?: number;\n}\n\n/**\n * Time-series collection options. Lifted from a `type =` data shape to\n * an AST class extending `IRNodeBase` per FR18.\n *\n * MongoDB requires `timeField` for any time-series collection; the\n * constructor enforces presence by type signature (`timeField: string`\n * is required on the input).\n */\nexport class MongoTimeSeriesCollectionOptions extends IRNodeBase {\n readonly kind = 'mongo-time-series-collection-options' as const;\n readonly timeField: string;\n declare readonly metaField?: string;\n declare readonly granularity?: MongoTimeSeriesGranularity;\n declare readonly bucketMaxSpanSeconds?: number;\n declare readonly bucketRoundingSeconds?: number;\n\n constructor(options: MongoTimeSeriesCollectionOptionsInput) {\n super();\n this.timeField = options.timeField;\n if (options.metaField !== undefined) this.metaField = options.metaField;\n if (options.granularity !== undefined) this.granularity = options.granularity;\n if (options.bucketMaxSpanSeconds !== undefined)\n this.bucketMaxSpanSeconds = options.bucketMaxSpanSeconds;\n if (options.bucketRoundingSeconds !== undefined)\n this.bucketRoundingSeconds = options.bucketRoundingSeconds;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport type { MongoJsonObject } from '../contract-types';\nimport {\n MongoChangeStreamPreAndPostImagesOptions,\n type MongoChangeStreamPreAndPostImagesOptionsInput,\n} from './mongo-change-stream-pre-and-post-images-options';\nimport type {\n MongoClusteredCollectionOptions,\n MongoClusteredCollectionOptionsInput,\n} from './mongo-clustered-collection-options';\nimport { MongoCollationOptions, type MongoCollationOptionsInput } from './mongo-collation-options';\nimport {\n MongoIndexOptionDefaults,\n type MongoIndexOptionDefaultsInput,\n} from './mongo-index-option-defaults';\nimport {\n MongoTimeSeriesCollectionOptions,\n type MongoTimeSeriesCollectionOptionsInput,\n} from './mongo-time-series-collection-options';\n\n/**\n * Storage-shape sub-shape: only `name` is persisted on the storage\n * `clusteredIndex` field. The richer authoring vocabulary\n * (`MongoClusteredCollectionOptions.key`, `…unique`) is intentionally\n * not round-tripped through the on-disk JSON envelope — those fields\n * are application-side configuration that informs collection creation\n * but does not survive into the persisted collection options.\n */\nexport interface MongoStorageClusteredIndexShape {\n readonly name?: string;\n}\n\n/**\n * Storage-shape sub-shape: `capped` collections persist `size` (required)\n * and optionally `max` document count. The authoring DSL surface uses a\n * flat `capped: boolean` + separate `size` / `max` fields; builders\n * translate that authoring vocabulary into this nested storage form\n * before constructing {@link MongoCollectionOptions}.\n */\nexport interface MongoStorageCappedShape {\n readonly size: number;\n readonly max?: number;\n}\n\n/**\n * Hydration / construction input shape for {@link MongoCollectionOptions}.\n * Mirrors the on-disk storage JSON envelope exactly (nested `capped`,\n * `clusteredIndex`, …) so the family-base serializer's hydration walker\n * can hand an arktype-validated object literal straight to `new`.\n * Nested IR-class fields may be supplied as either plain data literals\n * (typical for JSON-derived input) or already-constructed class\n * instances (typical when re-wrapping during a partial walk).\n */\nexport interface MongoCollectionOptionsInput {\n readonly capped?: MongoStorageCappedShape;\n readonly storageEngine?: MongoJsonObject;\n readonly indexOptionDefaults?: MongoIndexOptionDefaults | MongoIndexOptionDefaultsInput;\n readonly collation?: MongoCollationOptions | MongoCollationOptionsInput;\n readonly timeseries?: MongoTimeSeriesCollectionOptions | MongoTimeSeriesCollectionOptionsInput;\n readonly clusteredIndex?: MongoStorageClusteredIndexShape;\n readonly expireAfterSeconds?: number;\n readonly changeStreamPreAndPostImages?:\n | MongoChangeStreamPreAndPostImagesOptions\n | MongoChangeStreamPreAndPostImagesOptionsInput;\n}\n\n/**\n * Authoring-side flat vocabulary accepted by the contract-ts builder\n * DSL (e.g. `capped: boolean` + separate `size` / `max` scalars). The\n * builder translates this surface into a {@link MongoCollectionOptionsInput}\n * before constructing {@link MongoCollectionOptions}. Kept as a\n * standalone type so authoring DSL ergonomics do not leak into the\n * storage IR construction contract.\n */\nexport interface MongoCollectionOptionsAuthoringInput {\n readonly capped?: boolean;\n readonly size?: number;\n readonly max?: number;\n readonly storageEngine?: MongoJsonObject;\n readonly indexOptionDefaults?: MongoIndexOptionDefaults | MongoIndexOptionDefaultsInput;\n readonly collation?: MongoCollationOptions | MongoCollationOptionsInput;\n readonly timeseries?: MongoTimeSeriesCollectionOptions | MongoTimeSeriesCollectionOptionsInput;\n readonly clusteredIndex?: MongoClusteredCollectionOptions | MongoClusteredCollectionOptionsInput;\n readonly expireAfterSeconds?: number;\n readonly changeStreamPreAndPostImages?:\n | MongoChangeStreamPreAndPostImagesOptions\n | MongoChangeStreamPreAndPostImagesOptionsInput;\n}\n\n/**\n * Mongo Contract IR node for collection-level creation options (the\n * second argument to `db.createCollection(name, options)`). Lifted from\n * the pre-M2R2 `MongoStorageCollectionOptions` storage interface to a\n * class extending `IRNodeBase` per FR18.\n *\n * Single concrete family-layer class (no target subclass). The\n * constructor accepts the storage JSON envelope shape ({@link\n * MongoCollectionOptionsInput}) so the family-base hydration walker\n * can pass arktype-validated objects directly to `new`. Authoring\n * vocabulary is translated to this shape upstream in the contract-ts\n * builder.\n *\n * Nested IR sub-shapes (collation, timeseries, …) are normalised to\n * their respective IR class instances inside the constructor so\n * downstream walks see a uniform AST regardless of whether the input\n * was a JSON literal or an already-constructed class.\n */\nexport class MongoCollectionOptions extends IRNodeBase {\n readonly kind = 'mongo-collection-options' as const;\n declare readonly capped?: MongoStorageCappedShape;\n declare readonly storageEngine?: MongoJsonObject;\n declare readonly indexOptionDefaults?: MongoIndexOptionDefaults;\n declare readonly collation?: MongoCollationOptions;\n declare readonly timeseries?: MongoTimeSeriesCollectionOptions;\n declare readonly clusteredIndex?: MongoStorageClusteredIndexShape;\n declare readonly expireAfterSeconds?: number;\n declare readonly changeStreamPreAndPostImages?: MongoChangeStreamPreAndPostImagesOptions;\n\n constructor(input: MongoCollectionOptionsInput = {}) {\n super();\n if (input.capped !== undefined) {\n this.capped = {\n size: input.capped.size,\n ...(input.capped.max != null && { max: input.capped.max }),\n };\n }\n if (input.storageEngine !== undefined) this.storageEngine = input.storageEngine;\n if (input.indexOptionDefaults !== undefined) {\n this.indexOptionDefaults =\n input.indexOptionDefaults instanceof MongoIndexOptionDefaults\n ? input.indexOptionDefaults\n : new MongoIndexOptionDefaults(input.indexOptionDefaults);\n }\n if (input.collation !== undefined) {\n this.collation =\n input.collation instanceof MongoCollationOptions\n ? input.collation\n : new MongoCollationOptions(input.collation);\n }\n if (input.timeseries !== undefined) {\n this.timeseries =\n input.timeseries instanceof MongoTimeSeriesCollectionOptions\n ? input.timeseries\n : new MongoTimeSeriesCollectionOptions(input.timeseries);\n }\n if (input.clusteredIndex !== undefined) {\n this.clusteredIndex =\n input.clusteredIndex.name !== undefined ? { name: input.clusteredIndex.name } : {};\n }\n if (input.expireAfterSeconds !== undefined) this.expireAfterSeconds = input.expireAfterSeconds;\n if (input.changeStreamPreAndPostImages !== undefined) {\n this.changeStreamPreAndPostImages =\n input.changeStreamPreAndPostImages instanceof MongoChangeStreamPreAndPostImagesOptions\n ? input.changeStreamPreAndPostImages\n : new MongoChangeStreamPreAndPostImagesOptions(input.changeStreamPreAndPostImages);\n }\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport type { MongoIndexKey } from '../contract-types';\n\n/**\n * Hydration / construction input shape for {@link MongoIndex}. Mirrors\n * the on-disk storage JSON envelope exactly so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`.\n */\nexport interface MongoIndexInput {\n readonly keys: ReadonlyArray<MongoIndexKey>;\n readonly unique?: boolean;\n readonly sparse?: boolean;\n readonly expireAfterSeconds?: number;\n readonly partialFilterExpression?: Record<string, unknown>;\n readonly wildcardProjection?: Record<string, 0 | 1>;\n readonly collation?: Record<string, unknown>;\n readonly weights?: Record<string, number>;\n readonly default_language?: string;\n readonly language_override?: string;\n}\n\n/**\n * Mongo Contract IR node for a single collection index entry (one\n * element of `MongoCollection.indexes`). Lifted from the\n * pre-M2R2 `MongoStorageIndex` storage interface to a class extending\n * `IRNodeBase` per FR18.\n *\n * Single concrete family-layer class (no target subclass). The spec's\n * `MongoTargetIndex extends MongoIndex` pattern remains additive — a\n * future Mongo target with target-specific index extensions is free to\n * subclass; for the single Mongo target shipped today a concrete\n * family-layer class is enough and avoids a target-import layering\n * violation from the contract-ts builder.\n */\nexport class MongoIndex extends IRNodeBase {\n readonly kind = 'mongo-index' as const;\n readonly keys: ReadonlyArray<MongoIndexKey>;\n declare readonly unique?: boolean;\n declare readonly sparse?: boolean;\n declare readonly expireAfterSeconds?: number;\n declare readonly partialFilterExpression?: Record<string, unknown>;\n declare readonly wildcardProjection?: Record<string, 0 | 1>;\n declare readonly collation?: Record<string, unknown>;\n declare readonly weights?: Record<string, number>;\n declare readonly default_language?: string;\n declare readonly language_override?: string;\n\n constructor(input: MongoIndexInput) {\n super();\n this.keys = input.keys;\n if (input.unique !== undefined) this.unique = input.unique;\n if (input.sparse !== undefined) this.sparse = input.sparse;\n if (input.expireAfterSeconds !== undefined) this.expireAfterSeconds = input.expireAfterSeconds;\n if (input.partialFilterExpression !== undefined)\n this.partialFilterExpression = input.partialFilterExpression;\n if (input.wildcardProjection !== undefined) this.wildcardProjection = input.wildcardProjection;\n if (input.collation !== undefined) this.collation = input.collation;\n if (input.weights !== undefined) this.weights = input.weights;\n if (input.default_language !== undefined) this.default_language = input.default_language;\n if (input.language_override !== undefined) this.language_override = input.language_override;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport type MongoValidatorValidationLevel = 'strict' | 'moderate';\nexport type MongoValidatorValidationAction = 'error' | 'warn';\n\nexport interface MongoValidatorInput {\n readonly jsonSchema: Record<string, unknown>;\n readonly validationLevel: MongoValidatorValidationLevel;\n readonly validationAction: MongoValidatorValidationAction;\n}\n\n/**\n * Mongo Contract IR node for collection-level document validators (the\n * `validator` field on Mongo's `createCollection`). Lifted from the\n * pre-M2R2 `MongoStorageValidator` storage interface to a class extending\n * `IRNodeBase` per FR18.\n *\n * Concrete at the family layer (no target subclass). The spec's\n * abstract-family + target-concrete pattern (`MongoTargetValidator\n * extends MongoValidator`) becomes meaningful when a second Mongo target\n * introduces target-specific validator extensions (Atlas search rules,\n * DocumentDB-specific levels, …); for the single Mongo target shipped\n * today, a concrete family-layer class lets the PSL JSON-Schema deriver\n * and the contract-ts builder construct instances directly without a\n * target-import layering violation. Target subclassing remains additive\n * — a future `MongoTargetValidator extends MongoValidator` is an\n * additive change, not a breaking one.\n */\nexport class MongoValidator extends IRNodeBase {\n readonly kind = 'mongo-validator' as const;\n readonly jsonSchema: Record<string, unknown>;\n readonly validationLevel: MongoValidatorValidationLevel;\n readonly validationAction: MongoValidatorValidationAction;\n\n constructor(input: MongoValidatorInput) {\n super();\n this.jsonSchema = input.jsonSchema;\n this.validationLevel = input.validationLevel;\n this.validationAction = input.validationAction;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport {\n MongoCollectionOptions,\n type MongoCollectionOptionsInput,\n} from './mongo-collection-options';\nimport { MongoIndex, type MongoIndexInput } from './mongo-index';\nimport { MongoValidator, type MongoValidatorInput } from './mongo-validator';\n\n/**\n * Hydration / construction input shape for {@link MongoCollection}.\n * Mirrors the on-disk storage JSON envelope exactly (the value held at\n * `contract.storage.namespaces[<namespaceId>].collections[<name>]`) so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`. Nested IR-class fields may be supplied as either\n * plain data literals (typical for JSON-derived input) or\n * already-constructed class instances.\n */\nexport interface MongoCollectionInput {\n readonly indexes?: ReadonlyArray<MongoIndex | MongoIndexInput>;\n readonly validator?: MongoValidator | MongoValidatorInput;\n readonly options?: MongoCollectionOptions | MongoCollectionOptionsInput;\n}\n\n/**\n * Mongo Contract IR node for a single collection entry in a namespace's\n * `collections` map. Lifted from the pre-M2R2\n * `MongoStorageCollection` storage interface to a class extending\n * `IRNodeBase` per FR18.\n *\n * Concrete at the family layer (no target subclass). The spec's\n * `MongoTargetCollection extends MongoCollection` pattern remains\n * additive: a future Mongo target with target-specific extensions is\n * free to subclass without breaking the family-layer construction\n * sites.\n *\n * The unprefixed name `MongoCollection` is now the contract IR class.\n * Note that `@prisma-next/mongo-orm` also exports a (different)\n * `MongoCollection<TContract, ModelName>` generic for the user-facing\n * ORM query builder; the two live in separate packages and are\n * resolved by import path. A source file that needs both should alias\n * one (e.g. `import { MongoCollection as MongoContractCollection }\n * from '@prisma-next/mongo-contract'`).\n */\nexport class MongoCollection extends IRNodeBase {\n readonly kind = 'mongo-collection' as const;\n declare readonly indexes?: ReadonlyArray<MongoIndex>;\n declare readonly validator?: MongoValidator;\n declare readonly options?: MongoCollectionOptions;\n\n constructor(input: MongoCollectionInput = {}) {\n super();\n if (input.indexes !== undefined) {\n this.indexes = input.indexes.map((idx) =>\n idx instanceof MongoIndex ? idx : new MongoIndex(idx),\n );\n }\n if (input.validator !== undefined) {\n this.validator =\n input.validator instanceof MongoValidator\n ? input.validator\n : new MongoValidator(input.validator);\n }\n if (input.options !== undefined) {\n this.options =\n input.options instanceof MongoCollectionOptions\n ? input.options\n : new MongoCollectionOptions(input.options);\n }\n freezeNode(this);\n }\n}\n","import {\n freezeNode,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport type { MongoCollection } from './mongo-collection';\n\nexport class MongoUnboundNamespace extends NamespaceBase {\n static readonly instance: MongoUnboundNamespace = new MongoUnboundNamespace();\n\n readonly id = UNBOUND_NAMESPACE_ID;\n readonly collections: Readonly<Record<string, MongoCollection>> = Object.freeze({});\n declare readonly kind: string;\n\n private constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'mongo-namespace',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n}\n","import {\n freezeNode,\n type Namespace,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { blindCast, castAs } from '@prisma-next/utils/casts';\nimport { MongoCollection } from './mongo-collection';\nimport type { MongoNamespace, MongoNamespaceCollectionsInput } from './mongo-storage';\nimport { MongoUnboundNamespace } from './mongo-unbound-namespace';\n\nconst MONGO_NAMESPACE_KIND = 'mongo-namespace' as const;\n\nfunction isMaterializedMongoNamespace(\n ns: Namespace | MongoNamespaceCollectionsInput,\n): ns is MongoNamespace {\n if (typeof ns !== 'object' || ns === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(ns);\n if (proto === Object.prototype || proto === null) {\n return false;\n }\n return (ns as Namespace).kind === MONGO_NAMESPACE_KIND;\n}\n\nclass MongoBoundNamespace extends NamespaceBase {\n declare readonly kind: string;\n\n readonly id: string;\n readonly collections: Readonly<Record<string, MongoCollection>>;\n\n static fromCollectionsInput(input: MongoNamespaceCollectionsInput): MongoNamespace {\n const collectionCount = Object.keys(input.collections ?? {}).length;\n if (input.id === UNBOUND_NAMESPACE_ID && collectionCount === 0) {\n return castAs<MongoNamespace>(MongoUnboundNamespace.instance);\n }\n return castAs<MongoNamespace>(new MongoBoundNamespace(input));\n }\n\n private constructor(input: MongoNamespaceCollectionsInput) {\n super();\n this.id = input.id;\n this.collections = Object.freeze(\n Object.fromEntries(\n Object.entries(input.collections ?? {}).map(([name, c]) => [\n name,\n c instanceof MongoCollection ? c : new MongoCollection(c),\n ]),\n ),\n );\n Object.defineProperty(this, 'kind', {\n value: MONGO_NAMESPACE_KIND,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n}\n\nexport function buildMongoNamespace(input: MongoNamespaceCollectionsInput): MongoNamespace {\n return MongoBoundNamespace.fromCollectionsInput(input);\n}\n\nexport function buildMongoNamespaceMap(\n namespaces: Readonly<Record<string, Namespace | MongoNamespaceCollectionsInput>>,\n): Readonly<Record<string, MongoNamespace>> {\n return Object.fromEntries(\n Object.entries(namespaces).map(([nsKey, ns]) => [\n nsKey,\n isMaterializedMongoNamespace(ns)\n ? blindCast<\n MongoNamespace,\n 'a materialised Mongo-family namespace entry in a namespace map is a MongoNamespace'\n >(ns)\n : MongoBoundNamespace.fromCollectionsInput(ns),\n ]),\n );\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\n\nexport type MongoClusteredCollectionKey = Readonly<Record<string, 1>>;\n\nexport interface MongoClusteredCollectionOptionsInput {\n readonly name?: string;\n readonly key: MongoClusteredCollectionKey;\n readonly unique: boolean;\n}\n\n/**\n * Clustered-collection options (the `clusteredIndex` collection-creation\n * field). Lifted from a `type =` data shape to an AST class extending\n * `IRNodeBase` per FR18.\n *\n * MongoDB requires `key` and `unique` for any clustered collection; the\n * constructor enforces presence by type signature.\n */\nexport class MongoClusteredCollectionOptions extends IRNodeBase {\n readonly kind = 'mongo-clustered-collection-options' as const;\n declare readonly name?: string;\n readonly key: MongoClusteredCollectionKey;\n readonly unique: boolean;\n\n constructor(options: MongoClusteredCollectionOptionsInput) {\n super();\n if (options.name !== undefined) this.name = options.name;\n this.key = options.key;\n this.unique = options.unique;\n freezeNode(this);\n }\n}\n","import { freezeNode, IRNodeBase } from '@prisma-next/framework-components/ir';\nimport type { MongoJsonObject, MongoWildcardProjection } from '../contract-types';\nimport { MongoCollationOptions, type MongoCollationOptionsInput } from './mongo-collation-options';\n\n/**\n * Authoring / hydration input shape for {@link MongoIndexOptions}. Carries\n * the index option vocabulary as plain data without the IR-class `kind`\n * discriminator. `collation` accepts either a class instance or its own\n * input shape — the constructor normalises to the class form internally.\n */\nexport interface MongoIndexOptionsInput {\n readonly unique?: boolean;\n readonly name?: string;\n readonly partialFilterExpression?: MongoJsonObject;\n readonly sparse?: boolean;\n readonly expireAfterSeconds?: number;\n readonly weights?: Readonly<Record<string, number>>;\n readonly default_language?: string;\n readonly language_override?: string;\n readonly textIndexVersion?: number;\n readonly '2dsphereIndexVersion'?: number;\n readonly bits?: number;\n readonly min?: number;\n readonly max?: number;\n readonly bucketSize?: number;\n readonly hidden?: boolean;\n readonly collation?: MongoCollationOptions | MongoCollationOptionsInput;\n readonly wildcardProjection?: MongoWildcardProjection;\n}\n\n/**\n * Mongo Contract IR node for the per-index option vocabulary (the second\n * argument to `db.collection.createIndex(keys, options)` minus the keys\n * themselves). Lifted from a `type =` data shape to an AST class\n * extending `IRNodeBase` per FR18.\n *\n * Nested `collation` is itself an IR class (`MongoCollationOptions`); the\n * constructor accepts either a class instance or a data literal and\n * normalises to the class form so downstream walks see a uniform IR tree.\n */\nexport class MongoIndexOptions extends IRNodeBase {\n readonly kind = 'mongo-index-options' as const;\n declare readonly unique?: boolean;\n declare readonly name?: string;\n declare readonly partialFilterExpression?: MongoJsonObject;\n declare readonly sparse?: boolean;\n declare readonly expireAfterSeconds?: number;\n declare readonly weights?: Readonly<Record<string, number>>;\n declare readonly default_language?: string;\n declare readonly language_override?: string;\n declare readonly textIndexVersion?: number;\n declare readonly '2dsphereIndexVersion'?: number;\n declare readonly bits?: number;\n declare readonly min?: number;\n declare readonly max?: number;\n declare readonly bucketSize?: number;\n declare readonly hidden?: boolean;\n declare readonly collation?: MongoCollationOptions;\n declare readonly wildcardProjection?: MongoWildcardProjection;\n\n constructor(options: MongoIndexOptionsInput = {}) {\n super();\n if (options.unique !== undefined) this.unique = options.unique;\n if (options.name !== undefined) this.name = options.name;\n if (options.partialFilterExpression !== undefined)\n this.partialFilterExpression = options.partialFilterExpression;\n if (options.sparse !== undefined) this.sparse = options.sparse;\n if (options.expireAfterSeconds !== undefined)\n this.expireAfterSeconds = options.expireAfterSeconds;\n if (options.weights !== undefined) this.weights = options.weights;\n if (options.default_language !== undefined) this.default_language = options.default_language;\n if (options.language_override !== undefined) this.language_override = options.language_override;\n if (options.textIndexVersion !== undefined) this.textIndexVersion = options.textIndexVersion;\n if (options['2dsphereIndexVersion'] !== undefined)\n this['2dsphereIndexVersion'] = options['2dsphereIndexVersion'];\n if (options.bits !== undefined) this.bits = options.bits;\n if (options.min !== undefined) this.min = options.min;\n if (options.max !== undefined) this.max = options.max;\n if (options.bucketSize !== undefined) this.bucketSize = options.bucketSize;\n if (options.hidden !== undefined) this.hidden = options.hidden;\n if (options.collation !== undefined) {\n this.collation =\n options.collation instanceof MongoCollationOptions\n ? options.collation\n : new MongoCollationOptions(options.collation);\n }\n if (options.wildcardProjection !== undefined)\n this.wildcardProjection = options.wildcardProjection;\n freezeNode(this);\n }\n}\n","import type { StorageHashBase } from '@prisma-next/contract/types';\nimport {\n freezeNode,\n IRNodeBase,\n type Namespace,\n type Storage,\n} from '@prisma-next/framework-components/ir';\nimport type { MongoCollection, MongoCollectionInput } from './mongo-collection';\n\nexport interface MongoNamespaceCollectionsInput {\n readonly id: string;\n readonly collections?: Record<string, MongoCollection | MongoCollectionInput>;\n}\n\n// Mongo concretions always store `MongoCollection` instances in\n// `collections` (Mongo idiom — distinct from the SQL family's `tables`).\n// Narrowing the namespace map here lets target/family-level consumers\n// iterate `namespaces[*].collections[*]` and recover the concrete\n// collection type without the framework's wider `Namespace` tripping\n// them up.\nexport type MongoNamespace = Namespace & {\n readonly collections: Readonly<Record<string, MongoCollection>>;\n};\n\nexport interface MongoStorageInput<THash extends string = string> {\n readonly storageHash: StorageHashBase<THash>;\n readonly namespaces: Readonly<Record<string, MongoNamespace>>;\n}\n\nexport class MongoStorage<THash extends string = string> extends IRNodeBase implements Storage {\n declare readonly kind: 'mongo-storage';\n readonly storageHash: StorageHashBase<THash>;\n readonly namespaces: Readonly<Record<string, MongoNamespace>>;\n\n constructor(input: MongoStorageInput<THash>) {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'mongo-storage',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n this.storageHash = input.storageHash;\n this.namespaces = Object.freeze(input.namespaces);\n freezeNode(this);\n }\n}\n","import { MongoIndex, type MongoIndexInput } from './ir/mongo-index';\n\nexport type PolymorphicIndexScope = {\n readonly discriminatorField: string;\n readonly discriminatorValue: string | number | boolean;\n};\n\nexport type ApplyScopeResult =\n | { readonly kind: 'ok'; readonly index: MongoIndex }\n | { readonly kind: 'conflict'; readonly reason: string };\n\nfunction isScalarDiscriminatorValue(value: unknown): value is string | number | boolean {\n const t = typeof value;\n return t === 'string' || t === 'number' || t === 'boolean';\n}\n\nfunction formatValue(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value);\n if (value === null) return 'null';\n if (Array.isArray(value)) return JSON.stringify(value);\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n\nexport function applyPolymorphicScopeToMongoIndex(\n index: MongoIndex,\n scope: PolymorphicIndexScope,\n): ApplyScopeResult {\n if (!isScalarDiscriminatorValue(scope.discriminatorValue)) {\n return {\n kind: 'conflict',\n reason: `Variant-scoped indexes require a scalar (string, number, or boolean) discriminator value for field \"${scope.discriminatorField}\", but received ${formatValue(scope.discriminatorValue)}.`,\n };\n }\n\n const existing = index.partialFilterExpression;\n if (existing && Object.hasOwn(existing, scope.discriminatorField)) {\n const existingValue = existing[scope.discriminatorField];\n if (existingValue === scope.discriminatorValue) {\n return { kind: 'ok', index };\n }\n return {\n kind: 'conflict',\n reason: `Index partialFilterExpression sets \"${scope.discriminatorField}\" to ${formatValue(existingValue)}, which conflicts with the variant's discriminator value ${formatValue(scope.discriminatorValue)}.`,\n };\n }\n\n const merged: Record<string, unknown> = {\n ...(existing ?? {}),\n [scope.discriminatorField]: scope.discriminatorValue,\n };\n\n const cloned: MongoIndexInput = {\n keys: index.keys,\n ...(index.unique !== undefined && { unique: index.unique }),\n ...(index.sparse !== undefined && { sparse: index.sparse }),\n ...(index.expireAfterSeconds !== undefined && { expireAfterSeconds: index.expireAfterSeconds }),\n partialFilterExpression: merged,\n ...(index.wildcardProjection !== undefined && { wildcardProjection: index.wildcardProjection }),\n ...(index.collation !== undefined && { collation: index.collation }),\n ...(index.weights !== undefined && { weights: index.weights }),\n ...(index.default_language !== undefined && { default_language: index.default_language }),\n ...(index.language_override !== undefined && { language_override: index.language_override }),\n };\n\n return { kind: 'ok', index: new MongoIndex(cloned) };\n}\n","import type { MongoContract, MongoModelDefinition } from './contract-types';\n\nfunction formatCrossRef(crossRef: { readonly namespace: string; readonly model: string }): string {\n return `${crossRef.namespace}.${crossRef.model}`;\n}\n\nfunction storageDeclaresCollection(\n storage: MongoContract['storage'],\n collectionName: string,\n): boolean {\n for (const ns of Object.values(storage.namespaces)) {\n if (Object.hasOwn(ns.collections, collectionName)) {\n return true;\n }\n }\n return false;\n}\n\nexport function validateMongoStorage(contract: MongoContract): void {\n const errors: string[] = [];\n\n for (const [namespaceId, namespace] of Object.entries(contract.domain.namespaces)) {\n const models = namespace.models as Record<string, MongoModelDefinition>;\n for (const [modelName, model] of Object.entries(models)) {\n const qualifiedName = `${namespaceId}:${modelName}`;\n if (\n model.storage.collection &&\n !storageDeclaresCollection(contract.storage, model.storage.collection)\n ) {\n errors.push(\n `Model \"${qualifiedName}\" references collection \"${model.storage.collection}\" which is not declared under any namespace's collections map`,\n );\n }\n\n if (model.base) {\n const baseModel = models[model.base.model];\n if (baseModel) {\n const variantCollection = model.storage.collection;\n const baseCollection = baseModel.storage.collection;\n if (variantCollection !== baseCollection) {\n errors.push(\n `Mongo does not support multi-table inheritance; variant \"${qualifiedName}\" must share its base's collection (\"${baseCollection ?? '(none)'}\"), but has \"${variantCollection ?? '(none)'}\"`,\n );\n }\n }\n }\n\n for (const [relName, relation] of Object.entries(model.relations ?? {})) {\n const targetModel = models[relation.to.model];\n const targetLabel = formatCrossRef(relation.to);\n\n if (targetModel?.owner) {\n if (targetModel.owner !== modelName) {\n errors.push(\n `Embed relation \"${relName}\" targets \"${targetLabel}\" which is owned by \"${targetModel.owner}\", not \"${qualifiedName}\"`,\n );\n }\n if (targetModel.storage.collection) {\n errors.push(\n `Embed relation \"${relName}\" targets \"${targetLabel}\" which must not have a collection`,\n );\n }\n } else if ('on' in relation && relation.on) {\n for (const localField of relation.on.localFields) {\n if (!(localField in model.fields)) {\n errors.push(\n `Reference relation \"${relName}\": localField \"${localField}\" is not a field on model \"${qualifiedName}\"`,\n );\n }\n }\n\n if (targetModel) {\n for (const targetField of relation.on.targetFields) {\n if (!(targetField in targetModel.fields)) {\n errors.push(\n `Reference relation \"${relName}\": targetField \"${targetField}\" is not a field on model \"${targetLabel}\"`,\n );\n }\n }\n }\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new Error(`Contract storage validation failed:\\n- ${errors.join('\\n- ')}`);\n }\n}\n"],"mappings":";;;;;AAIA,MAAM,wBAAwB,KAAK;CACjC,KAAK;CACL,MAAM;CACN,SAAS;CACT,eAAe;AACjB,CAAC;AAED,MAAM,6BAA6B,KAAK;CACtC,KAAK;CACL,MAAM;CACN,MAAM;AACR,CAAC;AAED,MAAM,uBAAuB,KAAK;CAChC,KAAK;CACL,MAAM;CACN,SAAS,sBAAsB,GAAG,0BAA0B,EAAE,MAAM;AACtE,CAAC;AAcD,MAAM,cARiB,KAAK;CAC1B,KAAK;CACL,MANsB,sBAAsB,GAAG,0BAA0B,EAAE,GAC3E,oBAKoB;CACpB,aAAa;CACb,SAAS;CACT,SAAS;AACX,CAEiC,EAAE,MAAM,WAAW;CAClD,GAAG;CACH,UAAU,MAAM,YAAY;AAC9B,EAAE;AAQF,MAAM,iBAAiB,KAAK;CAC1B,KAAK;CACL,IAAI;CACJ,aAAa;CACb,OAVuB,KAAK;EAC5B,KAAK;EACL,aAAa;EACb,cAAc;CAChB,CAMwB;AACxB,CAAC;AAED,MAAM,6BAA6B,KAAK;CACtC,KAAK;CACL,OAAO;AACT,CAAC;AAED,MAAM,2BAA2B,KAC9B,QAA4B,EAC5B,KAAK,kCAAkC;AAE1C,SAAS,kBAAkB,OAAkD;CAC3E,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,OAAO;CAET,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,oBAAoB,OAAe,MAAuB,OA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,eAAe,SAAS,GAAG,cACpC,IAAI,EAAE,eAAe,YAAY,SAC/B,OAAO,KACL,uBAAuB,QAAQ,kBAAkB,YAAY,6BAA6B,YAAY,EACxG;KAAA;IAIR;GACF;EACF;CACF;CAEA,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MAAM,0CAA0C,OAAO,KAAK,MAAM,GAAG;AAEnF"}
|
package/package.json
CHANGED
|
@@ -1,33 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/mongo-contract",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "Contract types and validation for Prisma Next MongoDB support",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@prisma-next/contract": "0.
|
|
10
|
-
"@prisma-next/framework-components": "0.
|
|
11
|
-
"@prisma-next/utils": "0.
|
|
9
|
+
"@prisma-next/contract": "0.12.0",
|
|
10
|
+
"@prisma-next/framework-components": "0.12.0",
|
|
11
|
+
"@prisma-next/utils": "0.12.0",
|
|
12
12
|
"arktype": "^2.2.0"
|
|
13
13
|
},
|
|
14
14
|
"devDependencies": {
|
|
15
|
-
"@prisma-next/test-utils": "0.
|
|
16
|
-
"@prisma-next/tsconfig": "0.
|
|
17
|
-
"@prisma-next/tsdown": "0.
|
|
15
|
+
"@prisma-next/test-utils": "0.12.0",
|
|
16
|
+
"@prisma-next/tsconfig": "0.12.0",
|
|
17
|
+
"@prisma-next/tsdown": "0.12.0",
|
|
18
18
|
"tsdown": "0.22.0",
|
|
19
19
|
"typescript": "5.9.3",
|
|
20
20
|
"vitest": "4.1.6"
|
|
21
21
|
},
|
|
22
|
+
"peerDependencies": {
|
|
23
|
+
"typescript": ">=5.9"
|
|
24
|
+
},
|
|
25
|
+
"peerDependenciesMeta": {
|
|
26
|
+
"typescript": {
|
|
27
|
+
"optional": true
|
|
28
|
+
}
|
|
29
|
+
},
|
|
22
30
|
"files": [
|
|
23
31
|
"dist",
|
|
24
32
|
"src"
|
|
25
33
|
],
|
|
34
|
+
"types": "./dist/index.d.mts",
|
|
26
35
|
"exports": {
|
|
27
36
|
".": "./dist/index.mjs",
|
|
37
|
+
"./canonicalization-hooks": "./dist/canonicalization-hooks.mjs",
|
|
28
38
|
"./package.json": "./package.json"
|
|
29
39
|
},
|
|
30
|
-
"
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=24"
|
|
42
|
+
},
|
|
31
43
|
"repository": {
|
|
32
44
|
"type": "git",
|
|
33
45
|
"url": "https://github.com/prisma/prisma-next.git",
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { PreserveEmptyPredicate } from '@prisma-next/contract/hashing';
|
|
2
|
+
import {
|
|
3
|
+
createPreserveEmptyPredicate,
|
|
4
|
+
type PathPattern,
|
|
5
|
+
} from '@prisma-next/contract/hashing-utils';
|
|
6
|
+
|
|
7
|
+
const preserveEmptyPatterns = [
|
|
8
|
+
['storage', 'namespaces', '*', 'collections'],
|
|
9
|
+
['storage', 'namespaces', '*', 'collections', '*'],
|
|
10
|
+
] as const satisfies readonly PathPattern[];
|
|
11
|
+
|
|
12
|
+
const matchesPreserveEmptyPattern = createPreserveEmptyPredicate(preserveEmptyPatterns);
|
|
13
|
+
|
|
14
|
+
// `additionalProperties: false` is the closed-schema marker on a Mongo
|
|
15
|
+
// `$jsonSchema` validator. It is injected at every object level — top-level
|
|
16
|
+
// collections, nested embedded value objects, and each polymorphic `oneOf`
|
|
17
|
+
// branch — so it appears at an unbounded set of paths that fixed-length path
|
|
18
|
+
// patterns cannot enumerate. It is a meaningful constraint rather than an
|
|
19
|
+
// omittable default, so preserve it wherever it occurs in a Mongo contract.
|
|
20
|
+
const shouldPreserveEmpty: PreserveEmptyPredicate = (path) =>
|
|
21
|
+
path[path.length - 1] === 'additionalProperties' || matchesPreserveEmptyPattern(path);
|
|
22
|
+
|
|
23
|
+
export const mongoContractCanonicalizationHooks: {
|
|
24
|
+
readonly shouldPreserveEmpty: PreserveEmptyPredicate;
|
|
25
|
+
} = {
|
|
26
|
+
shouldPreserveEmpty,
|
|
27
|
+
};
|
package/src/contract-schema.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CrossReferenceSchema } from '@prisma-next/contract/types';
|
|
1
2
|
import { type Type, type } from 'arktype';
|
|
2
3
|
import type { MongoJsonObject, MongoJsonPrimitive, MongoJsonValue } from './contract-types';
|
|
3
4
|
|
|
@@ -45,7 +46,7 @@ const RelationOnSchema = type({
|
|
|
45
46
|
|
|
46
47
|
const RelationSchema = type({
|
|
47
48
|
'+': 'reject',
|
|
48
|
-
to:
|
|
49
|
+
to: CrossReferenceSchema,
|
|
49
50
|
cardinality: "'1:1' | '1:N' | 'N:1'",
|
|
50
51
|
'on?': RelationOnSchema,
|
|
51
52
|
});
|
|
@@ -209,7 +210,7 @@ const ModelDefinitionSchema = type({
|
|
|
209
210
|
'relations?': type({ '[string]': RelationSchema }),
|
|
210
211
|
'discriminator?': DiscriminatorSchema,
|
|
211
212
|
'variants?': type({ '[string]': VariantEntrySchema }),
|
|
212
|
-
'base?':
|
|
213
|
+
'base?': CrossReferenceSchema,
|
|
213
214
|
'owner?': 'string',
|
|
214
215
|
});
|
|
215
216
|
|
|
@@ -351,8 +352,8 @@ function collectionEntrySchema(fragments?: ReadonlyMap<string, Type<unknown>>):
|
|
|
351
352
|
* has no pack contributions; the composition surface exists for symmetry
|
|
352
353
|
* with SQL and as the substrate for future entity kinds.
|
|
353
354
|
*
|
|
354
|
-
* `'kind?': 'string'` because `kind` is non-enumerable on
|
|
355
|
-
*
|
|
355
|
+
* `'kind?': 'string'` because `kind` is non-enumerable on built
|
|
356
|
+
* Mongo namespace IR classes and therefore absent from the wire shape; the
|
|
356
357
|
* type-side narrowing is enforced by the IR class, not by this validator.
|
|
357
358
|
*/
|
|
358
359
|
export function createMongoNamespaceEnvelopeSchema(
|
|
@@ -382,22 +383,27 @@ export function createMongoContractSchema(
|
|
|
382
383
|
'target?': 'string',
|
|
383
384
|
'storageHash?': 'string',
|
|
384
385
|
'profileHash?': 'string',
|
|
385
|
-
roots: '
|
|
386
|
+
roots: type({ '[string]': CrossReferenceSchema }),
|
|
386
387
|
'capabilities?': 'Record<string, unknown>',
|
|
387
388
|
'extensionPacks?': 'Record<string, unknown>',
|
|
388
389
|
'meta?': 'Record<string, unknown>',
|
|
389
390
|
'sources?': 'Record<string, unknown>',
|
|
390
391
|
'_generated?': 'Record<string, unknown>',
|
|
391
|
-
|
|
392
|
+
domain: type({
|
|
393
|
+
namespaces: type({
|
|
394
|
+
'[string]': type({
|
|
395
|
+
models: type({ '[string]': ModelDefinitionSchema }),
|
|
396
|
+
'valueObjects?': type({
|
|
397
|
+
'[string]': type({ '+': 'reject', fields: type({ '[string]': FieldSchema }) }),
|
|
398
|
+
}),
|
|
399
|
+
}),
|
|
400
|
+
}),
|
|
401
|
+
}),
|
|
392
402
|
storage: type({
|
|
393
403
|
'+': 'reject',
|
|
394
404
|
namespaces: type({ '[string]': namespaceEnvelope }),
|
|
395
405
|
'storageHash?': 'string',
|
|
396
406
|
}),
|
|
397
|
-
models: type({ '[string]': ModelDefinitionSchema }),
|
|
398
|
-
'valueObjects?': type({
|
|
399
|
-
'[string]': type({ '+': 'reject', fields: type({ '[string]': FieldSchema }) }),
|
|
400
|
-
}),
|
|
401
407
|
}) as Type<unknown>;
|
|
402
408
|
}
|
|
403
409
|
|
package/src/contract-types.ts
CHANGED
|
@@ -2,7 +2,9 @@ import type {
|
|
|
2
2
|
Contract,
|
|
3
3
|
ContractField,
|
|
4
4
|
ContractModel,
|
|
5
|
+
ContractModelsMap,
|
|
5
6
|
ContractValueObject,
|
|
7
|
+
ContractValueObjectsMap,
|
|
6
8
|
StorageBase,
|
|
7
9
|
} from '@prisma-next/contract/types';
|
|
8
10
|
import type { Namespace } from '@prisma-next/framework-components/ir';
|
|
@@ -71,6 +73,16 @@ export type MongoContract<
|
|
|
71
73
|
M extends Record<string, MongoModelDefinition> = Record<string, MongoModelDefinition>,
|
|
72
74
|
> = Contract<S, M>;
|
|
73
75
|
|
|
76
|
+
/** Model map inferred from a {@link MongoContract} (domain.namespaces union). */
|
|
77
|
+
export type MongoModelsMap<TContract extends MongoContract> = ContractModelsMap<TContract>;
|
|
78
|
+
|
|
79
|
+
export type RootModelName<
|
|
80
|
+
TContract extends MongoContract,
|
|
81
|
+
RootName extends keyof TContract['roots'] & string,
|
|
82
|
+
> = TContract['roots'][RootName] extends { readonly model: infer M extends string }
|
|
83
|
+
? M & keyof import('@prisma-next/contract/types').ContractModelsMap<TContract>
|
|
84
|
+
: never;
|
|
85
|
+
|
|
74
86
|
export type MongoTypeMaps<
|
|
75
87
|
TCodecTypes extends Record<string, { output: unknown }> = Record<string, { output: unknown }>,
|
|
76
88
|
TFieldOutputTypes extends Record<string, Record<string, unknown>> = Record<
|
|
@@ -118,11 +130,7 @@ export type ExtractMongoFieldInputTypes<T> =
|
|
|
118
130
|
: Record<string, never>
|
|
119
131
|
: Record<string, never>;
|
|
120
132
|
|
|
121
|
-
type ExtractValueObjects<TContract> = TContract
|
|
122
|
-
valueObjects: infer VO extends Record<string, ContractValueObject>;
|
|
123
|
-
}
|
|
124
|
-
? VO
|
|
125
|
-
: Record<never, never>;
|
|
133
|
+
type ExtractValueObjects<TContract extends Contract> = ContractValueObjectsMap<TContract>;
|
|
126
134
|
|
|
127
135
|
type NormalizeContractFields<TFields> = {
|
|
128
136
|
[K in keyof TFields]: TFields[K] extends ContractField ? TFields[K] : never;
|
|
@@ -174,8 +182,8 @@ type InferFieldType<
|
|
|
174
182
|
|
|
175
183
|
export type InferModelRow<
|
|
176
184
|
TContract extends MongoContractWithTypeMaps<MongoContract, MongoTypeMaps>,
|
|
177
|
-
ModelName extends string & keyof TContract
|
|
178
|
-
TFields extends Record<string, ContractField> = TContract[
|
|
185
|
+
ModelName extends string & keyof ContractModelsMap<TContract>,
|
|
186
|
+
TFields extends Record<string, ContractField> = ContractModelsMap<TContract>[ModelName]['fields'],
|
|
179
187
|
TCodecTypes extends Record<string, { output: unknown }> = ExtractMongoCodecTypes<TContract>,
|
|
180
188
|
TValueObjects extends Record<string, ContractValueObject> = ExtractValueObjects<TContract>,
|
|
181
189
|
> = {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { mongoContractCanonicalizationHooks } from '../canonicalization-hooks';
|
package/src/exports/index.ts
CHANGED
|
@@ -21,11 +21,14 @@ export type {
|
|
|
21
21
|
MongoJsonValue,
|
|
22
22
|
MongoModelDefinition,
|
|
23
23
|
MongoModelStorage,
|
|
24
|
+
MongoModelsMap,
|
|
24
25
|
MongoStorageShape,
|
|
25
26
|
MongoTypeMaps,
|
|
26
27
|
MongoTypeMapsPhantomKey,
|
|
27
28
|
MongoWildcardProjection,
|
|
29
|
+
RootModelName,
|
|
28
30
|
} from '../contract-types';
|
|
31
|
+
export { buildMongoNamespace, buildMongoNamespaceMap } from '../ir/build-mongo-namespace';
|
|
29
32
|
export type { MongoChangeStreamPreAndPostImagesOptionsInput } from '../ir/mongo-change-stream-pre-and-post-images-options';
|
|
30
33
|
export { MongoChangeStreamPreAndPostImagesOptions } from '../ir/mongo-change-stream-pre-and-post-images-options';
|
|
31
34
|
export type {
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import {
|
|
2
|
+
freezeNode,
|
|
3
|
+
type Namespace,
|
|
4
|
+
NamespaceBase,
|
|
5
|
+
UNBOUND_NAMESPACE_ID,
|
|
6
|
+
} from '@prisma-next/framework-components/ir';
|
|
7
|
+
import { blindCast, castAs } from '@prisma-next/utils/casts';
|
|
8
|
+
import { MongoCollection } from './mongo-collection';
|
|
9
|
+
import type { MongoNamespace, MongoNamespaceCollectionsInput } from './mongo-storage';
|
|
10
|
+
import { MongoUnboundNamespace } from './mongo-unbound-namespace';
|
|
11
|
+
|
|
12
|
+
const MONGO_NAMESPACE_KIND = 'mongo-namespace' as const;
|
|
13
|
+
|
|
14
|
+
function isMaterializedMongoNamespace(
|
|
15
|
+
ns: Namespace | MongoNamespaceCollectionsInput,
|
|
16
|
+
): ns is MongoNamespace {
|
|
17
|
+
if (typeof ns !== 'object' || ns === null) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
const proto = Object.getPrototypeOf(ns);
|
|
21
|
+
if (proto === Object.prototype || proto === null) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
return (ns as Namespace).kind === MONGO_NAMESPACE_KIND;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
class MongoBoundNamespace extends NamespaceBase {
|
|
28
|
+
declare readonly kind: string;
|
|
29
|
+
|
|
30
|
+
readonly id: string;
|
|
31
|
+
readonly collections: Readonly<Record<string, MongoCollection>>;
|
|
32
|
+
|
|
33
|
+
static fromCollectionsInput(input: MongoNamespaceCollectionsInput): MongoNamespace {
|
|
34
|
+
const collectionCount = Object.keys(input.collections ?? {}).length;
|
|
35
|
+
if (input.id === UNBOUND_NAMESPACE_ID && collectionCount === 0) {
|
|
36
|
+
return castAs<MongoNamespace>(MongoUnboundNamespace.instance);
|
|
37
|
+
}
|
|
38
|
+
return castAs<MongoNamespace>(new MongoBoundNamespace(input));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private constructor(input: MongoNamespaceCollectionsInput) {
|
|
42
|
+
super();
|
|
43
|
+
this.id = input.id;
|
|
44
|
+
this.collections = Object.freeze(
|
|
45
|
+
Object.fromEntries(
|
|
46
|
+
Object.entries(input.collections ?? {}).map(([name, c]) => [
|
|
47
|
+
name,
|
|
48
|
+
c instanceof MongoCollection ? c : new MongoCollection(c),
|
|
49
|
+
]),
|
|
50
|
+
),
|
|
51
|
+
);
|
|
52
|
+
Object.defineProperty(this, 'kind', {
|
|
53
|
+
value: MONGO_NAMESPACE_KIND,
|
|
54
|
+
writable: false,
|
|
55
|
+
enumerable: false,
|
|
56
|
+
configurable: true,
|
|
57
|
+
});
|
|
58
|
+
freezeNode(this);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function buildMongoNamespace(input: MongoNamespaceCollectionsInput): MongoNamespace {
|
|
63
|
+
return MongoBoundNamespace.fromCollectionsInput(input);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function buildMongoNamespaceMap(
|
|
67
|
+
namespaces: Readonly<Record<string, Namespace | MongoNamespaceCollectionsInput>>,
|
|
68
|
+
): Readonly<Record<string, MongoNamespace>> {
|
|
69
|
+
return Object.fromEntries(
|
|
70
|
+
Object.entries(namespaces).map(([nsKey, ns]) => [
|
|
71
|
+
nsKey,
|
|
72
|
+
isMaterializedMongoNamespace(ns)
|
|
73
|
+
? blindCast<
|
|
74
|
+
MongoNamespace,
|
|
75
|
+
'a materialised Mongo-family namespace entry in a namespace map is a MongoNamespace'
|
|
76
|
+
>(ns)
|
|
77
|
+
: MongoBoundNamespace.fromCollectionsInput(ns),
|
|
78
|
+
]),
|
|
79
|
+
);
|
|
80
|
+
}
|