@prisma-next/target-mongo 0.8.0 → 0.9.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/control.d.mts +168 -101
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +1194 -1138
- package/dist/control.mjs.map +1 -1
- package/dist/{migration-factories-ZBsWqXt-.mjs → migration-factories-BRBKKZia.mjs} +1 -1
- package/dist/{migration-factories-ZBsWqXt-.mjs.map → migration-factories-BRBKKZia.mjs.map} +1 -1
- package/dist/migration.d.mts +2 -2
- package/dist/migration.mjs +1 -1
- package/dist/{op-factory-call-9z5D19cP.d.mts → op-factory-call-BC-llGKt.d.mts} +2 -2
- package/dist/{op-factory-call-9z5D19cP.d.mts.map → op-factory-call-BC-llGKt.d.mts.map} +1 -1
- package/package.json +21 -19
- package/src/core/control-target.ts +192 -0
- package/src/core/mongo-planner.ts +1 -1
- package/src/core/mongo-runner.ts +3 -45
- package/src/core/mongo-target-contract-serializer.ts +73 -0
- package/src/core/mongo-target-contract.ts +15 -0
- package/src/core/mongo-target-database.ts +82 -0
- package/src/core/mongo-target-schema-verifier.ts +54 -0
- package/src/exports/control.ts +8 -9
- package/dist/schema-verify.d.mts +0 -22
- package/dist/schema-verify.d.mts.map +0 -1
- package/dist/schema-verify.mjs +0 -2
- package/dist/verify-mongo-schema-DlPXaotB.mjs +0 -578
- package/dist/verify-mongo-schema-DlPXaotB.mjs.map +0 -1
- package/src/core/contract-to-schema.ts +0 -63
- package/src/core/ddl-formatter.ts +0 -112
- package/src/core/marker-ledger.ts +0 -232
- package/src/core/schema-diff.ts +0 -402
- package/src/core/schema-verify/canonicalize-introspection.ts +0 -389
- package/src/core/schema-verify/verify-mongo-schema.ts +0 -60
- package/src/exports/schema-verify.ts +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"verify-mongo-schema-DlPXaotB.mjs","names":["MongoSchemaIRCtor","MongoSchemaCollectionCtor","MongoSchemaIndexCtor","MongoSchemaCollectionOptionsCtor"],"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;CAChE,OAAO,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;CACxE,OAAO,IAAI,qBAAqB;EAC9B,YAAY,EAAE;EACd,iBAAiB,EAAE;EACnB,kBAAkB,EAAE;EACrB,CAAC;;AAGJ,SAAS,eAAe,GAAgE;CACtF,OAAO,IAAI,6BAA6B,EAAE;;AAG5C,SAAS,kBAAkB,MAAc,KAAoD;CAE3F,OAAO,IAAI,sBAAsB;EAC/B;EACA,UAHe,IAAI,WAAW,EAAE,EAAE,IAAI,aAG/B;EACP,GAAI,IAAI,aAAa,QAAQ,EAAE,WAAW,iBAAiB,IAAI,UAAU,EAAE;EAC3E,GAAI,IAAI,WAAW,QAAQ,EAAE,SAAS,eAAe,IAAI,QAAQ,EAA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AAK,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"}
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
MongoContract,
|
|
3
|
-
MongoStorageCollection,
|
|
4
|
-
MongoStorageCollectionOptions,
|
|
5
|
-
MongoStorageIndex,
|
|
6
|
-
MongoStorageValidator,
|
|
7
|
-
} from '@prisma-next/mongo-contract';
|
|
8
|
-
import {
|
|
9
|
-
MongoSchemaCollection,
|
|
10
|
-
MongoSchemaCollectionOptions,
|
|
11
|
-
MongoSchemaIndex,
|
|
12
|
-
MongoSchemaIR,
|
|
13
|
-
MongoSchemaValidator,
|
|
14
|
-
} from '@prisma-next/mongo-schema-ir';
|
|
15
|
-
|
|
16
|
-
function convertIndex(index: MongoStorageIndex): MongoSchemaIndex {
|
|
17
|
-
return new MongoSchemaIndex({
|
|
18
|
-
keys: index.keys,
|
|
19
|
-
unique: index.unique,
|
|
20
|
-
sparse: index.sparse,
|
|
21
|
-
expireAfterSeconds: index.expireAfterSeconds,
|
|
22
|
-
partialFilterExpression: index.partialFilterExpression,
|
|
23
|
-
wildcardProjection: index.wildcardProjection,
|
|
24
|
-
collation: index.collation,
|
|
25
|
-
weights: index.weights,
|
|
26
|
-
default_language: index.default_language,
|
|
27
|
-
language_override: index.language_override,
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function convertValidator(v: MongoStorageValidator): MongoSchemaValidator {
|
|
32
|
-
return new MongoSchemaValidator({
|
|
33
|
-
jsonSchema: v.jsonSchema,
|
|
34
|
-
validationLevel: v.validationLevel,
|
|
35
|
-
validationAction: v.validationAction,
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function convertOptions(o: MongoStorageCollectionOptions): MongoSchemaCollectionOptions {
|
|
40
|
-
return new MongoSchemaCollectionOptions(o);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function convertCollection(name: string, def: MongoStorageCollection): MongoSchemaCollection {
|
|
44
|
-
const indexes = (def.indexes ?? []).map(convertIndex);
|
|
45
|
-
return new MongoSchemaCollection({
|
|
46
|
-
name,
|
|
47
|
-
indexes,
|
|
48
|
-
...(def.validator != null && { validator: convertValidator(def.validator) }),
|
|
49
|
-
...(def.options != null && { options: convertOptions(def.options) }),
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export function contractToMongoSchemaIR(contract: MongoContract | null): MongoSchemaIR {
|
|
54
|
-
if (!contract) {
|
|
55
|
-
return new MongoSchemaIR([]);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const collections = Object.entries(contract.storage.collections).map(([name, def]) =>
|
|
59
|
-
convertCollection(name, def),
|
|
60
|
-
);
|
|
61
|
-
|
|
62
|
-
return new MongoSchemaIR(collections);
|
|
63
|
-
}
|
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
import type { MigrationPlanOperation } from '@prisma-next/framework-components/control';
|
|
2
|
-
import type {
|
|
3
|
-
CollModCommand,
|
|
4
|
-
CreateCollectionCommand,
|
|
5
|
-
CreateIndexCommand,
|
|
6
|
-
DropCollectionCommand,
|
|
7
|
-
DropIndexCommand,
|
|
8
|
-
MongoDdlCommandVisitor,
|
|
9
|
-
MongoIndexKey,
|
|
10
|
-
} from '@prisma-next/mongo-query-ast/control';
|
|
11
|
-
|
|
12
|
-
function formatKeySpec(keys: ReadonlyArray<MongoIndexKey>): string {
|
|
13
|
-
const entries = keys.map((k) => `${JSON.stringify(k.field)}: ${JSON.stringify(k.direction)}`);
|
|
14
|
-
return `{ ${entries.join(', ')} }`;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function formatOptions(cmd: CreateIndexCommand): string | undefined {
|
|
18
|
-
const parts: string[] = [];
|
|
19
|
-
if (cmd.unique) parts.push('unique: true');
|
|
20
|
-
if (cmd.sparse) parts.push('sparse: true');
|
|
21
|
-
if (cmd.expireAfterSeconds !== undefined)
|
|
22
|
-
parts.push(`expireAfterSeconds: ${cmd.expireAfterSeconds}`);
|
|
23
|
-
if (cmd.name) parts.push(`name: ${JSON.stringify(cmd.name)}`);
|
|
24
|
-
if (cmd.collation) parts.push(`collation: ${JSON.stringify(cmd.collation)}`);
|
|
25
|
-
if (cmd.weights) parts.push(`weights: ${JSON.stringify(cmd.weights)}`);
|
|
26
|
-
if (cmd.default_language) parts.push(`default_language: ${JSON.stringify(cmd.default_language)}`);
|
|
27
|
-
if (cmd.language_override)
|
|
28
|
-
parts.push(`language_override: ${JSON.stringify(cmd.language_override)}`);
|
|
29
|
-
if (cmd.wildcardProjection)
|
|
30
|
-
parts.push(`wildcardProjection: ${JSON.stringify(cmd.wildcardProjection)}`);
|
|
31
|
-
if (cmd.partialFilterExpression)
|
|
32
|
-
parts.push(`partialFilterExpression: ${JSON.stringify(cmd.partialFilterExpression)}`);
|
|
33
|
-
if (parts.length === 0) return undefined;
|
|
34
|
-
return `{ ${parts.join(', ')} }`;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function formatCreateCollectionOptions(cmd: CreateCollectionCommand): string | undefined {
|
|
38
|
-
const parts: string[] = [];
|
|
39
|
-
if (cmd.capped) parts.push('capped: true');
|
|
40
|
-
if (cmd.size !== undefined) parts.push(`size: ${cmd.size}`);
|
|
41
|
-
if (cmd.max !== undefined) parts.push(`max: ${cmd.max}`);
|
|
42
|
-
if (cmd.timeseries) parts.push(`timeseries: ${JSON.stringify(cmd.timeseries)}`);
|
|
43
|
-
if (cmd.collation) parts.push(`collation: ${JSON.stringify(cmd.collation)}`);
|
|
44
|
-
if (cmd.clusteredIndex) parts.push(`clusteredIndex: ${JSON.stringify(cmd.clusteredIndex)}`);
|
|
45
|
-
if (cmd.validator) parts.push(`validator: ${JSON.stringify(cmd.validator)}`);
|
|
46
|
-
if (cmd.validationLevel) parts.push(`validationLevel: ${JSON.stringify(cmd.validationLevel)}`);
|
|
47
|
-
if (cmd.validationAction) parts.push(`validationAction: ${JSON.stringify(cmd.validationAction)}`);
|
|
48
|
-
if (cmd.changeStreamPreAndPostImages)
|
|
49
|
-
parts.push(`changeStreamPreAndPostImages: ${JSON.stringify(cmd.changeStreamPreAndPostImages)}`);
|
|
50
|
-
if (parts.length === 0) return undefined;
|
|
51
|
-
return `{ ${parts.join(', ')} }`;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
class MongoDdlCommandFormatter implements MongoDdlCommandVisitor<string> {
|
|
55
|
-
createIndex(cmd: CreateIndexCommand): string {
|
|
56
|
-
const keySpec = formatKeySpec(cmd.keys);
|
|
57
|
-
const opts = formatOptions(cmd);
|
|
58
|
-
return opts
|
|
59
|
-
? `db.${cmd.collection}.createIndex(${keySpec}, ${opts})`
|
|
60
|
-
: `db.${cmd.collection}.createIndex(${keySpec})`;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
dropIndex(cmd: DropIndexCommand): string {
|
|
64
|
-
return `db.${cmd.collection}.dropIndex(${JSON.stringify(cmd.name)})`;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
createCollection(cmd: CreateCollectionCommand): string {
|
|
68
|
-
const opts = formatCreateCollectionOptions(cmd);
|
|
69
|
-
return opts
|
|
70
|
-
? `db.createCollection(${JSON.stringify(cmd.collection)}, ${opts})`
|
|
71
|
-
: `db.createCollection(${JSON.stringify(cmd.collection)})`;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
dropCollection(cmd: DropCollectionCommand): string {
|
|
75
|
-
return `db.${cmd.collection}.drop()`;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
collMod(cmd: CollModCommand): string {
|
|
79
|
-
const parts: string[] = [`collMod: ${JSON.stringify(cmd.collection)}`];
|
|
80
|
-
if (cmd.validator) parts.push(`validator: ${JSON.stringify(cmd.validator)}`);
|
|
81
|
-
if (cmd.validationLevel) parts.push(`validationLevel: ${JSON.stringify(cmd.validationLevel)}`);
|
|
82
|
-
if (cmd.validationAction)
|
|
83
|
-
parts.push(`validationAction: ${JSON.stringify(cmd.validationAction)}`);
|
|
84
|
-
if (cmd.changeStreamPreAndPostImages)
|
|
85
|
-
parts.push(
|
|
86
|
-
`changeStreamPreAndPostImages: ${JSON.stringify(cmd.changeStreamPreAndPostImages)}`,
|
|
87
|
-
);
|
|
88
|
-
return `db.runCommand({ ${parts.join(', ')} })`;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
const formatter = new MongoDdlCommandFormatter();
|
|
93
|
-
|
|
94
|
-
interface MongoExecuteStep {
|
|
95
|
-
readonly command: { readonly accept: <R>(visitor: MongoDdlCommandVisitor<R>) => R };
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export function formatMongoOperations(operations: readonly MigrationPlanOperation[]): string[] {
|
|
99
|
-
const statements: string[] = [];
|
|
100
|
-
for (const operation of operations) {
|
|
101
|
-
const candidate = operation as unknown as Record<string, unknown>;
|
|
102
|
-
if (!('execute' in candidate) || !Array.isArray(candidate['execute'])) {
|
|
103
|
-
continue;
|
|
104
|
-
}
|
|
105
|
-
for (const step of candidate['execute'] as MongoExecuteStep[]) {
|
|
106
|
-
if (step.command && typeof step.command.accept === 'function') {
|
|
107
|
-
statements.push(step.command.accept(formatter));
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
return statements;
|
|
112
|
-
}
|
|
@@ -1,232 +0,0 @@
|
|
|
1
|
-
import type { ContractMarkerRecord } from '@prisma-next/contract/types';
|
|
2
|
-
import {
|
|
3
|
-
RawAggregateCommand,
|
|
4
|
-
RawFindOneAndUpdateCommand,
|
|
5
|
-
RawInsertOneCommand,
|
|
6
|
-
} from '@prisma-next/mongo-query-ast/execution';
|
|
7
|
-
import { type } from 'arktype';
|
|
8
|
-
import type { Db, Document, UpdateFilter } from 'mongodb';
|
|
9
|
-
|
|
10
|
-
const COLLECTION = '_prisma_migrations';
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Marker doc shape.
|
|
14
|
-
*
|
|
15
|
-
* Same fields as the SQL marker row but camelCase + Mongo-native types:
|
|
16
|
-
* `Date` is BSON-hydrated, `meta` is a native object (not JSON-stringified),
|
|
17
|
-
* `_id` and any extension fields are tolerated. `invariants?` is optional —
|
|
18
|
-
* absent reads as `[]` (schemaless default); present-but-malformed throws.
|
|
19
|
-
*
|
|
20
|
-
* `space` is required: every marker doc is keyed by its space id (`_id`)
|
|
21
|
-
* and stamped with a matching `space` field for partitioned reads.
|
|
22
|
-
*/
|
|
23
|
-
const MongoMarkerDocSchema = type({
|
|
24
|
-
space: 'string',
|
|
25
|
-
storageHash: 'string',
|
|
26
|
-
profileHash: 'string',
|
|
27
|
-
'contractJson?': 'unknown | null',
|
|
28
|
-
'canonicalVersion?': 'number | null',
|
|
29
|
-
'updatedAt?': 'Date',
|
|
30
|
-
'appTag?': 'string | null',
|
|
31
|
-
'meta?': type({ '[string]': 'unknown' }).or('null'),
|
|
32
|
-
'invariants?': type('string').array(),
|
|
33
|
-
'+': 'delete',
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
function parseMongoMarkerDoc(doc: unknown): ContractMarkerRecord {
|
|
37
|
-
const result = MongoMarkerDocSchema(doc);
|
|
38
|
-
if (result instanceof type.errors) {
|
|
39
|
-
throw new Error(`Invalid marker doc on ${COLLECTION}: ${result.summary}`);
|
|
40
|
-
}
|
|
41
|
-
return {
|
|
42
|
-
storageHash: result.storageHash,
|
|
43
|
-
profileHash: result.profileHash,
|
|
44
|
-
contractJson: result.contractJson ?? null,
|
|
45
|
-
canonicalVersion: result.canonicalVersion ?? null,
|
|
46
|
-
updatedAt: result.updatedAt ?? new Date(),
|
|
47
|
-
appTag: result.appTag ?? null,
|
|
48
|
-
meta: (result.meta as Record<string, unknown> | null) ?? {},
|
|
49
|
-
invariants: result.invariants ?? [],
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async function executeAggregate(db: Db, cmd: RawAggregateCommand): Promise<Document[]> {
|
|
54
|
-
return db
|
|
55
|
-
.collection(cmd.collection)
|
|
56
|
-
.aggregate(cmd.pipeline as Record<string, unknown>[])
|
|
57
|
-
.toArray();
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async function executeInsertOne(db: Db, cmd: RawInsertOneCommand): Promise<void> {
|
|
61
|
-
await db.collection(cmd.collection).insertOne(cmd.document);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
async function executeFindOneAndUpdate(
|
|
65
|
-
db: Db,
|
|
66
|
-
cmd: RawFindOneAndUpdateCommand,
|
|
67
|
-
): Promise<Document | null> {
|
|
68
|
-
// `cmd.update` is `Document | ReadonlyArray<Document>` per the AST. The
|
|
69
|
-
// MongoDB driver's `findOneAndUpdate` accepts the same shape under the
|
|
70
|
-
// type `UpdateFilter<T> | Document[]`. The driver's runtime path handles
|
|
71
|
-
// both forms identically — pipelines (array) and update docs (object).
|
|
72
|
-
// One cast to that union keeps the call single-arm.
|
|
73
|
-
return db
|
|
74
|
-
.collection(cmd.collection)
|
|
75
|
-
.findOneAndUpdate(cmd.filter, cmd.update as UpdateFilter<Document> | Document[], {
|
|
76
|
-
upsert: cmd.upsert,
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Reads the marker document for the given contract space, or returns
|
|
82
|
-
* `null` if no marker has been written for that space yet. Each space
|
|
83
|
-
* owns one row keyed by `_id: <space>` — see ADR 212 for the per-space
|
|
84
|
-
* mechanism this enables.
|
|
85
|
-
*/
|
|
86
|
-
export async function readMarker(db: Db, space: string): Promise<ContractMarkerRecord | null> {
|
|
87
|
-
const cmd = new RawAggregateCommand(COLLECTION, [
|
|
88
|
-
{ $match: { _id: space, space } },
|
|
89
|
-
{ $limit: 1 },
|
|
90
|
-
]);
|
|
91
|
-
const docs = await executeAggregate(db, cmd);
|
|
92
|
-
const doc = docs[0];
|
|
93
|
-
if (!doc) return null;
|
|
94
|
-
return parseMongoMarkerDoc(doc);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Reads every marker doc in the collection (one per contract space)
|
|
99
|
-
* and returns them keyed by `space`. Used by the per-space verifier
|
|
100
|
-
* to detect marker-vs-on-disk drift and orphan marker rows. Returns
|
|
101
|
-
* an empty map when no marker docs have been written yet.
|
|
102
|
-
*
|
|
103
|
-
* Marker docs are keyed by `_id: <space>` (string); ledger entries
|
|
104
|
-
* live in the same collection but use a driver-generated `ObjectId`
|
|
105
|
-
* `_id` plus `type: 'ledger'`. The filter selects string-keyed docs
|
|
106
|
-
* with a `space` field, which excludes ledger entries by construction.
|
|
107
|
-
*/
|
|
108
|
-
export async function readAllMarkers(db: Db): Promise<ReadonlyMap<string, ContractMarkerRecord>> {
|
|
109
|
-
const cmd = new RawAggregateCommand(COLLECTION, [
|
|
110
|
-
{
|
|
111
|
-
$match: {
|
|
112
|
-
_id: { $type: 'string' },
|
|
113
|
-
space: { $type: 'string' },
|
|
114
|
-
$expr: { $eq: ['$_id', '$space'] },
|
|
115
|
-
},
|
|
116
|
-
},
|
|
117
|
-
]);
|
|
118
|
-
const docs = await executeAggregate(db, cmd);
|
|
119
|
-
const out = new Map<string, ContractMarkerRecord>();
|
|
120
|
-
for (const doc of docs) {
|
|
121
|
-
const space = doc['space'];
|
|
122
|
-
/* v8 ignore next -- @preserve type-narrowing guard: the $match stage above filters on `space: { $type: 'string' }`, so this branch is unreachable at runtime. The check exists so the `out.set(space, ...)` call below can accept `string`. */
|
|
123
|
-
if (typeof space !== 'string') continue;
|
|
124
|
-
out.set(space, parseMongoMarkerDoc(doc));
|
|
125
|
-
}
|
|
126
|
-
return out;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
export async function initMarker(
|
|
130
|
-
db: Db,
|
|
131
|
-
space: string,
|
|
132
|
-
destination: {
|
|
133
|
-
readonly storageHash: string;
|
|
134
|
-
readonly profileHash: string;
|
|
135
|
-
readonly invariants?: readonly string[];
|
|
136
|
-
},
|
|
137
|
-
): Promise<void> {
|
|
138
|
-
const cmd = new RawInsertOneCommand(COLLECTION, {
|
|
139
|
-
_id: space,
|
|
140
|
-
space,
|
|
141
|
-
storageHash: destination.storageHash,
|
|
142
|
-
profileHash: destination.profileHash,
|
|
143
|
-
contractJson: null,
|
|
144
|
-
canonicalVersion: null,
|
|
145
|
-
updatedAt: new Date(),
|
|
146
|
-
appTag: null,
|
|
147
|
-
meta: {},
|
|
148
|
-
invariants: destination.invariants ?? [],
|
|
149
|
-
});
|
|
150
|
-
await executeInsertOne(db, cmd);
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* Updates the marker doc for the given space atomically (CAS on
|
|
155
|
-
* `expectedFrom`).
|
|
156
|
-
*
|
|
157
|
-
* `destination.invariants`:
|
|
158
|
-
* - `undefined` → existing field left untouched.
|
|
159
|
-
* - explicit value → merged into the existing field server-side via an
|
|
160
|
-
* aggregation pipeline (`$setUnion + $sortArray`), atomic at the
|
|
161
|
-
* document level. `[]` is a no-op merge.
|
|
162
|
-
*/
|
|
163
|
-
export async function updateMarker(
|
|
164
|
-
db: Db,
|
|
165
|
-
space: string,
|
|
166
|
-
expectedFrom: string,
|
|
167
|
-
destination: {
|
|
168
|
-
readonly storageHash: string;
|
|
169
|
-
readonly profileHash: string;
|
|
170
|
-
readonly invariants?: readonly string[];
|
|
171
|
-
},
|
|
172
|
-
): Promise<boolean> {
|
|
173
|
-
const setBase: Record<string, unknown> = {
|
|
174
|
-
storageHash: destination.storageHash,
|
|
175
|
-
profileHash: destination.profileHash,
|
|
176
|
-
updatedAt: new Date(),
|
|
177
|
-
};
|
|
178
|
-
// When invariants is supplied, use an aggregation pipeline so the
|
|
179
|
-
// merge runs server-side against the doc's current value (atomic, no
|
|
180
|
-
// read-then-write window). When omitted, a regular update doc keeps
|
|
181
|
-
// the field untouched.
|
|
182
|
-
const update: Document | Document[] =
|
|
183
|
-
destination.invariants === undefined
|
|
184
|
-
? { $set: setBase }
|
|
185
|
-
: [
|
|
186
|
-
{
|
|
187
|
-
$set: {
|
|
188
|
-
...setBase,
|
|
189
|
-
invariants: {
|
|
190
|
-
$sortArray: {
|
|
191
|
-
input: { $setUnion: [{ $ifNull: ['$invariants', []] }, destination.invariants] },
|
|
192
|
-
sortBy: 1,
|
|
193
|
-
},
|
|
194
|
-
},
|
|
195
|
-
},
|
|
196
|
-
},
|
|
197
|
-
];
|
|
198
|
-
const cmd = new RawFindOneAndUpdateCommand(
|
|
199
|
-
COLLECTION,
|
|
200
|
-
{ _id: space, space, storageHash: expectedFrom },
|
|
201
|
-
update,
|
|
202
|
-
false,
|
|
203
|
-
);
|
|
204
|
-
const result = await executeFindOneAndUpdate(db, cmd);
|
|
205
|
-
return result !== null;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
/**
|
|
209
|
-
* Appends a ledger entry for the given space. Ledger entries co-exist
|
|
210
|
-
* with marker docs in the same collection; marker docs use `_id: <space>`
|
|
211
|
-
* (string), ledger entries use `type: 'ledger'` plus a driver-generated
|
|
212
|
-
* ObjectId. Reads partition the two by filter shape.
|
|
213
|
-
*
|
|
214
|
-
* The same `edgeId` may legitimately recur across different spaces (e.g.
|
|
215
|
-
* a synthetic ∅→head edge on first apply), so the ledger key is
|
|
216
|
-
* `(space, edgeId)` — the doc carries `space` for partitioned reads.
|
|
217
|
-
*/
|
|
218
|
-
export async function writeLedgerEntry(
|
|
219
|
-
db: Db,
|
|
220
|
-
space: string,
|
|
221
|
-
entry: { readonly edgeId: string; readonly from: string; readonly to: string },
|
|
222
|
-
): Promise<void> {
|
|
223
|
-
const cmd = new RawInsertOneCommand(COLLECTION, {
|
|
224
|
-
type: 'ledger',
|
|
225
|
-
space,
|
|
226
|
-
edgeId: entry.edgeId,
|
|
227
|
-
from: entry.from,
|
|
228
|
-
to: entry.to,
|
|
229
|
-
appliedAt: new Date(),
|
|
230
|
-
});
|
|
231
|
-
await executeInsertOne(db, cmd);
|
|
232
|
-
}
|