Repository navigation
feat(mongo-contract-psl): add Mongo PSL interpreter and wire demo to CLI - #289
Conversation
Add a minimal ControlAdapterDescriptor for the Mongo adapter, exported from @prisma-next/adapter-mongo/control. This satisfies the framework config requirement for an adapter descriptor.
Add package structure for the Mongo PSL interpreter with interpreter stub, scalar type descriptor map, PSL helpers, and architecture.config.json registration. Provider export deferred since MongoFamilyDescriptor.create() requires assembledState (CLI emit path not yet available).
Map PSL models to Mongo ContractIR: scalar types via the descriptor map, collection names via lowerFirst with @@Map override, field names via @Map, nullable from optional marker, N:1 relations from @relation(fields/references), and 1:N backrelations inferred from list fields. Add ObjectId to the scalar type map.
Replace the hand-built ContractIR in generate-contract.ts with a prisma/schema.psl file parsed by @prisma-next/psl-parser and interpreted by @prisma-next/mongo-contract-psl. The generated contract.json and contract.d.ts are byte-identical to before. Add tsconfig.prod.json for the interpreter package build.
tsdown collapses single-entry packages to "." in the exports map. Updated customExports in the base config to derive the subpath from the output filename (e.g. control.mjs -> ./control) when the entry is not index.ts. Updated consumer imports for @prisma-next/postgres, @prisma-next/target-mongo, and @prisma-next/family-mongo to use the correct named subpaths.
Documents the full authoring-to-runtime pipeline, available scripts, key files, and how the demo compares to the SQL prisma-next-demo.
…ation disambiguation Use DomainField/DomainReferenceRelation from @prisma-next/contract/types instead of ad-hoc Record<string, unknown> accumulators, eliminating unsafe casts and ensuring forward-compatibility with M5. Replace naive .find() backrelation matching with pair-indexed lookup that disambiguates by relation name. Emit PSL_ORPHANED_BACKRELATION and PSL_AMBIGUOUS_BACKRELATION diagnostics instead of silently producing wrong output for multi-FK schemas.
Add mongoContract() provider to @prisma-next/mongo-contract-psl/provider, mirroring prismaContract() from the SQL side. The mongo-demo now uses prisma-next.config.ts with prisma-next contract emit instead of a custom script, matching the SQL demo pattern. Also: promote mongoTargetDescriptor to ControlTargetDescriptor (adds create()), allow sources field in MongoContractSchema, remove unused deps from mongo-demo.
Aligns with the SQL demo naming convention.
createDb was misleading since it creates a client, not a database. Add a comment explaining that seeding uses raw MongoClient because the ORM is currently read-only.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
✅ Files skipped from review due to trivial changes (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds a Mongo PSL authoring package and provider, integrates a Mongo demo and CLI fixture, implements a PSL→Mongo ContractIR interpreter with diagnostics and tests, updates architecture layer ordering and package export surfaces, and adjusts related build/config files and small API renames. Changes
Sequence Diagram(s)sequenceDiagram
participant File as "Schema File"
participant Reader as "File Reader"
participant Parser as "PSL Parser"
participant Interpreter as "PSL→ContractIR Interpreter"
participant Descriptors as "Scalar Descriptors"
participant Contract as "ContractIR / CLI Output"
File->>Reader: read(schemaPath)
Reader->>Parser: provide file content
Parser->>Interpreter: parsed PSL document
Interpreter->>Descriptors: request scalar mappings
Descriptors-->>Interpreter: scalar codec map
Interpreter->>Interpreter: build models, fields, collections
Interpreter->>Interpreter: resolve FK relations & backrelations
Interpreter->>Interpreter: collect diagnostics (if any)
alt diagnostics present
Interpreter->>Contract: return notOk with diagnostics
else
Interpreter->>Contract: return ok ContractIR
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
@prisma-next/runtime-executor
@prisma-next/mongo-core
@prisma-next/mongo-orm
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract-authoring
@prisma-next/contract-ts
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/emitter
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-contract-psl
@prisma-next/mongo-emitter
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/family-sql
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/adapter-postgres
@prisma-next/driver-postgres
@prisma-next/core-control-plane
@prisma-next/core-execution-plane
@prisma-next/config
@prisma-next/contract
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/plan
@prisma-next/utils
commit: |
Use conditional spread for exactOptionalPropertyTypes compliance, replace non-null assertions with optional chaining and guard clauses.
Emit PSL_MISSING_ID_FIELD diagnostic when a model lacks an @id-attributed field. Without this, models missing @id would silently produce contracts without an ID field, failing at runtime.
There was a problem hiding this comment.
Actionable comments posted: 9
🧹 Nitpick comments (2)
packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts (1)
55-57: Replace inline conditional spreads withifDefined().Please switch these conditional spreads to the repo-standard
ifDefined()helper for consistency and lint-policy alignment.As per coding guidelines, "Use
ifDefined()from@prisma-next/utils/definedfor conditional object spreads instead of inline conditional spread patterns."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts` around lines 55 - 57, Replace the three inline conditional spreads for relationName, fields, and references with the repo-standard helper: import { ifDefined } from '@prisma-next/utils/defined' and change ...(relationName !== undefined ? { relationName } : {}) to ...ifDefined({ relationName }), and similarly use ...ifDefined({ fields }) and ...ifDefined({ references }) so the optional properties are spread using ifDefined in psl-helpers.ts (preserve existing behavior and types).packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts (1)
1-515: Split this suite along its existingdescribe()boundaries.This file is now 515 lines and bundles scalar mapping, naming, relations, and full-IR assertions in one place. Splitting it into focused files such as
interpreter.scalar.test.ts,interpreter.naming.test.ts, andinterpreter.relations.test.tswould keep each concern easier to navigate and independently runnable.As per coding guidelines, "Keep test files under 500 lines to maintain readability and navigability. If a test file exceeds this limit, it should be split into multiple files."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts` around lines 1 - 515, The test file is too large; split it into multiple focused test files along its existing describe() boundaries by creating separate files for the scalar-mapping tests (describe 'scalar type mapping'), naming tests (describe 'collection naming' and 'field naming' and 'nullable fields'), relations tests (describe 'relations'), and contract/IR-level tests (describe 'contract structure' and 'full blog schema'); copy shared helpers and imports (parsePslDocument, interpretPslDocumentToMongoContractIR, createMongoScalarTypeDescriptors, the MongoModel/interface, model(), interpret(), interpretOk()) into a test-helpers module or duplicate them at the top of each new file so each test file is self-contained, update test file names like interpreter.scalar.test.ts, interpreter.naming.test.ts, interpreter.relations.test.ts, interpreter.contract.test.ts, and ensure each new file imports vitest and the same utilities and uses the exact describe/it blocks moved from the original file.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@examples/mongo-demo/README.md`:
- Around line 17-19: The fenced code block containing the schema relation "User
(id, name, email, bio?) ←1:N→ Post (id, title, content, authorId, createdAt)"
lacks a language identifier; update the triple-backtick fence to include a
language tag (e.g., "text") so the block becomes ```text ... ``` to satisfy
markdown linting and maintain consistency in README.md.
In `@packages/2-mongo-family/2-authoring/contract-psl/package.json`:
- Line 14: The "clean" npm script in package.json currently only removes "dist"
and "coverage", leaving TypeScript emit folders behind; update the "clean"
script (the "clean" entry in package.json) to also remove "dist-tsc" and
"dist-tsc-prod" so that running the script deletes "dist", "dist-tsc",
"dist-tsc-prod", and "coverage" to avoid stale TypeScript outputs affecting
subsequent builds and typechecks.
In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 106-134: The current loop only processes relations when
parseRelationAttribute(field.attributes) yields both fields and references and
then unconditionally continues, which drops inverse singular sides (e.g.,
User.profile Profile?) silently; update the logic in the interpreter loop that
uses parseRelationAttribute, fieldMappings, resolveFieldMappings and
allFkRelations so that: if relation exists but lacks fields/references (i.e.,
it's the inverse singular side) you still emit an entry in relations[field.name]
with to: field.typeName and cardinality: '1:1' (or appropriate singular marker)
and omit the on object and the allFkRelations push (since no FK is declared
here); only skip/continue when the field is unrelated, and keep the existing
behavior when both fields and references are present (including building
localMapped/targetMapped, setting on, and pushing to allFkRelations).
- Around line 137-152: The code path using resolveFieldCodecId ignores
field.list, so scalar list fields (e.g. tags String[]) are treated as scalars;
update the branch that sets fields[mappedName] to detect field.list and handle
it: for list fields call or derive a list codec (e.g. resolve the item codec via
resolveFieldCodecId(field, scalarTypeDescriptors) then wrap/lookup a list codec
id) and set the resulting codecId/list flag on fields[mappedName] (or add an
explicit isList or itemCodecId property) so array semantics are preserved; if
list codecs are not supported, push a diagnostic (PSL_UNSUPPORTED_FIELD_TYPE)
instead of silently emitting a scalar. Ensure you reference field.list,
resolveFieldCodecId, fields, diagnostics and fieldMappings.pslNameToMapped when
implementing the fix.
In `@packages/2-mongo-family/2-authoring/contract-psl/src/provider.ts`:
- Around line 15-51: Update the mongoContract provider so its inner source
function accepts the ContractSourceContext parameter and forwards
composedExtensionPacks from that context into
interpretPslDocumentToMongoContractIR; specifically, import
ContractSourceContext in the type imports, change the source signature to
receive (ctx: ContractSourceContext), and pass ctx.composedExtensionPacks (or
composedExtensionPacks) into interpretPslDocumentToMongoContractIR along with
document and scalarTypeDescriptors; keep the existing error handling and return
behavior in mongoContract and the source function.
In
`@packages/2-mongo-family/2-authoring/contract-psl/src/scalar-type-descriptors.ts`:
- Around line 1-12: The createMongoScalarTypeDescriptors map exposes codec IDs
(mongo/int64@1, mongo/double@1, mongo/binary@1) for types BigInt, Float, and
Bytes but the Mongo adapter's codec-ids.ts and codecs.ts only provide
implementations for objectId, string, int32, bool, and date; fix by either (A)
implementing and exporting codecs and codec IDs for mongo/int64@1,
mongo/double@1, and mongo/binary@1 in codec-ids.ts and codecs.ts (with proper
encode/decode and registration) so createMongoScalarTypeDescriptors can keep all
eight mappings, or (B) remove the BigInt, Float, and Bytes entries from
createMongoScalarTypeDescriptors so it only returns descriptors for the five
supported types (String, Int, Boolean, DateTime, ObjectId).
In `@packages/2-mongo-family/2-authoring/contract-psl/tsconfig.json`:
- Line 8: Update the tsconfig.json "exclude" array to also exclude test fixture
files; specifically modify the existing "exclude" entry (currently ["dist"]) to
include "test/fixtures/**/*" so that test/fixtures is not typechecked by
TypeScript. Ensure the "exclude" array contains both "dist" and
"test/fixtures/**/*".
In `@packages/2-mongo-family/9-family/package.json`:
- Around line 41-43: The package.json "exports" removed the root export ("."),
breaking imports from the package root used in docs; restore the root export by
adding a "." entry that points to the same target as "./control" (e.g., map "."
to "./dist/control.mjs"), or alternatively update all README examples to import
from the subpath "./control" instead of the package root; modify the "exports"
section in package.json (referencing the "exports" object and the "./control"
entry) or update documentation examples where imports reference
"@prisma-next/family-mongo" to use "@prisma-next/family-mongo/control".
In `@packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts`:
- Around line 3-12: The descriptor object mongoAdapterDescriptor is missing the
required manifest property; update mongoAdapterDescriptor to include a manifest:
ExtensionPackManifest entry (import the ExtensionPackManifest type if not
already imported) that satisfies the control-plane manifest requirements (e.g.,
name, version and any required metadata per the repo manifest shape) so the
ControlAdapterDescriptor<'mongo','mongo'> type-checks; keep the existing
create() and other fields unchanged and ensure the manifest value uses concrete
literals/values matching the package (name/version/description) for static
typing.
---
Nitpick comments:
In `@packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts`:
- Around line 55-57: Replace the three inline conditional spreads for
relationName, fields, and references with the repo-standard helper: import {
ifDefined } from '@prisma-next/utils/defined' and change ...(relationName !==
undefined ? { relationName } : {}) to ...ifDefined({ relationName }), and
similarly use ...ifDefined({ fields }) and ...ifDefined({ references }) so the
optional properties are spread using ifDefined in psl-helpers.ts (preserve
existing behavior and types).
In `@packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts`:
- Around line 1-515: The test file is too large; split it into multiple focused
test files along its existing describe() boundaries by creating separate files
for the scalar-mapping tests (describe 'scalar type mapping'), naming tests
(describe 'collection naming' and 'field naming' and 'nullable fields'),
relations tests (describe 'relations'), and contract/IR-level tests (describe
'contract structure' and 'full blog schema'); copy shared helpers and imports
(parsePslDocument, interpretPslDocumentToMongoContractIR,
createMongoScalarTypeDescriptors, the MongoModel/interface, model(),
interpret(), interpretOk()) into a test-helpers module or duplicate them at the
top of each new file so each test file is self-contained, update test file names
like interpreter.scalar.test.ts, interpreter.naming.test.ts,
interpreter.relations.test.ts, interpreter.contract.test.ts, and ensure each new
file imports vitest and the same utilities and uses the exact describe/it blocks
moved from the original file.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 71a2d036-1225-4492-a6a4-ff99f8897c56
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (31)
architecture.config.jsonexamples/mongo-demo/README.mdexamples/mongo-demo/package.jsonexamples/mongo-demo/prisma-next.config.tsexamples/mongo-demo/prisma/contract.prismaexamples/mongo-demo/scripts/generate-contract.tsexamples/mongo-demo/src/contract.jsonexamples/mongo-demo/src/db.tsexamples/mongo-demo/src/server.tsexamples/prisma-next-demo/src/prisma/db.tspackages/0-config/tsdown/base.tspackages/2-mongo-family/1-core/src/contract-schema.tspackages/2-mongo-family/2-authoring/contract-psl/biome.jsoncpackages/2-mongo-family/2-authoring/contract-psl/package.jsonpackages/2-mongo-family/2-authoring/contract-psl/src/exports/index.tspackages/2-mongo-family/2-authoring/contract-psl/src/exports/provider.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.tspackages/2-mongo-family/2-authoring/contract-psl/src/provider.tspackages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.tspackages/2-mongo-family/2-authoring/contract-psl/src/scalar-type-descriptors.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.tspackages/2-mongo-family/2-authoring/contract-psl/tsconfig.jsonpackages/2-mongo-family/2-authoring/contract-psl/tsconfig.prod.jsonpackages/2-mongo-family/2-authoring/contract-psl/tsdown.config.tspackages/2-mongo-family/9-family/package.jsonpackages/2-mongo-family/9-family/src/core/mongo-target-descriptor.tspackages/3-extensions/postgres/package.jsonpackages/3-mongo-target/1-mongo-target/package.jsonpackages/3-mongo-target/2-mongo-adapter/package.jsonpackages/3-mongo-target/2-mongo-adapter/src/exports/control.tspackages/3-mongo-target/2-mongo-adapter/tsdown.config.ts
💤 Files with no reviewable changes (1)
- examples/mongo-demo/scripts/generate-contract.ts
Exercises the full prisma-next contract emit path through the CLI with a Mongo PSL schema, validating that the emit command works end-to-end for non-SQL families.
There was a problem hiding this comment.
♻️ Duplicate comments (2)
packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts (2)
139-154:⚠️ Potential issue | 🟠 MajorScalar list fields are emitted as scalars.
Line 139 resolves codec by scalar type only, and Line 151 stores a plain
DomainField.String[]/Int[]currently lose array semantics instead of being modeled or rejected.Minimal safe guard until list codecs are modeled
+ if (field.list) { + diagnostics.push({ + code: 'PSL_UNSUPPORTED_FIELD_TYPE', + message: `Scalar list field "${pslModel.name}.${field.name}" is not supported in Mongo PSL interpreter`, + sourceId, + span: field.span, + }); + continue; + } + const codecId = resolveFieldCodecId(field, scalarTypeDescriptors); if (!codecId) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts` around lines 139 - 154, The interpreter currently treats scalar list fields (e.g., String[]/Int[]) as plain scalars; update the logic around resolveFieldCodecId and the fields[...] assignment to detect list/array fields (e.g., check field.isList or field.array/field.kind === 'list' depending on the Field shape) and do not emit a plain DomainField for them; instead push the same PSL_UNSUPPORTED_FIELD_TYPE diagnostic (with the same message/metadata) and continue for list-typed fields until list codecs are modeled, so fields only receives true scalar fields.
108-136:⚠️ Potential issue | 🟠 MajorInverse singular relations are still silently dropped.
Line 136 unconditionally continues for singular relation fields that are not FK-side (
@relationwithoutfields/references, or implicit inverse), so no relation entry is emitted and no diagnostic is produced.Proposed fix
- const relation = parseRelationAttribute(field.attributes); - if (relation?.fields && relation?.references) { + const mappedRelationName = fieldMappings.pslNameToMapped.get(field.name) ?? field.name; + const relation = parseRelationAttribute(field.attributes); + if (relation?.fields && relation?.references) { const localMapped = relation.fields.map((f) => fieldMappings.pslNameToMapped.get(f) ?? f); @@ - relations[field.name] = { + relations[mappedRelationName] = { to: field.typeName, cardinality: 'N:1' as const, on: { localFields: localMapped, targetFields: targetMapped, }, }; @@ - } + } else { + relations[mappedRelationName] = { + to: field.typeName, + cardinality: '1:1' as const, + }; + } continue;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts` around lines 108 - 136, The code currently treats any relation lacking fields/references as a no-op and does an unconditional continue, silently dropping inverse singular relations; update the block that uses parseRelationAttribute to detect when relation exists but relation.fields and relation.references are missing for a singular field (field is not a list) and instead of just continuing, push a clear diagnostic (e.g., document.diagnostics.push or document.addDiagnostic) referencing pslModel.name and field.name explaining the inverse singular relation is unsupported/omitted, and then continue; keep the existing behavior for the FK-side case that builds relations and allFkRelations, but ensure inverse singular cases produce a diagnostic so they are not silently ignored.
🧹 Nitpick comments (1)
test/integration/test/cli.emit-command.test.ts (1)
652-748: Split this test file; it exceeds repository size limits.This file is now well over the 500-line cap. Please move Mongo emit coverage into a dedicated file (for example
cli.emit-command.mongo.test.ts) to keep concerns and navigation manageable.As per coding guidelines "
**/*.test.ts: Keep test files under 500 lines to maintain readability and navigability. If a test file exceeds this limit, it should be split into multiple files."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/cli.emit-command.test.ts` around lines 652 - 748, The test file exceeds the 500-line limit; extract the Mongo-specific "it('emits contract.json and contract.d.ts with Mongo config')" test block into its own test file and keep the remaining tests in the original file. Copy the test body along with any helpers it uses (createContractEmitCommand, setupIntegrationTestDirectoryFromFixtures, executeCommand, timeouts) and necessary imports (expect, readFileSync, writeFileSync, join, existsSync, processLogger mocks if used) into the new test file, update any relative imports as needed, ensure the new file registers with the test runner, and leave the original file with the non-Mongo tests under 500 lines; run the test suite to confirm behavior and preserve cleanupMongo() usage.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 139-154: The interpreter currently treats scalar list fields
(e.g., String[]/Int[]) as plain scalars; update the logic around
resolveFieldCodecId and the fields[...] assignment to detect list/array fields
(e.g., check field.isList or field.array/field.kind === 'list' depending on the
Field shape) and do not emit a plain DomainField for them; instead push the same
PSL_UNSUPPORTED_FIELD_TYPE diagnostic (with the same message/metadata) and
continue for list-typed fields until list codecs are modeled, so fields only
receives true scalar fields.
- Around line 108-136: The code currently treats any relation lacking
fields/references as a no-op and does an unconditional continue, silently
dropping inverse singular relations; update the block that uses
parseRelationAttribute to detect when relation exists but relation.fields and
relation.references are missing for a singular field (field is not a list) and
instead of just continuing, push a clear diagnostic (e.g.,
document.diagnostics.push or document.addDiagnostic) referencing pslModel.name
and field.name explaining the inverse singular relation is unsupported/omitted,
and then continue; keep the existing behavior for the FK-side case that builds
relations and allFkRelations, but ensure inverse singular cases produce a
diagnostic so they are not silently ignored.
---
Nitpick comments:
In `@test/integration/test/cli.emit-command.test.ts`:
- Around line 652-748: The test file exceeds the 500-line limit; extract the
Mongo-specific "it('emits contract.json and contract.d.ts with Mongo config')"
test block into its own test file and keep the remaining tests in the original
file. Copy the test body along with any helpers it uses
(createContractEmitCommand, setupIntegrationTestDirectoryFromFixtures,
executeCommand, timeouts) and necessary imports (expect, readFileSync,
writeFileSync, join, existsSync, processLogger mocks if used) into the new test
file, update any relative imports as needed, ensure the new file registers with
the test runner, and leave the original file with the non-Mongo tests under 500
lines; run the test suite to confirm behavior and preserve cleanupMongo() usage.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 840cb231-b008-4770-b9f4-689c60db3720
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (6)
packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.tspackages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.tstest/integration/test/cli.emit-command.test.tstest/integration/test/fixtures/cli/cli-integration-test-app/fixtures/emit-command/prisma-next.config.mongo.tstest/integration/test/fixtures/cli/cli-integration-test-app/package.json
✅ Files skipped from review due to trivial changes (3)
- test/integration/test/fixtures/cli/cli-integration-test-app/fixtures/emit-command/prisma-next.config.mongo.ts
- test/integration/test/fixtures/cli/cli-integration-test-app/package.json
- packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
Fixes lint:docs CI failure for missing README.
- Handle singular non-FK relation fields as 1:1 inverse relations (previously silently dropped) - Emit PSL_UNSUPPORTED_LIST_FIELD for scalar list fields like String[] instead of silently treating them as scalars - Remove BigInt, Float, Bytes from default scalar type descriptors since their runtime codecs are not yet implemented (they now produce PSL_UNSUPPORTED_FIELD_TYPE diagnostics)
- mongoContract provider now accepts ContractSourceContext parameter, matching the SQL prismaContract() provider signature - Add language tag to fenced code block in mongo-demo README - Fix family-mongo README to use ./control import subpath
|
Merging without review to unblock later tasks, everyone is on vacation |
closes TML-2187
Key snippet
Intent
Complete the MongoDB authoring → emit → runtime pipeline by replacing the demo's hand-built
ContractIRwith a PSL schema parsed and interpreted by a new Mongo PSL interpreter. This validates that the contract authoring system generalizes across database families and that the CLI'scontract emitcommand is genuinely family-agnostic.Change map
mongoContract()CLI providermongoContract()schema.psl)createClient()(renamed fromcreateDb())The story
Scaffold the
@prisma-next/mongo-contract-pslpackage atpackages/2-mongo-family/2-authoring/contract-psl/with the correct domain/layer/plane registration inarchitecture.config.json.Build the PSL → Mongo ContractIR interpreter that maps PSL models to
ContractIR: scalar fields becomeDomainFieldentries keyed by mapped name, FK-side@relationfields becomeN:1DomainReferenceRelationentries, and list fields referencing other models become1:Nbackrelations. Collection naming uses@@maporlowerFirst(modelName). Field naming uses@mapor the PSL field name. Multi-FK disambiguation indexes by model pair and matches by relation name, with diagnostics for orphaned and ambiguous cases.Wire the demo through CLI-driven emission by creating a
mongoContract()provider, addingprisma-next.config.tsto the demo (withmongoFamilyDescriptor,mongoTargetDescriptor,mongoAdapterDescriptor), and deleting the customgenerate-contract.tsscript. This requires adding the missingmongoAdapterDescriptorin@prisma-next/adapter-mongo/control.Polish the demo by renaming
schema.psl→contract.prisma,createDb()→createClient(), and adding a comment explaining why seeding uses rawMongoClient.Behavior changes & evidence
Adds a Mongo PSL interpreter that deterministically maps PSL schemas to Mongo
ContractIR. Given a PSL document and scalar type descriptors,interpretPslDocumentToMongoContractIR()produces aContractIRwith typed fields (DomainField), typed relations (DomainReferenceRelation), collection-based storage, and roots. Unsupported field types, orphaned backrelations, and ambiguous backrelations produce diagnostics.ContractIRliteral. A PSL interpreter completes the authoring → emit → runtime pipeline, matching the SQL family's pattern.Adds CLI-driven contract emission for the Mongo demo via
mongoContract()provider. The demo usesprisma-next.config.ts+prisma-next contract emitinstead of a custom script, validating that the CLI's emit pipeline is family-agnostic.mongoContract()factoryexamples/mongo-demo/scripts/generate-contract.ts— deletedcontract.jsondiff is empty vs base (the PSL interpreter produces identical output to the hand-built IR)Adds
mongoAdapterDescriptorfor full control-stack composition. The descriptor fills the missing adapter slot socreateControlStack(config)can compose family + target + adapter for Mongo.prisma-next.config.tsrequires all three component types. The family and target descriptors existed; the adapter descriptor did not.prisma-next contract emitsucceeds with the Mongo config (the demo'spnpm emitscript)Compatibility / migration / risk
pnpm emitscript now invokes the CLI instead.contract.jsonandcontract.d.tsare unchanged.cfe68a9ba): a tsdown base config change ensures packages with a single entry point don't collapse their output to the rootdist/directory. This is a build infrastructure fix that preventsexports→dist/path mismatches.Follow-ups / open questions
@idvalidation: The interpreter does not validate that every model has an@idfield — a model missing it would silently produce a contract without an ID field. Should emit a diagnostic.psl-helpers.tsreimplements functions from the SQL interpreter. Consider extracting shared helpers to@prisma-next/psl-parser.mongoContract()provider currently takesscalarTypeDescriptorsas an explicit option. Task 3.14 will refactor the provider system so theControlStackis provided by the framework automatically.Non-goals / intentionally out of scope
MongoClient.Summary by CodeRabbit
New Features
Bug Fixes / Refactor
Tests
Documentation