Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

TML-1817: Vite plugin - #109

Merged
wmadden merged 52 commits into
mainfrom
tml-1817-vite-plugin-auto-contract-emit-during-development
Jan 20, 2026
Merged

wmadden merged 52 commits into
mainfrom
tml-1817-vite-plugin-auto-contract-emit-during-development

Conversation

@wmadden

@wmadden wmadden commented Jan 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Vite plugin for automatic Prisma contract emission with HMR, debounce and full-reload behavior
    • Contract viewer demo app with dark-themed UI to preview emitted contracts
    • CLI operation to emit contracts offline (returns hashes and artifact paths)
    • New abortable utility to race async work against an AbortSignal
  • Behavior Changes

    • Contract TypeScript definitions are now colocated with contract.json (separate types path removed)
  • Documentation

    • Detailed README for the Vite plugin and updated onboarding convention
  • Tests

    • Unit and e2e tests for plugin, emit flow, HMR, and cancellation utility

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 10, 2026 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds a Vite plugin that emits Prisma Next contract artifacts during dev, a CLI/offline contract emit operation, colocates generated .d.ts next to emitted .json (removing explicit contract.types), an abortable utility, a demo app, unit and e2e HMR tests, and packaging/config for the new plugin.

Changes

Cohort / File(s) Summary
Vite plugin package
packages/1-framework/3-tooling/vite-plugin-contract-emit/{README.md,biome.jsonc,package.json,src/exports/index.ts,src/plugin.ts,src/types.ts,test/plugin.test.ts,tsconfig.json,tsconfig.prod.json,vitest.config.ts,tsdown.config.ts}
New package exposing prismaVitePlugin(configPath?, options?) and PrismaVitePluginOptions. Implements module-graph dependency collection, file watching, debounced/coalesced emits, in-flight emit cancellation, error overlay reporting, logging, and full-page reloads. Includes tests and packaging/config.
CLI contract emit operation & types
packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts, packages/1-framework/3-tooling/cli/src/exports/control-api.ts, packages/1-framework/3-tooling/cli/src/control-api/types.ts
Adds executeContractEmit(options) and types (ContractEmitOptions, ContractEmitResult) for offline emit. Validates config (output must end with .json), runs control plane emit, writes .json and colocated .d.ts, and respects AbortSignal cancellation.
CLI command & tests
packages/1-framework/3-tooling/cli/src/commands/contract-emit.ts, packages/1-framework/3-tooling/cli/test/control-api/contract-emit.test.ts, packages/1-framework/3-tooling/cli/test/**, packages/1-framework/3-tooling/cli/package.json
Updates CLI emit command to require/validate contract.output (.json), derive colocated .d.ts, ensure directories, write artifacts. Adds tests for executeContractEmit and a runtime pathe dependency.
Contract config refactor & validation
packages/1-framework/1-core/migration/control-plane/src/config-types.ts, packages/1-framework/1-core/migration/control-plane/src/config-validation.ts, related tests
Removes contract.types from config/schema/normalization/validation and updates tests; .d.ts is now derived/colocated from contract.output.
Prisma Next demo app
examples/prisma-next-demo
examples/prisma-next-demo/{index.html,package.json,src/entry.ts,vite.config.ts,tsconfig.json,prisma-next.config.ts}
New example app and Vite config. Adds static index.html, src/entry.ts that renders imported contract JSON into the DOM, dev script and vite plugin dependency; removes contract.types from example config.
Integration fixtures & e2e tests
test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/vite-plugin/{contract.ts,prisma-next.config.ts,vite.config.ts}, test/integration/test/vite-plugin.hmr.e2e.test.ts, test/integration/package.json
New fixtures and an e2e HMR test that starts a Vite dev server, verifies initial contract.json emission, mutates source to trigger HMR, and asserts re-emitted contract JSON updates. Integration package now depends on the plugin.
Shared utils — abortable
packages/1-framework/1-core/shared/utils/src/{abortable.ts,exports/abortable.ts}, packages/1-framework/1-core/shared/utils/test/abortable.test.ts, packages/1-framework/1-core/shared/utils/package.json, packages/1-framework/1-core/shared/utils/tsdown.config.ts
Adds abortable(signal) utility that races a promise against an AbortSignal, throws if already aborted, and propagates abort reason; re-exported and covered by tests. Adds package export entry for ./abortable.
Tests & tooling
packages/1-framework/3-tooling/vite-plugin-contract-emit/test/plugin.test.ts, various test/**
Extensive unit and integration tests for plugin behavior (timers, module graph, overlay), CLI emit, HMR e2e, and abortable utility.
Workspace, deps & configs
pnpm-workspace.yaml, test/integration/package.json, coverage.config.json, packages/2-sql/1-core/schema-ir/vitest.config.ts, .gitignore
Adds Vite catalog entry and integration dependency on the plugin, adds pathe runtime dep for CLI, adjusts coverage warnings/excludes, and ignores .pnpm-store.
Developer guidance
.cursor/rules/use-pathe-for-paths.mdc, docs/onboarding/Conventions.md
New rule and onboarding note advising pathe over node:path for cross-platform compatibility.

Sequence Diagram(s)

sequenceDiagram
    participant ViteServer as Vite Dev Server
    participant Plugin as prismaVitePlugin
    participant ModuleGraph as Vite Module Graph
    participant ContractEmit as executeContractEmit
    participant FileSystem as File System

    ViteServer->>Plugin: configResolved(config)
    Plugin->>Plugin: resolve absolute configPath

    ViteServer->>Plugin: configureServer(server)
    activate Plugin
    Plugin->>ModuleGraph: collect transitive dependencies
    ModuleGraph-->>Plugin: return watchedFiles
    Plugin->>Plugin: watch files & schedule initial emit
    Plugin->>ContractEmit: execute emit (with AbortSignal)
    activate ContractEmit
    ContractEmit->>FileSystem: write contract.json and contract.d.ts
    FileSystem-->>ContractEmit: files written
    ContractEmit-->>Plugin: emit result (hashes, paths)
    deactivate ContractEmit
    Plugin->>ViteServer: full page reload
    deactivate Plugin

    FileSystem->>Plugin: file change detected
    activate Plugin
    Plugin->>Plugin: debounce & cancel in-flight emit
    Plugin->>ContractEmit: execute debounced emit
    activate ContractEmit
    ContractEmit->>FileSystem: write updated artifacts
    FileSystem-->>ContractEmit: files written
    ContractEmit-->>Plugin: emit result
    deactivate ContractEmit
    Plugin->>ViteServer: full page reload
    deactivate Plugin
Loading
sequenceDiagram
    participant Caller as executeContractEmit caller
    participant ConfigLoader as Config loader
    participant ControlPlane as Control plane / Stack
    participant Family as Family instance
    participant FileSystem as File System

    Caller->>ConfigLoader: load config (configPath)
    ConfigLoader-->>Caller: config object
    Caller->>Caller: validate contract.output exists and endsWith .json
    Caller->>ControlPlane: create stack from config
    ControlPlane->>Family: instantiate family instance
    Caller->>Family: resolve contract source
    Caller->>Family: emit contract artifacts
    Family-->>Caller: coreHash, profileHash, artifact buffers
    Caller->>Caller: derive colocated .d.ts path from .json
    Caller->>FileSystem: ensure JSON output dir exists
    Caller->>FileSystem: write contract.json
    Caller->>FileSystem: write contract.d.ts
    FileSystem-->>Caller: files written
    Caller-->>Caller: return ContractEmitResult (hashes + paths)
Loading

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 13

🤖 Fix all issues with AI agents
In
@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts:
- Around line 58-70: The code currently resolves contractConfig.output and
contractConfig.types against process.cwd(); instead, when computing
outputJsonPath and outputDtsPath resolve them relative to the config file
directory (dirname(configPath)) unless the values are already
absolute/normalized. Update the logic around outputJsonPath/outputDtsPath to
check path.isAbsolute(contractConfig.output) /
path.isAbsolute(contractConfig.types) (or similar normalization) and otherwise
use path.resolve(path.dirname(configPath), contractConfig.output) and
path.resolve(path.dirname(configPath), contractConfig.types) so relative paths
are interpreted relative to the config file.
- Around line 24-40: The cancellation checks in executeContractEmit currently
throw generic Error('Contract emit was cancelled'), causing callers to rely on
brittle message substring checks; replace those throws (all occurrences in
executeContractEmit) by calling signal?.throwIfAborted?.() when available, and
if not, define and throw a dedicated ContractEmitCancelledError class (override
name = 'ContractEmitCancelledError' and set the same message) so callers can
reliably detect cancellation via error.name === 'ContractEmitCancelledError'
(update all four checks mentioned to use the new approach).

In @packages/1-framework/3-tooling/vite-plugin-contract-emit/biome.jsonc:
- Line 3: The "extends" value in biome.jsonc is invalid ("//"); locate the
repository root Biome config (biome.json or biome.jsonc) using the provided
search script and update the "extends" field in this package's biome.jsonc to
the correct relative path to that root config (e.g., "../../../biome.json" or
similar), or remove the field if this package should not inherit a root config;
ensure the updated "extends" points to an existing file so Biome can inherit the
expected rules.

In @packages/1-framework/3-tooling/vite-plugin-contract-emit/README.md:
- Around line 88-92: Update the "Related" links to point directly to the ADR and
subsystem files instead of directory links with %20-encoded paths: replace the
three directory-style links with the exact file paths for ADR 032, ADR 008, and
Subsystem "Contract Emitter & Types" using the provided target filenames (ADR
032 — Dev Auto-Emit Integration, ADR 008 — Dev Auto-Emit, CI Explicit Emit, and
Subsystem: Contract Emitter & Types) so the links reference the specific
Markdown files rather than their containing directories.

In @packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts:
- Around line 130-168: The watchedFiles set becomes stale because it is only
built once in configureServer; after each successful emit you must re-run
collectWatchedFiles and reconcile the Vite watcher and the module-scoped
watchedFiles set so newly-transitive imports will trigger future emits.
Specifically, after the emit completes in the code path that uses
handleHotUpdate/scheduleEmit, call collectWatchedFiles(viteServer) to get an
updated Set, compute files to add and remove relative to the existing
watchedFiles, call viteServer.watcher.add(...) for new files and
viteServer.watcher.unwatch(...) or remove for deleted files, then replace the
module-level watchedFiles with the new Set. Ensure you reference the existing
functions/vars (collectWatchedFiles, configureServer, handleHotUpdate,
watchedFiles, viteServer.watcher) when making the change.
- Around line 135-136: ssrLoadModule and getModuleById are being given a raw
absolute filesystem path (absoluteConfigPath) which Vite does not accept;
convert absoluteConfigPath to Vite's normalized module ID before use (for
absolute paths prefix with "/@fs/" or otherwise normalize to a server-rooted
path like "/src/...") and pass that normalized ID into
viteServer.ssrLoadModule(...) and viteServer.moduleGraph.getModuleById(...);
update the code locations that call ssrLoadModule and getModuleById to use the
normalized ID (e.g., normalizedConfigId = `/@fs/${absoluteConfigPath}` for
absolute files) so Vite can resolve the module correctly.

In
@packages/1-framework/3-tooling/vite-plugin-contract-emit/test/plugin.test.ts:
- Around line 4-36: Add behavioral tests for prismaVitePlugin: call
prismaVitePlugin(...) then invoke its configResolved(config) and assert it
resolves/normalizes paths expected (use a minimal Vite config object and check
plugin-internal path fields), call configureServer(server) with a mocked server
object and verify it registers file watchers/uses server.watcher.add or
equivalent, call handleHotUpdate(ctx) with simulated file change events for
tracked files and assert it triggers the emission logic (e.g., returns/awaits
expected result or calls the emit function), test debounceMs by using fake
timers to ensure rapid successive handleHotUpdate calls only trigger emission
once after debounce, and add tests that mock failures in the emission path to
assert error handling paths are exercised; reference prismaVitePlugin,
configResolved, configureServer, handleHotUpdate, and debounceMs when locating
functions to test.
- Around line 38-48: The test performs a direct type assertion on
plugin.configResolved; replace that direct cast with a double cast (as unknown
as (config: { root: string }) => void) to follow the guideline for mocks/dynamic
proxies. Update the line that assigns configResolved from plugin.configResolved
to use the double-cast pattern, keeping the same variable name and call site
unchanged.
- Around line 51-63: The test uses direct type assertions for plugin methods;
replace them with double casts to match test patterns: where you cast
plugin.configResolved and plugin.handleHotUpdate (both obtained from
prismaVitePlugin('prisma-next.config.ts', ...)), change each direct cast to use
"as unknown as (config: { root: string }) => void" and "as unknown as (ctx: {
file: string }) => void" respectively so the mocks use the required as unknown
as X pattern.

In @packages/1-framework/3-tooling/vite-plugin-contract-emit/tsconfig.json:
- Line 2: Update the "extends" field in
packages/1-framework/3-tooling/vite-plugin-contract-emit/tsconfig.json to use
the package-based extension pattern instead of the relative path; replace the
current extends value ("../../../../tsconfig.base.json") with the package-based
reference "prisma-next/tsconfig/base" so the project inherits the shared base
config via the package name.

In @packages/1-framework/3-tooling/vite-plugin-contract-emit/tsup.config.ts:
- Line 11: The build currently disables TypeScript declaration generation (dts:
false) which prevents consumers from getting types for prismaVitePlugin and
PrismaVitePluginOptions; enable declarations by setting dts to true (or
configure a dts option with proper output paths) in tsup.config.ts so the build
emits .d.ts files alongside the JavaScript artifacts and ensure the package's
entry points include the generated declarations so prismaVitePlugin and
PrismaVitePluginOptions are exported with types.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Fix all issues with AI agents
In @examples/prisma-next-demo/index.html:
- Around line 95-100: The subtitle text is misleadingly telling users to "Edit
contract.ts" even though the page is loaded from the generated artifact
contract.json; update the copy inside the <p class="subtitle"> element to
reference the correct source (e.g., "This page is loaded from contract.json.
Edit the contract generator or the source that produces contract.json to see
changes.") and ensure only the text content of the element with class "subtitle"
is changed (leave the "contract-view" div and the <script src="/src/entry.ts">
unchanged).

In @examples/prisma-next-demo/src/entry.ts:
- Around line 1-40: The code uses blind casts (e.g., casting parsed JSON or
module.default to Contract) and unsafe string interpolation in HTML; fix by
importing the generated Contract type and replacing casts with runtime narrowing
via validateContract<Contract>(value) wherever JSON is parsed or module.default
is used (e.g., in your module hot-accept handler and initial load), and update
renderContract to escape interpolated values (or build DOM nodes instead of
using template strings) for fieldName/name/tableName to avoid XSS; also update
import.meta.hot.accept callback to check the incoming module (module?.default)
and validate it with validateContract before using.

In @examples/prisma-next-demo/src/prisma/contract.json:
- Around line 75-88: The relation metadata for post.user is inverted: swap the
childCols and parentCols so childCols is ["userId"] and parentCols is ["id"]; do
not edit the JSON by hand—re-run the contract emitter (prisma-next contract
emit) to regenerate the file so the post.user relation metadata (the on clause
specifying childCols/parentCols) matches the foreign key post.userId → user.id
and aligns with the inverse user.posts mapping.

In @examples/prisma-next-demo/tsconfig.json:
- Around line 2-7: Update the tsconfig "extends" to use package-based array
syntax instead of the relative path: replace the current string value of
"extends" with an array containing "prisma-next/tsconfig/base" so the compiler
config inherits from the package-provided base; ensure no other changes to
"compilerOptions" are made and that the JSON remains valid.

In @packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts:
- Around line 170-209: The dev server lifecycle isn't cleaned up: add a server
close hook inside configureServer to clear any pending debounceTimer and abort
any in-flight work via currentAbortController when the Vite server closes;
specifically, inside configureServer (where server is set and emit/scheduling
happens) register viteServer.httpServer?.on('close', ...) or
viteServer.watcher.on('close', ...) / viteServer?.config?.server?.close hook to
call clearTimeout(debounceTimer) and if (currentAbortController)
currentAbortController.abort(), and also null out
debounceTimer/currentAbortController/server to avoid dangling references so
scheduleEmit, handleHotUpdate, and emitContract won't act after shutdown.
- Around line 88-93: The catch block currently treats cancellation by inspecting
error.message.includes('cancelled'), which is brittle; update the cancellation
detection to check the AbortSignal or standard error names instead: if a signal
is available, check signal.aborted and handle as canceled; otherwise detect
abort errors by checking error.name === 'AbortError' (or error instanceof
DOMException with name 'AbortError') before logging 'Emit cancelled' and
returning null; replace the fragile string check in the catch block around the
current code in plugin.ts with these signal/error-name checks.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 26f9e0c and a67a7c3.

📒 Files selected for processing (6)
  • examples/prisma-next-demo/index.html
  • examples/prisma-next-demo/src/entry.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/tsconfig.json
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
🧰 Additional context used
📓 Path-based instructions (21)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/use-correct-tools.mdc)

**/*.{ts,tsx}: Use local pnpm typecheck scripts instead of writing tsc commands from scratch for TypeScript type checking
Never add file extensions to imports in TypeScript

**/*.{ts,tsx}: Core contract types (ContractBase, Source) and document family types (DocumentContract) should be imported from @prisma-next/contract/types
SQL emitter hook should be imported from @prisma-next/sql-contract-emitter (canonical source)
Target-neutral operations should be imported from @prisma-next/operations (canonical source)

**/*.{ts,tsx}: Extract CodecTypes from contract using ExtractCodecTypes<Contract> helper type with fallback to Record<string, never>
Extract OperationTypes from contract using ExtractOperationTypes<Contract> helper type with fallback to Record<string, never>
Never pass CodecTypes or OperationTypes as separate type parameters to schema(), sql(), or orm() functions
Always extract types from contract using the helper types instead of passing them directly
Contract must be validated before passing to createRuntimeContext() using validateContract<Contract>()

**/*.{ts,tsx}: Use pnpm and local scripts (not ad-hoc tsc, jest) for building and testing
Use adapters instead of branching on target in core code
Prefer links to canonical docs over long comments in code
Use type parameter pattern with .d.ts for precise types instead of inferring types from JSON imports
Always use validateContract<Contract>(json) with fully-typed Contract type parameter, not generic SqlContract<SqlStorage>
Access table columns using table.columns.fieldName to avoid conflicts with table properties
Builder methods return new instances; always chain calls instead of reassigning variables
No backward-compatibility shims; update call sites instead
Package layering is enforced; fix violations rather than bypassing them
Capability-gated features must be enabled in contract capabilities before use (e.g., includeMany, returning())
Expo...

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/use-correct-tools.mdc)

**/*.{ts,tsx,js,jsx}: Use arktype instead of zod for schema validation
Don't add comments if avoidable; prefer code which expresses its intent
Don't add exports for backwards compatibility unless explicitly requested
Do not reexport things from one file in another, except in the exports/ folders

Import from shared plane packages using package name and export identifier (e.g., @prisma-next/sql-contract/types), not /exports/ paths

**/*.{ts,tsx,js,jsx}: Follow layering rules and exceptions for imports as defined in .cursor/rules/import-validation.mdc and .cursor/architecture.config.json
Follow includeMany type inference patterns (as per .cursor/rules/include-many-patterns.mdc)
Follow Arktype usage guidelines defined in .cursor/rules/arktype-usage.mdc
Use Object.hasOwn() instead of hasOwnProperty() (as per .cursor/rules/object-hasown.mdc)
Prefer assertions over defensive checks to avoid schema validation redundancy (as per .cursor/rules/prefer-assertions-over-defensive-checks.mdc)

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
{packages,examples,test}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/object-hasown.mdc)

Always use Object.hasOwn() instead of hasOwnProperty() to check for own properties. The modern ES2022 API is preferred as it cannot be overridden or shadowed, and is enforced by Biome lint rule noPrototypeBuiltins.

Export interfaces and factory functions for public APIs; keep concrete classes as private implementation details

No generic defaults unless meaningful: defaults are semantics, not flexibility. See .cursor/rules/generic-parameters.mdc for details.

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
{packages/2-sql/**,packages/3-targets/**,examples/**,test/**}/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/sql-types-imports.mdc)

{packages/2-sql/**,packages/3-targets/**,examples/**,test/**}/*.{ts,tsx,js}: Import SQL-specific contract types (SqlContract, SqlStorage, SqlMappings, ModelDefinition, StorageTable, StorageColumn, etc.) from @prisma-next/sql-contract/types (shared plane package), not from @prisma-next/contract/types
SQL contract validators should be imported from @prisma-next/sql-contract/validators (shared plane)
SQL contract IR factories should be imported from @prisma-next/sql-contract/factories (shared plane)
SQL-specific operations should be imported from @prisma-next/sql-operations (canonical source, shared plane)

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/entry.ts
**/*.{ts,tsx,test-d.ts}

📄 CodeRabbit inference engine (.cursor/rules/validate-contract-usage.mdc)

When using validateContract<TContract>(), always use a fully-typed contract type (not a generic SqlContract<SqlStorage>). Using a generic type causes all subsequent type inference to fail, resulting in unknown types throughout the code.

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
**/!(*.test|*.test-d|*.spec).ts?(x)

📄 CodeRabbit inference engine (.cursor/rules/validate-contract-usage.mdc)

For production code using validateContract<TContract>(), always import the contract type from contract.d.ts (generated by the emitter) rather than defining types inline.

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
{packages,test,examples}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/arktype-usage.mdc)

{packages,test,examples}/**/*.{ts,tsx}: Use Arktype instead of Zod for schema validation and type definitions
Use optional keys via 'key?' syntax in Arktype schemas (not 'string | undefined')
Use 'type({ "[string]": Schema })' for defining record types in Arktype
Use 'Schema.array()' for array definitions in Arktype (avoid tuple mistakes)

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
examples/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/generic-parameters.mdc)

Don't add generic defaults unless the type is meaningfully usable with the default. Avoid defaults that create a false "optional" API where the type is pointless without concrete generics.

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/entry.ts
{packages,examples,test}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/no-target-branches.mdc)

Never branch on target in core code - use adapters instead. Target-specific logic should be encapsulated in adapter interfaces and target-specific packages, not in conditional branches checking the target value.

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
{packages,test,examples}/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/prefer-assertions-over-defensive-checks.mdc)

{packages,test,examples}/**/*.ts: Prefer assertions over defensive checks when data is guaranteed to be valid - use non-null assertions (e.g., columnMeta!) after validation checks instead of optional chaining
Remove optional chaining and conditional property spreading for properties that are guaranteed to exist after validation - access required properties directly without ?. operators

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
{packages/2-sql,packages/sql,examples,test}/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/query-patterns.mdc)

{packages/2-sql,packages/sql,examples,test}/**/*.ts: Prefer accessing columns via tables.user.columns.email pattern instead of conflicting with table properties
Extract local variables when a file uses tables frequently - use const user = tables.user and const cols = user.columns for readability

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/entry.ts
{packages,examples}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/type-predicates.mdc)

Avoid blind casts like as unknown as X in production TypeScript code. Use type predicates (value is X) or type guards instead to let the compiler narrow types safely.

{packages,examples}/**/*.{ts,tsx}: Export interfaces; construct via factories: keep classes as private implementation details.
Replace blind casts with type predicates. See .cursor/rules/type-predicates.mdc for details.
Use interface-based design with factory functions for object construction. See .cursor/rules/interface-factory-pattern.mdc for details.

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
**/*.{sql,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Use LATERAL and json_agg patterns as defined in .cursor/rules/postgres-lateral-patterns.mdc

Files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/control-plane-descriptors.mdc)

packages/**/*.{ts,tsx}: Use ControlFamilyDescriptor<TFamilyId, TFamilyInstance> type for family descriptors in control plane implementations
Use ControlTargetDescriptor<TFamilyId, TTargetId, TTargetInstance> type for target descriptors in control plane implementations
Use ControlAdapterDescriptor<TFamilyId, TTargetId, TAdapterInstance> type for adapter descriptors in control plane implementations
Use ControlDriverDescriptor<TFamilyId, TTargetId, TDriverInstance> type for driver descriptors in control plane implementations
Use ControlExtensionDescriptor<TFamilyId, TTargetId, TExtensionInstance> type for extension descriptors in control plane implementations
All control plane descriptors must include kind property as a discriminator with value 'family' | 'target' | 'adapter' | 'driver' | 'extension'
All control plane descriptors must include id property as a string identifier
All control plane descriptors must include familyId property as a literal type (e.g., 'sql')
Target, adapter, driver, and extension descriptors must include targetId property as a literal type (e.g., 'postgres')
All control plane descriptors must include manifest property of type ExtensionPackManifest
All control plane descriptors must include create() factory method that returns an instance
Always pass driver parameter to ControlFamilyDescriptor.create(), even for commands that don't use it (e.g., contract emit)
Do not use legacy descriptor types (FamilyDescriptor, TargetDescriptor, AdapterDescriptor, DriverDescriptor, ExtensionDescriptor, ControlPlaneDriver). Use Control*Descriptor and Control*Instance types instead

packages/**/*.{ts,tsx}: Family instances must implement control-plane domain actions (e.g., emitContract, verify, schemaVerify, introspect) as self-contained methods that own their implementation logic
In family instance domain actions, import and use pure helper functions (e.g., canonicalizeContract, `computeCoreHas...

Files:

  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
packages/**/src/**

📄 CodeRabbit inference engine (.cursor/rules/multi-plane-entrypoints.mdc)

Structure multi-plane packages with split sources by plane: src/core/** for shared, src/exports/control.ts for migration, src/exports/runtime.ts for runtime

Files:

  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
packages/**

📄 CodeRabbit inference engine (.cursor/rules/no-backward-compatibility.md)

Do not add backward-compatibility shims or migration scaffolding in the codebase

Files:

  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
packages/**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/no-backward-compatibility.md)

Do not add deprecation warnings or migration helpers

Files:

  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
packages/**/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/shared-plane-packages.mdc)

Organize shared plane package source code with separate files: types.ts, validators.ts (optional), and factories.ts (optional)

Files:

  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
packages/**/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/shared-plane-packages.mdc)

Do not import migration-plane packages (emitter, CLI) or runtime-plane packages (lanes, runtime) in shared plane packages

Files:

  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
packages/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/prefer-assertions-over-defensive-checks.mdc)

packages/**/*.ts: Use schema validators (Arktype) for structural validation of required fields, types, and shapes rather than redundant manual checks for these properties
Focus logical validators on consistency checks (foreign key references, model-to-table mappings, constraint relationships) that schema validators cannot perform, not on re-validating structural properties

Files:

  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
packages/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

For packages that span multiple planes, follow patterns in .cursor/rules/multi-plane-packages.mdc and .cursor/rules/multi-plane-entrypoints.mdc

Files:

  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
🧠 Learnings (3)
📚 Learning: 2025-12-26T23:02:40.679Z
Learnt from: wmadden
Repo: prisma/prisma-next PR: 38
File: packages/2-sql/3-tooling/family/src/core/migrations/plan-helpers.ts:40-47
Timestamp: 2025-12-26T23:02:40.679Z
Learning: In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations such as deep freezing or deep cloning. Favor reliable, battle-tested functions and ensure dependencies are reviewed for tree-shaking and bundle size. If a lightweight utility suffices, consider modern native approaches or smaller libs.

Applied to files:

  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • examples/prisma-next-demo/src/entry.ts
📚 Learning: 2026-01-05T23:16:08.932Z
Learnt from: igalklebanov
Repo: prisma/prisma-next PR: 85
File: examples/prisma-orm-demo/tsconfig.json:2-2
Timestamp: 2026-01-05T23:16:08.932Z
Learning: In the prisma-next monorepo, tsconfig.json files should extend the base config using an array syntax: "extends": ["prisma-next/tsconfig/base"]. Do not reference relative paths to the root tsconfig.base.json; prefer the package-based extension for maintainability across the monorepo.

Applied to files:

  • examples/prisma-next-demo/tsconfig.json
📚 Learning: 2026-01-08T11:52:08.389Z
Learnt from: igalklebanov
Repo: prisma/prisma-next PR: 103
File: packages/2-sql/3-tooling/family/package.json:13-13
Timestamp: 2026-01-08T11:52:08.389Z
Learning: Ensure TypeScript emit outputs are configured to dedicated output directories (e.g., dist-tsc for regular builds and dist-tsc-prod for production builds) via tsconfig settings. Update all tsconfig files accordingly and add a clean script that removes dist, dist-tsc, and dist-tsc-prod to keep build artifacts clean.

Applied to files:

  • examples/prisma-next-demo/tsconfig.json
🧬 Code graph analysis (1)
packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts (2)
packages/1-framework/3-tooling/vite-plugin-contract-emit/src/exports/index.ts (2)
  • prismaVitePlugin (1-1)
  • PrismaVitePluginOptions (2-2)
packages/1-framework/3-tooling/vite-plugin-contract-emit/src/types.ts (1)
  • PrismaVitePluginOptions (4-18)
🔇 Additional comments (2)
examples/prisma-next-demo/src/prisma/contract.d.ts (2)

76-82: FK typing update is consistent with contract.json.


117-126: The relation join keys are correct. The generator is working as intended.

The foreign key relationship is properly defined: post.userId -> user.id. In the contract definition, parentCols: ['userId'] refers to the post table (the "N" side holding the FK), and childCols: ['id'] refers to the user table (the "1" side holding the PK). This matches the schema's foreign key declaration: .foreignKey(['userId'], { table: 'user', columns: ['id'] }). The inverse relation (user.posts, 1:N cardinality) correctly uses parentCols: ['id'] and childCols: ['userId'], confirming the definition is consistent and semantically accurate.

Likely an incorrect or invalid review comment.

Comment thread examples/prisma-next-demo/index.html Resolved
Comment thread examples/prisma-next-demo/src/entry.ts Resolved
Comment thread examples/prisma-next-demo/tsconfig.json Resolved
@wmadden
wmadden force-pushed the tml-1817-vite-plugin-auto-contract-emit-during-development branch from a67a7c3 to c3f9615 Compare January 14, 2026 11:41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@examples/prisma-next-demo/package.json`:
- Line 42: Update the pinned Vite dependency in package.json from "vite":
"6.3.5" to the latest stable release (v7.1.4) so the project uses the current
stable Vite; locate the "vite" entry in examples/prisma-next-demo/package.json
(near the `@prisma-next/vite-plugin-contract-emit` dependency) and replace the
version string accordingly, then run your package manager install and verify the
app builds and dev server runs with the new Vite version.

In `@examples/prisma-next-demo/src/entry.ts`:
- Around line 42-159: The HTML template in renderContract interpolates unescaped
values (e.g., fieldName, name, tableName, relName, colName, etc.) which is an
XSS risk; add a small escapeHtml(s: string) helper that replaces &, <, >, ", '
with entities and apply it to every interpolated external value inside
renderContract (use escapeHtml(...) for values coming from c.models,
model.fields, c.relations, c.storage.tables, table.columns, fk references,
c.capabilities and c.extensionPacks) so all `${...}` insertions use the escaped
string; keep the helper local to the module and call it wherever values are
rendered in the template strings within renderContract.
♻️ Duplicate comments (9)
packages/1-framework/3-tooling/vite-plugin-contract-emit/biome.jsonc (1)

3-3: Invalid extends value - already flagged in previous review.

The "//" value for the extends field is not a valid path to a Biome configuration file. This appears to be a placeholder or comment artifact that should be corrected to properly extend the root configuration (e.g., "../../../../biome.jsonc" based on the package's location in the monorepo).

examples/prisma-next-demo/src/prisma/contract.json (1)

137-149: Inverted relation metadata in post.user relation.

The on clause has inverted columns. For the N:1 relation from post to user via the foreign key post.userId → user.id:

  • childCols should be ["userId"] (FK column in child table post)
  • parentCols should be ["id"] (referenced column in parent table user)

Currently it's reversed. Compare with the inverse user.posts relation (lines 154-159) which correctly has parentCols: ["id"] and childCols: ["userId"].

Since this is a generated file, regenerate by running prisma-next contract emit after fixing the emitter logic.

examples/prisma-next-demo/src/prisma/contract.d.ts (1)

117-126: Same inverted relation metadata as contract.json.

The post.user relation has parentCols: ['userId'] and childCols: ['id'], which should be swapped. This is the type representation of the same issue in contract.json.

Since this is a generated file, it will be corrected when contract.json is regenerated with the fixed emitter logic.

packages/1-framework/3-tooling/vite-plugin-contract-emit/test/plugin.test.ts (1)

73-90: Tests lack meaningful assertions.

The configResolved tests call the hook but don't verify any observable behavior. The consoleSpy on line 76 is created but never used for assertions. Consider asserting that paths are correctly resolved by checking internal plugin state or verifying expected log output.

examples/prisma-next-demo/index.html (1)

96-96: Misleading UI copy.

The subtitle mentions "Edit contract.ts to see changes" but contract.json is the generated artifact from the contract emission process, not directly edited from a contract.ts file. Consider updating to clarify the actual workflow (e.g., "Edit your schema files and the contract will be re-emitted automatically").

packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts (1)

111-115: Sync filesystem calls will block the event loop when invoked from the Vite plugin.

mkdirSync and writeFileSync are synchronous and will stall HMR/reload when the Vite plugin calls executeContractEmit on file changes.

Proposed fix using async fs/promises
-import { mkdirSync, writeFileSync } from 'node:fs';
+import { mkdir, writeFile } from 'node:fs/promises';
 import { dirname, isAbsolute, resolve } from 'node:path';
 ...
-  mkdirSync(dirname(outputJsonPath), { recursive: true });
-  mkdirSync(dirname(outputDtsPath), { recursive: true });
-  writeFileSync(outputJsonPath, emitResult.contractJson, 'utf-8');
-  writeFileSync(outputDtsPath, emitResult.contractDts, 'utf-8');
+  await mkdir(dirname(outputJsonPath), { recursive: true });
+  await mkdir(dirname(outputDtsPath), { recursive: true });
+  await writeFile(outputJsonPath, emitResult.contractJson, 'utf-8');
+  await writeFile(outputDtsPath, emitResult.contractDts, 'utf-8');
packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts (1)

224-244: Missing server close cleanup: dangling timer and abort controller possible.

When the Vite dev server closes, debounceTimer may still be pending and currentAbortController may reference an in-flight operation. Add cleanup using the server's close hook.

Suggested fix
     async configureServer(viteServer) {
       server = viteServer;
+
+      // Cleanup on server close
+      viteServer.httpServer?.on('close', () => {
+        if (debounceTimer) {
+          clearTimeout(debounceTimer);
+          debounceTimer = null;
+        }
+        if (currentAbortController) {
+          currentAbortController.abort();
+          currentAbortController = null;
+        }
+        server = null;
+      });

       // Collect files to watch from the module graph
       watchedFiles = await collectWatchedFiles(viteServer);
examples/prisma-next-demo/src/entry.ts (2)

161-164: Avoid blind cast; prefer runtime validation or typed import.

as unknown as Contract bypasses TypeScript's type checking. If the JSON structure doesn't match, errors will occur at runtime with no compile-time warning.

Safer approach using validateContract
+import { validateContract } from '@prisma-next/sql-contract-ts/contract';
+import type { Contract } from './prisma/contract.d.ts';
 ...
 const app = document.getElementById('contract-view');
 if (app) {
-  app.innerHTML = renderContract(contract as unknown as Contract);
+  const validated = validateContract<Contract>(contract);
+  app.innerHTML = renderContract(validated);
 }

3-40: Consider importing types from the generated contract.d.ts instead of defining inline.

The contract emitter generates a contract.d.ts file alongside contract.json. Importing the generated types would ensure they stay in sync with the actual contract structure and avoid duplication.

Example
 import contract from './prisma/contract.json';
+import type { Contract } from './prisma/contract.d.ts';
-
-interface Column {
-  codecId: string;
-  ...
-}
-...
-interface Contract {
-  ...
-}

Comment thread examples/prisma-next-demo/package.json Resolved
Comment thread examples/prisma-next-demo/src/entry.ts Resolved
@wmadden wmadden changed the title TML-1817: Vite plugin Vite plugin Jan 15, 2026
@linear

linear Bot commented Jan 15, 2026

Copy link
Copy Markdown
TML-1817 Vite plugin: auto contract emit during development

Summary

Add a first-party Vite plugin (@prisma-next/vite-plugin-contract-emit) that automates the contract emit step during development.

Description

  • ControlClient.contractEmit: New control-api operation that loads config, emits contract, and writes artifacts
  • @prisma-next/vite-plugin-contract-emit: Vite plugin with:
    • Emit on server start
    • Watch mode with debounce (default 150ms)
    • Last-change-wins via AbortController
    • Error overlay + console logging
    • Configurable debounceMs and logLevel options
  • Demo integration: examples/prisma-next-demo now has pnpm dev that runs Vite with auto-emit
  • Contract viewer UI: Live-updating display of contract structure in browser

Usage

// vite.config.ts
import { prismaVitePlugin } from '@prisma-next/vite-plugin-contract-emit';
import { defineConfig } from 'vite';
export default defineConfig({
  plugins: [prismaVitePlugin('prisma-next.config.ts')],
});

@wmadden wmadden changed the title Vite plugin TML-1817: Vite plugin Jan 15, 2026
@wmadden
wmadden force-pushed the tml-1817-vite-plugin-auto-contract-emit-during-development branch from c3f9615 to 7ada4a4 Compare January 19, 2026 05:22

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts`:
- Around line 69-103: The code currently assumes contractConfig.source exists
and is a function or value, which can produce unclear errors later; add an
explicit validation for contractConfig.source (e.g., after resolving output
paths and before createControlPlaneStack or before the existing typeof check)
that it is defined and is either a function or a non-null value, and if not
throw a structured config error (use errorContractConfigMissing with a why
explaining "Contract config must include a valid source (function or value)").
Keep the existing logic that calls await contractConfig.source() when typeof
contractConfig.source === 'function' and otherwise assigns contractConfig.source
to contractRaw.

In `@packages/1-framework/3-tooling/vite-plugin-contract-emit/tsconfig.json`:
- Around line 8-9: Update the tsconfig.json exclude array so test fixtures
aren’t typechecked: in the JSON object containing the "include" and "exclude"
properties, add fixture paths (for example "test/fixtures/**",
"test/**/fixtures/**" and "fixtures/**") to the "exclude" array so fixture files
are ignored during type checking; keep the existing "dist" exclusion and ensure
the "exclude" value remains an array of strings.

In `@test/integration/test/vite-plugin.hmr.e2e.test.ts`:
- Around line 80-83: Consolidate the three separate assertions into a single
object matcher: instead of calling
expect(initialContract.storage.tables.user).toBeDefined() and
expect(initialContract.storage.tables.user.columns.email).toBeDefined(), replace
them with one expect(initialContract.storage).toMatchObject(...) that asserts
the expected nested shape (tables.user and user.columns.email) using appropriate
matchers (e.g., expect.anything() or expect.any(Type)) so the contract shape is
validated in one assertion; apply the same change to the similar block
referenced around lines 116-119. Use the variables initialContract and
contractJsonPath to locate the checks and update them to a single
toMatchObject-based assertion.
♻️ Duplicate comments (2)
packages/1-framework/3-tooling/vite-plugin-contract-emit/tsconfig.json (1)

2-2: Use package-based tsconfig extends.
Relative extends are brittle in the monorepo; switch to the shared base package.

♻️ Proposed fix
-  "extends": "../../../../tsconfig.base.json",
+  "extends": ["@prisma-next/tsconfig/base"],
Based on learnings, please update the extends path.
packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts (1)

135-165: Potential module-graph lookup mismatch when crawling dependencies.

collectWatchedFiles seeds traversal with absoluteConfigPath and imported.id strings. Vite module IDs can be normalized (e.g., /@fs/…, query params), so getModuleById may miss nodes and leave watchedFiles empty. Consider starting from getModulesByFile and walking ModuleNode references (or normalize to Vite IDs) to ensure reliable watching. Please verify against your Vite version.

🔧 Possible refactor (ModuleNode traversal)
-      await viteServer.ssrLoadModule(absoluteConfigPath);
-
-      // Crawl the module graph starting from the config file
-      const visited = new Set<string>();
-      const queue = [absoluteConfigPath];
-
-      while (queue.length > 0) {
-        const current = queue.shift();
-        if (current === undefined || visited.has(current)) continue;
-        visited.add(current);
-
-        const mod = viteServer.moduleGraph.getModuleById(current);
-        if (!mod) continue;
+      await viteServer.ssrLoadModule(absoluteConfigPath);
+
+      // Crawl the module graph starting from the config file
+      const rootModules = viteServer.moduleGraph.getModulesByFile(absoluteConfigPath);
+      const visited = new Set<import('vite').ModuleNode>();
+      const queue = rootModules ? [...rootModules] : [];
+
+      while (queue.length > 0) {
+        const mod = queue.shift();
+        if (!mod || visited.has(mod)) continue;
+        visited.add(mod);
 
         // Add file to watched set if it's a file path
         if (mod.file) {
           files.add(mod.file);
         }
 
         // Add imported modules to queue
         for (const imported of mod.importedModules) {
-          if (imported.id && !visited.has(imported.id)) {
-            queue.push(imported.id);
-          }
+          queue.push(imported);
         }
       }
Vite ssrLoadModule absolute path vs /@fs/ URL; what ID format does moduleGraph.getModulesByFile/getModuleById expect in Vite 5?

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@test/integration/test/vite-plugin.hmr.e2e.test.ts`:
- Around line 14-33: The waitForFileChange helper is vulnerable to filesystem
mtime granularity; update it to detect changes by comparing both mtime and file
size (or content) so rewrites that don't bump mtime still register as a change.
Inside waitForFileChange (and the other similar usages around the HMR tests),
read the file's initial stat (mtimeMs and size or a short content hash), then in
the poll loop fetch the current stat and treat the file as changed if
current.mtimeMs > originalMtime OR current.size !== originalSize (or content
differs); return true on either condition and keep the same timeout/poll
behavior. Ensure the same size-aware logic is applied to the other occurrences
referenced in the tests.
♻️ Duplicate comments (1)
test/integration/test/vite-plugin.hmr.e2e.test.ts (1)

80-83: Consolidate related contract assertions with toMatchObject (duplicate).

This is already noted in a prior review; please apply the object matcher consolidation to keep related assertions together. As per coding guidelines, prefer object matchers for related assertions.

Also applies to: 116-119

Comment on lines +14 to +33
async function waitForFileChange(
filePath: string,
originalMtime: number | null,
timeoutMs: number,
): Promise<boolean> {
const startTime = Date.now();
const pollIntervalMs = 50;

while (Date.now() - startTime < timeoutMs) {
if (existsSync(filePath)) {
const stats = await import('node:fs/promises').then((fs) => fs.stat(filePath));
const currentMtime = stats.mtimeMs;
if (originalMtime === null || currentMtime > originalMtime) {
return true;
}
}
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
}
return false;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n test/integration/test/vite-plugin.hmr.e2e.test.ts

Repository: prisma/prisma-next

Length of output: 5963


Guard against mtime granularity flakes in waitForFileChange.

Some filesystems only update mtime in 1s increments. With a 100ms delay, contract.json can be re-written without an mtime change, making the test fail even though HMR re-emit succeeded. Track size (or content) changes to make this robust.

🔧 Suggested fix (size-aware change detection)
-async function waitForFileChange(
-  filePath: string,
-  originalMtime: number | null,
-  timeoutMs: number,
-): Promise<boolean> {
+async function waitForFileChange(
+  filePath: string,
+  originalMtime: number | null,
+  originalSize: number | null,
+  timeoutMs: number,
+): Promise<boolean> {
   const startTime = Date.now();
   const pollIntervalMs = 50;

   while (Date.now() - startTime < timeoutMs) {
     if (existsSync(filePath)) {
       const stats = await import('node:fs/promises').then((fs) => fs.stat(filePath));
       const currentMtime = stats.mtimeMs;
-      if (originalMtime === null || currentMtime > originalMtime) {
+      if (
+        originalMtime === null ||
+        currentMtime > originalMtime ||
+        (originalSize !== null && stats.size !== originalSize)
+      ) {
         return true;
       }
     }
     await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
   }
   return false;
 }
@@
-const initialEmitSuccess = await waitForFileChange(contractJsonPath, null, 5000);
+const initialEmitSuccess = await waitForFileChange(contractJsonPath, null, null, 5000);
@@
-const initialMtime = initialStats.mtimeMs;
+const initialMtime = initialStats.mtimeMs;
+const initialSize = initialStats.size;
@@
-const reEmitSuccess = await waitForFileChange(contractJsonPath, initialMtime, 5000);
+const reEmitSuccess = await waitForFileChange(contractJsonPath, initialMtime, initialSize, 5000);

Also applies to: 93–94, 120

🤖 Prompt for AI Agents
In `@test/integration/test/vite-plugin.hmr.e2e.test.ts` around lines 14 - 33, The
waitForFileChange helper is vulnerable to filesystem mtime granularity; update
it to detect changes by comparing both mtime and file size (or content) so
rewrites that don't bump mtime still register as a change. Inside
waitForFileChange (and the other similar usages around the HMR tests), read the
file's initial stat (mtimeMs and size or a short content hash), then in the poll
loop fetch the current stat and treat the file as changed if current.mtimeMs >
originalMtime OR current.size !== originalSize (or content differs); return true
on either condition and keep the same timeout/poll behavior. Ensure the same
size-aware logic is applied to the other occurrences referenced in the tests.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts`:
- Around line 20-27: The native path (signal.throwIfAborted()) throws a
DOMException/AbortError while the fallback throws ContractEmitCancelledError,
causing inconsistent cancellation detection; update throwIfAborted to normalize
to ContractEmitCancelledError: when signal?.aborted is true, attempt to call
signal.throwIfAborted() inside a try/catch and if it throws (or if
throwIfAborted is absent) throw a new ContractEmitCancelledError so callers
always receive ContractEmitCancelledError; reference the throwIfAborted
function, the signal.throwIfAborted call, and ContractEmitCancelledError when
making the change.

In `@packages/1-framework/3-tooling/vite-plugin-contract-emit/tsconfig.json`:
- Around line 4-6: The tsconfig.json uses outDir "dist", which diverges from the
monorepo TS output convention; update the "outDir" property in this package's
tsconfig.json (alongside existing "rootDir" and "skipLibCheck") to the repo
standard ("dist-tsc" for normal builds or "dist-tsc-prod" for production builds)
and adjust any package scripts or cleanup tasks that reference "dist" to the new
directory to keep output/cleanup consistent.

In `@test/integration/test/vite-plugin.hmr.e2e.test.ts`:
- Around line 60-61: The test contains a redundant mkdirSync call creating
outputDir even though setupTestDirectoryFromFixtures already creates it; remove
the explicit mkdirSync(outputDir, { recursive: true }) from the test so the
directory creation is solely handled by setupTestDirectoryFromFixtures (refer to
setupTestDirectoryFromFixtures and the outputDir variable) to avoid duplicate
filesystem operations.
- Around line 91-97: The test captures only mtime for change detection; update
it to also capture file size by reading initialStats.size into a new variable
initialSize (alongside initialMtime) and then update calls to
waitForFileChange(contractJsonPath, ...) to pass the size: call
waitForFileChange(contractJsonPath, null, null, 5000) for the first wait and
waitForFileChange(contractJsonPath, initialMtime, initialSize, 5000) for the
later wait so waitForFileChange receives both initialMtime and initialSize for
robust detection.
♻️ Duplicate comments (2)
packages/1-framework/3-tooling/vite-plugin-contract-emit/tsconfig.json (1)

2-2: Use package-based tsconfig extends for monorepo consistency.
This was already flagged earlier; keeping the same recommendation. Based on learnings, use the package-based extension pattern.

♻️ Proposed fix
-  "extends": "../../../../tsconfig.base.json",
+  "extends": ["prisma-next/tsconfig/base"],
test/integration/test/vite-plugin.hmr.e2e.test.ts (1)

14-33: Mtime-only detection can cause flaky tests on certain filesystems.

Some filesystems (HFS+, FAT32, older ext3) only update mtime with 1-2 second granularity. The 100ms delay before re-write may not guarantee a different mtime, causing the test to timeout even though the file was re-emitted successfully.

Consider also tracking file size to detect changes when mtime doesn't update:

🔧 Suggested fix
 async function waitForFileChange(
   filePath: string,
   originalMtime: number | null,
+  originalSize: number | null,
   timeoutMs: number,
 ): Promise<boolean> {
   const startTime = Date.now();
   const pollIntervalMs = 50;
+  const { stat } = await import('node:fs/promises');

   while (Date.now() - startTime < timeoutMs) {
     if (existsSync(filePath)) {
-      const stats = await import('node:fs/promises').then((fs) => fs.stat(filePath));
+      const stats = await stat(filePath);
       const currentMtime = stats.mtimeMs;
-      if (originalMtime === null || currentMtime > originalMtime) {
+      if (
+        originalMtime === null ||
+        currentMtime > originalMtime ||
+        (originalSize !== null && stats.size !== originalSize)
+      ) {
         return true;
       }
     }
     await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
   }
   return false;
 }

This also hoists the dynamic import outside the loop for efficiency.

Comment on lines +4 to +6
"rootDir": ".",
"outDir": "dist",
"skipLibCheck": true

@coderabbitai coderabbitai Bot Jan 19, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Align TS emit output with monorepo standard (dist-tsc / dist-tsc-prod).
Using "dist" diverges from the repo’s TS output convention and can complicate cleanup/scripts. Consider switching to the dedicated TS output dir. Based on learnings, this should be aligned.

♻️ Proposed fix
   "compilerOptions": {
     "rootDir": ".",
-    "outDir": "dist",
+    "outDir": "dist-tsc",
     "skipLibCheck": true
   },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"rootDir": ".",
"outDir": "dist",
"skipLibCheck": true
"rootDir": ".",
"outDir": "dist-tsc",
"skipLibCheck": true
🤖 Prompt for AI Agents
In `@packages/1-framework/3-tooling/vite-plugin-contract-emit/tsconfig.json`
around lines 4 - 6, The tsconfig.json uses outDir "dist", which diverges from
the monorepo TS output convention; update the "outDir" property in this
package's tsconfig.json (alongside existing "rootDir" and "skipLibCheck") to the
repo standard ("dist-tsc" for normal builds or "dist-tsc-prod" for production
builds) and adjust any package scripts or cleanup tasks that reference "dist" to
the new directory to keep output/cleanup consistent.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see many packages with outDir: dist. Why do you say it's not conventional? @coderabbitai

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find all tsconfig.json files and extract their outDir settings
echo "=== Searching for outDir settings in tsconfig.json files ==="
fd -e json 'tsconfig.json' --exec sh -c '
  file="$1"
  outdir=$(jq -r ".compilerOptions.outDir // empty" "$file" 2>/dev/null)
  if [ -n "$outdir" ]; then
    echo "$file: $outdir"
  fi
' _ {} \; | head -50

echo ""
echo "=== Summary of outDir patterns ==="
fd -e json 'tsconfig.json' --exec sh -c '
  jq -r ".compilerOptions.outDir // empty" "$1" 2>/dev/null
' _ {} \; | sort | uniq -c | sort -rn

Length of output: 1774


@wmadden You're absolutely right, and I apologize for the incorrect suggestion.

Based on the search results across the monorepo, "dist" is indeed the standard convention:

  • 21 packages use "outDir": "dist"
  • 5 packages use "outDir": "./dist"
  • Only 2 packages use "./dist-ts"

Your current configuration with "outDir": "dist" is correct and follows the monorepo convention. My suggestion to change it to "dist-tsc" was mistaken. Thank you for pushing back on this!

🐰💭

   /)_/)
  (•_•)  "Oops, my mistake!
  />📊   Data shows you're right"

@igalklebanov igalklebanov Jan 19, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wmadden we're migrating over to a different setup. one that doesn't use tsc to generate dts. See workspace packages that use tsdown.
In that setup, tsconfigs point at non-dist folders to not interfere with tsdown's output, while still allowing you to tsc for research purposes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@igalklebanov addressed 👍

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts`:
- Line 3: Replace the direct import and use of errorContractConfigMissing with
the CLI structured error factory from utils/cli-errors.ts: remove import of
errorContractConfigMissing and instead import/create a CliStructuredError (or
the project's throw/create CLI error helper) and use it where
errorContractConfigMissing is currently thrown or returned (including the other
occurrences in this file around the current import and the two other spots
referenced). Ensure the new error includes the same message/context but is an
instance created by the CLI error factory (CliStructuredError) so CLI tooling
receives the structured error payload.
- Around line 94-102: The family instance is being created without the required
driver argument; update the call to config.family.create to pass the driver from
the control plane config (i.e., change config.family.create(stack) to
config.family.create(stack, config.driver)) so that
ControlFamilyDescriptor.create receives the driver consistently; locate the
invocation of createControlPlaneStack and the subsequent config.family.create
call to apply this change.
- Around line 106-116: After awaiting contractConfig.source (the resolved
contractRaw), check the operation cancellation before calling
familyInstance.emitContract to avoid wasted work if the signal was aborted;
specifically, inspect the AbortSignal (e.g., signal.aborted or throw if
signal.reason) that's in the surrounding scope and return/throw early when
aborted so the subsequent call to familyInstance.emitContract({ contractIR:
contractRaw }) is skipped.
- Around line 74-82: Normalize configPath with resolve() before deriving its
directory: call resolve(configPath) then dirname() to get configDir, and use
join(configDir, contractConfig.output) and join(configDir, contractConfig.types)
when contractConfig paths are relative. Update the logic that sets
outputJsonPath and outputDtsPath (which currently use isAbsolute(...) ? ... :
resolve(configDir, ...)) to instead use the normalized configDir and join(...)
per CLI guidelines, while keeping the isAbsolute checks for absolute inputs.
♻️ Duplicate comments (1)
test/integration/test/vite-plugin.hmr.e2e.test.ts (1)

10-33: Harden waitForFileChange against mtime granularity flakes.

Some filesystems only update mtime in 1s increments, so the 100ms delay can still miss a rewrite. Track size (or content) to avoid false negatives and update call sites accordingly.

🔧 Proposed fix (size-aware change detection)
-async function waitForFileChange(
-  filePath: string,
-  originalMtime: number | null,
-  timeoutMs: number,
-): Promise<boolean> {
+async function waitForFileChange(
+  filePath: string,
+  originalMtime: number | null,
+  originalSize: number | null,
+  timeoutMs: number,
+): Promise<boolean> {
   const startTime = Date.now();
   const pollIntervalMs = 50;

   while (Date.now() - startTime < timeoutMs) {
     if (existsSync(filePath)) {
       const stats = await import('node:fs/promises').then((fs) => fs.stat(filePath));
       const currentMtime = stats.mtimeMs;
-      if (originalMtime === null || currentMtime > originalMtime) {
+      if (
+        originalMtime === null ||
+        currentMtime > originalMtime ||
+        (originalSize !== null && stats.size !== originalSize)
+      ) {
         return true;
       }
     }
     await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
   }
   return false;
 }
@@
-const initialEmitSuccess = await waitForFileChange(contractJsonPath, null, 5000);
+const initialEmitSuccess = await waitForFileChange(contractJsonPath, null, null, 5000);
@@
 const initialStats = await stat(contractJsonPath);
 const initialMtime = initialStats.mtimeMs;
+const initialSize = initialStats.size;
@@
-const reEmitSuccess = await waitForFileChange(contractJsonPath, initialMtime, 5000);
+const reEmitSuccess = await waitForFileChange(contractJsonPath, initialMtime, initialSize, 5000);

Also applies to: 72-118

wmadden commented Jan 19, 2026 •

Copy link
Copy Markdown
Contributor Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpicky

good opportunity to start with tsdown. See lower-level workspace packages that were already migrated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good callout 👍

Comment thread examples/prisma-next-demo/src/entry.ts Resolved
Comment thread examples/prisma-next-demo/package.json Outdated
"tsup": "catalog:",
"tsx": "^4.19.2",
"typescript": "catalog:",
"vite": "7.3.1",

@igalklebanov igalklebanov Jan 19, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpicky

seeing that it's being used in the plugin's package as well, let's catalog it to keep it aligned.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed 👍

@@ -0,0 +1,138 @@
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, isAbsolute, join, resolve } from 'node:path';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we test on Windows?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We haven't yet. Isn't join() OS-independent?

@igalklebanov igalklebanov Jan 19, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

node:path detects OS and behaves differently. It expects/creates all paths to be suitable for that OS. This'll break when the code is written in one OS' path style, and ran in a machine with another OS. Most web tooling nowadays mostly expects POSIX.

Something like pathe solves this problem, as a drop-in replacement for node:path, it normalizes everything to POSIX to behave the same on all OS.

TLDR: no Windows users being annoying about paths not working.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done 👍

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts`:
- Around line 8-18: Remove the deprecated compatibility shim
ContractEmitCancelledError: delete the class definition
(ContractEmitCancelledError) and any re-exports of it so callers use AbortSignal
semantics (signal.aborted or error.name === 'AbortError') instead; ensure no
other modules import or expect ContractEmitCancelledError—update any local
references to use AbortError/AbortSignal checks and run tests to catch remaining
usages.
♻️ Duplicate comments (1)
packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts (1)

95-95: Pass driver into ControlFamilyDescriptor.create()

Control-plane guidelines require always passing the driver argument to family.create; omitting it can leave the instance inconsistently initialized. As per coding guidelines, pass config.driver here.

🔧 Proposed fix
-  const familyInstance = config.family.create(stack);
+  const familyInstance = config.family.create(stack, config.driver);

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@packages/1-framework/3-tooling/vite-plugin-contract-emit/package.json`:
- Around line 23-34: Check that the declared peerDependencies.vite range matches
the plugin's actual compatibility: inspect the package
"vite-plugin-contract-emit" source for Vite API usage (entry points that export
a plugin, e.g., the plugin factory function or hooks) against Vite 5/6/7
changelogs; if it relies on Vite 7-only APIs tighten peerDependencies.vite to
the exact supported majors (e.g., ">=7 <8" or ">=6 <8") or list multiple
supported majors explicitly, or relax it only if you confirm backward
compatibility; update the peerDependencies.vite range in package.json
accordingly and ensure devDependencies.vite remains aligned for local testing.
- Around line 38-44: The package.json currently uses a flat "exports" mapping
pointing "." to "./dist/index.mjs", which can cause TypeScript/NodeNext to
ignore the top-level "types" entry; update the "exports" entry to a conditional
exports object that explicitly associates runtime entry points with their
corresponding types (e.g., under "." use condition branches like "import" and/or
"require" and include the path to "./dist/index.d.mts" for the TypeScript
resolution) so that the "types" resolution is aligned with the runtime entry;
adjust or remove the separate top-level "main"/"module"/"types" fields as needed
to avoid duplication and verify compatibility against your tsconfig/Node
resolution settings.

In
`@packages/1-framework/3-tooling/vite-plugin-contract-emit/test/plugin.test.ts`:
- Around line 71-88: The tests call plugin.configResolved but make no
assertions; update both tests to assert the resolved config path is computed and
used: for prismaVitePlugin('prisma-next.config.ts', ...) call configResolved({
root: '/project' }) then verify the plugin stored or used the resolved path
(e.g., check a public/debug property like plugin.resolvedConfigPath or spy on
executeContractEmit to assert it was called with
'/project/prisma-next.config.ts'); do the same for the absolute path case to
assert '/absolute/prisma-next.config.ts' is preserved. Reference
plugin.configResolved and executeContractEmit (or the plugin's resolved path
property) to locate where to add the assertions or spy.
♻️ Duplicate comments (2)
packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts (1)

76-84: Pass the driver into ControlFamilyDescriptor.create().

Line 83 omits the required driver parameter, which can yield a partially initialized family instance.

🐛 Proposed fix
-  const familyInstance = config.family.create(stack);
+  const familyInstance = config.family.create(stack, config.driver);
As per coding guidelines, always pass the driver into `ControlFamilyDescriptor.create()`.
packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts (1)

141-179: Module graph traversal could miss dependencies due to ID normalization differences.

The BFS uses string IDs (imported.id) as queue entries and looks them up via getModuleById(current). In Vite, id can include query parameters or be normalized differently than the file path, causing getModuleById to return null for valid modules.

The fallback at lines 172-176 mitigates this by catching errors and ensuring the config file is always watched, but transitive dependencies could be missed in edge cases.

♻️ Consider traversing ModuleNode references directly
   async function collectWatchedFiles(viteServer: ViteDevServer): Promise<Set<string>> {
     const files = new Set<string>();

     try {
       // Load the config module through Vite's SSR loader to populate the module graph
       await viteServer.ssrLoadModule(absoluteConfigPath);

       // Crawl the module graph starting from the config file
-      const visited = new Set<string>();
-      const queue = [absoluteConfigPath];
+      const visited = new Set<import('vite').ModuleNode>();
+      const rootMod = viteServer.moduleGraph.getModuleById(absoluteConfigPath);
+      const queue = rootMod ? [rootMod] : [];

       while (queue.length > 0) {
-        const current = queue.shift();
-        if (current === undefined || visited.has(current)) continue;
-        visited.add(current);
-
-        const mod = viteServer.moduleGraph.getModuleById(current);
-        if (!mod) continue;
+        const mod = queue.shift()!;
+        if (visited.has(mod)) continue;
+        visited.add(mod);

         // Add file to watched set if it's a file path
         if (mod.file) {
           files.add(mod.file);
         }

         // Add imported modules to queue
         for (const imported of mod.importedModules) {
-          if (imported.id && !visited.has(imported.id)) {
-            queue.push(imported.id);
-          }
+          if (!visited.has(imported)) {
+            queue.push(imported);
+          }
         }
       }
     } catch (error) {

Comment on lines +23 to +34
"devDependencies": {
"@prisma-next/tsconfig": "workspace:*",
"@prisma-next/tsdown": "workspace:*",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "catalog:"
},
"peerDependencies": {
"vite": ">=5.0.0"
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Verify the Vite peer range matches actual compatibility.

Dev uses the catalog-pinned Vite, but the peer allows >=5.0.0. If the plugin uses Vite 7–specific APIs, consider tightening the peer range (or explicitly listing supported majors) to avoid mismatched installs.

🤖 Prompt for AI Agents
In `@packages/1-framework/3-tooling/vite-plugin-contract-emit/package.json` around
lines 23 - 34, Check that the declared peerDependencies.vite range matches the
plugin's actual compatibility: inspect the package "vite-plugin-contract-emit"
source for Vite API usage (entry points that export a plugin, e.g., the plugin
factory function or hooks) against Vite 5/6/7 changelogs; if it relies on Vite
7-only APIs tighten peerDependencies.vite to the exact supported majors (e.g.,
">=7 <8" or ">=6 <8") or list multiple supported majors explicitly, or relax it
only if you confirm backward compatibility; update the peerDependencies.vite
range in package.json accordingly and ensure devDependencies.vite remains
aligned for local testing.

signal.addEventListener(
'abort',
() => {
reject(signal.reason ?? new Error('Operation cancelled'));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpicky

the fallback could be abort spec compliant - DOMException with the right message and name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure it's worth throwing a DOMException outside the DOM just to say we're spec compliant?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done 👍🏻

* @returns A function that wraps promises to be cancelable
* @throws If signal is already aborted
*/
export function cancelable(signal: AbortSignal): <T>(promise: Promise<T>) => Promise<T> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpicky af

Suggested change
export function cancelable(signal: AbortSignal): <T>(promise: Promise<T>) => Promise<T> {
export function abortable(signal: AbortSignal): <T>(promise: Promise<T>) => Promise<T> {

wmadden and others added 10 commits January 20, 2026 07:28
The cancelable() wrapper already rejects on abort, so explicit
signal.throwIfAborted() calls between await points are unnecessary.
Replace node:path with pathe in contract-emit.ts for consistent
behavior across Windows/macOS/Linux and non-Node runtimes.

Document this as a codebase convention in .cursor/rules and
docs/onboarding/Conventions.md.
Better aligns with the AbortSignal/AbortController naming convention.
Types file (.d.ts) is now always colocated with JSON output.
For example, contract.json produces contract.d.ts in the same directory.

This simplifies configuration - users only need to specify output path.
Verify that relative paths are resolved against vite root and
absolute paths are preserved when passed to executeContractEmit.
@wmadden
wmadden force-pushed the tml-1817-vite-plugin-auto-contract-emit-during-development branch from a6d4742 to 7d971b6 Compare January 20, 2026 00:28

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/1-framework/3-tooling/cli/src/commands/contract-emit.ts (1)

84-90: Update error guidance to remove types.
The help text still references types, which is no longer part of the contract config shape.

Proposed fix
-      errorContractConfigMissing({
-        why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ..., types: ... }',
-      }),
+      errorContractConfigMissing({
+        why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }',
+      }),
🤖 Fix all issues with AI agents
In @.cursor/rules/use-pathe-for-paths.mdc:
- Around line 3-6: Update the "globs" patterns to also match TSX files: modify
the include pattern "packages/**/*.ts" to also capture ".tsx" (e.g.,
"packages/**/*.{ts,tsx}") and add a corresponding exclude for test TSX files
(e.g., "!packages/**/*.test.{ts,tsx}") so UI packages using .tsx are covered
while test files remain excluded.

In `@packages/1-framework/1-core/shared/utils/test/abortable.test.ts`:
- Around line 65-76: Replace the three related assertions in the test that call
expect(result1).toBe(1), expect(result2).toBe(2), expect(result3).toBe(3) with a
single object/array matcher assertion; after calling
abortable(controller.signal) and resolving the three promises into result1/2/3
(or collect them into an array), assert the combined structure with a matcher
such as toMatchObject or toEqual on the object/array of results so the three
related values are validated in one assertion (refer to abortable and
unlessAborted to locate the test and result1/result2/result3 variables).

In `@packages/1-framework/3-tooling/cli/src/commands/contract-emit.ts`:
- Around line 104-107: The current derivation of outputDtsPath blindly does
outputJsonPath.replace(/\.json$/, '.d.ts') which will return the same path when
the provided output lacks a .json suffix and cause the .d.ts to overwrite the
JSON; update the logic around resolve(contractConfig.output) so that after
computing outputJsonPath you check if outputJsonPath.endsWith('.json') and only
perform the replace in that case, otherwise derive outputDtsPath by appending
'.d.ts' (e.g., outputJsonPath + '.d.ts'); modify the variables outputJsonPath
and outputDtsPath in this block to use this conditional derivation to avoid
accidental overwrites.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts`:
- Around line 60-65: The validation currently treats typeof
contractConfig.source === 'object' as valid which allows null; update the check
used before calling emitContract so null is rejected explicitly. In the
contract-emit validation block (referencing contractConfig.source and
errorContractConfigMissing and the downstream emitContract call) change the
condition to require that contractConfig.source is not null when it is an object
(e.g., check contractConfig.source !== null) and throw
errorContractConfigMissing with the same message if it is null or of an invalid
type, so emitContract never receives a null source.
- Around line 51-58: The code assumes contractConfig.output ends with ".json"
which can cause outputDtsPath to equal outputJsonPath; validate that
contractConfig.output endsWith('.json') and throw a clear error if not, then
derive the .d.ts path using path.parse() (or parse()/format()) instead of a
regex: compute normalizedConfigPath, configDir and outputJsonPath as before,
confirm contractConfig.output has .json, then create outputDtsPath by replacing
the parsed ext with ".d.ts" (using path.parse/format) to guarantee distinct
filenames.

In `@pnpm-workspace.yaml`:
- Line 24: The catalog entry currently pins Vite to a non-existent version
"vite: 7.3.1"; update the version string to the published release "vite: 7.3.0"
by changing the version value for the "vite" entry in pnpm-workspace.yaml (the
line containing the symbol vite: 7.3.1) so the workspace uses the correct
published Vite release.
♻️ Duplicate comments (6)
packages/1-framework/3-tooling/vite-plugin-contract-emit/package.json (1)

32-34: Vite peer dependency range already flagged for verification.

The broad >=5.0.0 peer range was previously flagged to verify compatibility with the actual Vite APIs used by this plugin.

packages/1-framework/3-tooling/vite-plugin-contract-emit/tsconfig.json (1)

6-7: Exclude fixture dirs from typechecking.

Line 7 should exclude fixture paths to avoid false positives from internal-only types. As per coding guidelines, add fixture globs to exclude.

♻️ Proposed fix
-  "exclude": ["dist", "dist-tsc", "dist-tsc-prod", "node_modules"]
+  "exclude": [
+    "dist",
+    "dist-tsc",
+    "dist-tsc-prod",
+    "node_modules",
+    "fixtures/**",
+    "test/**/fixtures/**"
+  ]
packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts (1)

67-70: Pass the driver into ControlFamilyDescriptor.create().

Line 69 omits the required driver parameter, which can leave the family instance partially initialized.

🔧 Proposed fix
-  const familyInstance = config.family.create(stack);
+  const familyInstance = config.family.create(stack, config.driver);
As per coding guidelines, always pass the driver parameter.
test/integration/test/vite-plugin.hmr.e2e.test.ts (1)

14-33: Guard against mtime granularity flakes by also tracking file size.

Some filesystems only update mtime in 1-second increments. With a 100ms delay, contract.json can be rewritten without an mtime change, causing test flakiness. Track size changes as a fallback.

🔧 Suggested fix
 async function waitForFileChange(
   filePath: string,
   originalMtime: number | null,
+  originalSize: number | null,
   timeoutMs: number,
 ): Promise<boolean> {
   const startTime = Date.now();
   const pollIntervalMs = 50;

   while (Date.now() - startTime < timeoutMs) {
     if (existsSync(filePath)) {
       const stats = await import('node:fs/promises').then((fs) => fs.stat(filePath));
       const currentMtime = stats.mtimeMs;
-      if (originalMtime === null || currentMtime > originalMtime) {
+      if (
+        originalMtime === null ||
+        currentMtime > originalMtime ||
+        (originalSize !== null && stats.size !== originalSize)
+      ) {
         return true;
       }
     }
     await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
   }
   return false;
 }

Update call sites accordingly:

  • Line 73: waitForFileChange(contractJsonPath, null, null, 5000)
  • Line 117: waitForFileChange(contractJsonPath, initialMtime, initialStats.size, 5000)
packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts (2)

148-171: Module graph traversal uses string IDs which may miss normalized paths.

Vite's module IDs can include /@fs/ prefixes, query params, or other normalizations that differ from the raw absolute path. The current approach of queuing imported.id and looking up via getModuleById may miss some modules.

Consider traversing ModuleNode references directly to avoid ID format mismatches:

♻️ Suggested refactor
-      const visited = new Set<string>();
-      const queue = [absoluteConfigPath];
+      const visited = new Set<import('vite').ModuleNode>();
+      const rootMod = viteServer.moduleGraph.getModuleById(absoluteConfigPath);
+      const queue: import('vite').ModuleNode[] = rootMod ? [rootMod] : [];

       while (queue.length > 0) {
-        const current = queue.shift();
-        if (current === undefined || visited.has(current)) continue;
-        visited.add(current);
-
-        const mod = viteServer.moduleGraph.getModuleById(current);
-        if (!mod) continue;
+        const mod = queue.shift()!;
+        if (visited.has(mod)) continue;
+        visited.add(mod);

         // Add file to watched set if it's a file path
         if (mod.file) {
           files.add(mod.file);
         }

         // Add imported modules to queue
         for (const imported of mod.importedModules) {
-          if (imported.id && !visited.has(imported.id)) {
-            queue.push(imported.id);
-          }
+          if (!visited.has(imported)) {
+            queue.push(imported);
+          }
         }
       }

92-96: Potential race: emitRequestId may change during async updateWatchedFiles.

Between await updateWatchedFiles(server) and server.ws.send({ type: 'full-reload' }), another emit could start and increment emitRequestId. This would send a full-reload for a superseded request.

🔧 Suggested fix
       // Update watched files to include any new transitive dependencies
       if (server) {
+        const currentRequestId = requestId;
         await updateWatchedFiles(server);
-        server.ws.send({ type: 'full-reload' });
+        // Only send reload if this is still the latest request
+        if (currentRequestId === emitRequestId) {
+          server.ws.send({ type: 'full-reload' });
+        }
       }

Comment thread .cursor/rules/use-pathe-for-paths.mdc Resolved
Comment on lines +51 to +58
// Normalize configPath and resolve artifact paths relative to config file directory
const normalizedConfigPath = resolve(configPath);
const configDir = dirname(normalizedConfigPath);
const outputJsonPath = isAbsolute(contractConfig.output)
? contractConfig.output
: join(configDir, contractConfig.output);
// Colocate .d.ts with .json (e.g., contract.json → contract.d.ts)
const outputDtsPath = outputJsonPath.replace(/\.json$/, '.d.ts');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts | head -80

Repository: prisma/prisma-next

Length of output: 3960


🏁 Script executed:

# Check the file size first
wc -l packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts

Repository: prisma/prisma-next

Length of output: 143


🏁 Script executed:

# Find the contractConfig source and its schema/validation
rg "contractConfig" packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts -A 3 -B 3

Repository: prisma/prisma-next

Length of output: 1440


🏁 Script executed:

# Search for where outputJsonPath and outputDtsPath are used
rg "outputJsonPath|outputDtsPath" packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts -A 2 -B 2

Repository: prisma/prisma-next

Length of output: 958


🏁 Script executed:

# Check for contractConfig validation/schema
fd "contract-emit" packages/1-framework/3-tooling/cli/src -type f | head -20

Repository: prisma/prisma-next

Length of output: 232


🏁 Script executed:

# Look for config validation patterns
rg "contractConfig" packages/1-framework/3-tooling/cli/src -l | head -5

Repository: prisma/prisma-next

Length of output: 326


🏁 Script executed:

# Check the config loader and types to see if contractConfig.output is validated
cat -n packages/1-framework/3-tooling/cli/src/config-loader.ts | head -100

Repository: prisma/prisma-next

Length of output: 3681


🏁 Script executed:

# Look for contract config types and validation
rg "contractConfig|contract:" packages/1-framework/3-tooling/cli/src -l | grep -E "(types|config)" | head -10

Repository: prisma/prisma-next

Length of output: 121


🏁 Script executed:

# Check if there's validation for .json extension in config schema
rg "\.json|output.*json" packages/1-framework/3-tooling/cli/src -B 3 -A 3 | head -50

Repository: prisma/prisma-next

Length of output: 4210


🏁 Script executed:

# Check the config validation in core-control-plane
rg "validateConfig|contract.*output" packages/1-framework/1-core/0-control-plane/src -B 3 -A 3 | head -80

Repository: prisma/prisma-next

Length of output: 149


🏁 Script executed:

# Look for the types definition for contract config
rg "type.*ContractConfig|interface.*ContractConfig" packages -B 2 -A 10 | head -100

Repository: prisma/prisma-next

Length of output: 4113


🏁 Script executed:

# Check config-types in core-control-plane
cat packages/1-framework/1-core/0-control-plane/src/config-types.ts | head -150

Repository: prisma/prisma-next

Length of output: 157


🏁 Script executed:

# Check what other validation errors are available in cli-errors
cat packages/1-framework/3-tooling/cli/src/utils/cli-errors.ts | head -150

Repository: prisma/prisma-next

Length of output: 924


🏁 Script executed:

# Look at the full file to see all error factories
cat packages/1-framework/3-tooling/cli/src/utils/cli-errors.ts

Repository: prisma/prisma-next

Length of output: 924


Validate contract output must end with .json to prevent file collision.

The code assumes contractConfig.output ends with .json when deriving the .d.ts path via regex. If the output path lacks a .json extension, the regex fails to match and outputDtsPath equals outputJsonPath. Both files are then written to the same path, causing the DTS write to overwrite the JSON file. Validate the extension and derive the DTS path using parse().

Suggested fix
-import { dirname, isAbsolute, join, resolve } from 'pathe';
+import { dirname, isAbsolute, join, parse, resolve } from 'pathe';
@@
   const outputJsonPath = isAbsolute(contractConfig.output)
     ? contractConfig.output
     : join(configDir, contractConfig.output);
-  // Colocate .d.ts with .json (e.g., contract.json → contract.d.ts)
-  const outputDtsPath = outputJsonPath.replace(/\.json$/, '.d.ts');
+  const { dir: outputDir, name: outputName, ext } = parse(outputJsonPath);
+  if (ext !== '.json') {
+    throw errorContractConfigMissing({
+      why: 'Contract output must end with .json to colocate the .d.ts file.',
+    });
+  }
+  const outputDtsPath = join(outputDir, `${outputName}.d.ts`);
🤖 Prompt for AI Agents
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts`
around lines 51 - 58, The code assumes contractConfig.output ends with ".json"
which can cause outputDtsPath to equal outputJsonPath; validate that
contractConfig.output endsWith('.json') and throw a clear error if not, then
derive the .d.ts path using path.parse() (or parse()/format()) instead of a
regex: compute normalizedConfigPath, configDir and outputJsonPath as before,
confirm contractConfig.output has .json, then create outputDtsPath by replacing
the parsed ext with ".d.ts" (using path.parse/format) to guarantee distinct
filenames.

Comment thread pnpm-workspace.yaml Resolved
- Require output path to end with .json to prevent .d.ts overwrite
- Explicitly reject null as contract source (typeof null === 'object')
- Use slice instead of regex for reliable .d.ts derivation
- Update pathe rule globs to include TSX files
Update integration tests to derive dts path from json output path,
matching the removal of the contract.types config option.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/1-framework/3-tooling/cli/src/commands/contract-emit.ts (1)

150-156: Missing explicit validation for null/undefined contract source.

The commit message mentions "Explicitly reject null as contract source (typeof null === 'object')", but this validation appears to be missing. Since typeof null === 'object', a null source would pass to the value branch and likely fail downstream with an unclear error.

Proposed fix
     // Convert user config source to discriminated union
     // Type assertion is safe: we check typeof to determine if it's a function
+    if (contractConfig.source === null || contractConfig.source === undefined) {
+      return notOk(
+        errorContractConfigMissing({
+          why: 'Contract config must have a source. Define it in your config: contract: { source: ..., output: ... }',
+        }),
+      );
+    }
     const source: EmitContractSource =
       typeof contractConfig.source === 'function'
         ? { kind: 'loader', load: contractConfig.source as () => unknown | Promise<unknown> }
         : { kind: 'value', value: contractConfig.source };
♻️ Duplicate comments (1)
packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts (1)

75-77: Pass driver to ControlFamilyDescriptor.create().

Per coding guidelines: "Always pass driver parameter to ControlFamilyDescriptor.create(), even for commands that don't use it (e.g., contract emit)".

🔧 Proposed fix
   const stack = createControlPlaneStack(config);
-  const familyInstance = config.family.create(stack);
+  const familyInstance = config.family.create(stack, config.driver);

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @.cursor/rules/use-pathe-for-paths.mdc:
- Around line 1-4: The frontmatter in use-pathe-for-paths.mdc is missing the
required globs field, so add a globs entry to the YAML frontmatter (key name:
globs) matching the pattern(s) used by other rulecards that determine when this
rule runs (e.g., file path glob(s) relevant to path imports). Update the
existing frontmatter block at the top of .cursor/rules/use-pathe-for-paths.mdc
to include globs as an array of one or more glob patterns so the rule has a
defined scope.

Comment thread .cursor/rules/use-pathe-for-paths.mdc Resolved
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants