You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(server): make RouterClient cheaper to type-check - #2452
RouterClient used to infer every key through the Procedure class and the Lazyable union. Two changes make it cheaper:
A procedure is matched through its ~orpc definition instead of the Procedure class.
A key that is already a router takes a fast path, TRouter[K] extends AnyRouter, which has no infer. Only lazy keys fall through to the original Lazyable<infer U> inference.
RouterClient keeps its signature and still recurses on itself, so there is no new helper type and nothing new to export.
Measurements
Measured with the typecheck project of orpc-benchmarks (3,000 procedures plus a typed client call for each), tsc --singleThreaded --extendedDiagnostics, TypeScript 7.0.2. "Before" is the published 2.0.0-beta.50, "after" is @orpc/server built from this branch. These counts are deterministic.
Inputs declared with
Instantiations
Types
The benchmark's vendored Standard Schema interface
1,040,001 → 898,469 (−13.6%)
247,841 → 238,834 (−3.6%)
Zod 4.6.7
1,982,622 → 1,841,090 (−7.1%)
365,229 → 356,222 (−2.5%)
Valibot 1.5.0
1,674,556 → 1,545,024 (−7.7%)
335,747 → 326,740 (−2.7%)
oRPC's own Schema<I, O> type
886,914 → 745,382 (−16.0%)
169,788 → 160,781 (−5.3%)
This is independent of #2451. With both applied, the benchmark goes from 1,040,001 to 770,912 instantiations (−25.9%).
Why ProcedureDefinition and not Procedure
Matching TRouter extends Procedure<any, any, infer ..., infer ..., infer ...> also works, but costs 39,024 more instantiations on the benchmark (937,493 instead of 898,469, so −9.9% instead of −13.6%). .handler() returns a DecoratedProcedure, a different class from Procedure, so TypeScript compares the two classes structurally for every procedure. Matching { '~orpc': ProcedureDefinition<...> } compares the same interface on both sides, by its type arguments. As a check, when .handler() is made to return a plain Procedure, the gap shrinks from 39,024 to 9,018.
Behavior
No difference from main. I compared the old and new definitions directly on procedures, nested routers, lazy routers and procedures, keys typed as Lazyable<...>, optional and readonly keys, os.router() output, AnyRouter, any and never: all resolve to identical types.
Emitted declarations are unchanged too. A consumer installed from packed tarballs (pnpm, depending only on @orpc/server) and built with composite: true, including generic code that takes a router as a type parameter, emits a .d.ts byte-identical to the one built against main, on TypeScript 7.0.2, 6.0.3 and 5.9.3.
History of this branch
An earlier version moved the recursion into a helper type, RouterClientInner. That needed an export: without it, generic consumer code made TypeScript unroll the recursive type into the emitted .d.ts (588 lines instead of 104). The current version is faster than the helper version (898,469 instead of 910,989) and avoids the question, so the helper is gone.
Verification
pnpm check and pnpm docs:validate pass. The full pnpm test (4,585 tests) passed on the first commit; after the later commits I re-ran the @orpc/server tests (670 pass).
All new type tests (lazy at any depth, Lazyable keys, an optional key, createRouterClient with an untyped router) also pass on main, so they describe behavior this PR keeps.
RouterClient inferred every key through the Procedure class and the
Lazyable union. It now matches a procedure through its `~orpc`
definition, unwraps Lazy with its own conditional and maps the remaining
keys directly.
The mapped type uses `as K` so TypeScript does not infer the router
backwards from an expected client, which is unbounded for a recursive
type; a test covers it.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SLCp5Vav859sAFS6N
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.
No actionable comments were generated in the recent review.
Summary
Summary by CodeRabbit
Bug Fixes
Improved TypeScript support for router clients, including procedures and nested routers defined directly or loaded lazily.
Optional router entries are handled more accurately in client types.
Router clients can now be created from untyped routers, with support for the general nested-client type.
Nested router properties retain their type information, improving editor feedback and helping catch type mismatches during development.
RouterClient now derives client types from procedure metadata and recursively maps router and lazy router types. Added type assertions cover lazy and non-lazy router shapes, optional keys, and createRouterClient with an untyped router.
RouterClient identifies procedures through ~orpcProcedureDefinition metadata. It recursively maps AnyRouter and Lazyable members.
RouterClient type assertions packages/server/src/router-client.test-d.ts
Type assertions cover lazy procedures, nested lazy routers, lazy-or-non-lazy keys, optional keys, and the createRouterClient result for an untyped router.
This change only reworks how the router client type is computed, with no runtime change. Optional keys are still typed as never, as before, so callers get no new way to call a missing procedure. It looks safe to merge.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: RouterClient is made cheaper to type-check, and the perf(server) prefix identifies the package. The description and objectives confirm that the change reduces type ins…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description is specific and related to the changeset. It explains that RouterClient now matches procedures through their ~orpc definition and adds a fast path for router keys before the Lazyable i…
Full details: Title check
Explanation
The title names the main change: RouterClient is made cheaper to type-check, and the perf(server) prefix identifies the package. The description and objectives confirm that the change reduces type instantiations by matching procedures via ~orpc and recursing over keys. The title is short, specific, and matches the changeset.
Full details: Description check
Explanation
The description is specific and related to the changeset. It explains that RouterClient now matches procedures through their ~orpc definition and adds a fast path for router keys before the Lazyable inference. It gives benchmark measurements, the reason for choosing ProcedureDefinition over Procedure, the history of the RouterClientInner helper, and verification steps. It matches the raw summary and objectives.
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.
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 9424c927-82f2-404e-a15f-15cc06732345
Commits
Reviewing files that changed from the base of the PR and between c20aba0 and 9ced750.
Files selected for processing: 1
packages/server/src/router-client.ts
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.
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.
A project that emits declarations writes out the expanded client shape,
never the helper's name, so the helper does not need to be exported.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SLCp5Vav859sAFS6N
The reason will be displayed to describe this comment to others. Learn more.
✅ No new issues found.
Reviewed changes
This run reviewed the single commit 9bae120, a type-only rewrite of RouterClient, checked against a full-repo typecheck and a differential old-vs-new type probe.
Recursion moved into RouterClientInner — procedure detection now matches the ~orpcProcedureDefinition shape, Lazy gets its own unwrap branch, and remaining keys are mapped directly, while RouterClient keeps its TRouter extends AnyRouter signature.
as K on the mapped branch — prevents reverse mapped-type inference when an expected client type is in scope, without losing homomorphic behavior.
New type tests — lazy unwrapping at depth, Lazyable keys, and createRouterClient with an untyped router.
Verification beyond the PR body: the old and new conditionals resolve to identical client types for concrete procedures, nested routers, Lazy/Lazyable keys, os.router/AugmentedRouter and ContractedRouter shapes, Router<Ctx>/AnyRouter/AnyProcedure, Record-indexed, readonly, union, and generic-wrapper routers; ? and readonly modifiers survive the as K remap; LazyDefinition and ProcedureContractDefinition cannot be mistaken for a procedure because they lack orderedMiddlewares/handler. Only the two deltas already documented in the PR body (optional router keys, any-typed routers) differ, and pnpm check's type-aware oxlint passes on both changed files.
The reason will be displayed to describe this comment to others. Learn more.
✅ No new issues found.
Reviewed changes
This run reviewed the delta since the previous pullfrog review: dea4b4d makes RouterClientInner module-local so it no longer becomes public API through export * from './router-client'.
Helper kept local — nothing outside router-client.ts references it, RouterClient still resolves through it, and createRouterClient keeps its signature.
Declaration emit checked — pnpm --filter @orpc/server prepack succeeds, and dist/router-client.d.ts keeps RouterClientInner as an unexported alias that the exported RouterClient references, so the helper stays off the public surface.
Full-repo tsc --noEmit (TypeScript 7.0.2) still passes with the change.
The reason will be displayed to describe this comment to others. Learn more.
Additional comments: 1
packages/server/src/router-client.ts-28-28: 1
28-28: Major · Data Integrity & Integration · Heavy lift
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Keep optional lazy keys consistent with the runtime client.
When a lazy router has an absent optional ping procedure, client.nested.ping is still a callable proxy. An if (client.nested.ping) check therefore passes, but the call rejects when the lazy loader finds no procedure. The new type permits this check and call. Align optional-key support with lazy resolution, or prevent this combination from being represented as an optional client. (raw.githubusercontent.com)
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: 7007a911-ce7c-4230-bf92-f5a16f155bac
Commits
Reviewing files that changed from the base of the PR and between 9bae120 and dea4b4d.
Files selected for processing: 1
packages/server/src/router-client.ts
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review.
Mapping every key directly turned an optional router key into an optional
client. Inside a lazy router that client is always a truthy proxy at
runtime, so the type promised a check that cannot work. Each key is now
guarded with `extends Lazyable<AnyRouter>`, as before this branch, and a
test pins it.
The guard also stops TypeScript from inferring the router backwards
through the mapped type, so the `as K` clause is no longer needed.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SLCp5Vav859sAFS6N
The reason will be displayed to describe this comment to others. Learn more.
✅ No new issues found.
Reviewed changes
This run reviewed the delta since the previous pullfrog review: 5f088a2 restores the per-key Lazyable<AnyRouter> guard in RouterClient, so an optional router key maps to never again, and pins that with a type test.
Optional keys map to never again — each remaining key is now checked with T[K] extends Lazyable<AnyRouter> before recursing, restoring the pre-PR result for optional router keys instead of the ProcedureClient | undefined the guard-free version produced.
as K dropped from the mapped branch — with a conditional in the template, reverse mapped-type inference no longer applies, and ?/readonly modifiers still survive.
New type test — it('maps an optional key to never') asserts RouterClient<{ ping?: typeof router.ping }> is { ping?: never }.
Verified beyond the test suite: a differential probe against main's RouterClient (root tsc --noEmit) resolves identical types for os.router output, single procedures, Lazyable keys, optional keys, Record-indexed and readonly routers, and ContractedRouter; removing the guard makes the new test fail, so it is load-bearing. On a synthetic 300-procedure router the new type is still cheaper than main (117,086 vs 122,123 instantiations), so restoring the guard does not negate the PR's purpose.
## Summary
`InferSchemaInput` and `InferSchemaOutput` now read `~standard.types` by
indexed access, the same way the Standard Schema spec defines its own
`InferInput` / `InferOutput`, instead of matching `T extends
StandardSchemaV1<infer U, any>`.
Zod, Valibot, ArkType and others each ship their own copy of the
Standard Schema interface. With the conditional form, TypeScript had to
compare that whole interface structurally for every schema. Indexed
access skips that comparison.
## Measurements
Measured with the `typecheck` project of
[orpc-benchmarks](https://github.com/middleapi/orpc-benchmarks) (3,000
procedures plus a typed client call for each), `tsc --singleThreaded
--extendedDiagnostics`, TypeScript 7.0.2. "Before" is the published
`2.0.0-beta.50`, "after" is `@orpc/contract` and `@orpc/server` built
from this branch. These counts are deterministic.
| Inputs declared with | Instantiations | Types |
| :-- | :-- | :-- |
| The benchmark's vendored Standard Schema interface | 1,040,001 →
912,444 (−12.3%) | 247,841 → 204,327 (−17.6%) |
| Zod 4.6.7 | 1,982,622 → 1,750,047 (−11.7%) | 365,229 → 321,714
(−11.9%) |
| Valibot 1.5.0 | 1,674,556 → 1,381,969 (−17.5%) | 335,747 → 292,233
(−13.0%) |
| oRPC's own `Schema<I, O>` type | 886,914 → 894,428 (+0.8%) | 169,788 →
189,311 (+11.5%) |
The last row gets slightly worse. When a schema's type is the very same
declaration oRPC imports, the conditional form had a fast path that
indexed access does not beat.
This is independent of #2452. With
both applied, the benchmark goes from 1,040,001 to 783,432
instantiations (−24.7%).
## Behavior
- **`any` schema:** still infers `unknown`, through the `0 extends 1 &
T` guard. Without the guard, 24 type-test assertions fail. The cheaper
`unknown extends T` guard breaks two `ai-sdk` type tests, so it is not
used.
- **`createProcedureClient`:** two internal casts changed. They relied
on the old conditional resolving to `any` inside generic code. No
runtime change.
Schemas from Zod, Valibot, ArkType and anything typed as `Schema<I, O>`
are unaffected. The difference is for a hand-written schema whose type
does not declare usable `types`:
| Schema type | Before | After |
| :-- | :-- | :-- |
| `types` omitted | input `unknown`, output read from `validate`'s
return type | input `unknown`, output `unknown` |
| `types: undefined` declared explicitly | input `unknown`, output read
from `validate`'s return type | input `never`, output `never` |
Both can be avoided at a cost, and neither option is in this PR:
- Returning `unknown` for the `types: undefined` case too, with
`[T['~standard']['types']] extends [undefined]` as the guard: 931,964
instantiations on the benchmark (−10.4% instead of −12.3%).
- Keeping the old conditional as a fallback when `types` is omitted:
949,954 (−8.7%).
## Verification
- `pnpm check`, `pnpm test` (4,585 tests) and `pnpm docs:validate` pass.
- `schema.test-d.ts` gains assertions for Valibot, ArkType, a union of
schemas, `AnySchema`, `any`, and a schema with `types` omitted. All but
the last also pass on `main`; the last one is the difference described
above.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01VVaw7SLCp5Vav859sAFS6N
---------
Co-authored-by: Claude <noreply@anthropic.com>
With the helper local, generic code that takes a router as a type
parameter cannot name it in an emitted declaration. TypeScript then
unrolls the recursive type instead: a consumer built with
`composite: true` emitted 588 lines where main emits 104, and
re-checking that declaration did not finish.
Exported, the same code emits
`import("@orpc/server").RouterClientInner<T, object>` and builds on
TypeScript 7.0.2, 6.0.3 and 5.9.3.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SLCp5Vav859sAFS6N
The reason will be displayed to describe this comment to others. Learn more.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
This run reviewed the delta since the prior pullfrog review: c20aba04 re-exports RouterClientInner, reversing the module-local decision from dea4b4d, so generic consumer code can name the helper in its emitted declarations.
RouterClientInner returned to the public surface — the recursive helper is exported again, and therefore re-exported from @orpc/server through export * from './router-client', for consumers whose router type parameter is Lazyable<AnyRouter> rather than AnyRouter and so cannot spell RouterClient<T>.
Rationale documented in the PR body — a packed-tarball comparison now backs the export: 104-line consumer .d.ts that re-checks cleanly versus 588 lines for the unexported helper that did not finish re-checking in five minutes.
Verified beyond the body: pnpm --filter @orpc/server prepack emits export type RouterClientInner<T, TClientContext extends ClientContext> in dist/router-client.d.ts; a probe consumer declaring makeClient<T extends Lazyable<AnyRouter>>(router: T): RouterClientInner<T, object> emits a two-line .d.ts that names the helper instead of unrolling it, which is exactly the case RouterClient's AnyRouter constraint cannot express. Root tsc -p tsconfig.json --noEmit passes and oxlint reports no warnings on either changed file.
RouterClient now recurses on itself again. A key that is already a router
takes a fast path with no `infer`; only lazy keys go through the original
`Lazyable<infer U>` inference.
This is faster than the helper version (898,469 instead of 910,989
instantiations on the benchmark), resolves to the same types as main for
every router shape including `any`, and adds no exported type, so emitted
declarations are identical to main.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7SLCp5Vav859sAFS6N
The reason will be displayed to describe this comment to others. Learn more.
✅ No new issues found.
Reviewed changes
This run reviewed the delta since the previous pullfrog review: 9ced750 drops the RouterClientInner helper and lands the final self-recursive shape of RouterClient.
Helper type removed — RouterClient recurses on itself again, so RouterClientInner is no longer part of the file or the public surface, and nothing needs exporting; the previous JSDoc note no longer applies and its thread is resolved.
Router fast path added — each remaining key is now checked with TRouter[K] extends AnyRouter before the existing Lazyable<infer U> inference, so router keys skip inference and only lazy keys infer.
Type tests unchanged — the lazy-at-depth, Lazyable key, optional-key and createRouterClient tests from earlier commits still cover the new control flow as-is.
Verified beyond the body: a differential probe through the root tsc program compares this definition against main's for nested routers, procedures, Lazy/Lazyable keys, unions, optional, readonly, symbol, numeric and Record-indexed keys, AnyRouter, Router<object>, mixed AnyRouter/Router/AnyProcedure keys, never, and any-typed keys — all resolve identically. Lazy<...> is confirmed not to satisfy AnyRouter (no index signature), so the fast path cannot swallow lazy keys. pnpm --filter @orpc/server prepack emits only the self-recursive alias, with no helper left in dist/router-client.d.ts. Root tsc -p tsconfig.json --noEmit, oxlint and oxfmt --check are clean, and no tracked file references RouterClientInner.
## Summary
`AugmentedRouter` and `AugmentedRouterWithMiddlewares` are the types
returned by `os.router()`, `os.use(...).router()`, `os.lazy()` and the
implementer's `.router()`. Two changes make them cheaper:
- A procedure is matched through its `~orpc` definition instead of the
`Procedure` class. `.handler()` returns a `DecoratedProcedure`, a
different class, so the class match compared the two classes
structurally for every procedure.
- Each key is tested against `AnyRouter` first, which has no `infer`.
The `Lazy<infer $>` inference now runs only for keys that are not plain
routers.
Both types still recurse on themselves; there is no new helper type.
## Measurements
The workload is the `typecheck` project of
[orpc-benchmarks](https://github.com/middleapi/orpc-benchmarks) (3,000
procedures plus a typed client call for each), with routers wrapped as
described in each row. `tsc --singleThreaded --extendedDiagnostics`,
TypeScript 7.0.2. "Before" is the published `2.0.0-beta.50`, "after" is
`@orpc/server` built from this branch. These counts are deterministic.
| Routers wrapped with | Instantiations | Types |
| :-- | :-- | :-- |
| `os.router()` at the root | 1,349,789 → 1,274,217 (−5.6%) | 262,932 →
265,928 (+1.1%) |
| `os.router()` in each of the 500 router files | 1,362,253 → 1,307,191
(−4.0%) | 279,425 → 282,421 (+1.1%) |
| `os.use(middleware).router()` at the root | 1,388,983 → 1,313,411
(−5.4%) | 263,503 → 266,499 (+1.1%) |
| nothing (plain objects, the unmodified benchmark) | 1,040,001 →
1,040,001 | 247,841 → 247,841 |
The type count rises by one per procedure. For scale: the same project
with plain object routers is 1,040,001 instantiations, so `os.router()`
at the root accounts for about 309,800 of them before and 234,200 after
(−24%).
This is independent of #2451 and
#2452.
## Behavior
No difference from `main`. I compared the old and new definitions
directly on procedures, nested routers, lazy routers and procedures,
keys typed as `Lazyable<...>`, optional and readonly keys, `os.router()`
output, `AnyRouter`, `any` and `never`, with and without an error map:
all resolve to identical types.
Emitted declarations are unchanged too. A consumer installed from packed
tarballs (pnpm, depending only on `@orpc/server`) and built with
`composite: true`, including generic code that passes a router type
parameter to `.router()`, emits a `.d.ts` byte-identical to the one
built against `main`, on TypeScript 7.0.2, 6.0.3 and 5.9.3.
## Verification
`pnpm check`, `pnpm test` (4,585 tests) and `pnpm docs:validate` pass.
The existing type tests in `router-utils.test-d.ts` cover a single
procedure, a nested router and a lazy router for both types.
## Summary
This applies the same two changes as
#2452 to the remaining types that
walk a router with `Lazyable<infer U>`:
- `InferRouterInputs`, `InferRouterOutputs`,
`InferRouterInitialContexts`, `InferRouterFinalContexts`,
`InferRouterError` and `InferRouterErrors` match a procedure through its
`~orpc` definition instead of the `Procedure` class.
- Those six, and `UnlaziedRouter`, test each key against `AnyRouter`
first, which has no `infer`. The `Lazyable<infer U>` inference now runs
only for keys that are not plain routers.
Every type still recurses on itself; there is no new helper type.
## Measurements
The base workload is the `typecheck` project of
[orpc-benchmarks](https://github.com/middleapi/orpc-benchmarks): 500
routers, 3,000 procedures. Each row replaces its client calls with the
lookups described. `tsc --singleThreaded --extendedDiagnostics`,
TypeScript 7.0.2. "Before" is the published `2.0.0-beta.50`, "after" is
`@orpc/server` built from this branch. These counts are deterministic.
| Workload | Instantiations | Types |
| :-- | :-- | :-- |
| `InferRouterInputs` and `InferRouterOutputs`, one lookup per procedure
each | 1,010,371 → 830,327 (−17.8%) | 226,790 → 217,779 (−4.0%) |
| `InferRouterInitialContexts`, `InferRouterFinalContexts` and
`InferRouterErrors`, one lookup per procedure each | 953,314 → 726,737
(−23.8%) | 192,260 → 183,245 (−4.7%) |
| Root router passed through `unlazyRouter()`, then read by a typed
client call per procedure | 1,168,031 → 1,112,523 (−4.8%) | 253,867 →
250,863 (−1.2%) |
`InferRouterError` has the same shape as `InferRouterErrors` and is
changed the same way, but I did not build a separate workload for it.
This is independent of #2451,
#2452 and
#2453.
## Behavior
No difference from `main`. I compared the old and new definitions of all
seven types directly on procedures, nested routers, lazy routers and
procedures, keys typed as `Lazyable<...>`, optional and readonly keys,
`os.router()` output, `AnyRouter`, `any` and `never`: all resolve to
identical types.
Emitted declarations are unchanged too. A consumer installed from packed
tarballs (pnpm, depending only on `@orpc/server`) and built with
`composite: true`, including generic code that takes a router as a type
parameter, emits a `.d.ts` byte-identical to the one built against
`main`, on TypeScript 7.0.2, 6.0.3 and 5.9.3.
## Tests
`router.test-d.ts` and `router-utils.test-d.ts` now cover a key typed as
`Lazy<...>` and a key typed as `Lazyable<...>` (a router or its lazy
form) for all seven types. The `Lazyable` cases are the reason the
fallback stays `Lazyable<infer U>`: with `Lazy<infer U>` there, each of
the seven types fails its `Lazyable` case and nothing else does. The new
tests also pass against the definitions on `main`.
## Verification
`pnpm check`, `pnpm test` (4,585 tests) and `pnpm docs:validate` pass.
The first `pnpm test` run had two failures in `packages/bun` (`cancel
and abort: bun-fetch`), which are runtime timing tests this type-only
change cannot reach; they passed in three separate re-runs and in a
second full run.
After adding the tests I re-ran `pnpm check`, the root type-check and
the `packages/server` router tests, not the full suite.
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
RouterClientused to infer every key through theProcedureclass and theLazyableunion. Two changes make it cheaper:~orpcdefinition instead of theProcedureclass.TRouter[K] extends AnyRouter, which has noinfer. Only lazy keys fall through to the originalLazyable<infer U>inference.RouterClientkeeps its signature and still recurses on itself, so there is no new helper type and nothing new to export.Measurements
Measured with the
typecheckproject of orpc-benchmarks (3,000 procedures plus a typed client call for each),tsc --singleThreaded --extendedDiagnostics, TypeScript 7.0.2. "Before" is the published2.0.0-beta.50, "after" is@orpc/serverbuilt from this branch. These counts are deterministic.Schema<I, O>typeThis is independent of #2451. With both applied, the benchmark goes from 1,040,001 to 770,912 instantiations (−25.9%).
Why
ProcedureDefinitionand notProcedureMatching
TRouter extends Procedure<any, any, infer ..., infer ..., infer ...>also works, but costs 39,024 more instantiations on the benchmark (937,493 instead of 898,469, so −9.9% instead of −13.6%)..handler()returns aDecoratedProcedure, a different class fromProcedure, so TypeScript compares the two classes structurally for every procedure. Matching{ '~orpc': ProcedureDefinition<...> }compares the same interface on both sides, by its type arguments. As a check, when.handler()is made to return a plainProcedure, the gap shrinks from 39,024 to 9,018.Behavior
No difference from
main. I compared the old and new definitions directly on procedures, nested routers, lazy routers and procedures, keys typed asLazyable<...>, optional and readonly keys,os.router()output,AnyRouter,anyandnever: all resolve to identical types.Emitted declarations are unchanged too. A consumer installed from packed tarballs (pnpm, depending only on
@orpc/server) and built withcomposite: true, including generic code that takes a router as a type parameter, emits a.d.tsbyte-identical to the one built againstmain, on TypeScript 7.0.2, 6.0.3 and 5.9.3.History of this branch
An earlier version moved the recursion into a helper type,
RouterClientInner. That needed an export: without it, generic consumer code made TypeScript unroll the recursive type into the emitted.d.ts(588 lines instead of 104). The current version is faster than the helper version (898,469 instead of 910,989) and avoids the question, so the helper is gone.Verification
pnpm checkandpnpm docs:validatepass. The fullpnpm test(4,585 tests) passed on the first commit; after the later commits I re-ran the@orpc/servertests (670 pass).Lazyablekeys, an optional key,createRouterClientwith an untyped router) also pass onmain, so they describe behavior this PR keeps.🤖 Generated with Claude Code
https://claude.ai/code/session_01VVaw7SLCp5Vav859sAFS6N