@prisma-next/target-mongo 0.4.0-dev.9 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify-mongo-schema-P0TRBJNs.mjs","names":["issues: SchemaIssue[]","collectionChildren: SchemaVerificationNode[]","nodes: SchemaVerificationNode[]","MongoSchemaIRCtor","MongoSchemaCollectionCtor","MongoSchemaIndexCtor","projectedKeys: IndexKey[]","MongoSchemaCollectionOptionsCtor","out: Record<string, unknown>"],"sources":["../src/core/contract-to-schema.ts","../src/core/schema-diff.ts","../src/core/schema-verify/canonicalize-introspection.ts","../src/core/schema-verify/verify-mongo-schema.ts"],"sourcesContent":["import type {\n MongoContract,\n MongoStorageCollection,\n MongoStorageCollectionOptions,\n MongoStorageIndex,\n MongoStorageValidator,\n} from '@prisma-next/mongo-contract';\nimport {\n MongoSchemaCollection,\n MongoSchemaCollectionOptions,\n MongoSchemaIndex,\n MongoSchemaIR,\n MongoSchemaValidator,\n} from '@prisma-next/mongo-schema-ir';\n\nfunction convertIndex(index: MongoStorageIndex): MongoSchemaIndex {\n return new MongoSchemaIndex({\n keys: index.keys,\n unique: index.unique,\n sparse: index.sparse,\n expireAfterSeconds: index.expireAfterSeconds,\n partialFilterExpression: index.partialFilterExpression,\n wildcardProjection: index.wildcardProjection,\n collation: index.collation,\n weights: index.weights,\n default_language: index.default_language,\n language_override: index.language_override,\n });\n}\n\nfunction convertValidator(v: MongoStorageValidator): MongoSchemaValidator {\n return new MongoSchemaValidator({\n jsonSchema: v.jsonSchema,\n validationLevel: v.validationLevel,\n validationAction: v.validationAction,\n });\n}\n\nfunction convertOptions(o: MongoStorageCollectionOptions): MongoSchemaCollectionOptions {\n return new MongoSchemaCollectionOptions(o);\n}\n\nfunction convertCollection(name: string, def: MongoStorageCollection): MongoSchemaCollection {\n const indexes = (def.indexes ?? []).map(convertIndex);\n return new MongoSchemaCollection({\n name,\n indexes,\n ...(def.validator != null && { validator: convertValidator(def.validator) }),\n ...(def.options != null && { options: convertOptions(def.options) }),\n });\n}\n\nexport function contractToMongoSchemaIR(contract: MongoContract | null): MongoSchemaIR {\n if (!contract) {\n return new MongoSchemaIR([]);\n }\n\n const collections = Object.entries(contract.storage.collections).map(([name, def]) =>\n convertCollection(name, def),\n );\n\n return new MongoSchemaIR(collections);\n}\n","import type {\n SchemaIssue,\n SchemaVerificationNode,\n} from '@prisma-next/framework-components/control';\nimport type {\n MongoSchemaCollection,\n MongoSchemaIndex,\n MongoSchemaIR,\n} from '@prisma-next/mongo-schema-ir';\nimport { canonicalize, deepEqual } from '@prisma-next/mongo-schema-ir';\n\nexport function diffMongoSchemas(\n live: MongoSchemaIR,\n expected: MongoSchemaIR,\n strict: boolean,\n): {\n root: SchemaVerificationNode;\n issues: SchemaIssue[];\n counts: { pass: number; warn: number; fail: number; totalNodes: number };\n} {\n const issues: SchemaIssue[] = [];\n const collectionChildren: SchemaVerificationNode[] = [];\n let pass = 0;\n let warn = 0;\n let fail = 0;\n\n const allNames = new Set([...live.collectionNames, ...expected.collectionNames]);\n\n for (const name of [...allNames].sort()) {\n const liveColl = live.collection(name);\n const expectedColl = expected.collection(name);\n\n if (!liveColl && expectedColl) {\n issues.push({\n kind: 'missing_table',\n table: name,\n message: `Collection \"${name}\" is missing from the database`,\n });\n collectionChildren.push({\n status: 'fail',\n kind: 'collection',\n name,\n contractPath: `storage.collections.${name}`,\n code: 'MISSING_COLLECTION',\n message: `Collection \"${name}\" is missing`,\n expected: name,\n actual: null,\n children: [],\n });\n fail++;\n continue;\n }\n\n if (liveColl && !expectedColl) {\n const status = strict ? 'fail' : 'warn';\n issues.push({\n kind: 'extra_table',\n table: name,\n message: `Extra collection \"${name}\" exists in the database but not in the contract`,\n });\n collectionChildren.push({\n status,\n kind: 'collection',\n name,\n contractPath: `storage.collections.${name}`,\n code: 'EXTRA_COLLECTION',\n message: `Extra collection \"${name}\" found`,\n expected: null,\n actual: name,\n children: [],\n });\n if (status === 'fail') fail++;\n else warn++;\n continue;\n }\n\n const lc = liveColl as MongoSchemaCollection;\n const ec = expectedColl as MongoSchemaCollection;\n const indexChildren = diffIndexes(name, lc, ec, strict, issues);\n const validatorChildren = diffValidator(name, lc, ec, strict, issues);\n const optionsChildren = diffOptions(name, lc, ec, strict, issues);\n const children = [...indexChildren, ...validatorChildren, ...optionsChildren];\n\n const worstStatus = children.reduce<'pass' | 'warn' | 'fail'>(\n (s, c) => (c.status === 'fail' ? 'fail' : c.status === 'warn' && s !== 'fail' ? 'warn' : s),\n 'pass',\n );\n\n for (const c of children) {\n if (c.status === 'pass') pass++;\n else if (c.status === 'warn') warn++;\n else fail++;\n }\n\n if (children.length === 0) {\n pass++;\n }\n\n collectionChildren.push({\n status: worstStatus,\n kind: 'collection',\n name,\n contractPath: `storage.collections.${name}`,\n code: worstStatus === 'pass' ? 'MATCH' : 'DRIFT',\n message:\n worstStatus === 'pass' ? `Collection \"${name}\" matches` : `Collection \"${name}\" has drift`,\n expected: name,\n actual: name,\n children,\n });\n }\n\n const rootStatus = fail > 0 ? 'fail' : warn > 0 ? 'warn' : 'pass';\n const totalNodes = pass + warn + fail + collectionChildren.length;\n\n const root: SchemaVerificationNode = {\n status: rootStatus,\n kind: 'root',\n name: 'mongo-schema',\n contractPath: 'storage',\n code: rootStatus === 'pass' ? 'MATCH' : 'DRIFT',\n message: rootStatus === 'pass' ? 'Schema matches' : 'Schema has drift',\n expected: null,\n actual: null,\n children: collectionChildren,\n };\n\n return { root, issues, counts: { pass, warn, fail, totalNodes } };\n}\n\nfunction buildIndexLookupKey(index: MongoSchemaIndex): string {\n const keys = index.keys.map((k) => `${k.field}:${k.direction}`).join(',');\n const opts = [\n index.unique ? 'unique' : '',\n index.sparse ? 'sparse' : '',\n index.expireAfterSeconds != null ? `ttl:${index.expireAfterSeconds}` : '',\n index.partialFilterExpression ? `pfe:${canonicalize(index.partialFilterExpression)}` : '',\n index.wildcardProjection ? `wp:${canonicalize(index.wildcardProjection)}` : '',\n index.collation ? `col:${canonicalize(index.collation)}` : '',\n index.weights ? `wt:${canonicalize(index.weights)}` : '',\n index.default_language ? `dl:${index.default_language}` : '',\n index.language_override ? `lo:${index.language_override}` : '',\n ]\n .filter(Boolean)\n .join(';');\n return opts ? `${keys}|${opts}` : keys;\n}\n\nfunction formatIndexName(index: MongoSchemaIndex): string {\n return index.keys.map((k) => `${k.field}:${k.direction}`).join(', ');\n}\n\nfunction diffIndexes(\n collName: string,\n live: MongoSchemaCollection,\n expected: MongoSchemaCollection,\n strict: boolean,\n issues: SchemaIssue[],\n): SchemaVerificationNode[] {\n const nodes: SchemaVerificationNode[] = [];\n const liveLookup = new Map<string, MongoSchemaIndex>();\n for (const idx of live.indexes) liveLookup.set(buildIndexLookupKey(idx), idx);\n\n const expectedLookup = new Map<string, MongoSchemaIndex>();\n for (const idx of expected.indexes) expectedLookup.set(buildIndexLookupKey(idx), idx);\n\n for (const [key, idx] of expectedLookup) {\n if (liveLookup.has(key)) {\n nodes.push({\n status: 'pass',\n kind: 'index',\n name: formatIndexName(idx),\n contractPath: `storage.collections.${collName}.indexes`,\n code: 'MATCH',\n message: `Index ${formatIndexName(idx)} matches`,\n expected: key,\n actual: key,\n children: [],\n });\n } else {\n issues.push({\n kind: 'index_mismatch',\n table: collName,\n indexOrConstraint: formatIndexName(idx),\n message: `Index ${formatIndexName(idx)} missing on collection \"${collName}\"`,\n });\n nodes.push({\n status: 'fail',\n kind: 'index',\n name: formatIndexName(idx),\n contractPath: `storage.collections.${collName}.indexes`,\n code: 'MISSING_INDEX',\n message: `Index ${formatIndexName(idx)} missing`,\n expected: key,\n actual: null,\n children: [],\n });\n }\n }\n\n for (const [key, idx] of liveLookup) {\n if (!expectedLookup.has(key)) {\n const status = strict ? 'fail' : 'warn';\n issues.push({\n kind: 'extra_index',\n table: collName,\n indexOrConstraint: formatIndexName(idx),\n message: `Extra index ${formatIndexName(idx)} on collection \"${collName}\"`,\n });\n nodes.push({\n status,\n kind: 'index',\n name: formatIndexName(idx),\n contractPath: `storage.collections.${collName}.indexes`,\n code: 'EXTRA_INDEX',\n message: `Extra index ${formatIndexName(idx)}`,\n expected: null,\n actual: key,\n children: [],\n });\n }\n }\n\n return nodes;\n}\n\nfunction diffValidator(\n collName: string,\n live: MongoSchemaCollection,\n expected: MongoSchemaCollection,\n strict: boolean,\n issues: SchemaIssue[],\n): SchemaVerificationNode[] {\n if (!live.validator && !expected.validator) return [];\n\n if (expected.validator && !live.validator) {\n issues.push({\n kind: 'type_missing',\n table: collName,\n message: `Validator missing on collection \"${collName}\"`,\n });\n return [\n {\n status: 'fail',\n kind: 'validator',\n name: 'validator',\n contractPath: `storage.collections.${collName}.validator`,\n code: 'MISSING_VALIDATOR',\n message: 'Validator missing',\n expected: canonicalize(expected.validator.jsonSchema),\n actual: null,\n children: [],\n },\n ];\n }\n\n if (!expected.validator && live.validator) {\n const status = strict ? 'fail' : 'warn';\n issues.push({\n kind: 'extra_validator',\n table: collName,\n message: `Extra validator on collection \"${collName}\"`,\n });\n return [\n {\n status,\n kind: 'validator',\n name: 'validator',\n contractPath: `storage.collections.${collName}.validator`,\n code: 'EXTRA_VALIDATOR',\n message: 'Extra validator found',\n expected: null,\n actual: canonicalize(live.validator.jsonSchema),\n children: [],\n },\n ];\n }\n\n const liveVal = live.validator as NonNullable<typeof live.validator>;\n const expectedVal = expected.validator as NonNullable<typeof expected.validator>;\n const liveSchema = canonicalize(liveVal.jsonSchema);\n const expectedSchema = canonicalize(expectedVal.jsonSchema);\n\n if (\n liveSchema !== expectedSchema ||\n liveVal.validationLevel !== expectedVal.validationLevel ||\n liveVal.validationAction !== expectedVal.validationAction\n ) {\n issues.push({\n kind: 'type_mismatch',\n table: collName,\n expected: expectedSchema,\n actual: liveSchema,\n message: `Validator mismatch on collection \"${collName}\"`,\n });\n return [\n {\n status: 'fail',\n kind: 'validator',\n name: 'validator',\n contractPath: `storage.collections.${collName}.validator`,\n code: 'VALIDATOR_MISMATCH',\n message: 'Validator mismatch',\n expected: {\n jsonSchema: expectedVal.jsonSchema,\n validationLevel: expectedVal.validationLevel,\n validationAction: expectedVal.validationAction,\n },\n actual: {\n jsonSchema: liveVal.jsonSchema,\n validationLevel: liveVal.validationLevel,\n validationAction: liveVal.validationAction,\n },\n children: [],\n },\n ];\n }\n\n return [\n {\n status: 'pass',\n kind: 'validator',\n name: 'validator',\n contractPath: `storage.collections.${collName}.validator`,\n code: 'MATCH',\n message: 'Validator matches',\n expected: expectedSchema,\n actual: liveSchema,\n children: [],\n },\n ];\n}\n\nfunction diffOptions(\n collName: string,\n live: MongoSchemaCollection,\n expected: MongoSchemaCollection,\n strict: boolean,\n issues: SchemaIssue[],\n): SchemaVerificationNode[] {\n if (!live.options && !expected.options) return [];\n\n if (!expected.options && live.options) {\n const status = strict ? 'fail' : 'warn';\n issues.push({\n kind: 'type_mismatch',\n table: collName,\n actual: canonicalize(live.options),\n message: `Extra collection options on \"${collName}\"`,\n });\n return [\n {\n status,\n kind: 'options',\n name: 'options',\n contractPath: `storage.collections.${collName}.options`,\n code: 'EXTRA_OPTIONS',\n message: 'Extra collection options found',\n expected: null,\n actual: live.options,\n children: [],\n },\n ];\n }\n\n if (deepEqual(live.options, expected.options)) {\n return [\n {\n status: 'pass',\n kind: 'options',\n name: 'options',\n contractPath: `storage.collections.${collName}.options`,\n code: 'MATCH',\n message: 'Collection options match',\n expected: canonicalize(expected.options),\n actual: canonicalize(live.options),\n children: [],\n },\n ];\n }\n\n issues.push({\n kind: 'type_mismatch',\n table: collName,\n expected: canonicalize(expected.options),\n actual: canonicalize(live.options),\n message: `Collection options mismatch on \"${collName}\"`,\n });\n return [\n {\n status: 'fail',\n kind: 'options',\n name: 'options',\n contractPath: `storage.collections.${collName}.options`,\n code: 'OPTIONS_MISMATCH',\n message: 'Collection options mismatch',\n expected: expected.options,\n actual: live.options,\n children: [],\n },\n ];\n}\n","/**\n * Canonicalizes a live (introspected) `MongoSchemaIR` against the expected\n * (contract-built) IR before diffing. MongoDB applies server-side defaults\n * to several option/index families that are absent from authored contracts,\n * which would otherwise cause `verifyMongoSchema` to report false-positive\n * drift on a fresh `migration apply`.\n *\n * The normalization is contract-aware where it has to be: server defaults\n * are stripped from the live IR for fields the contract did not specify, so\n * a contract that *does* specify a value still gets compared faithfully.\n *\n * Symmetric defaults — like `changeStreamPreAndPostImages: { enabled: false }`,\n * which is equivalent to \"absent\" on both sides — are stripped from both IRs\n * so either authoring style verifies.\n */\n\nimport type {\n MongoSchemaCollection,\n MongoSchemaCollectionOptions,\n MongoSchemaIndex,\n MongoSchemaIR,\n} from '@prisma-next/mongo-schema-ir';\nimport {\n MongoSchemaCollection as MongoSchemaCollectionCtor,\n MongoSchemaCollectionOptions as MongoSchemaCollectionOptionsCtor,\n MongoSchemaIndex as MongoSchemaIndexCtor,\n MongoSchemaIR as MongoSchemaIRCtor,\n} from '@prisma-next/mongo-schema-ir';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\nexport interface CanonicalizedSchemas {\n readonly live: MongoSchemaIR;\n readonly expected: MongoSchemaIR;\n}\n\nexport function canonicalizeSchemasForVerification(\n live: MongoSchemaIR,\n expected: MongoSchemaIR,\n): CanonicalizedSchemas {\n const expectedByName = new Map<string, MongoSchemaCollection>();\n for (const c of expected.collections) expectedByName.set(c.name, c);\n\n const liveByName = new Map<string, MongoSchemaCollection>();\n for (const c of live.collections) liveByName.set(c.name, c);\n\n const canonicalLive = live.collections.map((c) =>\n canonicalizeLiveCollection(c, expectedByName.get(c.name)),\n );\n const canonicalExpected = expected.collections.map((c) =>\n canonicalizeExpectedCollection(c, liveByName.get(c.name)),\n );\n\n return {\n live: new MongoSchemaIRCtor(canonicalLive),\n expected: new MongoSchemaIRCtor(canonicalExpected),\n };\n}\n\nfunction canonicalizeLiveCollection(\n liveColl: MongoSchemaCollection,\n expectedColl: MongoSchemaCollection | undefined,\n): MongoSchemaCollection {\n const expectedIndexes = expectedColl?.indexes ?? [];\n const indexes = liveColl.indexes.map((idx) =>\n canonicalizeLiveIndex(idx, findExpectedIndexCounterpart(idx, expectedIndexes)),\n );\n\n const options = liveColl.options\n ? canonicalizeLiveOptions(liveColl.options, expectedColl?.options)\n : undefined;\n\n return new MongoSchemaCollectionCtor({\n name: liveColl.name,\n indexes,\n ...ifDefined('validator', liveColl.validator),\n ...ifDefined('options', options),\n });\n}\n\nfunction canonicalizeExpectedCollection(\n expectedColl: MongoSchemaCollection,\n liveColl: MongoSchemaCollection | undefined,\n): MongoSchemaCollection {\n // Symmetric text-index key ordering: a contract-shaped text index preserves\n // the user-authored field order, but the introspected counterpart comes\n // back from MongoDB with `weights` keys in alphabetical order, so we\n // canonicalize both sides to alphabetical text-key order. The order of\n // text fields within the text block is semantically irrelevant — relevance\n // is governed by `weights`, not key order.\n const indexes = expectedColl.indexes.map(canonicalizeTextIndexKeyOrder);\n\n const options = expectedColl.options\n ? canonicalizeExpectedOptions(expectedColl.options, liveColl?.options)\n : undefined;\n\n return new MongoSchemaCollectionCtor({\n name: expectedColl.name,\n indexes,\n ...ifDefined('validator', expectedColl.validator),\n ...ifDefined('options', options),\n });\n}\n\nfunction canonicalizeTextIndexKeyOrder(index: MongoSchemaIndex): MongoSchemaIndex {\n const hasTextKey = index.keys.some((k) => k.direction === 'text');\n if (!hasTextKey) return index;\n return new MongoSchemaIndexCtor({\n keys: sortTextKeys(index.keys),\n unique: index.unique,\n ...ifDefined('sparse', index.sparse),\n ...ifDefined('expireAfterSeconds', index.expireAfterSeconds),\n ...ifDefined('partialFilterExpression', index.partialFilterExpression),\n ...ifDefined('wildcardProjection', index.wildcardProjection),\n ...ifDefined('collation', index.collation),\n ...ifDefined('weights', index.weights),\n ...ifDefined('default_language', index.default_language),\n ...ifDefined('language_override', index.language_override),\n });\n}\n\n/**\n * Returns a copy of `keys` with text-direction entries sorted alphabetically\n * while preserving the relative position of non-text entries. Compound text\n * indexes (`{a: 1, _fts: 'text', _ftsx: 1, b: 1}`) keep their scalar\n * prefix/suffix layout; only the contiguous text block is reordered.\n */\nfunction sortTextKeys(\n keys: ReadonlyArray<{\n readonly field: string;\n readonly direction: 'text' | 1 | -1 | '2dsphere' | '2d' | 'hashed';\n }>,\n): ReadonlyArray<{\n readonly field: string;\n readonly direction: 'text' | 1 | -1 | '2dsphere' | '2d' | 'hashed';\n}> {\n const textEntries = keys.filter((k) => k.direction === 'text');\n if (textEntries.length <= 1) return keys;\n const sortedText = [...textEntries].sort((a, b) => a.field.localeCompare(b.field));\n let textIdx = 0;\n return keys.map((k) => {\n if (k.direction !== 'text') return k;\n const next = sortedText[textIdx++];\n /* v8 ignore next 3 -- @preserve invariant guard: textIdx is always < sortedText.length here because we only consume sortedText for text-direction entries and sortedText is built from the same filter. */\n if (next === undefined) {\n throw new Error('sortTextKeys: text-key counts mismatched');\n }\n return next;\n });\n}\n\nfunction canonicalizeLiveIndex(\n liveIndex: MongoSchemaIndex,\n expectedIndex: MongoSchemaIndex | undefined,\n): MongoSchemaIndex {\n const projectedKeys = sortTextKeys(projectTextIndexKeys(liveIndex));\n const collation = liveIndex.collation\n ? stripUnspecifiedFields(liveIndex.collation, expectedIndex?.collation)\n : liveIndex.collation;\n\n // Text-index server defaults: when the contract did not set\n // `weights`/`default_language`/`language_override`, MongoDB applies\n // `weights = {<field>: 1, ...}` (uniform), `'english'`, and `'language'`\n // respectively. Strip them from live *only* when the live value matches\n // those defaults — preserving non-default live values lets the verifier\n // surface drift when the live index is tampered (e.g. weights tuned\n // out-of-band, custom `default_language`/`language_override`) even though\n // the contract authored neither.\n const weights =\n expectedIndex?.weights === undefined && hasDefaultTextWeights(projectedKeys, liveIndex.weights)\n ? undefined\n : liveIndex.weights;\n const default_language =\n expectedIndex?.default_language === undefined && liveIndex.default_language === 'english'\n ? undefined\n : liveIndex.default_language;\n const language_override =\n expectedIndex?.language_override === undefined && liveIndex.language_override === 'language'\n ? undefined\n : liveIndex.language_override;\n\n return new MongoSchemaIndexCtor({\n keys: projectedKeys,\n unique: liveIndex.unique,\n ...ifDefined('sparse', liveIndex.sparse),\n ...ifDefined('expireAfterSeconds', liveIndex.expireAfterSeconds),\n ...ifDefined('partialFilterExpression', liveIndex.partialFilterExpression),\n ...ifDefined('wildcardProjection', liveIndex.wildcardProjection),\n ...ifDefined('collation', collation),\n ...ifDefined('weights', weights),\n ...ifDefined('default_language', default_language),\n ...ifDefined('language_override', language_override),\n });\n}\n\n/**\n * Locate the contract-side index that corresponds to a live index for the\n * purpose of contract-aware normalization. We deliberately match by the\n * *projected* (contract-shaped) key list — so a live `_fts/_ftsx` index\n * resolves to a contract `{title: 'text', body: 'text'}` index — and pick\n * the first match. Contracts very rarely contain duplicate-key indexes; if\n * we have no counterpart we fall back to no normalization for that index.\n */\nfunction findExpectedIndexCounterpart(\n liveIndex: MongoSchemaIndex,\n expectedIndexes: ReadonlyArray<MongoSchemaIndex>,\n): MongoSchemaIndex | undefined {\n const projectedLiveKeys = sortTextKeys(projectTextIndexKeys(liveIndex));\n const liveKeySig = projectedLiveKeys.map((k) => `${k.field}:${k.direction}`).join(',');\n for (const expected of expectedIndexes) {\n const expectedKeySig = sortTextKeys(expected.keys)\n .map((k) => `${k.field}:${k.direction}`)\n .join(',');\n if (expectedKeySig === liveKeySig) return expected;\n }\n return undefined;\n}\n\n/**\n * MongoDB expands a contract-shaped text index like\n * `[{title: 'text'}, {body: 'text'}]` into its internal weighted vector\n * representation `[{_fts: 'text'}, {_ftsx: 1}]`. We project back to\n * contract-shaped keys via `weights`, iterating in whatever order MongoDB\n * returns them (alphabetical, in practice). `sortTextKeys` is applied\n * downstream to canonicalize the order on both sides, so this projection\n * does not depend on a specific iteration order.\n */\nfunction projectTextIndexKeys(liveIndex: MongoSchemaIndex): ReadonlyArray<{\n readonly field: string;\n readonly direction: 'text' | 1 | -1 | '2dsphere' | '2d' | 'hashed';\n}> {\n const isTextIndex =\n liveIndex.keys.length >= 1 &&\n liveIndex.keys.some((k) => k.field === '_fts' && k.direction === 'text');\n\n if (!isTextIndex || !liveIndex.weights) return liveIndex.keys;\n\n const textKeys = Object.keys(liveIndex.weights).map((field) => ({\n field,\n direction: 'text' as const,\n }));\n\n // Splice the projected text fields into the original `_fts/_ftsx` slot so\n // compound text indexes that mix scalar prefixes *and* suffixes — e.g.\n // `[prefix, _fts, _ftsx, suffix]` — keep their original layout. Flattening\n // scalars first would yield `[prefix, suffix, ...text]`, which `sortTextKeys`\n // (downstream) cannot recover because it only reorders text-direction\n // entries within their existing positions. MongoDB always emits exactly one\n // `_fts`/`_ftsx` pair per index, so we don't need to guard against\n // duplicates.\n type IndexKey = (typeof liveIndex.keys)[number];\n const projectedKeys: IndexKey[] = [];\n for (const key of liveIndex.keys) {\n if (key.field === '_ftsx') continue;\n if (key.field === '_fts') {\n projectedKeys.push(...textKeys);\n continue;\n }\n projectedKeys.push(key);\n }\n return projectedKeys;\n}\n\n/**\n * MongoDB's server-default `weights` for an authored-without-weights text\n * index assigns `1` to every text-direction field. Returns `true` only when\n * `liveWeights` is exactly that uniform shape (every projected text-direction\n * key weighted at `1`) so the canonicalizer leaves non-default weights —\n * including out-of-band relevance tweaks — visible to the verifier.\n *\n * `projectTextIndexKeys` derives text-direction keys from the live weights\n * map, so the count is guaranteed to match; we only have to check the value\n * shape.\n */\nfunction hasDefaultTextWeights(\n projectedKeys: ReadonlyArray<{\n readonly field: string;\n readonly direction: 'text' | 1 | -1 | '2dsphere' | '2d' | 'hashed';\n }>,\n liveWeights: MongoSchemaIndex['weights'],\n): boolean {\n if (liveWeights === undefined) return false;\n const textFields = projectedKeys.filter((k) => k.direction === 'text').map((k) => k.field);\n return textFields.every((field) => liveWeights[field] === 1);\n}\n\nfunction canonicalizeLiveOptions(\n liveOptions: MongoSchemaCollectionOptions,\n expectedOptions: MongoSchemaCollectionOptions | undefined,\n): MongoSchemaCollectionOptions | undefined {\n const collation = liveOptions.collation\n ? stripUnspecifiedFields(liveOptions.collation, expectedOptions?.collation)\n : undefined;\n\n // Timeseries: drop `bucketMaxSpanSeconds` (and any other server-applied\n // extras) when the contract did not specify them.\n const timeseries = liveOptions.timeseries\n ? (stripUnspecifiedFields(\n liveOptions.timeseries as Record<string, unknown>,\n expectedOptions?.timeseries as Record<string, unknown> | undefined,\n ) as MongoSchemaCollectionOptions['timeseries'])\n : undefined;\n\n // ClusteredIndex: drop `key`, `unique`, `v` and any other server-applied\n // extras when the contract did not specify them.\n const clusteredIndex = liveOptions.clusteredIndex\n ? (stripUnspecifiedFields(\n liveOptions.clusteredIndex as Record<string, unknown>,\n expectedOptions?.clusteredIndex as Record<string, unknown> | undefined,\n ) as MongoSchemaCollectionOptions['clusteredIndex'])\n : undefined;\n\n // changeStreamPreAndPostImages: `{enabled: false}` is equivalent to\n // \"absent\". Strip it from live so it round-trips with a contract that\n // omits the field, and is symmetric with the expected-side stripping.\n const changeStreamPreAndPostImages = isDisabledChangeStream(\n liveOptions.changeStreamPreAndPostImages,\n )\n ? undefined\n : liveOptions.changeStreamPreAndPostImages;\n\n const hasMeaningful =\n liveOptions.capped || timeseries || collation || changeStreamPreAndPostImages || clusteredIndex;\n if (!hasMeaningful) return undefined;\n\n return new MongoSchemaCollectionOptionsCtor({\n ...ifDefined('capped', liveOptions.capped),\n ...ifDefined('timeseries', timeseries),\n ...ifDefined('collation', collation),\n ...ifDefined('changeStreamPreAndPostImages', changeStreamPreAndPostImages),\n ...ifDefined('clusteredIndex', clusteredIndex),\n });\n}\n\nfunction canonicalizeExpectedOptions(\n expectedOptions: MongoSchemaCollectionOptions,\n _liveOptions: MongoSchemaCollectionOptions | undefined,\n): MongoSchemaCollectionOptions | undefined {\n // Symmetric: a contract `{enabled: false}` is equivalent to absent.\n const changeStreamPreAndPostImages = isDisabledChangeStream(\n expectedOptions.changeStreamPreAndPostImages,\n )\n ? undefined\n : expectedOptions.changeStreamPreAndPostImages;\n\n const hasMeaningful =\n expectedOptions.capped ||\n expectedOptions.timeseries ||\n expectedOptions.collation ||\n changeStreamPreAndPostImages ||\n expectedOptions.clusteredIndex;\n if (!hasMeaningful) return undefined;\n\n return new MongoSchemaCollectionOptionsCtor({\n ...ifDefined('capped', expectedOptions.capped),\n ...ifDefined('timeseries', expectedOptions.timeseries),\n ...ifDefined('collation', expectedOptions.collation),\n ...ifDefined('changeStreamPreAndPostImages', changeStreamPreAndPostImages),\n ...ifDefined('clusteredIndex', expectedOptions.clusteredIndex),\n });\n}\n\nfunction isDisabledChangeStream(value: { enabled: boolean } | undefined): boolean {\n return value !== undefined && value.enabled === false;\n}\n\n/**\n * Returns a copy of `live` containing only the keys that `expected` defines.\n * Used for option families whose individual sub-fields are server-extended\n * with platform defaults (collation, timeseries, clusteredIndex), so the\n * verifier should compare only what the contract actually authored.\n *\n * When `expected` is `undefined` — i.e. the contract authored nothing for\n * this whole option family but the live IR has it — we return `live`\n * unchanged so the verifier still sees the entire live block and can\n * surface it as drift. (Returning `undefined` here would silently strip a\n * server-attached collation/timeseries/clusteredIndex that the contract\n * never asked for, hiding real drift.)\n */\nfunction stripUnspecifiedFields(\n live: Record<string, unknown>,\n expected: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n if (expected === undefined) return live;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(expected)) {\n if (Object.hasOwn(live, key)) out[key] = live[key];\n }\n return out;\n}\n","import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n OperationContext,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport { VERIFY_CODE_SCHEMA_FAILURE } from '@prisma-next/framework-components/control';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { contractToMongoSchemaIR } from '../contract-to-schema';\nimport { diffMongoSchemas } from '../schema-diff';\nimport { canonicalizeSchemasForVerification } from './canonicalize-introspection';\n\nexport interface VerifyMongoSchemaOptions {\n readonly contract: MongoContract;\n readonly schema: MongoSchemaIR;\n readonly strict: boolean;\n readonly context?: OperationContext;\n /**\n * Active framework components participating in this composition. Mongo\n * verification does not currently consult them, but the parameter exists\n * for parity with `verifySqlSchema` so callers can pass the same envelope.\n */\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', string>>;\n}\n\nexport function verifyMongoSchema(options: VerifyMongoSchemaOptions): VerifyDatabaseSchemaResult {\n const { contract, schema, strict, context } = options;\n const startTime = Date.now();\n\n const expectedIR = contractToMongoSchemaIR(contract);\n // Strip server-applied defaults (and authored equivalents) before diffing so\n // the verifier compares like-with-like — see `canonicalize-introspection.ts`.\n const { live: canonicalLive, expected: canonicalExpected } = canonicalizeSchemasForVerification(\n schema,\n expectedIR,\n );\n const { root, issues, counts } = diffMongoSchemas(canonicalLive, canonicalExpected, strict);\n\n const ok = counts.fail === 0;\n const profileHash = typeof contract.profileHash === 'string' ? contract.profileHash : '';\n\n return {\n ok,\n ...ifDefined('code', ok ? undefined : VERIFY_CODE_SCHEMA_FAILURE),\n summary: ok ? 'Schema matches contract' : `Schema verification found ${counts.fail} issue(s)`,\n contract: {\n storageHash: contract.storage.storageHash,\n ...(profileHash ? { profileHash } : {}),\n },\n target: { expected: contract.target },\n schema: { issues, root, counts },\n meta: {\n strict,\n ...ifDefined('contractPath', context?.contractPath),\n ...ifDefined('configPath', context?.configPath),\n },\n timings: { total: Date.now() - startTime },\n };\n}\n"],"mappings":";;;;;AAeA,SAAS,aAAa,OAA4C;AAChE,QAAO,IAAI,iBAAiB;EAC1B,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd,oBAAoB,MAAM;EAC1B,yBAAyB,MAAM;EAC/B,oBAAoB,MAAM;EAC1B,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,kBAAkB,MAAM;EACxB,mBAAmB,MAAM;EAC1B,CAAC;;AAGJ,SAAS,iBAAiB,GAAgD;AACxE,QAAO,IAAI,qBAAqB;EAC9B,YAAY,EAAE;EACd,iBAAiB,EAAE;EACnB,kBAAkB,EAAE;EACrB,CAAC;;A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Q,WAAW,iBAAiB,eAAe,mBAAmB,OAAO;CAE3F,MAAM,KAAK,OAAO,SAAS;CAC3B,MAAM,cAAc,OAAO,SAAS,gBAAgB,WAAW,SAAS,cAAc;AAEtF,QAAO;EACL;EACA,GAAG,UAAU,QAAQ,KAAK,SAAY,2BAA2B;EACjE,SAAS,KAAK,4BAA4B,6BAA6B,OAAO,KAAK;EACnF,UAAU;GACR,aAAa,SAAS,QAAQ;GAC9B,GAAI,cAAc,EAAE,aAAa,GAAG,EAAE;GACvC;EACD,QAAQ,EAAE,UAAU,SAAS,QAAQ;EACrC,QAAQ;GAAE;GAAQ;GAAM;GAAQ;EAChC,MAAM;GACJ;GACA,GAAG,UAAU,gBAAgB,SAAS,aAAa;GACnD,GAAG,UAAU,cAAc,SAAS,WAAW;GAChD;EACD,SAAS,EAAE,OAAO,KAAK,KAAK,GAAG,WAAW;EAC3C"}
package/package.json CHANGED
@@ -1,22 +1,23 @@
1
1
  {
2
2
  "name": "@prisma-next/target-mongo",
3
- "version": "0.4.0-dev.9",
3
+ "version": "0.4.2",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "MongoDB target pack for Prisma Next",
7
7
  "dependencies": {
8
8
  "arktype": "^2.1.29",
9
9
  "mongodb": "^6.16.0",
10
- "@prisma-next/contract": "0.4.0-dev.9",
11
- "@prisma-next/migration-tools": "0.4.0-dev.9",
12
- "@prisma-next/errors": "0.4.0-dev.9",
13
- "@prisma-next/mongo-contract": "0.4.0-dev.9",
14
- "@prisma-next/mongo-lowering": "0.4.0-dev.9",
15
- "@prisma-next/mongo-schema-ir": "0.4.0-dev.9",
16
- "@prisma-next/framework-components": "0.4.0-dev.9",
17
- "@prisma-next/mongo-query-ast": "0.4.0-dev.9",
18
- "@prisma-next/utils": "0.4.0-dev.9",
19
- "@prisma-next/mongo-value": "0.4.0-dev.9"
10
+ "@prisma-next/errors": "0.4.2",
11
+ "@prisma-next/contract": "0.4.2",
12
+ "@prisma-next/framework-components": "0.4.2",
13
+ "@prisma-next/migration-tools": "0.4.2",
14
+ "@prisma-next/ts-render": "0.4.2",
15
+ "@prisma-next/mongo-contract": "0.4.2",
16
+ "@prisma-next/mongo-query-ast": "0.4.2",
17
+ "@prisma-next/mongo-lowering": "0.4.2",
18
+ "@prisma-next/mongo-schema-ir": "0.4.2",
19
+ "@prisma-next/mongo-value": "0.4.2",
20
+ "@prisma-next/utils": "0.4.2"
20
21
  },
21
22
  "devDependencies": {
22
23
  "mongodb-memory-server": "10.4.3",
@@ -24,9 +25,9 @@
24
25
  "tsdown": "0.18.4",
25
26
  "typescript": "5.9.3",
26
27
  "vitest": "4.0.17",
27
- "@prisma-next/test-utils": "0.0.1",
28
+ "@prisma-next/tsconfig": "0.0.0",
28
29
  "@prisma-next/tsdown": "0.0.0",
29
- "@prisma-next/tsconfig": "0.0.0"
30
+ "@prisma-next/test-utils": "0.0.1"
30
31
  },
31
32
  "files": [
32
33
  "dist",
@@ -37,6 +38,7 @@
37
38
  "./control": "./dist/control.mjs",
38
39
  "./migration": "./dist/migration.mjs",
39
40
  "./pack": "./dist/pack.mjs",
41
+ "./schema-verify": "./dist/schema-verify.mjs",
40
42
  "./package.json": "./package.json"
41
43
  },
42
44
  "repository": {
@@ -47,6 +49,9 @@
47
49
  "main": "./dist/pack.mjs",
48
50
  "module": "./dist/pack.mjs",
49
51
  "types": "./dist/pack.d.mts",
52
+ "prismaNext": {
53
+ "minServerVersion": "6.0"
54
+ },
50
55
  "scripts": {
51
56
  "build": "tsdown",
52
57
  "test": "vitest run --passWithNoTests",
@@ -243,12 +243,11 @@ export class MongoMigrationPlanner implements MigrationPlanner<'mongo', 'mongo'>
243
243
  /**
244
244
  * Produce an empty `migration.ts` authoring surface for `migration new`.
245
245
  *
246
- * Mongo is a class-flow target, so the "empty migration" is a
247
- * `PlannerProducedMongoMigration` with no operations; `renderTypeScript()`
248
- * emits a stub class with the correct `from`/`to` metadata that the user
249
- * then fills in with operations. The contract path on the context is
250
- * unused — Mongo's emitted source does not import from the generated
251
- * contract `.d.ts`.
246
+ * The "empty migration" is a `PlannerProducedMongoMigration` with no
247
+ * operations; `renderTypeScript()` emits a stub class with the correct
248
+ * `from`/`to` metadata that the user then fills in with operations. The
249
+ * contract path on the context is unused Mongo's emitted source does
250
+ * not import from the generated contract `.d.ts`.
252
251
  */
253
252
  emptyMigration(context: MigrationScaffoldContext): MigrationPlanWithAuthoringSurface {
254
253
  return new PlannerProducedMongoMigration([], {
@@ -8,7 +8,9 @@ import type {
8
8
  MigrationRunnerExecutionChecks,
9
9
  MigrationRunnerFailure,
10
10
  MigrationRunnerResult,
11
+ OperationContext,
11
12
  } from '@prisma-next/framework-components/control';
13
+ import type { MongoContract } from '@prisma-next/mongo-contract';
12
14
  import type { MongoAdapter, MongoDriver } from '@prisma-next/mongo-lowering';
13
15
  import type {
14
16
  AnyMongoMigrationOperation,
@@ -19,21 +21,13 @@ import type {
19
21
  MongoMigrationCheck,
20
22
  MongoMigrationPlanOperation,
21
23
  } from '@prisma-next/mongo-query-ast/control';
24
+ import type { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';
22
25
  import { notOk, ok } from '@prisma-next/utils/result';
23
-
24
- const READ_ONLY_CHECK_COMMAND_KINDS: ReadonlySet<string> = new Set(['aggregate', 'rawAggregate']);
25
-
26
- function hasProfileHash(value: unknown): value is { readonly profileHash: string } {
27
- return (
28
- typeof value === 'object' &&
29
- value !== null &&
30
- Object.hasOwn(value, 'profileHash') &&
31
- typeof (value as { profileHash: unknown }).profileHash === 'string'
32
- );
33
- }
34
-
35
26
  import { FilterEvaluator } from './filter-evaluator';
36
27
  import { deserializeMongoOps } from './mongo-ops-serializer';
28
+ import { verifyMongoSchema } from './schema-verify/verify-mongo-schema';
29
+
30
+ const READ_ONLY_CHECK_COMMAND_KINDS: ReadonlySet<string> = new Set(['aggregate', 'rawAggregate']);
37
31
 
38
32
  export interface MarkerOperations {
39
33
  readMarker(): Promise<ContractMarkerRecord | null>;
@@ -58,6 +52,21 @@ export interface MongoRunnerDependencies {
58
52
  readonly adapter: MongoAdapter;
59
53
  readonly driver: MongoDriver;
60
54
  readonly markerOps: MarkerOperations;
55
+ readonly introspectSchema: () => Promise<MongoSchemaIR>;
56
+ }
57
+
58
+ export interface MongoMigrationRunnerExecuteOptions {
59
+ readonly plan: MigrationPlan;
60
+ readonly destinationContract: MongoContract;
61
+ readonly policy: MigrationOperationPolicy;
62
+ readonly callbacks?: {
63
+ onOperationStart?(op: MigrationPlanOperation): void;
64
+ onOperationComplete?(op: MigrationPlanOperation): void;
65
+ };
66
+ readonly executionChecks?: MigrationRunnerExecutionChecks;
67
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;
68
+ readonly strictVerification?: boolean;
69
+ readonly context?: OperationContext;
61
70
  }
62
71
 
63
72
  function runnerFailure(
@@ -75,17 +84,7 @@ function runnerFailure(
75
84
  export class MongoMigrationRunner {
76
85
  constructor(private readonly deps: MongoRunnerDependencies) {}
77
86
 
78
- async execute(options: {
79
- readonly plan: MigrationPlan;
80
- readonly destinationContract: unknown;
81
- readonly policy: MigrationOperationPolicy;
82
- readonly callbacks?: {
83
- onOperationStart?(op: MigrationPlanOperation): void;
84
- onOperationComplete?(op: MigrationPlanOperation): void;
85
- };
86
- readonly executionChecks?: MigrationRunnerExecutionChecks;
87
- readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;
88
- }): Promise<MigrationRunnerResult> {
87
+ async execute(options: MongoMigrationRunnerExecuteOptions): Promise<MigrationRunnerResult> {
89
88
  const { commandExecutor, inspectionExecutor, adapter, driver, markerOps } = this.deps;
90
89
  const operations = deserializeMongoOps(options.plan.operations as readonly unknown[]);
91
90
 
@@ -176,9 +175,7 @@ export class MongoMigrationRunner {
176
175
  }
177
176
 
178
177
  const destination = options.plan.destination;
179
- const profileHash = hasProfileHash(options.destinationContract)
180
- ? options.destinationContract.profileHash
181
- : destination.storageHash;
178
+ const profileHash = options.destinationContract.profileHash ?? destination.storageHash;
182
179
 
183
180
  if (
184
181
  operationsExecuted === 0 &&
@@ -188,6 +185,21 @@ export class MongoMigrationRunner {
188
185
  return ok({ operationsPlanned: operations.length, operationsExecuted });
189
186
  }
190
187
 
188
+ const liveSchema = await this.deps.introspectSchema();
189
+ const verifyResult = verifyMongoSchema({
190
+ contract: options.destinationContract,
191
+ schema: liveSchema,
192
+ strict: options.strictVerification ?? true,
193
+ frameworkComponents: options.frameworkComponents,
194
+ ...(options.context ? { context: options.context } : {}),
195
+ });
196
+ if (!verifyResult.ok) {
197
+ return runnerFailure('SCHEMA_VERIFY_FAILED', verifyResult.summary, {
198
+ why: 'The resulting database schema does not satisfy the destination contract.',
199
+ meta: { issues: verifyResult.schema.issues },
200
+ });
201
+ }
202
+
191
203
  if (existingMarker) {
192
204
  const updated = await markerOps.updateMarker(existingMarker.storageHash, {
193
205
  storageHash: destination.storageHash,
@@ -1,9 +1,32 @@
1
- import type { MigrationOperationClass } from '@prisma-next/framework-components/control';
1
+ /**
2
+ * Mongo migration IR: one concrete `*Call` class per pure factory under
3
+ * `migration-factories.ts`, plus a shared `OpFactoryCallNode` abstract
4
+ * base. Every call class carries the literal arguments its backing
5
+ * factory would receive, computes a human-readable `label` in its
6
+ * constructor, and implements two polymorphic hooks:
7
+ *
8
+ * - `toOp()` — converts the IR node to a runtime
9
+ * `MongoMigrationPlanOperation` by delegating to the matching pure
10
+ * factory in `migration-factories.ts`.
11
+ * - `renderTypeScript()` / `importRequirements()` — inherited from
12
+ * `TsExpression`. Used by `renderCallsToTypeScript` to emit the call
13
+ * as a TypeScript expression inside the scaffolded `migration.ts`.
14
+ *
15
+ * The abstract base and all concrete classes are package-private.
16
+ * External consumers see only the framework-level `OpFactoryCall`
17
+ * interface and the `OpFactoryCall` union.
18
+ */
19
+
20
+ import type {
21
+ OpFactoryCall as FrameworkOpFactoryCall,
22
+ MigrationOperationClass,
23
+ } from '@prisma-next/framework-components/control';
2
24
  import type {
3
25
  CollModOptions,
4
26
  CreateCollectionOptions,
5
27
  CreateIndexOptions,
6
28
  MongoIndexKey,
29
+ MongoMigrationPlanOperation,
7
30
  } from '@prisma-next/mongo-query-ast/control';
8
31
  import type {
9
32
  MongoSchemaCollection,
@@ -11,6 +34,14 @@ import type {
11
34
  MongoSchemaIndex,
12
35
  MongoSchemaValidator,
13
36
  } from '@prisma-next/mongo-schema-ir';
37
+ import { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';
38
+ import {
39
+ collMod,
40
+ createCollection,
41
+ createIndex,
42
+ dropCollection,
43
+ dropIndex,
44
+ } from './migration-factories';
14
45
 
15
46
  export interface CollModMeta {
16
47
  readonly id?: string;
@@ -18,19 +49,17 @@ export interface CollModMeta {
18
49
  readonly operationClass?: MigrationOperationClass;
19
50
  }
20
51
 
21
- export interface OpFactoryCallVisitor<R> {
22
- createIndex(call: CreateIndexCall): R;
23
- dropIndex(call: DropIndexCall): R;
24
- createCollection(call: CreateCollectionCall): R;
25
- dropCollection(call: DropCollectionCall): R;
26
- collMod(call: CollModCall): R;
27
- }
52
+ const TARGET_MIGRATION_MODULE = '@prisma-next/target-mongo/migration';
28
53
 
29
- abstract class OpFactoryCallNode {
30
- abstract readonly factory: string;
54
+ abstract class OpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {
55
+ abstract readonly factoryName: string;
31
56
  abstract readonly operationClass: MigrationOperationClass;
32
57
  abstract readonly label: string;
33
- abstract accept<R>(visitor: OpFactoryCallVisitor<R>): R;
58
+ abstract toOp(): MongoMigrationPlanOperation;
59
+
60
+ importRequirements(): readonly ImportRequirement[] {
61
+ return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];
62
+ }
34
63
 
35
64
  protected freeze(): void {
36
65
  Object.freeze(this);
@@ -42,7 +71,7 @@ function formatKeys(keys: ReadonlyArray<MongoIndexKey>): string {
42
71
  }
43
72
 
44
73
  export class CreateIndexCall extends OpFactoryCallNode {
45
- readonly factory = 'createIndex' as const;
74
+ readonly factoryName = 'createIndex' as const;
46
75
  readonly operationClass = 'additive' as const;
47
76
  readonly collection: string;
48
77
  readonly keys: ReadonlyArray<MongoIndexKey>;
@@ -62,13 +91,19 @@ export class CreateIndexCall extends OpFactoryCallNode {
62
91
  this.freeze();
63
92
  }
64
93
 
65
- accept<R>(visitor: OpFactoryCallVisitor<R>): R {
66
- return visitor.createIndex(this);
94
+ toOp(): MongoMigrationPlanOperation {
95
+ return createIndex(this.collection, this.keys, this.options);
96
+ }
97
+
98
+ renderTypeScript(): string {
99
+ return this.options
100
+ ? `createIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)}, ${jsonToTsSource(this.options)})`
101
+ : `createIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)})`;
67
102
  }
68
103
  }
69
104
 
70
105
  export class DropIndexCall extends OpFactoryCallNode {
71
- readonly factory = 'dropIndex' as const;
106
+ readonly factoryName = 'dropIndex' as const;
72
107
  readonly operationClass = 'destructive' as const;
73
108
  readonly collection: string;
74
109
  readonly keys: ReadonlyArray<MongoIndexKey>;
@@ -82,13 +117,17 @@ export class DropIndexCall extends OpFactoryCallNode {
82
117
  this.freeze();
83
118
  }
84
119
 
85
- accept<R>(visitor: OpFactoryCallVisitor<R>): R {
86
- return visitor.dropIndex(this);
120
+ toOp(): MongoMigrationPlanOperation {
121
+ return dropIndex(this.collection, this.keys);
122
+ }
123
+
124
+ renderTypeScript(): string {
125
+ return `dropIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)})`;
87
126
  }
88
127
  }
89
128
 
90
129
  export class CreateCollectionCall extends OpFactoryCallNode {
91
- readonly factory = 'createCollection' as const;
130
+ readonly factoryName = 'createCollection' as const;
92
131
  readonly operationClass = 'additive' as const;
93
132
  readonly collection: string;
94
133
  readonly options: CreateCollectionOptions | undefined;
@@ -102,13 +141,19 @@ export class CreateCollectionCall extends OpFactoryCallNode {
102
141
  this.freeze();
103
142
  }
104
143
 
105
- accept<R>(visitor: OpFactoryCallVisitor<R>): R {
106
- return visitor.createCollection(this);
144
+ toOp(): MongoMigrationPlanOperation {
145
+ return createCollection(this.collection, this.options);
146
+ }
147
+
148
+ renderTypeScript(): string {
149
+ return this.options
150
+ ? `createCollection(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)})`
151
+ : `createCollection(${jsonToTsSource(this.collection)})`;
107
152
  }
108
153
  }
109
154
 
110
155
  export class DropCollectionCall extends OpFactoryCallNode {
111
- readonly factory = 'dropCollection' as const;
156
+ readonly factoryName = 'dropCollection' as const;
112
157
  readonly operationClass = 'destructive' as const;
113
158
  readonly collection: string;
114
159
  readonly label: string;
@@ -120,13 +165,17 @@ export class DropCollectionCall extends OpFactoryCallNode {
120
165
  this.freeze();
121
166
  }
122
167
 
123
- accept<R>(visitor: OpFactoryCallVisitor<R>): R {
124
- return visitor.dropCollection(this);
168
+ toOp(): MongoMigrationPlanOperation {
169
+ return dropCollection(this.collection);
170
+ }
171
+
172
+ renderTypeScript(): string {
173
+ return `dropCollection(${jsonToTsSource(this.collection)})`;
125
174
  }
126
175
  }
127
176
 
128
177
  export class CollModCall extends OpFactoryCallNode {
129
- readonly factory = 'collMod' as const;
178
+ readonly factoryName = 'collMod' as const;
130
179
  readonly collection: string;
131
180
  readonly options: CollModOptions;
132
181
  readonly meta: CollModMeta | undefined;
@@ -143,8 +192,14 @@ export class CollModCall extends OpFactoryCallNode {
143
192
  this.freeze();
144
193
  }
145
194
 
146
- accept<R>(visitor: OpFactoryCallVisitor<R>): R {
147
- return visitor.collMod(this);
195
+ toOp(): MongoMigrationPlanOperation {
196
+ return collMod(this.collection, this.options, this.meta);
197
+ }
198
+
199
+ renderTypeScript(): string {
200
+ return this.meta
201
+ ? `collMod(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)}, ${jsonToTsSource(this.meta)})`
202
+ : `collMod(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)})`;
148
203
  }
149
204
  }
150
205
 
@@ -1,39 +1,6 @@
1
1
  import type { MongoMigrationPlanOperation } from '@prisma-next/mongo-query-ast/control';
2
- import {
3
- collMod,
4
- createCollection,
5
- createIndex,
6
- dropCollection,
7
- dropIndex,
8
- } from './migration-factories';
9
- import type {
10
- CollModCall,
11
- CreateCollectionCall,
12
- CreateIndexCall,
13
- DropCollectionCall,
14
- DropIndexCall,
15
- OpFactoryCall,
16
- OpFactoryCallVisitor,
17
- } from './op-factory-call';
18
-
19
- const renderVisitor: OpFactoryCallVisitor<MongoMigrationPlanOperation> = {
20
- createIndex(call: CreateIndexCall) {
21
- return createIndex(call.collection, call.keys, call.options);
22
- },
23
- dropIndex(call: DropIndexCall) {
24
- return dropIndex(call.collection, call.keys);
25
- },
26
- createCollection(call: CreateCollectionCall) {
27
- return createCollection(call.collection, call.options);
28
- },
29
- dropCollection(call: DropCollectionCall) {
30
- return dropCollection(call.collection);
31
- },
32
- collMod(call: CollModCall) {
33
- return collMod(call.collection, call.options, call.meta);
34
- },
35
- };
2
+ import type { OpFactoryCall } from './op-factory-call';
36
3
 
37
4
  export function renderOps(calls: ReadonlyArray<OpFactoryCall>): MongoMigrationPlanOperation[] {
38
- return calls.map((call) => call.accept(renderVisitor));
5
+ return calls.map((call) => call.toOp());
39
6
  }