Repository navigation
TML-2928: PSL formatter — CST-based pretty-printer + prisma format CLI - #850
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a PSL source formatter to the ChangesPSL Formatter, Config Types, and CLI format Command
Sequence Diagram(s)sequenceDiagram
participant User
participant createFormatCommand
participant executeFormat
participant loadConfig
participant format
participant FileSystem
User->>createFormatCommand: prisma format --config path
createFormatCommand->>executeFormat: configPath, eol
executeFormat->>loadConfig: configPath
loadConfig-->>executeFormat: config (sourceFormat, inputs, formatter)
alt sourceFormat !== 'psl'
executeFormat-->>createFormatCommand: ok, formatted: false
createFormatCommand-->>User: "Nothing to format"
else sourceFormat === 'psl'
executeFormat->>FileSystem: readFile(inputs[0])
FileSystem-->>executeFormat: source
executeFormat->>format: source, indent, resolvedNewline
alt parse diagnostics present
format-->>executeFormat: throw PslFormatError
executeFormat-->>createFormatCommand: err CliStructuredError
createFormatCommand-->>User: error + exit 1
else
format-->>executeFormat: formatted string
executeFormat->>FileSystem: writeFile(inputs[0], formatted)
executeFormat-->>createFormatCommand: ok, formatted: true, path
createFormatCommand-->>User: success message + exit 0
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@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/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
packages/1-framework/2-authoring/psl-parser/test/format/corpus.test.ts (1)
69-69: ⚡ Quick winOptimize: avoid reading the file twice in the filter condition.
Line 69 reads the file twice: once for the formatted output and once for the original. Store the file content in a variable to avoid redundant I/O.
♻️ Proposed fix
const noOp = corpus - .filter((file) => format(readFileSync(file, 'utf8')) === readFileSync(file, 'utf8')) + .filter((file) => { + const source = readFileSync(file, 'utf8'); + return format(source) === source; + })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/1-framework/2-authoring/psl-parser/test/format/corpus.test.ts` at line 69, The filter function at line 69 is reading the file twice with readFileSync, causing redundant I/O operations. Store the file content in a variable by calling readFileSync once at the beginning of the filter callback, then use that variable both in the format() function call and in the comparison, eliminating the duplicate read operation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/1-framework/2-authoring/psl-parser/src/format/emit.ts`:
- Around line 585-588: The code in the object field emission within the
Array.from() mapping function assumes objField.key() is always an identifier and
calls identifierText() on it. Since object keys can now be string literals, this
approach will produce malformed output for string-literal keys. Modify the
mapping function to check the type of objField.key() and handle both cases
appropriately: use identifierText() for identifier keys, and apply proper
string-literal formatting for string-literal keys to ensure the emitted output
is correctly formatted.
In `@packages/1-framework/2-authoring/psl-parser/src/parse.ts`:
- Around line 307-309: The object-literal recovery logic currently only checks
for 'Ident' kind when detecting following keys without commas, but since string
literal keys are now supported, the `followsWithKey` check needs to be updated.
Modify the condition that checks `cursor.peekKind() === 'Ident'` to also check
for 'StringLiteral' kind, ensuring that both identifier and string literal keys
are properly detected during error recovery. This change needs to be applied in
two locations as indicated in the comment: around line 307 and around line
346-347 in the parse function.
- Around line 360-367: The isCallAhead function currently only detects direct
function calls (Ident + LParen) and dot-qualified calls (Ident + Dot + Ident +
LParen), but it is missing detection for colon-qualified call names like
space:fn(...) and space:ns.fn(...). Add additional conditions to the return
statement in isCallAhead to check for patterns where cursor.peekKind(1) is a
Colon token, followed by an Ident and LParen for simple colon-qualified calls,
and also for the extended pattern Colon + Ident + Dot + Ident + LParen for
namespace-qualified calls. This will ensure these valid call forms are properly
recognized and routed to parseFunctionCall instead of being misparsed as
separate tokens.
In `@packages/1-framework/2-authoring/psl-parser/test/parse-diagnostics.test.ts`:
- Around line 311-313: The test title "enum with a name but no brace reports the
missing brace as a generic block" does not match the actual test input, which is
just the string 'enum' with no name and no brace. Either rename the test title
in the it function to accurately describe what is being tested (e.g., "enum with
no name and no brace reports invalid declaration"), or update the source input
to include an enum name like 'enum Color' to match the test description's
intent. Choose whichever approach aligns better with the test's actual purpose.
---
Nitpick comments:
In `@packages/1-framework/2-authoring/psl-parser/test/format/corpus.test.ts`:
- Line 69: The filter function at line 69 is reading the file twice with
readFileSync, causing redundant I/O operations. Store the file content in a
variable by calling readFileSync once at the beginning of the filter callback,
then use that variable both in the format() function call and in the comparison,
eliminating the duplicate read operation.
🪄 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: 33f96074-0cf7-4256-8adf-c1d45fd758a7
📒 Files selected for processing (64)
packages/1-framework/1-core/framework-components/src/shared/psl-extension-block.tspackages/1-framework/2-authoring/psl-parser/package.jsonpackages/1-framework/2-authoring/psl-parser/src/exports/format.tspackages/1-framework/2-authoring/psl-parser/src/exports/syntax.tspackages/1-framework/2-authoring/psl-parser/src/format/emit.tspackages/1-framework/2-authoring/psl-parser/src/format/error.tspackages/1-framework/2-authoring/psl-parser/src/format/format.tspackages/1-framework/2-authoring/psl-parser/src/format/options.tspackages/1-framework/2-authoring/psl-parser/src/parse.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast-helpers.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/attributes.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/declarations.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/expressions.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/identifier.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/qualified-name.tspackages/1-framework/2-authoring/psl-parser/src/syntax/ast/type-annotation.tspackages/1-framework/2-authoring/psl-parser/src/syntax/syntax-kind.tspackages/1-framework/2-authoring/psl-parser/src/tokenizer.tspackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__mongo-blog-leaderboard__src__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__mongo-demo__migrations__app__20260409T1030_migration__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__mongo-demo__migrations__app__20260415_add-posts-author-index__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__mongo-demo__src__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__multi-extension-monorepo__app__src__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__multi-extension-monorepo__packages__audit__src__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__multi-extension-monorepo__packages__feature-flags__src__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-cloudflare-worker__src__prisma__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__fixtures__converging-branches__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__fixtures__diamond__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__fixtures__long-spine__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__fixtures__multi-branch__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__fixtures__showcase__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__fixtures__skip-rollback__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__fixtures__wide-fan__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__migrations__app__20260422T0720_initial__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__migrations__app__20260422T0742_migration__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__migrations__app__20260422T0748_migration__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__migrations__app__20260605T1145_mti_variant_link_columns__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__migrations__app__20260610T0000_add_priority_enum__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__migrations__app__20260610T2216_set_priority_default__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-demo__src__prisma__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-postgis-demo__migrations__app__20260512T1309_migration__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__prisma-next-postgis-demo__src__prisma__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__react-router-demo__src__prisma__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__retail-store__migrations__app__20260513T0505_initial__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__retail-store__migrations__app__20260513T0507_add_product_category_index__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__retail-store__migrations__app__20260513T0508_backfill_product_status__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__retail-store__src__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/examples__supabase__src__contract.prismapackages/1-framework/2-authoring/psl-parser/test/format/__snapshots__/corpus/packages__1-framework__2-authoring__psl-parser__test__fixtures__schema.prismapackages/1-framework/2-authoring/psl-parser/test/format/alignment.test.tspackages/1-framework/2-authoring/psl-parser/test/format/block-attribute-spacing.test.tspackages/1-framework/2-authoring/psl-parser/test/format/corpus.test.tspackages/1-framework/2-authoring/psl-parser/test/format/exports.test.tspackages/1-framework/2-authoring/psl-parser/test/format/format.test.tspackages/1-framework/2-authoring/psl-parser/test/format/idempotence.test.tspackages/1-framework/2-authoring/psl-parser/test/format/options.test.tspackages/1-framework/2-authoring/psl-parser/test/format/trivia.test.tspackages/1-framework/2-authoring/psl-parser/test/format/type-annotation.test.tspackages/1-framework/2-authoring/psl-parser/test/parse-diagnostics.test.tspackages/1-framework/2-authoring/psl-parser/test/parse-document.test.tspackages/1-framework/2-authoring/psl-parser/test/parse-leaf.test.tspackages/1-framework/2-authoring/psl-parser/test/support.tspackages/1-framework/2-authoring/psl-parser/test/syntax/ast.test.tspackages/1-framework/2-authoring/psl-parser/tsdown.config.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/1-framework/1-core/config/src/config-types.ts`:
- Around line 149-152: The FormatterConfigSchema definition for the indent field
currently accepts any number type, which allows invalid values like 0, negative
numbers, and decimals to pass validation at config parse time. Update the schema
definition for the `'indent?'` field in FormatterConfigSchema to add validation
constraints that enforce the number must be a positive integer (greater than 0)
or the string 'tab', rejecting values like 0, -1, and 1.5 during config parsing
rather than failing downstream. Apply the same validation fix to the other
FormatterConfigSchema instance mentioned in the range 178-186.
🪄 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: de73342d-4e71-4aec-a9c4-7a4aa6a6e66b
📒 Files selected for processing (29)
packages/1-framework/1-core/config/src/config-types.tspackages/1-framework/1-core/config/src/contract-source-types.tspackages/1-framework/1-core/config/src/exports/config-types.tspackages/1-framework/1-core/config/test/config-types.test-d.tspackages/1-framework/1-core/config/test/config-validation.test.tspackages/1-framework/2-authoring/psl-parser/test/format/fixtures.test.tspackages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-model/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-model/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/blank-lines/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/blank-lines/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/block-attributes/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/block-attributes/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/comments-preserved/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/comments-preserved/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/enum-and-generator-block/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/enum-and-generator-block/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/inline-comment-hard-break/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/inline-comment-hard-break/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/types-namespaced-constructor/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/types-namespaced-constructor/input.prismapackages/1-framework/3-tooling/cli/recordings/fixtures/prisma-next.config.tspackages/2-mongo-family/2-authoring/contract-psl/src/provider.tspackages/2-mongo-family/2-authoring/contract-psl/test/provider.test.tspackages/2-mongo-family/2-authoring/contract-ts/src/config-types.tspackages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/2-sql/2-authoring/contract-ts/src/config-types.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
✅ Files skipped from review due to trivial changes (11)
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/types-namespaced-constructor/expected.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-model/input.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-model/expected.prisma
- packages/2-sql/2-authoring/contract-psl/src/provider.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/blank-lines/input.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/inline-comment-hard-break/input.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/types-namespaced-constructor/input.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/comments-preserved/input.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/enum-and-generator-block/expected.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/inline-comment-hard-break/expected.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/blank-lines/expected.prisma
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/1-framework/3-tooling/cli/src/control-api/operations/format.ts`:
- Line 109: The writeFile call in the format operation at line 109 is not
wrapped in error handling, which allows any thrown errors to escape as rejected
promises instead of being returned as structured Result types. Wrap the
writeFile(inputPath, formatted, 'utf-8') call in a try-catch block and return
any caught errors as part of the operation's Result contract, ensuring
write-back failures are handled through the CLI's structured error path rather
than bubbling up as unhandled rejections.
🪄 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: a065c01f-9e90-470d-acc4-cdc2bbebc585
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (6)
packages/1-framework/3-tooling/cli/package.jsonpackages/1-framework/3-tooling/cli/src/cli.tspackages/1-framework/3-tooling/cli/src/commands/format.tspackages/1-framework/3-tooling/cli/src/control-api/operations/format.tspackages/1-framework/3-tooling/cli/src/exports/index.tspackages/1-framework/3-tooling/cli/test/control-api/format.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/1-framework/3-tooling/cli/src/exports/index.ts
2955947 to
588885c
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/1-framework/2-authoring/psl-parser/test/format/options.test.ts`:
- Around line 39-41: Remove the `@ts-expect-error` suppression comment on line 40
from the test that checks rejection of unknown string indent values in the
format function. Instead of using the suppression directive, explicitly type the
invalid indent option value (for example, by casting to a type that is
incompatible with the expected FormatOptions type) so that TypeScript naturally
rejects the invalid value at compile time without requiring error suppression.
Apply the same fix to line 57 as mentioned in the comment's "Also applies to"
section.
In `@test/integration/test/cli-journeys/format.e2e.test.ts`:
- Line 122: The assertion in the format.e2e.test.ts file is checking for the
"Nothing to format" message on result.stderr, but according to the repo's CLI
journey test conventions, machine-readable assertions should use result.stdout
as the assertion channel. Change the expect statement that contains the F.02
test case to assert against result.stdout instead of result.stderr to follow the
established conventions and prevent channel-coupled test flakes.
🪄 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: 03fd2fbb-6bd7-4cc6-a8fa-912eebc5aaec
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (58)
packages/1-framework/1-core/config/src/config-types.tspackages/1-framework/1-core/config/src/contract-source-types.tspackages/1-framework/1-core/config/src/exports/config-types.tspackages/1-framework/1-core/config/test/config-types.test-d.tspackages/1-framework/1-core/config/test/config-validation.test.tspackages/1-framework/2-authoring/psl-parser/package.jsonpackages/1-framework/2-authoring/psl-parser/src/exports/format.tspackages/1-framework/2-authoring/psl-parser/src/format/emit.tspackages/1-framework/2-authoring/psl-parser/src/format/error.tspackages/1-framework/2-authoring/psl-parser/src/format/format.tspackages/1-framework/2-authoring/psl-parser/src/format/options.tspackages/1-framework/2-authoring/psl-parser/test/format/fixtures.test.tspackages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-model/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-model/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-widths/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-widths/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/blank-lines/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/blank-lines/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/block-attribute-spacing/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/block-attribute-spacing/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/block-attributes/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/block-attributes/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/comments-preserved/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/comments-preserved/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/datasource-generic-blocks/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/datasource-generic-blocks/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/enum-and-generator-block/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/enum-and-generator-block/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/inline-comment-hard-break/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/inline-comment-hard-break/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/kitchen-sink/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/kitchen-sink/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/structural-emit/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/structural-emit/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/type-annotations/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/type-annotations/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/types-namespaced-constructor/expected.prismapackages/1-framework/2-authoring/psl-parser/test/format/fixtures/types-namespaced-constructor/input.prismapackages/1-framework/2-authoring/psl-parser/test/format/options.test.tspackages/1-framework/2-authoring/psl-parser/test/format/trivia.test.tspackages/1-framework/2-authoring/psl-parser/tsdown.config.tspackages/1-framework/3-tooling/cli/package.jsonpackages/1-framework/3-tooling/cli/recordings/fixtures/prisma-next.config.tspackages/1-framework/3-tooling/cli/src/cli.tspackages/1-framework/3-tooling/cli/src/commands/format.tspackages/1-framework/3-tooling/cli/src/control-api/operations/format.tspackages/1-framework/3-tooling/cli/src/exports/index.tspackages/1-framework/3-tooling/cli/test/control-api/format.test.tspackages/2-mongo-family/2-authoring/contract-psl/src/provider.tspackages/2-mongo-family/2-authoring/contract-psl/test/provider.test.tspackages/2-mongo-family/2-authoring/contract-ts/src/config-types.tspackages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/2-sql/2-authoring/contract-ts/src/config-types.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.tstest/integration/test/cli-journeys/format.e2e.test.tstest/integration/test/utils/journey-test-helpers.ts
✅ Files skipped from review due to trivial changes (9)
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-widths/expected.prisma
- packages/1-framework/3-tooling/cli/recordings/fixtures/prisma-next.config.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/type-annotations/expected.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/blank-lines/input.prisma
- packages/1-framework/2-authoring/psl-parser/src/exports/format.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/structural-emit/expected.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/inline-comment-hard-break/input.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/enum-and-generator-block/expected.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/enum-and-generator-block/input.prisma
🚧 Files skipped from review as they are similar to previous changes (36)
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/blank-lines/expected.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-model/expected.prisma
- packages/2-mongo-family/2-authoring/contract-psl/src/provider.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/alignment-model/input.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/types-namespaced-constructor/input.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/block-attributes/input.prisma
- packages/1-framework/1-core/config/src/contract-source-types.ts
- packages/2-sql/2-authoring/contract-psl/src/provider.ts
- packages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.ts
- packages/1-framework/2-authoring/psl-parser/src/format/error.ts
- packages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/inline-comment-hard-break/expected.prisma
- packages/1-framework/3-tooling/cli/src/exports/index.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures.test.ts
- packages/1-framework/1-core/config/src/config-types.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/types-namespaced-constructor/expected.prisma
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/block-attributes/expected.prisma
- packages/1-framework/2-authoring/psl-parser/package.json
- packages/1-framework/1-core/config/test/config-validation.test.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/comments-preserved/input.prisma
- packages/2-mongo-family/2-authoring/contract-ts/src/config-types.ts
- packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
- packages/1-framework/2-authoring/psl-parser/src/format/options.ts
- packages/1-framework/2-authoring/psl-parser/tsdown.config.ts
- packages/1-framework/2-authoring/psl-parser/test/format/fixtures/comments-preserved/expected.prisma
- packages/1-framework/2-authoring/psl-parser/src/format/format.ts
- packages/2-sql/2-authoring/contract-ts/src/config-types.ts
- packages/1-framework/3-tooling/cli/src/control-api/operations/format.ts
- packages/1-framework/1-core/config/test/config-types.test-d.ts
- packages/1-framework/3-tooling/cli/src/cli.ts
- packages/1-framework/3-tooling/cli/src/commands/format.ts
- packages/1-framework/2-authoring/psl-parser/test/format/trivia.test.ts
- packages/1-framework/3-tooling/cli/package.json
- packages/1-framework/1-core/config/src/exports/config-types.ts
- packages/1-framework/2-authoring/psl-parser/src/format/emit.ts
- packages/1-framework/3-tooling/cli/test/control-api/format.test.ts
c2c7569 to
fab546a
Compare
…tions Add the @prisma-next/psl-parser/format subpath export wiring (tsdown entry plus package.json exports map) and the option layer: FormatOptions (indent: number | tab, default 2; newline: LF | CRLF, default LF) validated and normalised with arktype, and PslFormatError carrying the refusing parse diagnostics. Covers export shape and option validation/rejection. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
format() parses via parse(), refuses with PslFormatError when diagnostics are
present, and otherwise walks document.declarations() in source order emitting
single-space-separated tokens: one declaration per line, single space around =,
@/@@ attributes space-separated, key: value arg lists with comma-space, block
bodies indented one indent-unit per depth. Handles model, composite type, enum,
types {}, namespace {}, and generic key = value blocks. Type annotations
round-trip exactly (namespace prefix, constructor call, list, optional). Column
alignment and comment preservation are deliberately not yet applied.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…led guards Remove arktype from psl-parser dependencies (NFR: no new deps). Hand-roll indent/newline validation in resolveFormatOptions using Number.isInteger guards and explicit equality checks; throw TypeError for invalid options (plain Error, not PslFormatError which is reserved for parse diagnostics carrying diagnostics arrays). Semantics are unchanged: indent defaults to 2, accepts positive int or 'tab'; newline defaults to 'LF', accepts 'LF'/'CRLF'. Signed-off-by: Serhii Tatarintsev <[email protected]>
Layer per-block column alignment onto the formatter's structural emit. Within each model, composite type, and enum block, field rows are collected as name / type / attribute cells before rendering so the per-block column widths can be computed once, then applied as padding: - field type names start one space past the widest field name in the block; - trailing field attributes start one space past the widest name+type cell (a field with no attributes ends immediately after its type); - enum value attributes align to the same right-hand column within the enum. Widths are computed independently per block, never across the file. The structural single-space emit for types blocks, generic key=value blocks, and namespaces is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
Reattach inter-construct trivia so trivia-bearing PSL round-trips. The emitter now walks each block body and the document in source order through a single trivia-aware sequencer that classifies interleaved comment and newline tokens: - Leading own-line comments (including a document-leading header) reattach on their own lines at the construct's indent, immediately before it. - A same-line comment after a construct reattaches at the end of that construct's line, separated by one space. - A run of one or more blank lines between members collapses to a single blank line, with no blank directly after an opening brace or before a closing one. Comment text is preserved verbatim (internal spacing untouched); only the line indentation is canonicalised. Alignment runs break at a blank line or a leading-comment line, so a visually separated group is also separately aligned, keeping re-formatting idempotent. Both already-conformant example schemas now format as byte-for-byte no-ops, covered by new idempotence tests. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
A comment on its own line after the last member of a region (block body or document) with no following construct was dropped: it accumulated as a pending leading comment that never attached to a member. Surface these as trailing comment items rendered at the region member indent immediately before the closing token, collapsing any preceding blank-line run to one. A same-line comment trailing a block declaration closing brace was also dropped: the block emit path ignored the member trailing comment. Thread it through to the closing brace line so it is carried like any other member trailing comment. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Serhii Tatarintsev <[email protected]>
The parser rewrite removed the native enum declaration (enum is now a domain concept parsed as a GenericBlockDeclaration with bare KeyValuePair members) and reshaped the type-annotation, attribute, and function-call AST around a single QualifiedName node. Port the emitter accordingly: - drop the EnumDeclaration/EnumValueDeclaration imports and the dedicated enum branch; enum blocks now flow through the generic-block path - render a bare KeyValuePair member (a key with no =) as the key alone - emit qualified names (type references, constructor callees, attribute names) from QualifiedName segments via one emitQualifiedName helper - read constructor args from TypeAnnotation.argList() / isConstructor() Update the enum cases in the alignment and format suites to the generic-block rendering, since single-@ attributes on enum members no longer parse under the new grammar. Signed-off-by: Serhii Tatarintsev <[email protected]>
…barrier A // line comment runs to end-of-line, so when a field or named-type declaration carries a trailing // comment and then continues onto the next source line (its @attributes following below), the emitter must preserve that break rather than hoist the attributes up onto the comment line. Hoisting both swallowed the attributes into the comment and relocated the comment off the token it documented, breaking idempotence. The continuation comment lives inside the declaration node (between the type and the first attribute), so it was previously dropped entirely and the attributes were collapsed onto the head line. Detect the in-node break barrier and render the head + comment on its own line, then each continuation attribute on its own line at the field-continuation indent. Matches Prettier, Biome, and rustfmt. Signed-off-by: Serhii Tatarintsev <[email protected]>
… qualified names Signed-off-by: Serhii Tatarintsev <[email protected]>
Enumerate every examples/**/contract.prisma plus the schema.psl fixture (deterministic sorted walk, pruning node_modules and build output), assert the corpus is at least the known set so a silent drop fails the suite, assert format(format(x)) === format(x) per file, and capture the formatted output as a committed reviewer-readable golden via toMatchFileSnapshot. A file that refuses to parse rethrows with its path so no file can be silently skipped. Signed-off-by: Serhii Tatarintsev <[email protected]>
…name from rebased base Signed-off-by: Serhii Tatarintsev <[email protected]>
…rms unformatted input The corpus harness asserted idempotence and self-generated goldens, both of which an identity formatter (format = x => x) trivially passes. Add per-file transform-direction assertions: every corpus file reformats (format(x) !== x) except an explicit, sorted no-op set, which must stay byte-for-byte unchanged. A classification guard asserts exactly those files are no-ops so a silent flip in either direction fails. The messy->clean identity-killer with an explicit human-authored expected output already lives in format.test.ts. Signed-off-by: Serhii Tatarintsev <[email protected]>
…sion PSL's canonical file extension is .prisma, not .psl. The corpus harness normalised golden names to .psl and the committed goldens lived under __snapshots__/corpus/*.psl; the formatted OUTPUT is PSL, so its golden belongs under .prisma too. Normalise goldenNameFor to .prisma and rename the 31 existing goldens via git mv so history is preserved. Signed-off-by: Serhii Tatarintsev <[email protected]>
…ribute House style (matching the legacy Prisma formatter): within a block, emit exactly one blank line between the last regular member and the first block-level (@@) attribute, inserting it even when the author wrote none. The blank goes before the first @@ only; a run of consecutive @@ attributes stays glued together, and a block whose only members are @@ attributes gets no leading blank. The existing collapse-to-one rule keeps it idempotent when the author already wrote a blank. Regenerate the .prisma goldens to reflect the rule (15 changed). The F2 classification guard now sees an empty no-op set: the two examples that were previously canonical (mongo-blog-leaderboard, prisma-next-cloudflare-worker) each place a field directly before a @@ attribute, so both now reformat. Update knownNoOpFiles to [] and retire the matching byte-for-byte no-op oracles in idempotence.test.ts, keeping the fixed-point oracles. Signed-off-by: Serhii Tatarintsev <[email protected]>
…gle source-order pass
Fold the block-header same-line comment handling (headerTrailingComment +
bodyStart) into sequenceRegion, which already walks each region in source
order once. The block interior is now passed brace-delimited so the one pass
recognises the { boundary (surfacing a header same-line comment) and the }
boundary itself, removing two bespoke re-walks of the block node children.
emitRegion is split into sequenceRegion (the pass) + emitItems (layout), so
both the document and block paths share the single pass.
The inline-break barrier (inlineBreakComment) is intentionally kept separate:
it is intra-declaration trivia (a comment inside one member node, between the
type and its attributes) that splits a member across lines, which the
inter-member leading/trailing/headerComment model cannot express. Its
distinctness is now documented rather than left implicit.
Behaviour-preserving: all 540 psl-parser tests pass unchanged and every
committed golden corpus snapshot stays byte-identical.
Signed-off-by: Serhii Tatarintsev <[email protected]>
The corpus test ran 30 machine-emitted examples/**/contract.prisma snapshots through format() and re-snapshotted each. Those inputs are emitter output, not a formatting oracle: they never demonstrate what the formatter does to messy human-authored source. Remove the test and its 31 goldens; a side-by-side fixture-pair suite replaces them. Signed-off-by: Serhii Tatarintsev <[email protected]>
Each case is a directory holding the messy input.prisma and its formatted expected.prisma adjacent, so a reviewer can open the pair and see exactly what the formatter did. fixtures.test.ts discovers each case, asserts format(input) === expected (the oracle), idempotence on expected, that input actually reformats, and a case-count floor so a dropped fixture dir fails. Cases cover alignment, comment preservation, the inline-comment hard break barrier, blank-line collapsing, the @@-block blank-line rule, an enum + generator (generic) block, and the namespaced-constructor types round-trip (postgis.Geometry(4326) survives). Signed-off-by: Serhii Tatarintsev <[email protected]>
Adds an optional sourceFormat: 'psl' | 'typescript' field to ContractSourceProvider so format-aware tooling can branch on the source language without sniffing file extensions or inspecting the opaque load closure. Every first-party provider declares it: the SQL/Mongo contract-psl providers tag 'psl'; the contract-ts and emptyContract helpers tag 'typescript'. The field is optional and validated in the config arktype schema; format-aware tooling treats an absent value as "not known to be PSL" (left untouched). Signed-off-by: Serhii Tatarintsev <[email protected]>
Adds an optional formatter?: { indent?: number | 'tab'; newline?: 'LF' |
'CRLF' } section to PrismaNextConfig, mirroring the PSL formatter
engine's FormatOptions shape. The section is validated with arktype
(FormatterConfigSchema) so an unsupported newline literal such as
'crlf' or a non-tab indent string is rejected at defineConfig time.
Both fields are optional; an absent section falls back to the engine
defaults (indent 2; newline resolved from os.EOL at the CLI). The type
is exported so the format command can read it.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Adds executeFormat: loads config, branches on config.contract.source.sourceFormat (psl => format inputs[0] in place; typescript/absent => leave untouched), and refuses unparseable PSL with a structured error and no partial write. The os.EOL -> newline resolution lives here as a pure resolveNewline helper (CLI-only; the engine never reads os). Wires @prisma-next/psl-parser/format as a CLI dependency. Signed-off-by: Serhii Tatarintsev <[email protected]>
Wires the format control-api operation into a commander Command (createFormatCommand) with a --config option, a styled header, and the shared handleResult/terminal-UI flow. Registers it as a top-level verb in cli.ts (alongside init/migrate) and exports the factory from the package index. Reports the formatted path on success and a nothing-to-format note when the source is not PSL. Signed-off-by: Serhii Tatarintsev <[email protected]>
Add an e2e CLI journey that runs the real `format` command against a temp project for the three behaviours that anchor the command: a PSL contract source is formatted in place, a non-PSL source is left byte-identical with a "nothing to format" report, and unparseable PSL is refused with a non-zero exit and no partial write. The expected formatted content is derived from the formatter engine itself (with an explicit LF newline for determinism) rather than hardcoded. Add a `runFormatWithConfig` journey helper alongside the existing `runContractEmitWithConfig`; the `createFormatCommand` factory is imported directly from source because it is not exposed via the CLI package`'s `./commands/*` subpath map. Signed-off-by: Serhii Tatarintsev <[email protected]>
Make the fixtures/<case>/{input,expected}.prisma pair the exclusive shape
for output-producing formatter tests. Adds six new pairs covering
structural emit, generic key=value blocks, per-block alignment widths,
type-annotation round-trips, block-attribute blank-line spacing, and a
canonical kitchen-sink. Each expected.prisma is generated by the real
formatter.
The kitchen-sink pair is already canonical (input === expected), so the
harness now branches on that equality: canonical cases assert a
fixed-point no-op instead of the reformat-happened !== check. Bumps
authoredCaseCount to 13.
Folds the refuse-on-diagnostics cases into options.test.ts so the
PslFormatError coverage survives the deletion of format.test.ts.
Signed-off-by: Serhii Tatarintsev <[email protected]>
Removes the six output-producing formatter unit files whose coverage now lives as side-by-side fixture pairs (format, alignment, block-attribute-spacing, type-annotation, idempotence) or as the refuse-on-diagnostics block folded into options.test.ts. exports.test.ts is dropped outright -- it only checked format is a function and that PslFormatError extends Error. Signed-off-by: Serhii Tatarintsev <[email protected]>
Add six side-by-side fixture pairs covering the trivia behaviours not already exercised by the existing fixtures: leading own-line comments (doc comments, consecutive lines, internal spacing, enum values), trailing same-line comments (squished, block attribute, declaration header, closing braces, nested braces), dangling comments (multiple, empty block, blank-run collapse, doc comment), alignment grouping broken by comments/blanks while keeping trailing-comment runs aligned, the named-type inline-comment break barrier, and top-level blank-line collapse. Bump authoredCaseCount to 19. Signed-off-by: Serhii Tatarintsev <[email protected]>
The formatter is tested exclusively through side-by-side fixture pairs. trivia.test.ts was the last output-producing unit file; its 33 cases are now subsumed by the fixture pairs (the full expected.prisma proves no attribute hoisting and the harness idempotence assertion proves the fixed point, so the two non-output assertions need no special-casing). Signed-off-by: Serhii Tatarintsev <[email protected]>
The formatter preserved an author blank between adjacent top-level and namespace-body blocks but never inserted one when blocks were authored back-to-back. House style wants at least one empty line between blocks. emitItems now inserts exactly one blank before a block member (model / composite type / enum or other generic block / namespace / types) when content already precedes it in the same region and no blank is present, including before the block`"'s own leading comment(s). The insertion is gated on a region-local emittedInRegion flag rather than writer-global content so the first member of a region (e.g. the first model inside a namespace body) gets no leading blank. Author multi-blank runs still collapse to one; the rule is idempotent and recurses into namespaces. The block-separation fixture pins the rule: adjacent model, enum, and a comment-led model collapse to one blank between each, including before the leading comment. Signed-off-by: Serhii Tatarintsev <[email protected]>
These eight fixtures had adjacent blocks authored back-to-back in their expected goldens. With the new block-separation rule the formatter now inserts one blank between them, so each golden gains inter-block blank lines (insertions only; no content change or reordering). Regenerated from the formatter and re-verified idempotent. Signed-off-by: Serhii Tatarintsev <[email protected]>
…stream Re-express the PSL formatter emitter as a token-driven LineWriter instead of reconstructing each line from AST accessors as strings. The writer walks the CST token stream, owning canonical inter-token spacing, indentation, and blank lines; per-construct functions drive it to their structural boundaries. The payoff is a single universal rule for inline // (and ///) line comments: wherever a Comment token appears between two tokens, the writer ends the line and indents the continuation, popped when the enclosing construct finishes. This replaces the member-only inlineBreakComment/emitBrokenMember special case, which could only see comments in the field/named-type position and dropped or mishandled them everywhere else. Alignment stays buffer-free: column widths are a pure function of a block AST, computed in a pre-pass and padded to while tokens stream past. All existing format fixtures remain byte-identical and idempotent; no golden was regenerated. Signed-off-by: Serhii Tatarintsev <[email protected]>
Add two format fixtures that exercise the universal inline-comment break in positions the previous member-only special case could not reach: a // comment inside a block-attribute argument list (@@index([a, // note\n b])) and a // comment after = in a key-value pair (url = // see env\n env(...)). Both round- trip through the break-and-indent rule and are idempotent. Bump the authored fixture-case floor to 22. Signed-off-by: Serhii Tatarintsev <[email protected]>
…n walk Replace the two-pass emitter (collectMembers reducing the token stream into a RegionItem[] with precomputed leading/trailing/blankBefore, then emitMembers re-walking that array with run/flushRun member-buffering and the leading/blankPending/sawContent/emittedInRegion/lastWasRegular layout flags) with a single source-order walk that writes as it goes. The trivia in the stream now decides layout in place: own-line vs same-line comments, author blank-run collapse, block separation and the block-attribute blank are all decided live from stream position plus the writer's own state, not from flags precomputed onto a buffered item array. Add the operator-specified writeUntil(syntax, tokenKind): it streams a node's significant tokens (and interior // comments) through the writer until and including the next token of tokenKind, normalising trivia and applying the universal inline-comment break+indent rule in place. Per-construct drivers are now thin: a block writes its header via writeUntil(..., LBrace) then recurses the interior; a member streams to exhaustion. Alignment stays the one allowed look-ahead: a per-region AST pre-pass groups field rows into runs and maps each field node to its run's column widths (pure numbers), which the walk pads to when it reaches each field. No rendered output is buffered. Every existing test/format fixture stays byte-identical; the suite is green and idempotent with no second-run churn. Signed-off-by: Serhii Tatarintsev <[email protected]>
…t functions Replace the single generic emitRegion + streamTokens + writeUntil machine with separate, named emit functions per construct (emitModel, emitCompositeType, emitGenericBlock, emitNamespace, emitTypesBlock, emitField, emitNamedType, emitBlockAttribute, emitKeyValue). Each reads its structure from the typed AST and prints it by streaming that node's tokens through the LineWriter. Delete the StreamToken interface and its typeAnnotationStart / fieldAttributeStart / pending* annotation plumbing: emitField now walks the declaration's direct children and pads the type and first-attribute cells to the precomputed alignment columns explicitly, because it knows from the AST when it is at those boundaries. The universal inline-comment break+indent, the spaceBetween table, the AST-based alignment width pre-pass, and the between-member comment/blank placement are preserved. All existing format fixtures remain byte-identical; the suite stays green and idempotent. Signed-off-by: Serhii Tatarintsev <[email protected]>
The five block emit functions (emitModel/emitCompositeType/emitGenericBlock/ emitNamespace/emitTypesBlock) were hollow wrappers that all delegated to one generic emitBlockMember -> emitMemberSequence engine, with emitNestedBlock and emitLeafMember dispatching member kinds generically. Replace that single block engine with genuinely distinct per-construct functions: each one names its own member kinds (a model owns fields + block attributes, a generic block owns key/value entries + block attributes, a types block owns named types, a namespace owns nested declarations) and picks the per-member function each is printed with. The shared trivia mechanics (header tokens, collapsed blank runs, own-line / same-line / dangling comments, house-style separation blanks) stay factored into emitBlockBody + walkRegion, now parameterized by a block-supplied MemberClassifier rather than re-deriving member kinds generically. Source-order walking over the block children is preserved, so interleaved comments and blank lines still land canonically. Alignment widths are still an AST pre-pass; the per-field column map is keyed by source offset so it survives the separate children() walk. Behaviour preserving: every existing test/format fixture stays byte-identical and the suite remains idempotent; no goldens changed. Signed-off-by: Serhii Tatarintsev <[email protected]>
Field column widths are now computed across every field in a model or composite type at once, so a blank line or an interior/leading comment between two fields no longer splits them into separately-aligned runs. alignmentMap collapses to a single pass that collects the block's alignable fields and returns one set of columns (or undefined when none exist); the per-run state machine and its map keyed by field offset are gone. Fields carrying an interior comment still break to continuation lines and are excluded from the width math. Regenerate the five goldens whose alignment merges across a blank or leading comment under whole-block widths. Signed-off-by: Serhii Tatarintsev <[email protected]>
The no-bare-cast ratchet flagged five bare `as` casts in the init command (carried in from main). Replace them with type-safe forms: - detect-package-manager: an isPackageManager type predicate narrows the detected/user-agent name instead of asserting it. - hygiene-package-scripts: JSON.parse results go through blindCast with a named reason (package.json is a JSON object). Signed-off-by: Serhii Tatarintsev <[email protected]>
The prisma-next shim package must mirror @prisma-next/cli dependencies (enforced by lint-sync). The format command added @prisma-next/psl-parser to the cli; add it to the shim and update the lockfile to match. Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
a9045cc to
40843ac
Compare
What
Delivers the PSL formatter for Prisma Next, end to end: a deterministic pretty-printer engine plus the
prisma formatCLI command that runs it.1. Engine —
@prisma-next/psl-parser/format:format(source, options?) -> stringparses via the CST and re-emits canonical PSL. Pure string→string: no file I/O, no node built-ins, no@prisma-next/configdependency.2. CLI —
prisma format:Reads
prisma-next.config.ts; when the contract source is PSL (config.contract.source.sourceFormat === 'psl'), formatsconfig.contract.source.inputs[0]in place. Non-PSL or absent sources are left untouched. Indent/newline come from an optionalformatterconfig section; the system newline (os.EOL) is resolved at the CLI.Closes TML-2928 (the whole issue — both the engine and the CLI).
Why
Prisma Next authors hand-write and machine-emit PSL, but there was no canonical formatter for the new authoring stack. The new red/green CST preserves all trivia (whitespace, comments, newlines) as tokens, making it the right substrate for a lossless pretty-printer: re-emit a normalized, deterministic layout while retaining comments and the full token stream.
Engine behaviour
parse+ typed AST wrappers); does not touch the legacyparsePslDocument.indent: positive integer (spaces) or'tab'; default 2.newline:'LF'(default) or'CRLF', applied uniformly.@@attribute (house style).format(format(x)) === format(x).PslFormatError) rather than emitting best-effort output.Key decisions
@prisma-next/psl-parservia a./formatsubpath — no separate package, no new runtime dependency. Engine option validation is hand-rolled (the option space is two enum-ish fields; a schema lib would have violated the package's no-new-deps constraint). Theformatterconfig section, by contrast, is arktype-validated —@prisma-next/configalready depends on arktype.os.EOLresolution lives only in the CLI. The engine never readsos; theprisma formatcommand resolvesconfig.formatter.newline ?? (os.EOL === '\r\n' ? 'CRLF' : 'LF')and passes an explicitnewlineinto the engine.ContractSourceProvidercarries an optionalsourceFormat: 'psl' | 'typescript'; every first-party provider declares it (prismaContract/mongoContract→'psl'; thetypescript*/emptyhelpers →'typescript'). The command formats only'psl'sources; anything else (incl. absent) is left untouched.//comments are a hard break barrier.field Type //commentfollowed by a continuation@attributepreserves the break rather than hoisting the attribute past the comment — matching Prettier, Biome, and rustfmt (a//comment runs to end-of-line; joining a later token onto its line is both a correctness and an idempotence hazard).Tests — side-by-side fixture pairs
The formatter's integration oracle is a set of hand-authored side-by-side pairs under
test/format/fixtures/<case>/{input,expected}.prisma— open a pair to see exactly what the formatter does. The test assertsformat(input) === expected, idempotence, and that formatting actually happened. Cases cover alignment, comment preservation, the inline-comment hard break, blank-line handling, block-attribute spacing, enum/generic blocks, and the namespaced-type round-trip (space:ns.Type). The CLI is covered by an e2e journey (format.e2e.test.ts) proving format-in-place, leave-untouched, and refuse-on-unparseable, each asserting on-disk file state.Validation
pnpm lint:deps— no violations (engine takes no node built-ins; the CLI→engine edge is layering-safe).@prisma-next/psl-parser— 529 tests, no type errors; fixture pairs produce no snapshot churn.@prisma-next/config— 29 tests (discriminator +formattersection).@prisma-next/cli—prisma formatoperation tests + the e2e journey green. (Note: ~9 pre-existing flakes inversion.test.ts/removed-verb-redirects.test.tsare cold-boot subprocess-timeout fragility, unrelated to this work.)Base
Targets
main. The formatter consumes the fault-tolerant CST parser surface, which landed onmainvia #795 and #849; this branch was originally stacked on the pre-mergepsl-cst-parserbranch and has been rebased ontomainnow that the CST work is merged.Summary by CodeRabbit
Release Notes
formatCLI command with--configoption to format PSL files in place.