defineContract() lacks a type-preserving isolatedDeclarations annotation, and a 2-table client triggers 344k+ type instantiations

Open
#31,352 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
deno, postgresql, typescript

Research direction

Start with the defineContract declarations in @prisma/orm-postgres/contract-builder and the emitted Contract client types; reproduce the diagnostics with TypeScript 5.9.3 using the supplied 2-model fixture and --isolatedDeclarations. Compare declaration output and type-instantiation diagnostics for the contract and client-only cases. Done means exact schema types can be exported portably and the reported baseline type-check cost is materially reduced.

Written by the indexing model from the issue text.

Description

Package and version
What happened?

Two distinct type-system issues affect even a minimal 2-model schema (User, Post) with zero chained .include() calls:

1. defineContract() cannot be exported with its exact inferred type under isolatedDeclarations: true (plus Deno TS2883 portability errors on hashed internals)

When exporting a TypeScript-authored contract (export const contract = defineContract(...)) under isolatedDeclarations: true:

  • tsc 5.9.3 explicit-annotation requirement (TS9010):
repro-isolated-decl.ts(9,14): error TS9010: Variable must have an explicit type annotation with --isolatedDeclarations.

In @prisma/orm-postgres/dist/contract-builder.d.mts:152-164, 202-207, 730, defineContract returns PostgresResult<...>, which is an internal unexported type alias (omitted from the export { ... } list on line 730). Annotating export const contract: Contract = defineContract(...) with the broad Contract type from @prisma/orm-postgres/contract-builder compiles under both tsc --isolatedDeclarations and deno check, but widens the exported contract type to generic Contract, discarding the model/column/relation schema types for downstream callers (PostgresClient<typeof contract>). There is no public type alias or annotation helper that preserves the exact inferred contract type.

  • Deno 2.9.8 (tsc / TypeScript 6.0.3 portability + isolatedDeclarations diagnostics — 15 errors total):
    Independently of TypeScript's explicit-annotation error (TS9010 + TS9027), Deno emits 14 TS2883 portability diagnostics referencing internal unexported hashed .d.mts chunk paths across @prisma/orm-framework, @prisma/orm-family-sql, @prisma/orm-target-postgres, and temporal-spec:
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'ColumnDefault' from 'file://<workdir>/node_modules/@prisma/orm-framework/dist/types-Cg3NoNFB-BkFyEy2j.d.mts'. This is likely not portable. A type annotation is necessary.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'Contract' from 'file://<workdir>/node_modules/@prisma/orm-framework/dist/contract-types-CiKWIMfr-By-toUdn.d.mts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'ContractExecutionSection' from 'file://<workdir>/node_modules/@prisma/orm-framework/dist/contract-types-CiKWIMfr-By-toUdn.d.mts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'ExtensionPackRef' from 'file://<workdir>/node_modules/@prisma/orm-framework/dist/framework-components-DKJQ4alZ-gzEpA3X5.d.mts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'ForeignKeyIndex' from 'file://<workdir>/node_modules/@prisma/orm-family-sql/dist/foreign-key-qkDFfG8t-TaK_GYWR.d.mts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'Instant' from 'file://<workdir>/node_modules/temporal-spec/index.d.ts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'JsonValue' from 'file://<workdir>/node_modules/@prisma/orm-framework/dist/types-Cg3NoNFB-BkFyEy2j.d.mts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'NamespaceId' from 'file://<workdir>/node_modules/@prisma/orm-framework/dist/domain-envelope-CU8IJvDH-CpPtMFaD.d.mts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'PgInterval' from 'file://<workdir>/node_modules/@prisma/orm-target-postgres/dist/codecs-BttOxm7v-Bg7ybHIE.d.mts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'PlainDate' from 'file://<workdir>/node_modules/temporal-spec/index.d.ts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'PlainDateTime' from 'file://<workdir>/node_modules/temporal-spec/index.d.ts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'PlainTime' from 'file://<workdir>/node_modules/temporal-spec/index.d.ts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'ReferentialAction' from 'file://<workdir>/node_modules/@prisma/orm-family-sql/dist/foreign-key-qkDFfG8t-TaK_GYWR.d.mts'.
TS2883 [ERROR]: The inferred type of 'contract' cannot be named without a reference to 'StorageHashBase' from 'file://<workdir>/node_modules/@prisma/orm-framework/dist/types-Cg3NoNFB-BkFyEy2j.d.mts'.
TS9010 [ERROR]: Variable must have an explicit type annotation with --isolatedDeclarations.
TS9027 [ERROR]:     Add a type annotation to the variable contract.

Found 15 errors.
  • Even with an emitted contract.d.ts (prisma contract emit): Exporting an unannotated query wrapper function (export function getPlainPost(db: PostgresClient<Contract>, id: number) { return db.orm.public.Post.where({ id }).first(); }) fails tsc --isolatedDeclarations with TS9007, and deno check additionally reports TS2883 pointing at the unexported chunk path node_modules/@prisma/orm-target-postgres/dist/codec-types-B-OBDw_P-CBflZnmD.d.mts (Varchar), even though Varchar is exported publicly by @prisma/orm-postgres/contract-types.
2. High baseline type-check size and instantiation cost on a 2-table schema (even with 0 queries / 0 .include() calls)

Measured with tsc 5.9.3 --strict --noEmit --target es2022 --module nodenext --moduleResolution nodenext --diagnostics (note: Files, Lines, Identifiers, Types, and Instantiations are deterministic per compiler version; Memory used and Total time below are from one observed run captured in the retained log):

File / Scenario --skipLibCheck Files Lines Types Instantiations Memory (observed run) Total time (observed run)
defineContract only (repro-isolated-decl.ts) Yes 470 142,980 29,768 93,285 198,011K 1.26s
defineContract only (repro-isolated-decl.ts) No 470 142,980 193,578 470,042 445,701K 3.34s
Emitted Contract + postgres() client only (0 queries) Yes 473 140,763 43,152 344,142 199,843K 1.41s
Emitted Contract + 1 plain where({ id }).first() (0 .include()) Yes 473 140,771 48,594 360,638 212,715K 1.46s
Emitted Contract + 1 .include('author').first() (repro-emitted-usage.ts) Yes 473 140,773 48,908 362,945 215,241K 1.64s
Emitted Contract + 1 .include('author').first() (repro-emitted-usage.ts) No 473 140,773 222,366 800,830 506,058K 4.20s

Single-line-edit incremental deno check latency on Deno 2.9.8 (1 warmup pass followed by 10 sequential trials appending // trial i to a copy of the target file):

Target (standalone 2-table fixture, 8.0.0-rc.28) Mean (ms) Conventional median (ms) Nearest-rank p50 (ms) Nearest-rank p95 (ms) Min / Max (ms)
defineContract (repro-isolated-decl.ts, isolatedDeclarations: false) 1,310.72 1,251.35 1,241.0 1,611.3 1,216.2 / 1,611.3
Emitted Contract + client only (0 queries, isolatedDeclarations: true) 1,557.64 1,547.35 1,531.9 1,938.3 1,378.3 / 1,938.3
Emitted Contract + plain where({ id }).first() (0 .include()) 1,691.28 1,682.45 1,673.1 1,796.5 1,607.1 / 1,796.5
Emitted Contract + .include('author').first() (repro-emitted-usage.ts) 1,599.30 1,585.25 1,577.7 1,699.6 1,553.0 / 1,699.6

Raw trials for repro-emitted-usage.ts (ms): [1699.6, 1608.7, 1633.1, 1563.6, 1573.0, 1568.7, 1553.0, 1577.7, 1592.8, 1622.8] (sorted[4] = 1577.7 nearest-rank p50; sorted[9] = 1699.6 nearest-rank p95; (1577.7 + 1592.8)/2 = 1585.25 conventional median).

Just importing @prisma/orm-postgres/runtime and typing PostgresClient<Contract> on a 2-table schema with zero queries already pulls 473 files (140,763 lines) and 344,142 type instantiations under --skipLibCheck.

What did you expect to happen?
  • export const contract = defineContract(...) (or an exported type helper / type alias) should let TypeScript users annotate or export contracts with their exact inferred schema type under isolatedDeclarations: true, without leaking unexported internal .d.mts chunk paths from @prisma/orm-framework, @prisma/orm-family-sql, @prisma/orm-target-postgres, or temporal-spec.
  • Referencing PostgresClient<Contract> and db.orm.<ns>.<Model> on a minimal 2-table emitted contract should not pull ~473 files / ~141k lines and instantiate ~344k types (--skipLibCheck) on every type-check.
Minimal reproduction

Shared package.json:

{
  "name": "prisma8-upstream-repro",
  "private": true,
  "type": "module",
  "dependencies": {
    "@prisma/orm-postgres": "8.0.0-rc.28",
    "@prisma/orm-toolchain": "8.0.0-rc.28",
    "pg": "^8.22.0",
    "prisma": "8.0.0-rc.39",
    "temporal-polyfill": "^1.0.8"
  },
  "devDependencies": {
    "@types/pg": "^8.20.0",
    "typescript": "^5.9.3"
  }
}
A. repro-isolated-decl.ts (self-contained, 41 lines)
import {
  autoincrement,
  defineContract,
  now,
  postgres18,
  postgresDriver,
} from '@prisma/orm-postgres/contract-builder';

export const contract = defineContract(
  { requiredCapabilities: [...postgres18, ...postgresDriver] },
  ({ field, model, rel, type }) => {
    const User = model('User', {
      fields: {
        id: field.column(type.Int()).id().default(autoincrement()),
        username: field.column(type.String({ storage: 'varchar', length: 255 })),
      },
    }).sql({ table: 'users' });

    const Post = model('Post', {
      fields: {
        id: field.column(type.Int()).id().default(autoincrement()),
        title: field.column(type.String({ storage: 'varchar', length: 255 })),
        authorId: field.column(type.Int()).column('author_id'),
        createdAt: field.column(type.DateTime()).column('created_at').default(now()),
      },
      relations: {
        author: rel.belongsTo(User, { from: 'authorId', to: 'id' }),
      },
    }).sql(({ cols, constraints }) => ({
      table: 'posts',
      indexes: [constraints.index([cols.authorId], { name: 'posts_author_id_idx' })],
    }));

    return {
      models: {
        User: User.relations({ posts: rel.hasMany(Post, { by: 'authorId' }) }),
        Post,
      },
    };
  },
);

deno.json:

{
  "nodeModulesDir": "manual",
  "compilerOptions": {
    "strict": true,
    "isolatedDeclarations": true,
    "lib": ["deno.ns", "dom"]
  }
}

Commands:

npm install

# TypeScript 5.9.3 (fails TS9010):
npx tsc --strict --isolatedDeclarations --declaration --emitDeclarationOnly \
  --outDir /tmp/tsc-iso-out --noEmit false --target es2022 \
  --module nodenext --moduleResolution nodenext repro-isolated-decl.ts

# Deno 2.9.8 (fails TS9010 + TS9027 + 14x TS2883):
deno check repro-isolated-decl.ts

# Diagnostics (TS5.9.3):
npx tsc --strict --skipLibCheck --noEmit --target es2022 --module nodenext \
  --moduleResolution nodenext --diagnostics repro-isolated-decl.ts
B. Emitted-contract baseline instantiation & incremental timing repro

contract.prisma:

// use prisma-8

model User {
  id       Int    @id @default(autoincrement())
  username String(storage: varchar, length: 255)
  posts    Post[]

  @@map("users")
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String(storage: varchar, length: 255)
  authorId  Int      @map("author_id")
  author    User     @relation(fields: [authorId], references: [id])
  createdAt DateTime @default(now()) @map("created_at")

  @@index([authorId], name: "posts_author_id_idx")
  @@map("posts")
}

prisma.config.ts:

import { defineConfig as ormConfig, postgres18, postgresDriver } from '@prisma/orm-postgres/config';
import { definePrismaConfig } from 'prisma/config';

export default definePrismaConfig({
  orm: ormConfig({
    contract: {
      path: './contract.prisma',
      requiredCapabilities: [...postgres18, ...postgresDriver],
    },
    db: {
      connection: process.env['DATABASE_URL'] ?? 'postgresql://postgres:[email protected]:5432/bench',
    },
  }),
});

Emit contract artifacts:

npm install
npx prisma contract emit

Variants checking baseline cost:

  1. Client-only (repro-client-only.ts, 0 queries):
import postgres from '@prisma/orm-postgres/runtime';
import type { PostgresClient } from '@prisma/orm-postgres/runtime';
import { contractFromJson } from '@prisma/orm-postgres/static';
import type { Contract } from './contract.d.ts';
import contractJson from './contract.json' with { type: 'json' };

export const contract: Contract = contractFromJson<Contract>(contractJson);
export function createClient(url: string): PostgresClient<Contract> {
  return postgres({ contract, url });
}
  1. Plain query (repro-plain-usage.ts, annotated, 0 .include() calls — matches plain-query tsc diagnostics and deno check timing rows):
import postgres from '@prisma/orm-postgres/runtime';
import type { PostgresClient } from '@prisma/orm-postgres/runtime';
import { contractFromJson } from '@prisma/orm-postgres/static';
import type { Contract } from './contract.d.ts';
import contractJson from './contract.json' with { type: 'json' };

export const contract: Contract = contractFromJson<Contract>(contractJson);
export function createClient(url: string): PostgresClient<Contract> {
  return postgres({ contract, url });
}
export async function getPlainPost(
  db: PostgresClient<Contract>,
  id: number,
): Promise<{ readonly id: number; readonly title: string } | null> {
  const row = await db.orm.public.Post.where({ id }).first();
  if (!row) return null;
  return { id: row.id, title: row.title };
}

Unannotated portability variant (repro-plain-unannotated.ts, triggers TS9007 in tsc --isolatedDeclarations and TS2883 on internal Varchar chunk path in deno check):

import type { PostgresClient } from '@prisma/orm-postgres/runtime';
import type { Contract } from './contract.d.ts';

// Unannotated export triggers TS9007 (tsc) and TS2883 (deno check) on internal `Varchar` chunk path:
export function getPlainPost(db: PostgresClient<Contract>, id: number) {
  return db.orm.public.Post.where({ id }).first();
}
  1. Include query (repro-emitted-usage.ts):
import postgres from '@prisma/orm-postgres/runtime';
import type { PostgresClient } from '@prisma/orm-postgres/runtime';
import { contractFromJson } from '@prisma/orm-postgres/static';
import type { Contract } from './contract.d.ts';
import contractJson from './contract.json' with { type: 'json' };

export const contract: Contract = contractFromJson<Contract>(contractJson);

export function createClient(url: string): PostgresClient<Contract> {
  return postgres({ contract, url });
}

export async function getPostWithAuthor(
  db: PostgresClient<Contract>,
  id: number,
): Promise<{ readonly id: number; readonly title: string; readonly author: { readonly username: string } } | null> {
  const row = await db.orm.public.Post.where({ id }).include('author').first();
  if (!row) return null;
  return { id: row.id, title: row.title, author: { username: row.author.username } };
}

Diagnostic & 10-trial incremental deno check commands:

npx tsc --strict --skipLibCheck --noEmit --target es2022 --module nodenext \
  --moduleResolution nodenext --diagnostics repro-emitted-usage.ts

# 10-trial incremental latency measurement (after 1 warmup run):
cp repro-emitted-usage.ts .tmp-check.ts
deno check .tmp-check.ts
for i in $(seq 0 9); do
  printf '\n// trial %s\n' "$i" >> .tmp-check.ts
  # measure wall-clock ms of: deno check .tmp-check.ts
done
rm -f .tmp-check.ts
Observed `tsc` diagnostics & `isolatedDeclarations` error summary (`tsc 5.9.3` & `Deno 2.9.8`; 10-trial `deno check` timings in table above)
repro-isolated-decl.ts tsc --isolatedDeclarations: EXIT 1 (TS9010)
repro-isolated-decl.ts deno check: EXIT 1 (15 errors: 14x TS2883 + TS9010/TS9027)
repro-isolated-decl.ts tsc --diagnostics --skipLibCheck: Files=470 Lines=142980 Types=29768 Instantiations=93285 Memory=198011K Total=1.26s
repro-isolated-decl.ts tsc --diagnostics (full lib check): Files=470 Lines=142980 Types=193578 Instantiations=470042 Memory=445701K Total=3.34s
client-only tsc --diagnostics --skipLibCheck: Files=473 Lines=140763 Types=43152 Instantiations=344142 Memory=199843K Total=1.41s
plain-query tsc --diagnostics --skipLibCheck: Files=473 Lines=140771 Types=48594 Instantiations=360638 Memory=212715K Total=1.46s
repro-emitted-usage.ts tsc --diagnostics --skipLibCheck: Files=473 Lines=140773 Types=48908 Instantiations=362945 Memory=215241K Total=1.64s
repro-emitted-usage.ts tsc --diagnostics (full lib check): Files=473 Lines=140773 Types=222366 Instantiations=800830 Memory=506058K Total=4.20s
Environment
  • OS: Linux 6.18.34+ (x86_64)
  • Node / TypeScript: v26.8.2 / [email protected]
  • Deno: 2.9.8 (typescript 6.0.3)
Additional context
  • Distinct from prisma/orm#30928 (install-time dependency graph / toolchain bundle size) and prisma/orm#31161 / PR #31162 (exponential type-check scaling on chained .include() calls). Here, even a 2-table schema with zero .include() calls imports 473 files (~141k lines) and triggers 344k–360k instantiations (--skipLibCheck), while defineContract() lacks a type-preserving annotation compatible with isolatedDeclarations: true.
Dominant language
TypeScript
Stars
47.8k
Forks
2.6k
Avg merge
1d 21h
Merged PRs (30d)
227

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from prisma/orm

All issues in prisma/orm

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.