@prisma-next/adapter-mongo 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codec-types.d.mts.map +1 -1
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +1 -1
- package/dist/control.mjs.map +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/{mongo-adapter-DfCmEYHR.mjs → mongo-adapter-DAC5qq3o.mjs} +381 -42
- package/dist/mongo-adapter-DAC5qq3o.mjs.map +1 -0
- package/dist/mongo-adapter-JuKx_-h9.d.mts.map +1 -1
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +4 -2
- package/dist/runtime.mjs.map +1 -1
- package/package.json +37 -25
- package/src/exports/runtime.ts +2 -0
- package/src/lowering.ts +261 -5
- package/src/mongo-adapter.ts +200 -71
- package/src/resolve-value.ts +64 -6
- package/dist/mongo-adapter-DfCmEYHR.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mongo-adapter-DAC5qq3o.mjs","names":["_exhaustive","#codecs","_exhaustive"],"sources":["../src/core/codec-ids.ts","../src/resolve-value.ts","../src/lowering.ts","../src/core/codecs.ts","../src/mongo-adapter.ts"],"sourcesContent":["export const MONGO_OBJECTID_CODEC_ID = 'mongo/objectId@1' as const;\nexport const MONGO_STRING_CODEC_ID = 'mongo/string@1' as const;\nexport const MONGO_DOUBLE_CODEC_ID = 'mongo/double@1' as const;\nexport const MONGO_INT32_CODEC_ID = 'mongo/int32@1' as const;\nexport const MONGO_BOOLEAN_CODEC_ID = 'mongo/bool@1' as const;\nexport const MONGO_DATE_CODEC_ID = 'mongo/date@1' as const;\nexport const MONGO_VECTOR_CODEC_ID = 'mongo/vector@1' as const;\n","import type { CodecCallContext } from '@prisma-next/framework-components/codec';\nimport {\n checkAborted,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport type { MongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type { Document, MongoValue } from '@prisma-next/mongo-value';\nimport { MongoParamRef } from '@prisma-next/mongo-value';\nimport { blindCast } from '@prisma-next/utils/casts';\n\n/**\n * Resolves a `MongoValue` (which may contain `MongoParamRef` leaves) into the\n * driver-ready wire shape. When a leaf has a `codecId` and the registry has a\n * codec for it, the codec's async `encode` is awaited so codecs may perform\n * asynchronous work (e.g. lookups, key derivations).\n *\n * Object/array nodes dispatch their child resolutions concurrently via\n * `Promise.all` so independent leaves encode in parallel.\n *\n * Codec encode failures are wrapped in a `RUNTIME.ENCODE_FAILED` envelope\n * (mirroring SQL's `wrapEncodeFailure` shape) with `{ label, codec }` details\n * and the original error attached on `cause`. An already-wrapped envelope is\n * re-thrown verbatim so nested resolvers don't double-wrap.\n *\n * `ctx: CodecCallContext` is forwarded verbatim to every\n * `codec.encode(value, ctx)` call. The same `ctx` reference is also passed\n * to nested `resolveValue` invocations so codec authors observe **signal\n * identity** across the entire recursive walk for one `runtime.execute()`.\n *\n * Abort observation (only when `ctx.signal` is provided):\n *\n * - **Already-aborted at entry** — every recursive call pre-checks\n * `ctx.signal.aborted` and short-circuits with\n * `RUNTIME.ABORTED { phase: 'encode' }` before any codec is invoked.\n * - **Mid-flight abort** — each per-level `Promise.all` races against the\n * signal via `raceAgainstAbort`. The runtime returns\n * `RUNTIME.ABORTED { phase: 'encode' }` promptly even if codec bodies\n * ignore the signal; in-flight bodies run to completion in the background\n * (cooperative cancellation, see ADR 204).\n * - `RUNTIME.ENCODE_FAILED` envelopes thrown by a codec body before the\n * runtime sees the abort pass through unchanged (AC-ERR4).\n */\nexport async function resolveValue(\n value: MongoValue,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<unknown> {\n checkAborted(ctx, 'encode');\n const signal = ctx.signal;\n\n if (value instanceof MongoParamRef) {\n if (value.codecId) {\n const codec = codecs.get(value.codecId);\n if (codec?.encode) {\n try {\n // Race even leaf scalar encodes against the signal so a leaf\n // `MongoParamRef` (e.g. a simple field filter, or any leaf reached\n // from `MongoAdapterImpl.#resolveDocument()` outside an enclosing\n // `Promise.all`) surfaces `RUNTIME.ABORTED` promptly instead of\n // blocking on a slow codec body.\n const encoded = codec.encode(value.value, ctx);\n return await raceAgainstAbort(encoded, signal, 'encode');\n } catch (error) {\n wrapEncodeFailure(error, value, codec.id);\n }\n }\n }\n return value.value;\n }\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (value instanceof Date) {\n return value;\n }\n if (Array.isArray(value)) {\n const tasks = Promise.all(value.map((v) => resolveValue(v, codecs, ctx)));\n return raceAgainstAbort(tasks, signal, 'encode');\n }\n const entries = Object.entries(value);\n const all = Promise.all(entries.map(([, val]) => resolveValue(val, codecs, ctx)));\n const resolved = await raceAgainstAbort(all, signal, 'encode');\n const result: Record<string, unknown> = {};\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (entry) {\n result[entry[0]] = resolved[i];\n }\n }\n return result;\n}\n\n/**\n * Resolves a draft slot value — which may be `MongoParamRef`, a primitive, a\n * nested plain-object, or an array — into the corresponding wire value.\n * Mirrors `resolveValue`'s traversal strategy but accepts `unknown` so it can\n * handle pipeline stage documents whose field types cannot be narrowed to\n * `MongoValue` statically (e.g. `$geoNear.near: unknown`).\n */\nasync function resolveDraftSlot(\n value: unknown,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<unknown> {\n if (value instanceof MongoParamRef) {\n return resolveValue(value, codecs, ctx);\n }\n if (value === null || typeof value !== 'object') return value;\n if (value instanceof Date) return value;\n if (Array.isArray(value)) {\n const tasks = Promise.all(value.map((v: unknown) => resolveDraftSlot(v, codecs, ctx)));\n return raceAgainstAbort(tasks, ctx.signal, 'encode');\n }\n return resolveDraftDoc(\n blindCast<\n Record<string, unknown>,\n 'narrowed by instanceof/typeof guards: non-null, non-Date, non-array object'\n >(value),\n codecs,\n ctx,\n );\n}\n\n/**\n * Resolves a pipeline stage draft document by walking every entry and\n * forwarding to {@link resolveDraftSlot}. Used by `MongoAdapterImpl.resolveParams`\n * for aggregate pipeline stages, which carry `unknown`-typed fields (e.g.\n * `$geoNear.near`) alongside filter sub-documents that may contain\n * `MongoParamRef` leaves.\n */\nexport async function resolveDraftDoc(\n doc: Record<string, unknown>,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<Document> {\n checkAborted(ctx, 'encode');\n const entries = Object.entries(doc);\n const all = Promise.all(entries.map(([, val]) => resolveDraftSlot(val, codecs, ctx)));\n const resolved = await raceAgainstAbort(all, ctx.signal, 'encode');\n const result: Record<string, unknown> = {};\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (entry) {\n result[entry[0]] = resolved[i];\n }\n }\n return result;\n}\n\nfunction paramRefLabel(ref: MongoParamRef, codecId: string): string {\n return ref.name ?? codecId;\n}\n\nfunction isErrorWithCode(error: unknown): error is Error & { code: unknown } {\n return error instanceof Error && 'code' in error;\n}\n\nfunction isAlreadyEncodeFailure(error: unknown): boolean {\n return isErrorWithCode(error) && error.code === 'RUNTIME.ENCODE_FAILED';\n}\n\nfunction wrapEncodeFailure(error: unknown, ref: MongoParamRef, codecId: string): never {\n if (isAlreadyEncodeFailure(error)) {\n throw error;\n }\n const label = paramRefLabel(ref, codecId);\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.ENCODE_FAILED',\n `Failed to encode parameter ${label} with codec '${codecId}': ${message}`,\n { label, codec: codecId },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n","import type { CodecCallContext } from '@prisma-next/framework-components/codec';\nimport type { MongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type {\n MongoAggExpr,\n MongoAggExprVisitor,\n MongoFilterExpr,\n MongoGroupId,\n MongoPipelineStage,\n MongoProjectionValue,\n MongoWindowField,\n} from '@prisma-next/mongo-query-ast/execution';\nimport { isExprArray, isRecordArgs } from '@prisma-next/mongo-query-ast/execution';\nimport type { Document } from '@prisma-next/mongo-value';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { resolveValue } from './resolve-value';\n\n// Biome flags `{ then: ... }` as a thenable object (noThenProperty). Build via Object.fromEntries to avoid.\nconst THEN_KEY = 'then';\n\nfunction condBranch(\n caseOrIf: MongoAggExpr,\n thenExpr: MongoAggExpr,\n elseExpr?: MongoAggExpr,\n): Record<string, unknown> {\n const entries: Array<[string, unknown]> = [\n [elseExpr ? 'if' : 'case', lowerAggExpr(caseOrIf)],\n [THEN_KEY, lowerAggExpr(thenExpr)],\n ];\n if (elseExpr) {\n entries.push(['else', lowerAggExpr(elseExpr)]);\n }\n return Object.fromEntries(entries);\n}\n\nconst aggExprLoweringVisitor: MongoAggExprVisitor<unknown> = {\n fieldRef(expr) {\n return `$${expr.path}`;\n },\n\n literal(expr) {\n return needsLiteralWrap(expr.value) ? { $literal: expr.value } : expr.value;\n },\n\n operator(expr) {\n const { args } = expr;\n let loweredArgs: unknown;\n if (isExprArray(args)) {\n loweredArgs = args.map((a) => lowerAggExpr(a));\n } else if (isRecordArgs(args)) {\n loweredArgs = lowerExprRecord(args);\n } else {\n loweredArgs = lowerAggExpr(args);\n }\n return { [expr.op]: loweredArgs };\n },\n\n accumulator(expr) {\n if (expr.arg === null) {\n return { [expr.op]: {} };\n }\n if (isRecordArgs(expr.arg)) {\n return { [expr.op]: lowerExprRecord(expr.arg) };\n }\n return { [expr.op]: lowerAggExpr(expr.arg) };\n },\n\n cond(expr) {\n return { $cond: condBranch(expr.condition, expr.then_, expr.else_) };\n },\n\n switch_(expr) {\n return {\n $switch: {\n branches: expr.branches.map((b) => condBranch(b.case_, b.then_)),\n default: lowerAggExpr(expr.default_),\n },\n };\n },\n\n filter(expr) {\n return {\n $filter: {\n input: lowerAggExpr(expr.input),\n cond: lowerAggExpr(expr.cond),\n as: expr.as,\n },\n };\n },\n\n map(expr) {\n return {\n $map: {\n input: lowerAggExpr(expr.input),\n in: lowerAggExpr(expr.in_),\n as: expr.as,\n },\n };\n },\n\n reduce(expr) {\n return {\n $reduce: {\n input: lowerAggExpr(expr.input),\n initialValue: lowerAggExpr(expr.initialValue),\n in: lowerAggExpr(expr.in_),\n },\n };\n },\n\n let_(expr) {\n const vars: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(expr.vars)) {\n vars[key] = lowerAggExpr(val);\n }\n return { $let: { vars, in: lowerAggExpr(expr.in_) } };\n },\n\n mergeObjects(expr) {\n return { $mergeObjects: expr.exprs.map((e) => lowerAggExpr(e)) };\n },\n};\n\nfunction needsLiteralWrap(value: unknown): boolean {\n if (typeof value === 'string' && value.startsWith('$')) {\n return true;\n }\n if (Array.isArray(value)) {\n return value.some((v) => needsLiteralWrap(v));\n }\n if (value !== null && typeof value === 'object') {\n return Object.entries(value as Record<string, unknown>).some(\n ([k, v]) => k.startsWith('$') || needsLiteralWrap(v),\n );\n }\n return false;\n}\n\nexport function lowerAggExpr(expr: MongoAggExpr): unknown {\n return expr.accept(aggExprLoweringVisitor);\n}\n\n/**\n * Structural phase of filter lowering: transforms the filter AST into a\n * plain object without resolving any `MongoParamRef` leaves. Field filter\n * values remain as `MongoValue` (which includes `MongoParamRef`), so the\n * returned document can be passed to `resolveDraftDoc` in the resolve phase.\n * Synchronous — no codec calls.\n */\nexport function structuralLowerFilter(filter: MongoFilterExpr): Record<string, unknown> {\n switch (filter.kind) {\n case 'field':\n return { [filter.field]: { [filter.op]: filter.value } };\n case 'and':\n return { $and: filter.exprs.map((e) => structuralLowerFilter(e)) };\n case 'or':\n return { $or: filter.exprs.map((e) => structuralLowerFilter(e)) };\n case 'not':\n return { $nor: [structuralLowerFilter(filter.expr)] };\n case 'exists':\n return { [filter.field]: { $exists: filter.exists } };\n case 'expr':\n return { $expr: lowerAggExpr(filter.aggExpr) };\n default: {\n const _exhaustive: never = filter;\n throw new Error(\n `Unhandled filter kind: ${blindCast<MongoFilterExpr, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,\n );\n }\n }\n}\n\nexport async function lowerFilter(\n filter: MongoFilterExpr,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<Document> {\n switch (filter.kind) {\n case 'field':\n return { [filter.field]: { [filter.op]: await resolveValue(filter.value, codecs, ctx) } };\n case 'and':\n return { $and: await Promise.all(filter.exprs.map((e) => lowerFilter(e, codecs, ctx))) };\n case 'or':\n return { $or: await Promise.all(filter.exprs.map((e) => lowerFilter(e, codecs, ctx))) };\n case 'not':\n return { $nor: [await lowerFilter(filter.expr, codecs, ctx)] };\n case 'exists':\n return { [filter.field]: { $exists: filter.exists } };\n case 'expr':\n return { $expr: lowerAggExpr(filter.aggExpr) };\n default: {\n const _exhaustive: never = filter;\n throw new Error(\n `Unhandled filter kind: ${blindCast<MongoFilterExpr, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,\n );\n }\n }\n}\n\nfunction isAggExprNode(value: object): value is MongoAggExpr {\n return 'accept' in value && typeof value.accept === 'function';\n}\n\nfunction isAggExprArray(\n val: MongoAggExpr | ReadonlyArray<MongoAggExpr>,\n): val is ReadonlyArray<MongoAggExpr> {\n return Array.isArray(val);\n}\n\nfunction lowerGroupId(groupId: MongoGroupId): unknown {\n if (groupId === null) return null;\n if (isAggExprNode(groupId)) return lowerAggExpr(groupId);\n return lowerExprRecord(groupId);\n}\n\nfunction lowerExprRecord(\n fields: Readonly<Record<string, MongoAggExpr | ReadonlyArray<MongoAggExpr>>>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(fields)) {\n if (isAggExprArray(val)) {\n result[key] = val.map((v) => lowerAggExpr(v));\n } else {\n result[key] = lowerAggExpr(val);\n }\n }\n return result;\n}\n\nfunction lowerProjectionValue(value: MongoProjectionValue): unknown {\n if (typeof value === 'number') return value;\n return lowerAggExpr(value);\n}\n\nfunction lowerWindowField(wf: MongoWindowField): Record<string, unknown> {\n const lowered = lowerAggExpr(wf.operator);\n if (typeof lowered !== 'object' || lowered === null) {\n throw new Error('Window field operator must lower to an object');\n }\n const result: Record<string, unknown> = { ...lowered };\n if (wf.window) {\n result['window'] = { ...wf.window };\n }\n return result;\n}\n\nexport async function lowerStage(\n stage: MongoPipelineStage,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<Record<string, unknown>> {\n switch (stage.kind) {\n case 'match':\n return { $match: await lowerFilter(stage.filter, codecs, ctx) };\n case 'project': {\n const projection: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(stage.projection)) {\n projection[key] = lowerProjectionValue(val);\n }\n return { $project: projection };\n }\n case 'sort':\n return { $sort: { ...stage.sort } };\n case 'limit':\n return { $limit: stage.limit };\n case 'skip':\n return { $skip: stage.skip };\n case 'lookup': {\n const lookup: Record<string, unknown> = {\n from: stage.from,\n as: stage.as,\n };\n if (stage.localField !== undefined) lookup['localField'] = stage.localField;\n if (stage.foreignField !== undefined) lookup['foreignField'] = stage.foreignField;\n if (stage.pipeline) {\n lookup['pipeline'] = await Promise.all(\n stage.pipeline.map((s) => lowerStage(s, codecs, ctx)),\n );\n }\n if (stage.let_) {\n lookup['let'] = lowerExprRecord(stage.let_);\n }\n return { $lookup: lookup };\n }\n case 'unwind': {\n const unwind: Record<string, unknown> = {\n path: stage.path,\n preserveNullAndEmptyArrays: stage.preserveNullAndEmptyArrays,\n };\n if (stage.includeArrayIndex !== undefined) {\n unwind['includeArrayIndex'] = stage.includeArrayIndex;\n }\n return { $unwind: unwind };\n }\n case 'group': {\n const group: Record<string, unknown> = { _id: lowerGroupId(stage.groupId) };\n for (const [key, acc] of Object.entries(stage.accumulators)) {\n group[key] = lowerAggExpr(acc);\n }\n return { $group: group };\n }\n case 'addFields':\n return { $addFields: lowerExprRecord(stage.fields) };\n case 'replaceRoot':\n return { $replaceRoot: { newRoot: lowerAggExpr(stage.newRoot) } };\n case 'count':\n return { $count: stage.field };\n case 'sortByCount':\n return { $sortByCount: lowerAggExpr(stage.expr) };\n case 'sample':\n return { $sample: { size: stage.size } };\n case 'redact':\n return { $redact: lowerAggExpr(stage.expr) };\n case 'out':\n return { $out: stage.db ? { db: stage.db, coll: stage.collection } : stage.collection };\n case 'unionWith': {\n const unionWith: Record<string, unknown> = { coll: stage.collection };\n if (stage.pipeline) {\n unionWith['pipeline'] = await Promise.all(\n stage.pipeline.map((s) => lowerStage(s, codecs, ctx)),\n );\n }\n return { $unionWith: unionWith };\n }\n case 'bucket': {\n const bucket: Record<string, unknown> = {\n groupBy: lowerAggExpr(stage.groupBy),\n boundaries: [...stage.boundaries],\n };\n if (stage.default_ !== undefined) bucket['default'] = stage.default_;\n if (stage.output) bucket['output'] = lowerExprRecord(stage.output);\n return { $bucket: bucket };\n }\n case 'bucketAuto': {\n const bucketAuto: Record<string, unknown> = {\n groupBy: lowerAggExpr(stage.groupBy),\n buckets: stage.buckets,\n };\n if (stage.output) bucketAuto['output'] = lowerExprRecord(stage.output);\n if (stage.granularity !== undefined) bucketAuto['granularity'] = stage.granularity;\n return { $bucketAuto: bucketAuto };\n }\n case 'geoNear': {\n const geoNear: Record<string, unknown> = {\n near: stage.near,\n distanceField: stage.distanceField,\n };\n if (stage.spherical !== undefined) geoNear['spherical'] = stage.spherical;\n if (stage.maxDistance !== undefined) geoNear['maxDistance'] = stage.maxDistance;\n if (stage.minDistance !== undefined) geoNear['minDistance'] = stage.minDistance;\n if (stage.query) geoNear['query'] = await lowerFilter(stage.query, codecs, ctx);\n if (stage.key !== undefined) geoNear['key'] = stage.key;\n if (stage.distanceMultiplier !== undefined)\n geoNear['distanceMultiplier'] = stage.distanceMultiplier;\n if (stage.includeLocs !== undefined) geoNear['includeLocs'] = stage.includeLocs;\n return { $geoNear: geoNear };\n }\n case 'facet': {\n const facetEntries = Object.entries(stage.facets);\n const facetPipelines = await Promise.all(\n facetEntries.map(([, pipeline]) =>\n Promise.all(pipeline.map((s) => lowerStage(s, codecs, ctx))),\n ),\n );\n const facet: Record<string, unknown> = {};\n for (let i = 0; i < facetEntries.length; i++) {\n const entry = facetEntries[i];\n if (entry) {\n facet[entry[0]] = facetPipelines[i];\n }\n }\n return { $facet: facet };\n }\n case 'graphLookup': {\n const graphLookup: Record<string, unknown> = {\n from: stage.from,\n startWith: lowerAggExpr(stage.startWith),\n connectFromField: stage.connectFromField,\n connectToField: stage.connectToField,\n as: stage.as,\n };\n if (stage.maxDepth !== undefined) graphLookup['maxDepth'] = stage.maxDepth;\n if (stage.depthField !== undefined) graphLookup['depthField'] = stage.depthField;\n if (stage.restrictSearchWithMatch)\n graphLookup['restrictSearchWithMatch'] = await lowerFilter(\n stage.restrictSearchWithMatch,\n codecs,\n ctx,\n );\n return { $graphLookup: graphLookup };\n }\n case 'merge': {\n const merge: Record<string, unknown> = { into: stage.into };\n if (stage.on !== undefined) merge['on'] = stage.on;\n if (stage.whenMatched !== undefined) {\n merge['whenMatched'] = Array.isArray(stage.whenMatched)\n ? await Promise.all(stage.whenMatched.map((s) => lowerStage(s, codecs, ctx)))\n : stage.whenMatched;\n }\n if (stage.whenNotMatched !== undefined) merge['whenNotMatched'] = stage.whenNotMatched;\n return { $merge: merge };\n }\n case 'setWindowFields': {\n const swf: Record<string, unknown> = {};\n if (stage.partitionBy) swf['partitionBy'] = lowerAggExpr(stage.partitionBy);\n if (stage.sortBy) swf['sortBy'] = { ...stage.sortBy };\n const output: Record<string, unknown> = {};\n for (const [key, wf] of Object.entries(stage.output)) {\n output[key] = lowerWindowField(wf);\n }\n swf['output'] = output;\n return { $setWindowFields: swf };\n }\n case 'densify': {\n const densify: Record<string, unknown> = {\n field: stage.field,\n range: { ...stage.range },\n };\n if (stage.partitionByFields) densify['partitionByFields'] = [...stage.partitionByFields];\n return { $densify: densify };\n }\n case 'fill': {\n const fill: Record<string, unknown> = {};\n if (stage.partitionBy) fill['partitionBy'] = lowerAggExpr(stage.partitionBy);\n if (stage.partitionByFields) fill['partitionByFields'] = [...stage.partitionByFields];\n if (stage.sortBy) fill['sortBy'] = { ...stage.sortBy };\n const output: Record<string, unknown> = {};\n for (const [key, fo] of Object.entries(stage.output)) {\n const entry: Record<string, unknown> = {};\n if (fo.method !== undefined) entry['method'] = fo.method;\n if (fo.value !== undefined) entry['value'] = lowerAggExpr(fo.value);\n output[key] = entry;\n }\n fill['output'] = output;\n return { $fill: fill };\n }\n case 'search': {\n const search: Record<string, unknown> = { ...stage.config };\n if (stage.index !== undefined) search['index'] = stage.index;\n return { $search: search };\n }\n case 'searchMeta': {\n const searchMeta: Record<string, unknown> = { ...stage.config };\n if (stage.index !== undefined) searchMeta['index'] = stage.index;\n return { $searchMeta: searchMeta };\n }\n case 'vectorSearch': {\n const vs: Record<string, unknown> = {\n index: stage.index,\n path: stage.path,\n queryVector: [...stage.queryVector],\n numCandidates: stage.numCandidates,\n limit: stage.limit,\n };\n if (stage.filter) vs['filter'] = { ...stage.filter };\n return { $vectorSearch: vs };\n }\n default: {\n const _exhaustive: never = stage;\n throw new Error(\n `Unhandled stage kind: ${blindCast<MongoPipelineStage, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,\n );\n }\n }\n}\n\nexport async function lowerPipeline(\n stages: ReadonlyArray<MongoPipelineStage>,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<Array<Record<string, unknown>>> {\n return Promise.all(stages.map((s) => lowerStage(s, codecs, ctx)));\n}\n\n/**\n * Structural phase of stage lowering: mirrors `lowerStage` but defers all\n * `MongoParamRef` resolution. Filter sub-documents within stages (e.g.\n * `$match`, `$geoNear.query`, `$graphLookup.restrictSearchWithMatch`) are\n * produced by `structuralLowerFilter` and therefore retain `MongoParamRef`\n * leaves. Sub-pipelines (e.g. `$lookup.pipeline`, `$facet.*`) recurse via\n * `structuralLowerPipeline`. Synchronous — no codec calls.\n */\nexport function structuralLowerStage(stage: MongoPipelineStage): Record<string, unknown> {\n switch (stage.kind) {\n case 'match':\n return { $match: structuralLowerFilter(stage.filter) };\n case 'project': {\n const projection: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(stage.projection)) {\n projection[key] = lowerProjectionValue(val);\n }\n return { $project: projection };\n }\n case 'sort':\n return { $sort: { ...stage.sort } };\n case 'limit':\n return { $limit: stage.limit };\n case 'skip':\n return { $skip: stage.skip };\n case 'lookup': {\n const lookup: Record<string, unknown> = {\n from: stage.from,\n as: stage.as,\n };\n if (stage.localField !== undefined) lookup['localField'] = stage.localField;\n if (stage.foreignField !== undefined) lookup['foreignField'] = stage.foreignField;\n if (stage.pipeline) {\n lookup['pipeline'] = structuralLowerPipeline(stage.pipeline);\n }\n if (stage.let_) {\n lookup['let'] = lowerExprRecord(stage.let_);\n }\n return { $lookup: lookup };\n }\n case 'unwind': {\n const unwind: Record<string, unknown> = {\n path: stage.path,\n preserveNullAndEmptyArrays: stage.preserveNullAndEmptyArrays,\n };\n if (stage.includeArrayIndex !== undefined) {\n unwind['includeArrayIndex'] = stage.includeArrayIndex;\n }\n return { $unwind: unwind };\n }\n case 'group': {\n const group: Record<string, unknown> = { _id: lowerGroupId(stage.groupId) };\n for (const [key, acc] of Object.entries(stage.accumulators)) {\n group[key] = lowerAggExpr(acc);\n }\n return { $group: group };\n }\n case 'addFields':\n return { $addFields: lowerExprRecord(stage.fields) };\n case 'replaceRoot':\n return { $replaceRoot: { newRoot: lowerAggExpr(stage.newRoot) } };\n case 'count':\n return { $count: stage.field };\n case 'sortByCount':\n return { $sortByCount: lowerAggExpr(stage.expr) };\n case 'sample':\n return { $sample: { size: stage.size } };\n case 'redact':\n return { $redact: lowerAggExpr(stage.expr) };\n case 'out':\n return { $out: stage.db ? { db: stage.db, coll: stage.collection } : stage.collection };\n case 'unionWith': {\n const unionWith: Record<string, unknown> = { coll: stage.collection };\n if (stage.pipeline) {\n unionWith['pipeline'] = structuralLowerPipeline(stage.pipeline);\n }\n return { $unionWith: unionWith };\n }\n case 'bucket': {\n const bucket: Record<string, unknown> = {\n groupBy: lowerAggExpr(stage.groupBy),\n boundaries: [...stage.boundaries],\n };\n if (stage.default_ !== undefined) bucket['default'] = stage.default_;\n if (stage.output) bucket['output'] = lowerExprRecord(stage.output);\n return { $bucket: bucket };\n }\n case 'bucketAuto': {\n const bucketAuto: Record<string, unknown> = {\n groupBy: lowerAggExpr(stage.groupBy),\n buckets: stage.buckets,\n };\n if (stage.output) bucketAuto['output'] = lowerExprRecord(stage.output);\n if (stage.granularity !== undefined) bucketAuto['granularity'] = stage.granularity;\n return { $bucketAuto: bucketAuto };\n }\n case 'geoNear': {\n const geoNear: Record<string, unknown> = {\n near: stage.near,\n distanceField: stage.distanceField,\n };\n if (stage.spherical !== undefined) geoNear['spherical'] = stage.spherical;\n if (stage.maxDistance !== undefined) geoNear['maxDistance'] = stage.maxDistance;\n if (stage.minDistance !== undefined) geoNear['minDistance'] = stage.minDistance;\n if (stage.query) geoNear['query'] = structuralLowerFilter(stage.query);\n if (stage.key !== undefined) geoNear['key'] = stage.key;\n if (stage.distanceMultiplier !== undefined)\n geoNear['distanceMultiplier'] = stage.distanceMultiplier;\n if (stage.includeLocs !== undefined) geoNear['includeLocs'] = stage.includeLocs;\n return { $geoNear: geoNear };\n }\n case 'facet': {\n const facet: Record<string, unknown> = {};\n for (const [key, pipeline] of Object.entries(stage.facets)) {\n facet[key] = structuralLowerPipeline(pipeline);\n }\n return { $facet: facet };\n }\n case 'graphLookup': {\n const graphLookup: Record<string, unknown> = {\n from: stage.from,\n startWith: lowerAggExpr(stage.startWith),\n connectFromField: stage.connectFromField,\n connectToField: stage.connectToField,\n as: stage.as,\n };\n if (stage.maxDepth !== undefined) graphLookup['maxDepth'] = stage.maxDepth;\n if (stage.depthField !== undefined) graphLookup['depthField'] = stage.depthField;\n if (stage.restrictSearchWithMatch)\n graphLookup['restrictSearchWithMatch'] = structuralLowerFilter(\n stage.restrictSearchWithMatch,\n );\n return { $graphLookup: graphLookup };\n }\n case 'merge': {\n const merge: Record<string, unknown> = { into: stage.into };\n if (stage.on !== undefined) merge['on'] = stage.on;\n if (stage.whenMatched !== undefined) {\n merge['whenMatched'] = Array.isArray(stage.whenMatched)\n ? structuralLowerPipeline(stage.whenMatched)\n : stage.whenMatched;\n }\n if (stage.whenNotMatched !== undefined) merge['whenNotMatched'] = stage.whenNotMatched;\n return { $merge: merge };\n }\n case 'setWindowFields': {\n const swf: Record<string, unknown> = {};\n if (stage.partitionBy) swf['partitionBy'] = lowerAggExpr(stage.partitionBy);\n if (stage.sortBy) swf['sortBy'] = { ...stage.sortBy };\n const output: Record<string, unknown> = {};\n for (const [key, wf] of Object.entries(stage.output)) {\n output[key] = lowerWindowField(wf);\n }\n swf['output'] = output;\n return { $setWindowFields: swf };\n }\n case 'densify': {\n const densify: Record<string, unknown> = {\n field: stage.field,\n range: { ...stage.range },\n };\n if (stage.partitionByFields) densify['partitionByFields'] = [...stage.partitionByFields];\n return { $densify: densify };\n }\n case 'fill': {\n const fill: Record<string, unknown> = {};\n if (stage.partitionBy) fill['partitionBy'] = lowerAggExpr(stage.partitionBy);\n if (stage.partitionByFields) fill['partitionByFields'] = [...stage.partitionByFields];\n if (stage.sortBy) fill['sortBy'] = { ...stage.sortBy };\n const output: Record<string, unknown> = {};\n for (const [key, fo] of Object.entries(stage.output)) {\n const entry: Record<string, unknown> = {};\n if (fo.method !== undefined) entry['method'] = fo.method;\n if (fo.value !== undefined) entry['value'] = lowerAggExpr(fo.value);\n output[key] = entry;\n }\n fill['output'] = output;\n return { $fill: fill };\n }\n case 'search': {\n const search: Record<string, unknown> = { ...stage.config };\n if (stage.index !== undefined) search['index'] = stage.index;\n return { $search: search };\n }\n case 'searchMeta': {\n const searchMeta: Record<string, unknown> = { ...stage.config };\n if (stage.index !== undefined) searchMeta['index'] = stage.index;\n return { $searchMeta: searchMeta };\n }\n case 'vectorSearch': {\n const vs: Record<string, unknown> = {\n index: stage.index,\n path: stage.path,\n queryVector: [...stage.queryVector],\n numCandidates: stage.numCandidates,\n limit: stage.limit,\n };\n if (stage.filter) vs['filter'] = { ...stage.filter };\n return { $vectorSearch: vs };\n }\n default: {\n const _exhaustive: never = stage;\n throw new Error(\n `Unhandled stage kind: ${blindCast<MongoPipelineStage, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,\n );\n }\n }\n}\n\nexport function structuralLowerPipeline(\n stages: ReadonlyArray<MongoPipelineStage>,\n): Array<Record<string, unknown>> {\n return stages.map((s) => structuralLowerStage(s));\n}\n","import type { CodecDescriptor, CodecTrait } from '@prisma-next/framework-components/codec';\nimport { voidParamsSchema } from '@prisma-next/framework-components/codec';\nimport {\n type MongoCodec,\n type MongoCodecRegistry,\n mongoCodec,\n newMongoCodecRegistry,\n} from '@prisma-next/mongo-codec';\nimport { ObjectId } from 'mongodb';\nimport {\n MONGO_BOOLEAN_CODEC_ID,\n MONGO_DATE_CODEC_ID,\n MONGO_DOUBLE_CODEC_ID,\n MONGO_INT32_CODEC_ID,\n MONGO_OBJECTID_CODEC_ID,\n MONGO_STRING_CODEC_ID,\n MONGO_VECTOR_CODEC_ID,\n} from './codec-ids';\n\nexport const mongoObjectIdCodec = mongoCodec({\n typeId: MONGO_OBJECTID_CODEC_ID,\n decode: (wire: ObjectId) => wire.toHexString(),\n encode: (value: string) => new ObjectId(value),\n});\n\nexport const mongoStringCodec = mongoCodec({\n typeId: MONGO_STRING_CODEC_ID,\n decode: (wire: string) => wire,\n encode: (value: string) => value,\n});\n\nexport const mongoDoubleCodec = mongoCodec({\n typeId: MONGO_DOUBLE_CODEC_ID,\n decode: (wire: number) => wire,\n encode: (value: number) => value,\n});\n\nexport const mongoInt32Codec = mongoCodec({\n typeId: MONGO_INT32_CODEC_ID,\n decode: (wire: number) => wire,\n encode: (value: number) => value,\n});\n\nexport const mongoBooleanCodec = mongoCodec({\n typeId: MONGO_BOOLEAN_CODEC_ID,\n decode: (wire: boolean) => wire,\n encode: (value: boolean) => value,\n});\n\nexport const mongoDateCodec = mongoCodec({\n typeId: MONGO_DATE_CODEC_ID,\n decode: (wire: Date) => wire,\n encode: (value: Date) => value,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n});\n\nexport const mongoVectorCodec = mongoCodec({\n typeId: MONGO_VECTOR_CODEC_ID,\n decode: (wire: readonly number[]) => wire,\n encode: (value: readonly number[]) => value,\n});\n\n/**\n * The canonical set of Mongo wire-type codecs.\n *\n * Single source of truth for both control- and runtime-plane adapter descriptors. Don't duplicate this list — import it.\n */\nexport const mongoStandardCodecs = [\n mongoObjectIdCodec,\n mongoStringCodec,\n mongoDoubleCodec,\n mongoInt32Codec,\n mongoBooleanCodec,\n mongoDateCodec,\n mongoVectorCodec,\n] as const;\n\n/**\n * Build a {@link CodecDescriptor} for a Mongo wire-type codec.\n *\n * Wraps an existing {@link MongoCodec} instance into a descriptor whose factory hands out the same shared codec. Mongo's full migration to descriptor-first authoring is tracked under TML-2324; for now the descriptor view is composed from the existing `mongoCodec()` outputs.\n */\nfunction descriptorFor<Id extends string>(\n codec: MongoCodec<Id, readonly CodecTrait[]>,\n metadata: {\n readonly traits: readonly CodecTrait[];\n readonly targetTypes: readonly string[];\n readonly renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;\n },\n): CodecDescriptor {\n // The descriptor's `P` is structurally `Record<string, unknown>` for codecs that take params (Mongo `vector`); non-parameterized codecs ignore the slot. Cast through `unknown` to fit the `CodecDescriptor` slot's `(params: P) => …` typing without leaking a per-codec `P` into the heterogeneous descriptor list.\n const renderOutputType = metadata.renderOutputType as\n | CodecDescriptor['renderOutputType']\n | undefined;\n return {\n codecId: codec.id,\n traits: metadata.traits,\n targetTypes: metadata.targetTypes,\n paramsSchema: voidParamsSchema as CodecDescriptor['paramsSchema'],\n isParameterized: false,\n factory: (() => () => codec) as CodecDescriptor['factory'],\n ...(renderOutputType !== undefined ? { renderOutputType } : {}),\n };\n}\n\nconst renderVectorOutputType = (typeParams: Record<string, unknown>): string | undefined => {\n const length = typeParams['length'];\n if (length === undefined) return undefined;\n if (\n typeof length !== 'number' ||\n !Number.isFinite(length) ||\n !Number.isInteger(length) ||\n length <= 0\n ) {\n throw new Error('renderOutputType: expected positive integer \"length\" for Vector');\n }\n return `Vector<${length}>`;\n};\n\n/**\n * Mongo wire-type codec descriptors. Static metadata for `traits`, `targetTypes`, and `renderOutputType` lives here (the descriptor shape) — `MongoCodec` itself is narrow and only carries the four conversion methods (TML-2357).\n */\nexport const mongoCodecDescriptors: ReadonlyArray<CodecDescriptor> = [\n descriptorFor(mongoObjectIdCodec, { traits: ['equality'], targetTypes: ['objectId'] }),\n descriptorFor(mongoStringCodec, {\n traits: ['equality', 'order', 'textual'],\n targetTypes: ['string'],\n }),\n descriptorFor(mongoDoubleCodec, {\n traits: ['equality', 'order', 'numeric'],\n targetTypes: ['double'],\n }),\n descriptorFor(mongoInt32Codec, {\n traits: ['equality', 'order', 'numeric'],\n targetTypes: ['int'],\n }),\n descriptorFor(mongoBooleanCodec, { traits: ['equality', 'boolean'], targetTypes: ['bool'] }),\n descriptorFor(mongoDateCodec, { traits: ['equality', 'order'], targetTypes: ['date'] }),\n descriptorFor(mongoVectorCodec, {\n traits: ['equality'],\n targetTypes: ['vector'],\n renderOutputType: renderVectorOutputType,\n }),\n];\n\n/**\n * Lookup descriptor metadata by codec id — used by tests and for descriptor-side reads of static metadata.\n */\nexport function mongoDescriptorById(codecId: string): CodecDescriptor | undefined {\n return mongoCodecDescriptors.find((d) => d.codecId === codecId);\n}\n\n/**\n * Build a {@link MongoCodecRegistry} preloaded with the standard Mongo wire-type codecs.\n *\n * Single point of truth for adapter-side codec construction: used by the legacy synchronous `createMongoAdapter()` factory and by the runtime adapter descriptor's `codecs()` getter. Userland code obtains a registry via the framework's execution-stack composition (see `createMongoExecutionContext`) instead of calling this directly.\n */\nexport function buildStandardCodecRegistry(): MongoCodecRegistry {\n const registry = newMongoCodecRegistry();\n for (const codec of mongoStandardCodecs) {\n registry.register(codec);\n }\n return registry;\n}\n","import type { CodecCallContext } from '@prisma-next/framework-components/codec';\nimport type { MongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type { MongoAdapter, MongoLoweredDraft } from '@prisma-next/mongo-lowering';\nimport type {\n MongoQueryPlan,\n MongoUpdatePipelineStage,\n MongoUpdateSpec,\n} from '@prisma-next/mongo-query-ast/execution';\nimport type { AnyMongoWireCommand } from '@prisma-next/mongo-wire';\nimport {\n AggregateWireCommand,\n DeleteManyWireCommand,\n DeleteOneWireCommand,\n FindOneAndDeleteWireCommand,\n FindOneAndUpdateWireCommand,\n InsertManyWireCommand,\n InsertOneWireCommand,\n UpdateManyWireCommand,\n UpdateOneWireCommand,\n} from '@prisma-next/mongo-wire';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { buildStandardCodecRegistry } from './core/codecs';\nimport { structuralLowerFilter, structuralLowerPipeline } from './lowering';\nimport { resolveDraftDoc } from './resolve-value';\n\nfunction isUpdatePipeline(\n update: MongoUpdateSpec,\n): update is ReadonlyArray<MongoUpdatePipelineStage> {\n return Array.isArray(update);\n}\n\nfunction isDraftUpdatePipeline(\n update: Record<string, unknown> | ReadonlyArray<Record<string, unknown>>,\n): update is ReadonlyArray<Record<string, unknown>> {\n return Array.isArray(update);\n}\n\nasync function resolveUpdate(\n update: Record<string, unknown> | ReadonlyArray<Record<string, unknown>>,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<Record<string, unknown> | ReadonlyArray<Record<string, unknown>>> {\n if (isDraftUpdatePipeline(update)) {\n return Promise.all(update.map((stage) => resolveDraftDoc(stage, codecs, ctx)));\n }\n return resolveDraftDoc(update, codecs, ctx);\n}\n\nclass MongoAdapterImpl implements MongoAdapter {\n readonly #codecs: MongoCodecRegistry;\n\n constructor(codecs: MongoCodecRegistry) {\n this.#codecs = codecs;\n }\n\n structuralLower(plan: MongoQueryPlan): MongoLoweredDraft {\n const { command } = plan;\n switch (command.kind) {\n case 'insertOne':\n return { kind: 'insertOne', collection: command.collection, document: command.document };\n case 'insertMany':\n return {\n kind: 'insertMany',\n collection: command.collection,\n documents: command.documents,\n };\n case 'updateOne':\n return {\n kind: 'updateOne',\n collection: command.collection,\n filter: structuralLowerFilter(command.filter),\n update: isUpdatePipeline(command.update)\n ? structuralLowerPipeline(command.update)\n : command.update,\n upsert: command.upsert,\n };\n case 'updateMany':\n return {\n kind: 'updateMany',\n collection: command.collection,\n filter: structuralLowerFilter(command.filter),\n update: isUpdatePipeline(command.update)\n ? structuralLowerPipeline(command.update)\n : command.update,\n upsert: command.upsert,\n };\n case 'deleteOne':\n return {\n kind: 'deleteOne',\n collection: command.collection,\n filter: structuralLowerFilter(command.filter),\n };\n case 'deleteMany':\n return {\n kind: 'deleteMany',\n collection: command.collection,\n filter: structuralLowerFilter(command.filter),\n };\n case 'findOneAndUpdate':\n return {\n kind: 'findOneAndUpdate',\n collection: command.collection,\n filter: structuralLowerFilter(command.filter),\n update: isUpdatePipeline(command.update)\n ? structuralLowerPipeline(command.update)\n : command.update,\n upsert: command.upsert,\n sort: command.sort,\n returnDocument: command.returnDocument,\n };\n case 'findOneAndDelete':\n return {\n kind: 'findOneAndDelete',\n collection: command.collection,\n filter: structuralLowerFilter(command.filter),\n sort: command.sort,\n };\n case 'aggregate':\n return {\n kind: 'aggregate',\n collection: command.collection,\n pipeline: structuralLowerPipeline(command.pipeline),\n };\n case 'rawAggregate':\n return { kind: 'rawAggregate', collection: command.collection, pipeline: command.pipeline };\n case 'rawInsertOne':\n return {\n kind: 'rawInsertOne',\n collection: command.collection,\n document: command.document,\n };\n case 'rawInsertMany':\n return {\n kind: 'rawInsertMany',\n collection: command.collection,\n documents: command.documents,\n };\n case 'rawUpdateOne':\n return {\n kind: 'rawUpdateOne',\n collection: command.collection,\n filter: command.filter,\n update: command.update,\n };\n case 'rawUpdateMany':\n return {\n kind: 'rawUpdateMany',\n collection: command.collection,\n filter: command.filter,\n update: command.update,\n };\n case 'rawDeleteOne':\n return { kind: 'rawDeleteOne', collection: command.collection, filter: command.filter };\n case 'rawDeleteMany':\n return { kind: 'rawDeleteMany', collection: command.collection, filter: command.filter };\n case 'rawFindOneAndUpdate':\n return {\n kind: 'rawFindOneAndUpdate',\n collection: command.collection,\n filter: command.filter,\n update: command.update,\n upsert: command.upsert,\n sort: command.sort,\n returnDocument: command.returnDocument,\n };\n case 'rawFindOneAndDelete':\n return {\n kind: 'rawFindOneAndDelete',\n collection: command.collection,\n filter: command.filter,\n sort: command.sort,\n };\n // v8 ignore next 4\n default: {\n const _exhaustive: never = command;\n throw new Error(\n `Unknown command kind: ${blindCast<{ kind: string }, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,\n );\n }\n }\n }\n\n async resolveParams(\n draft: MongoLoweredDraft,\n ctx: CodecCallContext,\n ): Promise<AnyMongoWireCommand> {\n switch (draft.kind) {\n case 'insertOne':\n return new InsertOneWireCommand(\n draft.collection,\n await resolveDraftDoc(draft.document, this.#codecs, ctx),\n );\n case 'insertMany':\n return new InsertManyWireCommand(\n draft.collection,\n await Promise.all(draft.documents.map((doc) => resolveDraftDoc(doc, this.#codecs, ctx))),\n );\n case 'updateOne': {\n const [filter, update] = await Promise.all([\n resolveDraftDoc(draft.filter, this.#codecs, ctx),\n resolveUpdate(draft.update, this.#codecs, ctx),\n ]);\n return new UpdateOneWireCommand(draft.collection, filter, update, draft.upsert);\n }\n case 'updateMany': {\n const [filter, update] = await Promise.all([\n resolveDraftDoc(draft.filter, this.#codecs, ctx),\n resolveUpdate(draft.update, this.#codecs, ctx),\n ]);\n return new UpdateManyWireCommand(draft.collection, filter, update, draft.upsert);\n }\n case 'deleteOne':\n return new DeleteOneWireCommand(\n draft.collection,\n await resolveDraftDoc(draft.filter, this.#codecs, ctx),\n );\n case 'deleteMany':\n return new DeleteManyWireCommand(\n draft.collection,\n await resolveDraftDoc(draft.filter, this.#codecs, ctx),\n );\n case 'findOneAndUpdate': {\n const [filter, update] = await Promise.all([\n resolveDraftDoc(draft.filter, this.#codecs, ctx),\n resolveUpdate(draft.update, this.#codecs, ctx),\n ]);\n return new FindOneAndUpdateWireCommand(\n draft.collection,\n filter,\n update,\n draft.upsert,\n draft.sort,\n draft.returnDocument,\n );\n }\n case 'findOneAndDelete':\n return new FindOneAndDeleteWireCommand(\n draft.collection,\n await resolveDraftDoc(draft.filter, this.#codecs, ctx),\n draft.sort,\n );\n case 'aggregate':\n return new AggregateWireCommand(\n draft.collection,\n await Promise.all(\n draft.pipeline.map((stage) => resolveDraftDoc(stage, this.#codecs, ctx)),\n ),\n );\n case 'rawAggregate':\n return new AggregateWireCommand(draft.collection, draft.pipeline);\n case 'rawInsertOne':\n return new InsertOneWireCommand(draft.collection, draft.document);\n case 'rawInsertMany':\n return new InsertManyWireCommand(draft.collection, draft.documents);\n case 'rawUpdateOne':\n return new UpdateOneWireCommand(draft.collection, draft.filter, draft.update);\n case 'rawUpdateMany':\n return new UpdateManyWireCommand(draft.collection, draft.filter, draft.update);\n case 'rawDeleteOne':\n return new DeleteOneWireCommand(draft.collection, draft.filter);\n case 'rawDeleteMany':\n return new DeleteManyWireCommand(draft.collection, draft.filter);\n case 'rawFindOneAndUpdate':\n return new FindOneAndUpdateWireCommand(\n draft.collection,\n draft.filter,\n draft.update,\n draft.upsert,\n draft.sort,\n draft.returnDocument,\n );\n case 'rawFindOneAndDelete':\n return new FindOneAndDeleteWireCommand(draft.collection, draft.filter, draft.sort);\n // v8 ignore next 4\n default: {\n const _exhaustive: never = draft;\n throw new Error(\n `Unknown draft kind: ${blindCast<{ kind: string }, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,\n );\n }\n }\n }\n\n lower(plan: MongoQueryPlan, ctx: CodecCallContext): Promise<AnyMongoWireCommand> {\n return this.resolveParams(this.structuralLower(plan), ctx);\n }\n}\n\n/**\n * Construct a Mongo adapter with the standard wire-type codecs registered\n * for encode-side dispatch (`MongoParamRef.codecId` lookups).\n *\n * The runtime-side codec registry the runtime decodes against is composed\n * separately by `createMongoExecutionContext`. This factory exists for\n * direct adapter use (the runtime descriptor's `create(stack)` calls\n * through it). User code should compose a stack/context instead.\n */\nexport function createMongoAdapter(): MongoAdapter {\n return new MongoAdapterImpl(buildStandardCodecRegistry());\n}\n\n/**\n * Internal escape hatch — direct adapter construction with a caller-supplied\n * codec registry, used only by adapter unit tests that exercise the\n * encode-side codec-dispatch path with synthetic codecs. Not re-exported\n * from the package's public surface and not for production use; production\n * callers compose a `MongoExecutionStack` and `MongoExecutionContext`.\n */\nexport function _unstable_createMongoAdapterWithCodecs(codecs: MongoCodecRegistry): MongoAdapter {\n return new MongoAdapterImpl(codecs);\n}\n"],"mappings":";;;;;;;;;AAAA,MAAa,0BAA0B;AACvC,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;AACrC,MAAa,uBAAuB;AACpC,MAAa,yBAAyB;AACtC,MAAa,sBAAsB;AACnC,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACqCrC,eAAsB,aACpB,OACA,QACA,KACkB;CAClB,aAAa,KAAK,QAAQ;CAC1B,MAAM,SAAS,IAAI;CAEnB,IAAI,iBAAiB,eAAe;EAClC,IAAI,MAAM,SAAS;GACjB,MAAM,QAAQ,OAAO,IAAI,MAAM,OAAO;GACtC,IAAI,OAAO,QACT,IAAI;IAOF,OAAO,MAAM,iBADG,MAAM,OAAO,MAAM,OAAO,GACN,GAAG,QAAQ,QAAQ;GACzD,SAAS,OAAO;IACd,kBAAkB,OAAO,OAAO,MAAM,EAAE;GAC1C;EAEJ;EACA,OAAO,MAAM;CACf;CACA,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAET,IAAI,iBAAiB,MACnB,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GAErB,OAAO,iBADO,QAAQ,IAAI,MAAM,KAAK,MAAM,aAAa,GAAG,QAAQ,GAAG,CAAC,CAC3C,GAAG,QAAQ,QAAQ;CAEjD,MAAM,UAAU,OAAO,QAAQ,KAAK;CAEpC,MAAM,WAAW,MAAM,iBADX,QAAQ,IAAI,QAAQ,KAAK,GAAG,SAAS,aAAa,KAAK,QAAQ,GAAG,CAAC,CACrC,GAAG,QAAQ,QAAQ;CAC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
{"version":3,"file":"mongo-adapter-JuKx_-h9.d.mts","names":[],"sources":["../src/mongo-adapter.ts"],"mappings":";;;;;;AAySA;;;;AAAkD;;;iBAAlC,kBAAA,CAAA,GAAsB,YAAY"}
|
package/dist/runtime.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/exports/runtime.ts"],"mappings":";;;;;;;AAMgE;;UAStD,2BAAA,SACA,sBAAA,oBACN,
|
|
1
|
+
{"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/exports/runtime.ts"],"mappings":";;;;;;;AAMgE;;UAStD,2BAAA,SACA,sBAAA,oBACN,YAAY;AAAA,cAEV,6BAAA,EAA+B,wBAAA,mBAGnC,2BAAA;EAAA,SAES,MAAA,QAAc,kBAAA;AAAA"}
|
package/dist/runtime.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as buildStandardCodecRegistry, r as mongoCodecDescriptors, t as createMongoAdapter } from "./mongo-adapter-
|
|
1
|
+
import { n as buildStandardCodecRegistry, r as mongoCodecDescriptors, t as createMongoAdapter } from "./mongo-adapter-DAC5qq3o.mjs";
|
|
2
2
|
//#region src/exports/runtime.ts
|
|
3
3
|
const mongoRuntimeAdapterDescriptor = {
|
|
4
4
|
kind: "adapter",
|
|
@@ -13,7 +13,9 @@ const mongoRuntimeAdapterDescriptor = {
|
|
|
13
13
|
return {
|
|
14
14
|
familyId: "mongo",
|
|
15
15
|
targetId: "mongo",
|
|
16
|
-
lower: adapter.lower.bind(adapter)
|
|
16
|
+
lower: adapter.lower.bind(adapter),
|
|
17
|
+
structuralLower: adapter.structuralLower.bind(adapter),
|
|
18
|
+
resolveParams: adapter.resolveParams.bind(adapter)
|
|
17
19
|
};
|
|
18
20
|
}
|
|
19
21
|
};
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","names":[],"sources":["../src/exports/runtime.ts"],"sourcesContent":["import type {\n ExecutionStack,\n RuntimeAdapterDescriptor,\n RuntimeAdapterInstance,\n} from '@prisma-next/framework-components/execution';\nimport type { MongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type { MongoAdapter } from '@prisma-next/mongo-lowering';\nimport { buildStandardCodecRegistry, mongoCodecDescriptors } from '../core/codecs';\nimport { createMongoAdapter } from '../mongo-adapter';\n\n/**\n * adapter-mongo deliberately does NOT import the `MongoRuntimeAdapterDescriptor` type alias from `@prisma-next/mongo-runtime`. The adapter package is downstream of the Mongo runtime package only conceptually; introducing a hard import would create a workspace dependency cycle (`mongo-runtime` consumes the runtime descriptor's `create(stack)` factory; `adapter-mongo` would then need `mongo-runtime` to type the\n * descriptor). The descriptor is shaped to satisfy the framework's `RuntimeAdapterDescriptor` plus the structural `MongoStaticContributions` (`codecs()`) that `@prisma-next/mongo-runtime` narrows to at composition time. This mirrors the `target-postgres` ↔ `sql-runtime` decoupling pattern.\n */\n\ninterface MongoRuntimeAdapterInstance\n extends RuntimeAdapterInstance<'mongo', 'mongo'>,\n MongoAdapter {}\n\nconst mongoRuntimeAdapterDescriptor: RuntimeAdapterDescriptor<\n 'mongo',\n 'mongo',\n MongoRuntimeAdapterInstance\n> & {\n readonly codecs: () => MongoCodecRegistry;\n} = {\n kind: 'adapter',\n id: 'mongo',\n familyId: 'mongo',\n targetId: 'mongo',\n version: '0.0.1',\n types: {\n codecTypes: {\n codecDescriptors: mongoCodecDescriptors,\n },\n },\n codecs: buildStandardCodecRegistry,\n create(_stack: ExecutionStack<'mongo', 'mongo'>): MongoRuntimeAdapterInstance {\n const adapter = createMongoAdapter();\n return {\n familyId: 'mongo' as const,\n targetId: 'mongo' as const,\n lower: adapter.lower.bind(adapter),\n };\n },\n};\n\nexport default mongoRuntimeAdapterDescriptor;\n"],"mappings":";;AAmBA,MAAM,gCAMF;CACF,MAAM;CACN,IAAI;CACJ,UAAU;CACV,UAAU;CACV,SAAS;CACT,OAAO,EACL,YAAY,EACV,kBAAkB,
|
|
1
|
+
{"version":3,"file":"runtime.mjs","names":[],"sources":["../src/exports/runtime.ts"],"sourcesContent":["import type {\n ExecutionStack,\n RuntimeAdapterDescriptor,\n RuntimeAdapterInstance,\n} from '@prisma-next/framework-components/execution';\nimport type { MongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type { MongoAdapter } from '@prisma-next/mongo-lowering';\nimport { buildStandardCodecRegistry, mongoCodecDescriptors } from '../core/codecs';\nimport { createMongoAdapter } from '../mongo-adapter';\n\n/**\n * adapter-mongo deliberately does NOT import the `MongoRuntimeAdapterDescriptor` type alias from `@prisma-next/mongo-runtime`. The adapter package is downstream of the Mongo runtime package only conceptually; introducing a hard import would create a workspace dependency cycle (`mongo-runtime` consumes the runtime descriptor's `create(stack)` factory; `adapter-mongo` would then need `mongo-runtime` to type the\n * descriptor). The descriptor is shaped to satisfy the framework's `RuntimeAdapterDescriptor` plus the structural `MongoStaticContributions` (`codecs()`) that `@prisma-next/mongo-runtime` narrows to at composition time. This mirrors the `target-postgres` ↔ `sql-runtime` decoupling pattern.\n */\n\ninterface MongoRuntimeAdapterInstance\n extends RuntimeAdapterInstance<'mongo', 'mongo'>,\n MongoAdapter {}\n\nconst mongoRuntimeAdapterDescriptor: RuntimeAdapterDescriptor<\n 'mongo',\n 'mongo',\n MongoRuntimeAdapterInstance\n> & {\n readonly codecs: () => MongoCodecRegistry;\n} = {\n kind: 'adapter',\n id: 'mongo',\n familyId: 'mongo',\n targetId: 'mongo',\n version: '0.0.1',\n types: {\n codecTypes: {\n codecDescriptors: mongoCodecDescriptors,\n },\n },\n codecs: buildStandardCodecRegistry,\n create(_stack: ExecutionStack<'mongo', 'mongo'>): MongoRuntimeAdapterInstance {\n const adapter = createMongoAdapter();\n return {\n familyId: 'mongo' as const,\n targetId: 'mongo' as const,\n lower: adapter.lower.bind(adapter),\n structuralLower: adapter.structuralLower.bind(adapter),\n resolveParams: adapter.resolveParams.bind(adapter),\n };\n },\n};\n\nexport default mongoRuntimeAdapterDescriptor;\n"],"mappings":";;AAmBA,MAAM,gCAMF;CACF,MAAM;CACN,IAAI;CACJ,UAAU;CACV,UAAU;CACV,SAAS;CACT,OAAO,EACL,YAAY,EACV,kBAAkB,sBACpB,EACF;CACA,QAAQ;CACR,OAAO,QAAuE;EAC5E,MAAM,UAAU,mBAAmB;EACnC,OAAO;GACL,UAAU;GACV,UAAU;GACV,OAAO,QAAQ,MAAM,KAAK,OAAO;GACjC,iBAAiB,QAAQ,gBAAgB,KAAK,OAAO;GACrD,eAAe,QAAQ,cAAc,KAAK,OAAO;EACnD;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,45 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/adapter-mongo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "MongoDB adapter for Prisma Next (lowers commands to wire format)",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@prisma-next/config": "0.
|
|
10
|
-
"@prisma-next/contract": "0.
|
|
11
|
-
"@prisma-next/errors": "0.
|
|
12
|
-
"@prisma-next/family-mongo": "0.
|
|
13
|
-
"@prisma-next/framework-components": "0.
|
|
14
|
-
"@prisma-next/mongo-codec": "0.
|
|
15
|
-
"@prisma-next/mongo-contract": "0.
|
|
16
|
-
"@prisma-next/mongo-lowering": "0.
|
|
17
|
-
"@prisma-next/mongo-query-ast": "0.
|
|
18
|
-
"@prisma-next/mongo-schema-ir": "0.
|
|
19
|
-
"@prisma-next/mongo-value": "0.
|
|
20
|
-
"@prisma-next/mongo-wire": "0.
|
|
21
|
-
"@prisma-next/operations": "0.
|
|
22
|
-
"@prisma-next/utils": "0.
|
|
23
|
-
"arktype": "^2.2.0"
|
|
24
|
-
"mongodb": "^6.16.0"
|
|
9
|
+
"@prisma-next/config": "0.12.0",
|
|
10
|
+
"@prisma-next/contract": "0.12.0",
|
|
11
|
+
"@prisma-next/errors": "0.12.0",
|
|
12
|
+
"@prisma-next/family-mongo": "0.12.0",
|
|
13
|
+
"@prisma-next/framework-components": "0.12.0",
|
|
14
|
+
"@prisma-next/mongo-codec": "0.12.0",
|
|
15
|
+
"@prisma-next/mongo-contract": "0.12.0",
|
|
16
|
+
"@prisma-next/mongo-lowering": "0.12.0",
|
|
17
|
+
"@prisma-next/mongo-query-ast": "0.12.0",
|
|
18
|
+
"@prisma-next/mongo-schema-ir": "0.12.0",
|
|
19
|
+
"@prisma-next/mongo-value": "0.12.0",
|
|
20
|
+
"@prisma-next/mongo-wire": "0.12.0",
|
|
21
|
+
"@prisma-next/operations": "0.12.0",
|
|
22
|
+
"@prisma-next/utils": "0.12.0",
|
|
23
|
+
"arktype": "^2.2.0"
|
|
25
24
|
},
|
|
26
25
|
"devDependencies": {
|
|
27
|
-
"
|
|
28
|
-
"@prisma-next/
|
|
29
|
-
"@prisma-next/
|
|
30
|
-
"@prisma-next/psl
|
|
31
|
-
"@prisma-next/
|
|
32
|
-
"@prisma-next/
|
|
33
|
-
"@prisma-next/
|
|
26
|
+
"mongodb": "^7.2.0",
|
|
27
|
+
"@prisma-next/driver-mongo": "0.12.0",
|
|
28
|
+
"@prisma-next/errors": "0.12.0",
|
|
29
|
+
"@prisma-next/mongo-contract-psl": "0.12.0",
|
|
30
|
+
"@prisma-next/psl-parser": "0.12.0",
|
|
31
|
+
"@prisma-next/test-utils": "0.12.0",
|
|
32
|
+
"@prisma-next/tsconfig": "0.12.0",
|
|
33
|
+
"@prisma-next/tsdown": "0.12.0",
|
|
34
34
|
"mongodb-memory-server": "11.1.0",
|
|
35
35
|
"tsdown": "0.22.0",
|
|
36
36
|
"typescript": "5.9.3",
|
|
37
37
|
"vitest": "4.1.6"
|
|
38
38
|
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"mongodb": "^7.0.0",
|
|
41
|
+
"typescript": ">=5.9"
|
|
42
|
+
},
|
|
43
|
+
"peerDependenciesMeta": {
|
|
44
|
+
"typescript": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
},
|
|
39
48
|
"files": [
|
|
40
49
|
"dist",
|
|
41
50
|
"src"
|
|
42
51
|
],
|
|
52
|
+
"types": "./dist/index.d.mts",
|
|
43
53
|
"exports": {
|
|
44
54
|
".": "./dist/index.mjs",
|
|
45
55
|
"./codec-types": "./dist/codec-types.mjs",
|
|
@@ -47,7 +57,9 @@
|
|
|
47
57
|
"./runtime": "./dist/runtime.mjs",
|
|
48
58
|
"./package.json": "./package.json"
|
|
49
59
|
},
|
|
50
|
-
"
|
|
60
|
+
"engines": {
|
|
61
|
+
"node": ">=24"
|
|
62
|
+
},
|
|
51
63
|
"repository": {
|
|
52
64
|
"type": "git",
|
|
53
65
|
"url": "https://github.com/prisma/prisma-next.git",
|
package/src/exports/runtime.ts
CHANGED
|
@@ -41,6 +41,8 @@ const mongoRuntimeAdapterDescriptor: RuntimeAdapterDescriptor<
|
|
|
41
41
|
familyId: 'mongo' as const,
|
|
42
42
|
targetId: 'mongo' as const,
|
|
43
43
|
lower: adapter.lower.bind(adapter),
|
|
44
|
+
structuralLower: adapter.structuralLower.bind(adapter),
|
|
45
|
+
resolveParams: adapter.resolveParams.bind(adapter),
|
|
44
46
|
};
|
|
45
47
|
},
|
|
46
48
|
};
|
package/src/lowering.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type {
|
|
|
11
11
|
} from '@prisma-next/mongo-query-ast/execution';
|
|
12
12
|
import { isExprArray, isRecordArgs } from '@prisma-next/mongo-query-ast/execution';
|
|
13
13
|
import type { Document } from '@prisma-next/mongo-value';
|
|
14
|
+
import { blindCast } from '@prisma-next/utils/casts';
|
|
14
15
|
import { resolveValue } from './resolve-value';
|
|
15
16
|
|
|
16
17
|
// Biome flags `{ then: ... }` as a thenable object (noThenProperty). Build via Object.fromEntries to avoid.
|
|
@@ -138,6 +139,36 @@ export function lowerAggExpr(expr: MongoAggExpr): unknown {
|
|
|
138
139
|
return expr.accept(aggExprLoweringVisitor);
|
|
139
140
|
}
|
|
140
141
|
|
|
142
|
+
/**
|
|
143
|
+
* Structural phase of filter lowering: transforms the filter AST into a
|
|
144
|
+
* plain object without resolving any `MongoParamRef` leaves. Field filter
|
|
145
|
+
* values remain as `MongoValue` (which includes `MongoParamRef`), so the
|
|
146
|
+
* returned document can be passed to `resolveDraftDoc` in the resolve phase.
|
|
147
|
+
* Synchronous — no codec calls.
|
|
148
|
+
*/
|
|
149
|
+
export function structuralLowerFilter(filter: MongoFilterExpr): Record<string, unknown> {
|
|
150
|
+
switch (filter.kind) {
|
|
151
|
+
case 'field':
|
|
152
|
+
return { [filter.field]: { [filter.op]: filter.value } };
|
|
153
|
+
case 'and':
|
|
154
|
+
return { $and: filter.exprs.map((e) => structuralLowerFilter(e)) };
|
|
155
|
+
case 'or':
|
|
156
|
+
return { $or: filter.exprs.map((e) => structuralLowerFilter(e)) };
|
|
157
|
+
case 'not':
|
|
158
|
+
return { $nor: [structuralLowerFilter(filter.expr)] };
|
|
159
|
+
case 'exists':
|
|
160
|
+
return { [filter.field]: { $exists: filter.exists } };
|
|
161
|
+
case 'expr':
|
|
162
|
+
return { $expr: lowerAggExpr(filter.aggExpr) };
|
|
163
|
+
default: {
|
|
164
|
+
const _exhaustive: never = filter;
|
|
165
|
+
throw new Error(
|
|
166
|
+
`Unhandled filter kind: ${blindCast<MongoFilterExpr, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
141
172
|
export async function lowerFilter(
|
|
142
173
|
filter: MongoFilterExpr,
|
|
143
174
|
codecs: MongoCodecRegistry,
|
|
@@ -158,7 +189,9 @@ export async function lowerFilter(
|
|
|
158
189
|
return { $expr: lowerAggExpr(filter.aggExpr) };
|
|
159
190
|
default: {
|
|
160
191
|
const _exhaustive: never = filter;
|
|
161
|
-
throw new Error(
|
|
192
|
+
throw new Error(
|
|
193
|
+
`Unhandled filter kind: ${blindCast<MongoFilterExpr, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,
|
|
194
|
+
);
|
|
162
195
|
}
|
|
163
196
|
}
|
|
164
197
|
}
|
|
@@ -167,6 +200,12 @@ function isAggExprNode(value: object): value is MongoAggExpr {
|
|
|
167
200
|
return 'accept' in value && typeof value.accept === 'function';
|
|
168
201
|
}
|
|
169
202
|
|
|
203
|
+
function isAggExprArray(
|
|
204
|
+
val: MongoAggExpr | ReadonlyArray<MongoAggExpr>,
|
|
205
|
+
): val is ReadonlyArray<MongoAggExpr> {
|
|
206
|
+
return Array.isArray(val);
|
|
207
|
+
}
|
|
208
|
+
|
|
170
209
|
function lowerGroupId(groupId: MongoGroupId): unknown {
|
|
171
210
|
if (groupId === null) return null;
|
|
172
211
|
if (isAggExprNode(groupId)) return lowerAggExpr(groupId);
|
|
@@ -178,10 +217,10 @@ function lowerExprRecord(
|
|
|
178
217
|
): Record<string, unknown> {
|
|
179
218
|
const result: Record<string, unknown> = {};
|
|
180
219
|
for (const [key, val] of Object.entries(fields)) {
|
|
181
|
-
if (
|
|
182
|
-
result[key] = val.map((v
|
|
220
|
+
if (isAggExprArray(val)) {
|
|
221
|
+
result[key] = val.map((v) => lowerAggExpr(v));
|
|
183
222
|
} else {
|
|
184
|
-
result[key] = lowerAggExpr(val
|
|
223
|
+
result[key] = lowerAggExpr(val);
|
|
185
224
|
}
|
|
186
225
|
}
|
|
187
226
|
return result;
|
|
@@ -417,7 +456,9 @@ export async function lowerStage(
|
|
|
417
456
|
}
|
|
418
457
|
default: {
|
|
419
458
|
const _exhaustive: never = stage;
|
|
420
|
-
throw new Error(
|
|
459
|
+
throw new Error(
|
|
460
|
+
`Unhandled stage kind: ${blindCast<MongoPipelineStage, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,
|
|
461
|
+
);
|
|
421
462
|
}
|
|
422
463
|
}
|
|
423
464
|
}
|
|
@@ -429,3 +470,218 @@ export async function lowerPipeline(
|
|
|
429
470
|
): Promise<Array<Record<string, unknown>>> {
|
|
430
471
|
return Promise.all(stages.map((s) => lowerStage(s, codecs, ctx)));
|
|
431
472
|
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Structural phase of stage lowering: mirrors `lowerStage` but defers all
|
|
476
|
+
* `MongoParamRef` resolution. Filter sub-documents within stages (e.g.
|
|
477
|
+
* `$match`, `$geoNear.query`, `$graphLookup.restrictSearchWithMatch`) are
|
|
478
|
+
* produced by `structuralLowerFilter` and therefore retain `MongoParamRef`
|
|
479
|
+
* leaves. Sub-pipelines (e.g. `$lookup.pipeline`, `$facet.*`) recurse via
|
|
480
|
+
* `structuralLowerPipeline`. Synchronous — no codec calls.
|
|
481
|
+
*/
|
|
482
|
+
export function structuralLowerStage(stage: MongoPipelineStage): Record<string, unknown> {
|
|
483
|
+
switch (stage.kind) {
|
|
484
|
+
case 'match':
|
|
485
|
+
return { $match: structuralLowerFilter(stage.filter) };
|
|
486
|
+
case 'project': {
|
|
487
|
+
const projection: Record<string, unknown> = {};
|
|
488
|
+
for (const [key, val] of Object.entries(stage.projection)) {
|
|
489
|
+
projection[key] = lowerProjectionValue(val);
|
|
490
|
+
}
|
|
491
|
+
return { $project: projection };
|
|
492
|
+
}
|
|
493
|
+
case 'sort':
|
|
494
|
+
return { $sort: { ...stage.sort } };
|
|
495
|
+
case 'limit':
|
|
496
|
+
return { $limit: stage.limit };
|
|
497
|
+
case 'skip':
|
|
498
|
+
return { $skip: stage.skip };
|
|
499
|
+
case 'lookup': {
|
|
500
|
+
const lookup: Record<string, unknown> = {
|
|
501
|
+
from: stage.from,
|
|
502
|
+
as: stage.as,
|
|
503
|
+
};
|
|
504
|
+
if (stage.localField !== undefined) lookup['localField'] = stage.localField;
|
|
505
|
+
if (stage.foreignField !== undefined) lookup['foreignField'] = stage.foreignField;
|
|
506
|
+
if (stage.pipeline) {
|
|
507
|
+
lookup['pipeline'] = structuralLowerPipeline(stage.pipeline);
|
|
508
|
+
}
|
|
509
|
+
if (stage.let_) {
|
|
510
|
+
lookup['let'] = lowerExprRecord(stage.let_);
|
|
511
|
+
}
|
|
512
|
+
return { $lookup: lookup };
|
|
513
|
+
}
|
|
514
|
+
case 'unwind': {
|
|
515
|
+
const unwind: Record<string, unknown> = {
|
|
516
|
+
path: stage.path,
|
|
517
|
+
preserveNullAndEmptyArrays: stage.preserveNullAndEmptyArrays,
|
|
518
|
+
};
|
|
519
|
+
if (stage.includeArrayIndex !== undefined) {
|
|
520
|
+
unwind['includeArrayIndex'] = stage.includeArrayIndex;
|
|
521
|
+
}
|
|
522
|
+
return { $unwind: unwind };
|
|
523
|
+
}
|
|
524
|
+
case 'group': {
|
|
525
|
+
const group: Record<string, unknown> = { _id: lowerGroupId(stage.groupId) };
|
|
526
|
+
for (const [key, acc] of Object.entries(stage.accumulators)) {
|
|
527
|
+
group[key] = lowerAggExpr(acc);
|
|
528
|
+
}
|
|
529
|
+
return { $group: group };
|
|
530
|
+
}
|
|
531
|
+
case 'addFields':
|
|
532
|
+
return { $addFields: lowerExprRecord(stage.fields) };
|
|
533
|
+
case 'replaceRoot':
|
|
534
|
+
return { $replaceRoot: { newRoot: lowerAggExpr(stage.newRoot) } };
|
|
535
|
+
case 'count':
|
|
536
|
+
return { $count: stage.field };
|
|
537
|
+
case 'sortByCount':
|
|
538
|
+
return { $sortByCount: lowerAggExpr(stage.expr) };
|
|
539
|
+
case 'sample':
|
|
540
|
+
return { $sample: { size: stage.size } };
|
|
541
|
+
case 'redact':
|
|
542
|
+
return { $redact: lowerAggExpr(stage.expr) };
|
|
543
|
+
case 'out':
|
|
544
|
+
return { $out: stage.db ? { db: stage.db, coll: stage.collection } : stage.collection };
|
|
545
|
+
case 'unionWith': {
|
|
546
|
+
const unionWith: Record<string, unknown> = { coll: stage.collection };
|
|
547
|
+
if (stage.pipeline) {
|
|
548
|
+
unionWith['pipeline'] = structuralLowerPipeline(stage.pipeline);
|
|
549
|
+
}
|
|
550
|
+
return { $unionWith: unionWith };
|
|
551
|
+
}
|
|
552
|
+
case 'bucket': {
|
|
553
|
+
const bucket: Record<string, unknown> = {
|
|
554
|
+
groupBy: lowerAggExpr(stage.groupBy),
|
|
555
|
+
boundaries: [...stage.boundaries],
|
|
556
|
+
};
|
|
557
|
+
if (stage.default_ !== undefined) bucket['default'] = stage.default_;
|
|
558
|
+
if (stage.output) bucket['output'] = lowerExprRecord(stage.output);
|
|
559
|
+
return { $bucket: bucket };
|
|
560
|
+
}
|
|
561
|
+
case 'bucketAuto': {
|
|
562
|
+
const bucketAuto: Record<string, unknown> = {
|
|
563
|
+
groupBy: lowerAggExpr(stage.groupBy),
|
|
564
|
+
buckets: stage.buckets,
|
|
565
|
+
};
|
|
566
|
+
if (stage.output) bucketAuto['output'] = lowerExprRecord(stage.output);
|
|
567
|
+
if (stage.granularity !== undefined) bucketAuto['granularity'] = stage.granularity;
|
|
568
|
+
return { $bucketAuto: bucketAuto };
|
|
569
|
+
}
|
|
570
|
+
case 'geoNear': {
|
|
571
|
+
const geoNear: Record<string, unknown> = {
|
|
572
|
+
near: stage.near,
|
|
573
|
+
distanceField: stage.distanceField,
|
|
574
|
+
};
|
|
575
|
+
if (stage.spherical !== undefined) geoNear['spherical'] = stage.spherical;
|
|
576
|
+
if (stage.maxDistance !== undefined) geoNear['maxDistance'] = stage.maxDistance;
|
|
577
|
+
if (stage.minDistance !== undefined) geoNear['minDistance'] = stage.minDistance;
|
|
578
|
+
if (stage.query) geoNear['query'] = structuralLowerFilter(stage.query);
|
|
579
|
+
if (stage.key !== undefined) geoNear['key'] = stage.key;
|
|
580
|
+
if (stage.distanceMultiplier !== undefined)
|
|
581
|
+
geoNear['distanceMultiplier'] = stage.distanceMultiplier;
|
|
582
|
+
if (stage.includeLocs !== undefined) geoNear['includeLocs'] = stage.includeLocs;
|
|
583
|
+
return { $geoNear: geoNear };
|
|
584
|
+
}
|
|
585
|
+
case 'facet': {
|
|
586
|
+
const facet: Record<string, unknown> = {};
|
|
587
|
+
for (const [key, pipeline] of Object.entries(stage.facets)) {
|
|
588
|
+
facet[key] = structuralLowerPipeline(pipeline);
|
|
589
|
+
}
|
|
590
|
+
return { $facet: facet };
|
|
591
|
+
}
|
|
592
|
+
case 'graphLookup': {
|
|
593
|
+
const graphLookup: Record<string, unknown> = {
|
|
594
|
+
from: stage.from,
|
|
595
|
+
startWith: lowerAggExpr(stage.startWith),
|
|
596
|
+
connectFromField: stage.connectFromField,
|
|
597
|
+
connectToField: stage.connectToField,
|
|
598
|
+
as: stage.as,
|
|
599
|
+
};
|
|
600
|
+
if (stage.maxDepth !== undefined) graphLookup['maxDepth'] = stage.maxDepth;
|
|
601
|
+
if (stage.depthField !== undefined) graphLookup['depthField'] = stage.depthField;
|
|
602
|
+
if (stage.restrictSearchWithMatch)
|
|
603
|
+
graphLookup['restrictSearchWithMatch'] = structuralLowerFilter(
|
|
604
|
+
stage.restrictSearchWithMatch,
|
|
605
|
+
);
|
|
606
|
+
return { $graphLookup: graphLookup };
|
|
607
|
+
}
|
|
608
|
+
case 'merge': {
|
|
609
|
+
const merge: Record<string, unknown> = { into: stage.into };
|
|
610
|
+
if (stage.on !== undefined) merge['on'] = stage.on;
|
|
611
|
+
if (stage.whenMatched !== undefined) {
|
|
612
|
+
merge['whenMatched'] = Array.isArray(stage.whenMatched)
|
|
613
|
+
? structuralLowerPipeline(stage.whenMatched)
|
|
614
|
+
: stage.whenMatched;
|
|
615
|
+
}
|
|
616
|
+
if (stage.whenNotMatched !== undefined) merge['whenNotMatched'] = stage.whenNotMatched;
|
|
617
|
+
return { $merge: merge };
|
|
618
|
+
}
|
|
619
|
+
case 'setWindowFields': {
|
|
620
|
+
const swf: Record<string, unknown> = {};
|
|
621
|
+
if (stage.partitionBy) swf['partitionBy'] = lowerAggExpr(stage.partitionBy);
|
|
622
|
+
if (stage.sortBy) swf['sortBy'] = { ...stage.sortBy };
|
|
623
|
+
const output: Record<string, unknown> = {};
|
|
624
|
+
for (const [key, wf] of Object.entries(stage.output)) {
|
|
625
|
+
output[key] = lowerWindowField(wf);
|
|
626
|
+
}
|
|
627
|
+
swf['output'] = output;
|
|
628
|
+
return { $setWindowFields: swf };
|
|
629
|
+
}
|
|
630
|
+
case 'densify': {
|
|
631
|
+
const densify: Record<string, unknown> = {
|
|
632
|
+
field: stage.field,
|
|
633
|
+
range: { ...stage.range },
|
|
634
|
+
};
|
|
635
|
+
if (stage.partitionByFields) densify['partitionByFields'] = [...stage.partitionByFields];
|
|
636
|
+
return { $densify: densify };
|
|
637
|
+
}
|
|
638
|
+
case 'fill': {
|
|
639
|
+
const fill: Record<string, unknown> = {};
|
|
640
|
+
if (stage.partitionBy) fill['partitionBy'] = lowerAggExpr(stage.partitionBy);
|
|
641
|
+
if (stage.partitionByFields) fill['partitionByFields'] = [...stage.partitionByFields];
|
|
642
|
+
if (stage.sortBy) fill['sortBy'] = { ...stage.sortBy };
|
|
643
|
+
const output: Record<string, unknown> = {};
|
|
644
|
+
for (const [key, fo] of Object.entries(stage.output)) {
|
|
645
|
+
const entry: Record<string, unknown> = {};
|
|
646
|
+
if (fo.method !== undefined) entry['method'] = fo.method;
|
|
647
|
+
if (fo.value !== undefined) entry['value'] = lowerAggExpr(fo.value);
|
|
648
|
+
output[key] = entry;
|
|
649
|
+
}
|
|
650
|
+
fill['output'] = output;
|
|
651
|
+
return { $fill: fill };
|
|
652
|
+
}
|
|
653
|
+
case 'search': {
|
|
654
|
+
const search: Record<string, unknown> = { ...stage.config };
|
|
655
|
+
if (stage.index !== undefined) search['index'] = stage.index;
|
|
656
|
+
return { $search: search };
|
|
657
|
+
}
|
|
658
|
+
case 'searchMeta': {
|
|
659
|
+
const searchMeta: Record<string, unknown> = { ...stage.config };
|
|
660
|
+
if (stage.index !== undefined) searchMeta['index'] = stage.index;
|
|
661
|
+
return { $searchMeta: searchMeta };
|
|
662
|
+
}
|
|
663
|
+
case 'vectorSearch': {
|
|
664
|
+
const vs: Record<string, unknown> = {
|
|
665
|
+
index: stage.index,
|
|
666
|
+
path: stage.path,
|
|
667
|
+
queryVector: [...stage.queryVector],
|
|
668
|
+
numCandidates: stage.numCandidates,
|
|
669
|
+
limit: stage.limit,
|
|
670
|
+
};
|
|
671
|
+
if (stage.filter) vs['filter'] = { ...stage.filter };
|
|
672
|
+
return { $vectorSearch: vs };
|
|
673
|
+
}
|
|
674
|
+
default: {
|
|
675
|
+
const _exhaustive: never = stage;
|
|
676
|
+
throw new Error(
|
|
677
|
+
`Unhandled stage kind: ${blindCast<MongoPipelineStage, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export function structuralLowerPipeline(
|
|
684
|
+
stages: ReadonlyArray<MongoPipelineStage>,
|
|
685
|
+
): Array<Record<string, unknown>> {
|
|
686
|
+
return stages.map((s) => structuralLowerStage(s));
|
|
687
|
+
}
|