Skip to content

perf(client, tanstack-query, swr, pinia-colada, effect, openapi): drop redundant per-key client checks in recursive types - #2467

Merged
dinwwwh merged 4 commits into
mainfrom
claude/vigilant-goodall-ghso9h
Nov 15, 2026
Merged

dinwwwh merged 4 commits into
mainfrom
claude/vigilant-goodall-ghso9h

Conversation

@dinwwwh

@dinwwwh dinwwwh commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

What

Recursive client-mapping types used this shape:

{ [K in keyof T]: T[K] extends AnyNestedClient ? X<T[K]> : never }

The outer T extends AnyNestedClient constraint already guarantees every property is a client or a nested router, so the per-key T[K] extends AnyNestedClient check was a second structural Client/NestedClient comparison on every key. The recursion now lives in an exported, unconstrained *Internal type. The public alias keeps the constraint:

export type InferClientInputs<T extends AnyNestedClient> = InferClientInputsInternal<T>
export type InferClientInputsInternal<T> = T extends Client<any, infer U, any, any> ? U : { [K in keyof T]: InferClientInputsInternal<T[K]> }

The *Internal types are exported so a consumer's declaration emit can always name them. Take a generic wrapper such as <T extends AnyNestedClient>(c: T) => createSafeClient(c). Its emitted return type refers to SafeClientInternal<T>. If that helper were not exported, TS could not name it from another package, so it would inline the whole type and truncate it to /*elided*/ any at depth 10.

Types changed (each gets an exported *Internal counterpart):

  • client: InferClientInputs, InferClientBodyInputs, InferClientOutputs, InferClientBodyOutputs, InferClientErrors, InferClientError, SafeClient, ORPCClientScoped
  • tanstack-query, pinia-colada: RouterUtils, RouterUtilsScoped
  • swr: RouterUtils
  • effect: EffectClient
  • openapi: JsonifiedClient

Benchmark

TS 7.0.2, --checkers 1, RouterClient of 60 routers × 50 procedures (3,000 Procedures), run on main @ 1df6f2b. Values are instantiation counts.

Scenario Before After Δ
Full evaluation of InferClientInputs / InferClientOutputs 785,316 610,617 −174.7k (−22.2%)
Full evaluation of InferClientError 767,493 592,794 −174.7k (−22.8%)
Full evaluation of createSafeClient(c) 815,684 640,984 −174.7k (−21.4%)
Full evaluation of createEffectClient(c) 827,771 653,082 −174.7k (−21.1%)
tanstack-query: 3,000 utils.rX.pY.queryOptions(...) calls (whole program) 1,396,861 1,222,003 −174.9k (−12.5%)
tanstack-query: single utils.r1.p1.queryOptions(...) access 575,539 572,567 −0.5%

"Full evaluation" means assigning the mapped result to Record<string, Record<string, unknown>>, which forces every property to be resolved. A single property access gains little: most of its cost is checking the outer T extends AnyNestedClient constraint once per call, and this PR leaves that check alone.

Behavior change (bug fix)

Optional procedures used to collapse to undefined. Client | undefined does not extend AnyNestedClient, so the property became never, and the optional modifier then turned it into undefined. They now map to X | undefined. For example, InferClientInputs<{ ping?: Client<{}, string, …> }> was { ping?: undefined } and is now { ping?: string | undefined }. JsonifiedClient passed optional procedures through unconverted, so Date was not turned into string. It now converts them. InferClientError uses -?, so optional procedures add their error type and no undefined.

Tests

  • Optional procedures: new test-d cases in every touched package. They fail on the old types and pass on the new ones.
  • Declaration emit: tests/types/declaration-emit.test.ts compiles a consumer module with the repo's typescript-6 API. For each of the 15 public types, the consumer has a generic wrapper whose return type must be inferred. The test asserts the emit has no diagnostics, contains no elided, and names the exported *Internal type. Un-exporting a helper fails the test.

Verification

  • pnpm format, pnpm check, pnpm docs:validate: pass
  • tsc -p tsconfig.json (includes all *.test-d.ts): pass
  • pnpm test: 302 files and 4,647 tests passed

🤖 Generated with Claude Code

https://claude.ai/code/session_01VVaw7SZS3Fak2JESZSqnFm

…p redundant per-key client checks in recursive types

Recursive client-mapping types re-checked `T[K] extends AnyNestedClient`
for every key, repeating a structural Client/NestedClient check that the
outer `T extends AnyNestedClient` constraint already guarantees. Move the
recursion into an unconstrained `*Impl<T>` helper that recurses directly.

Optional procedures now map to `X | undefined` instead of collapsing to
`undefined`, and `JsonifiedClient` now jsonifies optional procedures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SZS3Fak2JESZSqnFm
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
orpc 7fbd9f5 Commit Preview URL

Branch Preview URL
Nov 15 2026, 08:38 AM

@pkg-pr-new

pkg-pr-new Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
More templates

@orpc/ai-sdk

npm i https://pkg.pr.new/@orpc/ai-sdk@2467

@orpc/arktype

npm i https://pkg.pr.new/@orpc/arktype@2467

@orpc/bun

npm i https://pkg.pr.new/@orpc/bun@2467

@orpc/client

npm i https://pkg.pr.new/@orpc/client@2467

@orpc/cloudflare

npm i https://pkg.pr.new/@orpc/cloudflare@2467

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@2467

@orpc/effect

npm i https://pkg.pr.new/@orpc/effect@2467

@orpc/evlog

npm i https://pkg.pr.new/@orpc/evlog@2467

@orpc/hibernation

npm i https://pkg.pr.new/@orpc/hibernation@2467

@orpc/json-schema

npm i https://pkg.pr.new/@orpc/json-schema@2467

@orpc/experimental-lock

npm i https://pkg.pr.new/@orpc/experimental-lock@2467

@orpc/mcp

npm i https://pkg.pr.new/@orpc/mcp@2467

@orpc/msw

npm i https://pkg.pr.new/@orpc/msw@2467

@orpc/nest

npm i https://pkg.pr.new/@orpc/nest@2467

@orpc/next

npm i https://pkg.pr.new/@orpc/next@2467

@orpc/node

npm i https://pkg.pr.new/@orpc/node@2467

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@2467

@orpc/opentelemetry

npm i https://pkg.pr.new/@orpc/opentelemetry@2467

@orpc/pinia-colada

npm i https://pkg.pr.new/@orpc/pinia-colada@2467

@orpc/pino

npm i https://pkg.pr.new/@orpc/pino@2467

@orpc/publisher

npm i https://pkg.pr.new/@orpc/publisher@2467

@orpc/ratelimit

npm i https://pkg.pr.new/@orpc/ratelimit@2467

@orpc/server

npm i https://pkg.pr.new/@orpc/server@2467

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@2467

@orpc/swr

npm i https://pkg.pr.new/@orpc/swr@2467

@orpc/tanstack-query

npm i https://pkg.pr.new/@orpc/tanstack-query@2467

@orpc/trpc

npm i https://pkg.pr.new/@orpc/trpc@2467

@orpc/valibot

npm i https://pkg.pr.new/@orpc/valibot@2467

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@2467

commit: 7fbd9f5

@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Improved TypeScript support for optional procedures across client, Effect, OpenAPI, and router utility types.
    • Optional top-level and nested procedures now retain their inferred types and correctly account for undefined in calls, inputs, outputs, errors, and mapped results.
    • Scoped client and router utility types now preserve optional procedure types as well.

Recursive client and router utility types now map optional procedures and nested procedure groups. Type tests cover optional values across client, Effect, OpenAPI, and framework utility mappings. A declaration-emit test checks exported internal helper references.

Changes: Optional client type mappings

Layer / File(s) Summary
Core client type mappings
packages/client/src/types.ts, packages/client/src/client-safe.ts, packages/client/src/client.ts, packages/client/src/types.test-d.ts, packages/client/src/client-safe.test-d.ts, packages/client/src/client.test-d.ts
Client inference, safe-client, and scoped-client types now recursively map properties. Type tests cover optional procedure inputs, outputs, errors, and calls.
Effect and JSON client mappings
packages/effect/src/client.ts, packages/effect/src/client.test-d.ts, packages/openapi/src/types.ts, packages/openapi/src/types.test-d.ts
Effect and JSON client types now recursively map properties. Tests cover optional procedures; JSON client tests also check that Date outputs become string.
Framework router utility mappings
packages/pinia-colada/src/router-utils.ts, packages/pinia-colada/src/router-utils.test-d.ts, packages/swr/src/router-utils.ts, packages/swr/src/router-utils.test-d.ts, packages/tanstack-query/src/router-utils.ts, packages/tanstack-query/src/router-utils.test-d.ts
Router utility types in Pinia Colada, SWR, and TanStack Query now recursively map properties. Tests cover optional top-level and nested procedures.
Declaration emit validation
tests/types/declaration-emit.test.ts
The declaration-emit test checks that compilation succeeds, output is nonempty, no types are marked elided, and generic wrappers reference the corresponding exported internal helpers.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Merge Risk: Low · up to 7fbd9

Type inference for optional procedures that declare undefined as an error would drop that error. This is rare and affects only types, not runtime behavior. The change is otherwise low risk and can be merged once the edge case is fixed or accepted.

Pre-merge checks: Passed 2

Check name Status Explanation
Title check Passed The title names the change: recursive client-mapping types drop a redundant per-key AnyNestedClient check. The changeset matches this. It touches client, tanstack-query, swr, pinia-colada, effect, and…
Description check Passed The description explains the change in detail. It covers the removed per-key AnyNestedClient check, the new exported *Internal helper types, the affected types per package, benchmark results, the opti…
Full details: Title check

Explanation

The title names the change: recursive client-mapping types drop a redundant per-key AnyNestedClient check. The changeset matches this. It touches client, tanstack-query, swr, pinia-colada, effect, and openapi. The title lists those packages and states a perf goal. The change also adds exported *Internal helpers and fixes optional-procedure typing, which the title does not mention. That omission is expected for a short title.

Full details: Description check

Explanation

The description explains the change in detail. It covers the removed per-key AnyNestedClient check, the new exported *Internal helper types, the affected types per package, benchmark results, the optional-procedure behavior fix, and the tests added. It relates directly to the changeset.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 18bf8420-02aa-4a5e-9bc1-b65520c2ba6d
Commits

Reviewing files that changed from the base of the PR and between 1df6f2b and 69af539.

Files selected for processing: 15

  • packages/client/src/client-safe.test-d.ts
  • packages/client/src/client-safe.ts
  • packages/client/src/client.ts
  • packages/client/src/types.test-d.ts
  • packages/client/src/types.ts
  • packages/effect/src/client.test-d.ts
  • packages/effect/src/client.ts
  • packages/openapi/src/types.test-d.ts
  • packages/openapi/src/types.ts
  • packages/pinia-colada/src/router-utils.test-d.ts
  • packages/pinia-colada/src/router-utils.ts
  • packages/swr/src/router-utils.test-d.ts
  • packages/swr/src/router-utils.ts
  • packages/tanstack-query/src/router-utils.test-d.ts
  • packages/tanstack-query/src/router-utils.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 3 remain after this review.

@codecov

codecov Bot commented Nov 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@pullfrog pullfrog 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.

ℹ️ Minor suggestions only.

Reviewed changes

  • Client inference aliases (packages/client/src/types.ts) — the six InferClient* aliases now forward to unconstrained *Impl helpers, and InferClientError gained -? so optional procedures no longer leak undefined into the flattened error union.
  • SafeClient and ORPCClientScoped — same alias/helper split, so optional procedures stay typed as SafeResult<…> | undefined / ORPCClientScopedOptions<…> | undefined instead of collapsing to never.
  • EffectClient (packages/effect) — split into EffectClientImpl, same as the client package.
  • RouterUtils / RouterUtilsScoped (tanstack-query, pinia-colada, swr) — per-key client checks removed; the & Public<SharedUtils<unknown>> intersection and the ?/| undefined scoped shape are unchanged.
  • JsonifiedClient (packages/openapi) — recurses through JsonifiedClientImpl and drops the old : T[K] non-client passthrough, so optional procedures now get their outputs JSON-ified.
  • Type tests — optional-procedure cases added across client, client-safe, effect, openapi, pinia-colada, swr and tanstack-query.

Checked the claims rather than taking them on trust: AnyNestedClient's object branch requires every property to be NestedClient<any>, and a required property typed Client | undefined fails that constraint, so the removed per-key guards (and JsonifiedClient's passthrough) are genuinely unreachable from conforming inputs. Ad-hoc probes against this head confirm the new results, including InferClientError<{ ping?: Client<{}, string, number, Error> }> = Error with no undefined or {} leakage, and tsc -p tsconfig.json --noEmit (which pulls in every *.test-d.ts) passes.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Comment thread packages/client/src/client.ts Resolved
@codspeed

codspeed Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 5 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 40 untouched benchmarks
⏩ 2 skipped benchmarks1


Comparing claude/vigilant-goodall-ghso9h (7fbd9f5) with main (4c3652f)

Open in CodSpeed

Footnotes

  1. 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

… public alias names in generic declaration emit

Aliasing the public types directly to the unexported `*Impl` helpers made
generic signatures (e.g. a user's `<T extends AnyNestedClient>(c: T) =>
createSafeClient(c)`) emit an inlined, depth-limited type ending in
`/*elided*/ any` instead of `SafeClient<T>`. Wrap the helper in a
deferred `T extends unknown` conditional so the public alias is what gets
named, matching the previous output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SZS3Fak2JESZSqnFm

@pullfrog pullfrog 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.

ℹ️ No new issues in this delta — the emit fix holds up. One coverage gap worth a look below.

Reviewed changes

Reviewed the follow-up commit that defers every public recursive client type through a conditional wrapper so consumer declaration emit keeps the public alias name.

  • Deferred conditional on all 15 public aliases — SafeClient, ORPCClientScoped, the six InferClient* aliases, EffectClient, JsonifiedClient, and RouterUtils/RouterUtilsScoped in tanstack-query, pinia-colada and swr now forward as T extends unknown ? XImpl<T> : never rather than a bare = XImpl<T>.
  • Rationale comment above each *Impl helper — the same three-line note explains the removed per-key AnyNestedClient check and why the public alias defers, repeated at every site.
  • No test changes — *.test-d.ts files are untouched by this commit.

I reproduced both sides of the emit claim against the repo's TS 7.0.2: with the bare forward, a generic consumer wrapper (<T extends AnyNestedClient>(c: T) => createSafeClient(c)) emits a fully inlined mapped type truncated to /*elided*/ any at depth 10; with the wrapper it emits SafeClient<T>, including inside Promise<> and object-property positions. The wrapper is semantically neutral here because every *Impl is already a distributive conditional on naked T, so the extra layer distributes over unions of the client type identically. tsc -p tsconfig.json --noEmit is clean at ba07a46.

ℹ️ The declaration-emit guard is invisible to CI

T extends unknown is load-bearing only for consumer .d.ts, which no repo check exercises. pnpm check runs oxlint with typeCheck: true (no emit), vitest only collects *.test.ts, and the package build emits @orpc/client's own .d.ts, which is valid in the bare form as well — 69af539 shipped exactly that and stayed green. So the wrapper reads exactly like the redundancy this PR exists to delete, and the comment is currently the only thing protecting it.

Technical details
# Declaration-emit regression is unguarded

## Affected sites
- `packages/client/src/client-safe.ts:8` — `SafeClient` wrapper (the pattern is repeated in all 15 aliases)
- `packages/client/src/types.ts:53-166` — the six `InferClient*` aliases
- `packages/client/src/client.ts:46`, `packages/effect/src/client.ts:22`, `packages/openapi/src/types.ts:78`
- `packages/tanstack-query/src/router-utils.ts:30,42`, `packages/pinia-colada/src/router-utils.ts:30,42`, `packages/swr/src/router-utils.ts:10`

## Required outcome
- A future edit that reduces any public alias back to `= XImpl<T>` fails a check instead of silently truncating consumer declaration emit to `/*elided*/ any`.

## Suggested approach (optional)
- A single fixture test: write a temp consumer module that imports `@orpc/client` (and one integration) and declares a generic wrapper around `createSafeClient` / `createRouterUtils`, compile it with `--declaration --emitDeclarationOnly` via `execSync` using the pinned `typescript`, and assert the emitted `.d.ts` names the public alias and contains no `elided` / `Impl`. One case covers all aliases because the mechanism is shared.
- Cheaper alternative: leave the code as-is and record the constraint where contributors look (e.g. a line in `AGENTS.md` under the type-test section), so the invariant is discoverable outside the file-local comments.

## Open questions for the human
- Is an emit fixture test in scope for this PR, or should the invariant only be documented?

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Reviewed the follow-up commit that adds the last missing type-test case from the earlier review.

  • ORPCClientScoped optional-procedure coverage — a new top-level case in packages/client/src/client.test-d.ts asserts Scoped['ping'] is ORPCClientScopedOptions<{ cache: string }, number, string, Error> | undefined and that the nested optional pong keeps ORPCClientScopedOptions<…> | undefined.
  • Regression value confirmed — the test targets the exact behavior this PR changes: the old non-distributive per-key T[K] extends AnyNestedClient check collapsed both properties to undefined, so the assertions fail against the pre-PR types and pass now.
  • No production code touched — the commit is type-test only; tsc -p tsconfig.json --noEmit and oxlint packages/client/src/client.test-d.ts are clean at 3773234.

The earlier ORPCClientScoped thread is addressed by this commit and has been resolved.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

… export recursive helpers as `*Internal`

Replace the `T extends unknown` wrapper with exported `*Internal` helpers
(e.g. `SafeClientInternal`) that the public aliases point at directly.
Being exported, a consumer's declaration emit can always name them, so
generic wrappers no longer inline a truncated type.

Add a declaration-emit test that compiles a consumer with generic
wrappers for every recursive client type and fails if any is inlined
or unnameable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SZS3Fak2JESZSqnFm

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Reviewed the commit that replaces the elided-emit workaround with exported *Internal helpers and adds a declaration-emit regression test.

  • Exported *Internal counterparts for all 15 recursive client types — public aliases now forward straight through (export type X<T extends AnyNestedClient> = XInternal<T>), and the T extends unknown ? XImpl<T> : never deferral plus its repeated three-line comment are gone.
  • New declaration-emit test (tests/types/declaration-emit.test.ts) — compiles a virtual consumer module through the repo's typescript-6 API, one generic wrapper per public alias, and asserts the emitted .d.ts is diagnostic-free, names <alias>Internal<T>, and never contains elided.
  • CI coverage for the invariant — the file is collected by the root vitest project (**/*.test.ts), so the test:coverage job exercises it on every Node version in the matrix, closing the "emit guard is invisible to CI" gap raised on the ba07a46 review.

Verified rather than assumed: un-exporting EffectClientInternal fails both the elided assertion and the effect EffectClient naming assertion, so the guard has teeth; a probe that returns these types in nested positions (Promise<...>, object properties, array elements) emits ...Internal<T> everywhere without inlining, so dropping the deferral does not reintroduce elision; the new test (17 assertions, ~2s), tsc -p tsconfig.json --noEmit and oxlint on every touched file are clean at 7fbd9f5.

Emit now names the internal helper rather than the public alias (SafeClientInternal<T> instead of SafeClient<T>). That is the tradeoff documented in the PR body, and also the more robust side of it: an exported, nameable helper does not rely on the printer remembering a deferral.

@pullfrog pullfrog 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.

✅ Approving the 7fbd9f5 delta — verification detail is in the review above.

@dinwwwh
dinwwwh merged commit 426e1d0 into main Nov 15, 2026
12 of 13 checks passed
dinwwwh pushed a commit that referenced this pull request Nov 15, 2026
Resolve conflicts with #2467 (unconstrained `*Internal` infer types): keep
its structure, add `InferClientContextInternal` for the leaf walk, and
keep both sides' appended type tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SLD43iJSE4suogZAd
dinwwwh added a commit that referenced this pull request Nov 15, 2026
…hecks in recursive types (#2477)

## What

This applies the refactor from
#2467 to the server-side and
contract router types. They used this shape:

```ts
{ [K in keyof T]: T[K] extends RouterContract ? X<T[K]> : never }
// server types also had a fallback: T[K] extends Lazyable<infer U extends AnyRouter> ? X<U> : never
```

The outer `T extends RouterContract` / `T extends AnyRouter` constraint
already guarantees what the per-key check tests. The recursion now runs
through an exported, unconstrained `*Internal` helper, and the public
alias keeps the constraint:

```ts
export type X<T extends RouterContract> = XInternal<T>
export type XInternal<T> = T extends <leaf> ? ... : { [K in keyof T]: XInternal<T[K] & {}> }
```

For server types, the lazy unwrapping moves into the helper as a `T
extends Lazy<infer U>` branch. It only runs on non-procedure nodes.
Because `T` is distributive there, `Lazyable<...>` keys still work.

Types changed (each gains an exported `*Internal` helper):
- `contract`: `InferRouterContractInputs`, `InferRouterContractOutputs`,
`InferRouterContractErrorMap`, `InferRouterContractError`,
`InferRouterContractErrors`, `AugmentedContractRouter`
- `server`: `ContractedRouter`, `InferRouterInitialContexts`,
`InferRouterFinalContexts`, `InferRouterInputs`, `InferRouterOutputs`,
`InferRouterErrors`, `InferRouterError`, `UnlaziedRouter`,
`AugmentedRouter`, `AugmentedRouterWithMiddlewares`, `RouterClient`
- `openapi`: `PopulatedContractRouterOpenAPIPaths`
- `msw`: `HTTPRouterUtils`

### Why `T[K] & {}` instead of plain `T[K]`

With a bare `XInternal<T[K]>`, TS keeps inferring `T` back through the
mapped type when the call's contextual type is recursive. Each level
creates a fresh reverse-mapped type, and the comparison against the
constraint never ends. This happened inside the repo's own code and
tests:

```ts
// TS2321: Excessive stack depth comparing types '{ [x: string]: ...; }' and 'AnyRouter'
const client: AnyNestedClient = createRouterClient(router, { context: { db } })
```

It also showed up as an excessive-stack-depth error while TS measured
variance for `SharedRouterImplementerWithMiddlewares`, through
`InferRouterContractErrorMap`. A probe found the same failure in every
shape-preserving type here. The trigger is a generic function returning
the type, assigned to a recursive type, called with an object-literal
argument typed by `T`. `main` has no such error.

`T[K] & {}` stops the inference and is nearly free. Things I tried that
did not work:
- `NoInfer<T[K]>` keeps a wrapper around concrete object types. That
turns off distribution, which breaks `Lazyable` and optional keys.
- `T[K] extends infer U ? XInternal<U> : never` and `T[K] extends object
? ...` guards cost as much as the check they replace.

`& {}` also drops `undefined` from optional keys, which gives the
behavior described below.

### Other details
- **`any` handling.** `RouterClient`, `AugmentedRouter` and
`AugmentedRouterWithMiddlewares` map the first level in the public alias
itself. Otherwise `any` would reach the helper's `Lazy` branch:
`AugmentedRouter<any>` would gain a `Lazy<{}>` member, and `os.router({}
as any)` would stop being assignable to `AnyRouter`.
- **Declaration emit.** The helpers are exported so declaration emit can
name them. A generic wrapper around `oc.router`, `unlazyRouter`,
`populateRouterContractOpenAPIPaths` or `createHTTPUtils` now emits
`AugmentedContractRouterInternal<T, ...>`, `UnlaziedRouterInternal<T>`
and so on, where `main` emitted the public name. Before they were
exported, TS inlined the helper's body there instead. A declaration-emit
probe covering all 20 types shows these four renames and no other
differences from `main`, with no inlining and no `elided`.

## Benchmark

TS 7.0.2, `tsc --extendedDiagnostics --checkers 1`, on a synthetic
project: a contract and a router of 60 routers × 50 procedures (3,000
procedures). Each workload accesses all 3,000 leaves, or resolves the
full union for the union types. The numbers below are instantiations
above a base project that only defines the router. The base itself
changes by under 0.01%. The counts are deterministic.

| Type | Before | After | Δ |
| :-- | --: | --: | --: |
| `InferRouterContractInputs` / `Outputs` | 214,276 | 205,037 | −9,239
(−4.3%) |
| `InferRouterContractErrors` / `Error` | 205,276 / 205,459 | 196,037 /
196,220 | −9,239 (−4.5%) |
| `InferRouterContractErrorMap` | 136,459 | 127,220 | −9,239 (−6.8%) |
| `AugmentedContractRouter` (`oc.router`) | 196,566 | 187,326 | −9,240
(−4.7%) |
| `PopulatedContractRouterOpenAPIPaths` | 218,564 | 209,340 | −9,224
(−4.2%) |
| `HTTPRouterUtils` | 212,555 | 203,334 | −9,221 (−4.3%) |
| `ContractedRouter` (`implement(contract).router(router)`) | 301,745 |
289,449 | −12,296 (−4.1%) |
| `InferRouterInputs` / `Outputs` | 211,150 | 202,218 | −8,932 (−4.2%) |
| `InferRouterInitialContexts` / `FinalContexts` | 184,150 / 199,150 |
175,218 / 190,218 | −8,932 (−4.9% / −4.5%) |
| `InferRouterErrors` / `Error` | 241,150 / 241,333 | 232,218 / 232,401
| −8,932 (−3.7%) |
| `UnlaziedRouter` | 133,028 | 124,094 | −8,934 (−6.7%) |
| `RouterClient` | 238,150 | 229,270 | −8,880 (−3.7%) |
| `AugmentedRouter` / `WithMiddlewares` (`os.router`) | 244,204 /
245,161 | 235,324 / 236,401 | −8,880 / −8,760 (−3.6%) |

With all 60 routers wrapped in `os.lazy`, the server types save about
15k (−3.4% to −4.8%) and `ContractedRouter` saves 18k (−4.0%).

The saving is about 3 instantiations per procedure. That is much smaller
than the −22% on #2467. Here the
removed check is a cheap comparison:
#2452 to
#2454 already made these types
match procedures through `~orpc` and test `AnyRouter` before inferring.
Most of the remaining cost is in the leaf branches.

## Behavior change (bug fixes)

- **Optional keys** used to collapse to `undefined`. `X | undefined`
failed the per-key check, so the key became `never`, and the optional
modifier then turned it into `undefined`. They now map to their value.
For example, `InferRouterInputs<{ ping?: P }>` was `{ ping?: undefined
}` and is now `{ ping?: Input | undefined }`. The same applies to
`RouterClient`, `ContractedRouter` and the other shape-preserving types.
The existing `RouterClient` test that pinned the old result (`maps an
optional key to never`) now asserts the mapped client.
- **Union types** (`InferRouterError`, `InferRouterContractError`,
`InferRouterContractErrorMap`) use `-?`. For a router with optional keys
they were `undefined`; they now give the real union, with no
`undefined`.
- **`AugmentedRouter` / `AugmentedRouterWithMiddlewares`** mapped
`Lazyable<...>` keys (a router or its lazy form) to `never`.
`AugmentedRouter<AnyRouter>` was `{ [k: string]: never }`. Both now map
properly.

I compared old and new on procedures, nested, lazy, `Lazyable`, optional
and readonly keys, `os.router()` output, `AnyRouter`, `RouterContract`,
`any` and `never`. Apart from the cases above, the only difference is
for keys typed `any` in the server types, which pick up an extra `{}` /
`Lazy<{}>` union member.

## Tests

New test-d cases cover optional keys for every changed type. New
`AugmentedRouter*` cases cover `Lazyable` keys and assignability to
`AnyRouter` for `any` / `AnyRouter`. There is a new
`openapi/src/router-utils.test-d.ts`. All the new optional-key and
`Lazyable` assertions fail on the old types (19 errors) and pass on the
new ones.

A regression test, `const c: AnyNestedClient =
createRouterClient(router, { context })`, guards the overflow above. It
passes on `main` and fails if `& {}` is removed.

## Verification

- `pnpm check` and `pnpm docs:validate`: pass.
- `tsc -p tsconfig.json` (includes all `*.test-d.ts`): pass.
- `pnpm test`: 4,630 tests passed, plus `packages/bun` (100) and
`packages/cloudflare` (83). That full run was before the `*Internal`
rename. After the rename I re-ran the `server`, `contract`, `openapi`
and `msw` tests (1,411 passed) plus the root type check.
- The first full run had two failures in `packages/bun` (`cancel and
abort: compression-bun-fetch`). These runtime timing tests can't be
affected by a type-only change. They passed in three separate re-runs
and in two later full runs.
- `pnpm format` was run. It also reformatted `apps/content/sponsors/*`,
which I left out of this PR.

## Note on #2467

The same probe, run against that branch's client types, fails for
`InferClientInputs`, `InferClientOutputs`, `InferClientErrors`,
`SafeClient`, `RouterUtils`, `EffectClient` and `JsonifiedClient` with
`TS2321` (`main` passes). The probe is a generic `<T extends
AnyNestedClient>(c: T, o: { ctx?: InferClientContext<T> }) => X<T>`,
assigned to a recursive type and called with `{ ctx: {} }`. `T[K] & {}`
would likely fix it there too.
dinwwwh added a commit that referenced this pull request Nov 15, 2026
… reverse inference through recursive client types (#2478)

## Problem

#2467 rewrote the recursive client
types as `T extends Client<...> ? ... : { [K in keyof T]:
XInternal<T[K]> }`. The `XInternal<T[K]>` inside the mapped type isn't
guarded. When a call's contextual type is recursive, TS keeps inferring
`T` back through that homomorphic mapped type. Each level creates a new
reverse-mapped type, and the check against the `AnyNestedClient`
constraint fails:

```
TS2321: Excessive stack depth comparing types '{ [x: string]: ...; }' and 'AnyNestedClient'.
```

Minimal trigger:

```ts
type Recursive = { [k: string]: Recursive } | object
type Options<T extends AnyNestedClient> = { context?: InferClientContext<T> }
declare function fn<T extends AnyNestedClient>(client: T, options: Options<T>): InferClientInputs<T>
const _: Recursive = fn(client, { context: {} }) // TS2321 on main
```

## Fix

Recurse through `XInternal<T[K] & {}>` instead, the same approach
#2477 takes for the contract and
server router types. `& {}` stops the reverse inference. The helpers
still distribute over unions, and optional keys still map to `?: ... |
undefined` through the homomorphic mapping.

Changed helpers:
- `@orpc/client`: `InferClientInputs`, `InferClientBodyInputs`,
`InferClientOutputs`, `InferClientBodyOutputs`, `InferClientErrors`,
`InferClientError`, `SafeClient`, `ORPCClientScoped`
- `@orpc/tanstack-query`, `@orpc/pinia-colada`: `RouterUtils`,
`RouterUtilsScoped`
- `@orpc/swr`: `RouterUtils`
- `@orpc/effect`: `EffectClient`
- `@orpc/openapi`: `JsonifiedClient`

`InferClientError` never hit the error, because its result is an indexed
union rather than a mapped object. It's changed anyway to stay
consistent with the others.

### `JsonifiedClient` and non-client values

`& {}` changes the result for three kinds of leaf: an explicit `null` or
`undefined` leaf becomes `never`, and an `unknown` leaf becomes `{}`.
Other leaves (primitives, literals, `Date`, arrays, tuples, functions,
`any`, `never`, unions with clients, optional keys) give the same result
as before. None of the changed leaves pass the `AnyNestedClient`
constraint. `{ a: C, b: null }`, `{ a: C, b: undefined }`, `{ a: C, b:
unknown }` and `{ a: C | undefined }` are all rejected, so no public
type's result changes. `undefined` only gets in through optional keys,
and those still come out as `?: ... | undefined`.

## Tests

Each changed type gets a "with a recursive contextual type" case. In the
test files this PR touches, every tested type now has one `describe`
holding all of its cases: plain procedures, optional procedures, and the
recursive contextual type. That covers each `InferClient*` helper,
`SafeClient`, `ORPCClientScoped`, `RouterUtils`, `RouterUtilsScoped`,
`createRouterUtils`, `EffectClient` and `JsonifiedClient`. Cases that
used to cover `RouterUtils` and `RouterUtilsScoped` together are split
between the two groups. No assertions were added or dropped while moving
tests.

Each type gets its own generic function, which takes an object-literal
argument typed by `T` and is assigned to a recursive type. They aren't
combined into one tuple or object return, because that hid a regression
in a single helper. I removed the `& {}` from one helper at a time. For
each of the 14 helpers that had the bug, that made its own case fail
with TS2321; `InferClientError` passes either way. The
optional-procedure cases from #2467 still pass.

- `pnpm check` passes
- `pnpm test` passes (302 files, 4647 tests)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants