Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
Add nestjs-trpc skill
Lewis Carhart0ed6c3031e90
diff --git a/.agents/skills/nestjs-trpc/SKILL.md b/.agents/skills/nestjs-trpc/SKILL.mdnew file mode 100644index 00000000..d95b0a35--- /dev/null+++ b/.agents/skills/nestjs-trpc/SKILL.md@@ -0,0 +1,268 @@+---+name: nestjs-trpc+description: Build end-to-end type-safe tRPC APIs inside NestJS using the nestjs-trpc adapter — @Router/@Query/@Mutation/@Subscription decorators, TRPCModule.forRoot, injectable middlewares and context, Zod input/output schemas, and the Rust CLI that generates the AppRouter type for clients. Use this skill whenever the user mentions nestjs-trpc, tRPC in a NestJS app, @Router or @Query decorators, TRPCModule, AppRouterHost, "typed API between my Nest backend and frontend", generating AppRouter types, or is migrating a NestJS GraphQL/REST API to tRPC — even if they don't name the library explicitly.+license: MIT+metadata:+ version: "1.0.0"+ targets: "nestjs-trpc v2.x (verified against 2.13.0)"+ docs: "https://nestjs-trpc.io/docs"+---++# NestJS-tRPC++`nestjs-trpc` lets you define tRPC procedures as decorated NestJS classes instead of+chaining `t.procedure` builders. Routers are DI-aware classes that look like controllers;+a separate CLI reads those decorators and emits an `AppRouter` type for the client.++**Verified against v2.13.0.** The published docs at nestjs-trpc.io still contain v1-era+examples in several places. Where this skill and the docs disagree, this skill matches the+shipped `.d.ts` files and the official `examples/` in the repo — see+[Docs errata](#docs-errata) for the specific traps.++## The one thing to internalize++There are **two separate systems** that both need to be correct, and they fail+independently:++| | Runtime | Type generation |+|---|---|---|+| Driven by | Nest DI container at boot | Rust CLI doing static analysis of your source |+| Needs | classes listed in `providers` | decorators it can read literally |+| Fails as | 404 / "no procedures" / undefined injection | stale or missing `AppRouter` |++A router that works at runtime but was never picked up by the CLI produces a client with no+types, and vice versa. When something is wrong, first ask *which of the two* is broken.++## Setup workflow++### 1. Install++```shell+npm install nestjs-trpc zod @trpc/server+```++Peer deps (v2.13.0): `@nestjs/common` & `@nestjs/core` ^9.3.8 || ^10 || ^11,+`@trpc/server` ^11, `zod` ^3.14 || ^4, `rxjs` 7.8.1, `reflect-metadata` ^0.1.13 || ^0.2.+tRPC **v11 is required** — v10 will not work.++Standard NestJS `tsconfig.json` requirements apply: `experimentalDecorators: true`,+`emitDecoratorMetadata: true`. `tsc` must be resolvable, because the CLI shells out to it+to typecheck what it generates.++### 2. Register the module++```typescript+// app.module.ts+import { Module } from '@nestjs/common';+import { TRPCModule } from 'nestjs-trpc';+import { UserRouter } from './user.router';+import { UserService } from './user.service';+import { ProtectedMiddleware } from './protected.middleware';+import { AppContext } from './app.context';++@Module({+ imports: [+ TRPCModule.forRoot({+ context: AppContext,+ }),+ ],+ providers: [UserRouter, AppContext, UserService, ProtectedMiddleware],+})+export class AppModule {}+```++Routers, middlewares, and the context class are all **ordinary providers**. Listing them in+`providers` is what makes DI work — forgetting a router here is the single most common+reason procedures silently don't exist at runtime.++Default mount point is `/trpc`; override with `basePath`. Full option table in+[references/module-config.md](references/module-config.md).++### 3. Write a router++```typescript+// user.router.ts+import { Inject } from '@nestjs/common';+import { Router, Query, Mutation, UseMiddlewares, Input, Ctx } from 'nestjs-trpc';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';+import { UserService } from './user.service';+import { ProtectedMiddleware } from './protected.middleware';+import { userSchema, type User } from './user.schema';++@Router({ alias: 'users' })+export class UserRouter {+ constructor(@Inject(UserService) private readonly userService: UserService) {}++ @Query({+ input: z.object({ userId: z.string() }),+ output: userSchema,+ })+ @UseMiddlewares(ProtectedMiddleware)+ async getUserById(@Input('userId') userId: string): Promise<User> {+ const user = await this.userService.getUser(userId);++ if (user == null) {+ throw new TRPCError({ message: 'Could not find user.', code: 'NOT_FOUND' });+ }++ return user;+ }+}+```++Client call site: `trpc.users.getUserById.query({ userId })`. The `alias` sets that first+segment — without it the class name is used.++### 4. Generate the client type++```shell+npx nestjs-trpc generate # one-shot+npx nestjs-trpc watch # regenerate on change during development+```++Writes `server.ts` (containing `export type AppRouter = typeof appRouter`) to+`./src/@generated` by default; `--output <dir>` moves it. This is a **build step, not a+runtime import** — the generated file is types only, and your procedures still execute+through the Nest-managed router at runtime.++Add it to your scripts so it can't drift:++```json+{+ "scripts": {+ "dev": "nestjs-trpc watch & nest start --watch",+ "build": "nestjs-trpc generate && nest build"+ }+}+```++Run `nestjs-trpc generate --dry-run` in CI to fail the build when the committed types are+stale.++## Writing procedures++Three procedure decorators, all taking `{ input?, output?, meta? }`, all optional:++| Decorator | tRPC equivalent |+|---|---|+| `@Query()` | `publicProcedure.query()` |+| `@Mutation()` | `publicProcedure.mutation()` |+| `@Subscription()` | `publicProcedure.subscription()` |++`input` validates and types the incoming payload. `output` is optional — omit it and the+return type is inferred from the method signature (since v2.11.0). Prefer an explicit+`output` on anything crossing a trust boundary, because it strips fields the client+shouldn't see; a leaked `password` column is the classic version of this bug. Note the+example schema above deliberately keeps `password` in `userSchema` only to mirror the+upstream docs — in real code, define a separate public-facing schema.++Any Standard Schema validator works (Zod, Valibot, ArkType, Yup, Superstruct), but **the+CLI's schema flattening is built around Zod** — stay on Zod unless you have a reason not to.++Parameter decorators pull pieces out of the tRPC `opts` object:++| Decorator | Yields |+|---|---|+| `@Input(key?)` | `opts.input`, or `opts.input[key]` |+| `@Ctx()` | `opts.ctx` |+| `@Options()` | the whole `opts` (typed as `ProcedureOptions`) |+| `@RawInput()` | `opts.rawInput` (pre-validation) |+| `@Type()` | `'query' \| 'mutation' \| 'subscription'` |+| `@Path()` | the procedure path string |++Throw `TRPCError` from `@trpc/server` for client-visible failures. Nest's `HttpException`+is not translated into a tRPC error shape, so it surfaces as an opaque 500.++Details, subscription patterns, and router merging: [references/routers.md](references/routers.md).++## Middlewares and context++Middlewares are `@Injectable()` classes implementing `TRPCMiddleware`, applied with+`@UseMiddlewares(...)` on a class (all procedures) or a method (that one only), or globally+via `globalMiddlewares`. Execution order is global → router → procedure → handler.++```typescript+@Injectable()+export class ProtectedMiddleware implements TRPCMiddleware {+ constructor(@Inject(UserService) private readonly userService: UserService) {}++ async use(opts: MiddlewareOptions<object>): Promise<MiddlewareResponse> {+ const result = await opts.next({ ctx: { user: await this.userService.current() } });+ return result;+ }+}+```++Two rules that cause most middleware bugs: always `return` the result of `next()` so the+chain isn't swallowed, and pass added context *through* `next({ ctx })` rather than mutating+`opts.ctx` in place.++Context is a class implementing `TRPCContext` with a `create(opts)` method, registered in+`providers` and passed to `forRoot({ context })`. It runs once per request and is the right+home for the request object, session, and per-request loaders.++Full treatment including typing context across a middleware chain and procedure `meta`:+[references/middlewares-and-context.md](references/middlewares-and-context.md).++## Recommended file layout++Mirrors NestJS conventions, which is the whole point of the adapter:++```+src+├── app.module.ts+├── app.context.ts+├── main.ts+├── @generated/ # CLI output — gitignore or commit, but be consistent+└── user/+ ├── user.router.ts # the "controller" — thin, no business logic+ ├── user.service.ts # business logic, unit-testable without tRPC+ ├── user.schema.ts # Zod schemas + inferred types, shared by both+ └── protected.middleware.ts+```++Keep routers thin. A router method that only validates, delegates to a service, and maps+errors stays testable and keeps the CLI's job easy.++## Docs errata++The official docs mix v1 and v2 content. These are the ones that will actually break your+build:++- **`@Ctx()`, not `@Context()`.** The routers and middlewares pages show `@Context()`; the+ exported decorator is `Ctx`. (`Context` as an identifier does exist in the docs' prose as+ a *type* name, which is where the confusion comes from.)+- **`MiddlewareOptions`, not `TRPCMiddlewareOptions`.** The latter is not exported.+- **`TRPCMiddleware<TMeta>` — the single generic is the meta type, not the context type.**+ The docs' `implements TRPCMiddleware<Context>` is wrong. Context types are supplied via+ `MiddlewareOptions<TContext, TReturnContext, TMeta>` on the `use()` signature.+- **`autoSchemaFile` and `schemaFileImports` are v1 options.** They are absent from the v2+ `TRPCModuleOptions` type and will be TypeScript errors, even though the context, client,+ and integrations pages still show `autoSchemaFile`. Control output with the CLI's+ `--output` flag instead.+- **`nestjs-trpc/types` is a v1 import path.** v1's ts-morph generator wrote helper types+ (`Context`, `{Middleware}Context`) into the package; v2's Rust CLI emits a single+ `server.ts` instead. Don't import from `nestjs-trpc/types` on v2 — declare your context+ types yourself.+- **`@Middlewares()` is deprecated** in favour of `@UseMiddlewares()`, to match `@UseGuards`.+- The middlewares page's first example has a literal typo (`constructror`) and a missing+ `async`. Don't copy it verbatim.++## Reference files++Read these when the task goes past the basics:++- **[references/routers.md](references/routers.md)** — procedure and parameter decorators in+ full, subscriptions/SSE with `AbortSignal` cleanup, alias merging, error handling,+ testing routers.+- **[references/middlewares-and-context.md](references/middlewares-and-context.md)** —+ `MiddlewareOptions` generics, context propagation and typing, `meta`-driven authorization,+ global middleware ordering.+- **[references/module-config.md](references/module-config.md)** — every `forRoot` option,+ SSE and JSONL keep-alive settings, `onError` handlers, custom loggers, transformers.+- **[references/codegen-and-client.md](references/codegen-and-client.md)** — CLI flags,+ ESM `--import-extension`, schema-flattening failures, consuming `AppRouter` from React /+ Next.js / vanilla clients, `AppRouterHost` for e2e tests and trpc-ui.+- **[references/api-reference.md](references/api-reference.md)** — exact exported symbols and+ type signatures transcribed from the shipped `.d.ts`. Check here before guessing a name.diff --git a/.agents/skills/nestjs-trpc/references/api-reference.md b/.agents/skills/nestjs-trpc/references/api-reference.mdnew file mode 100644index 00000000..5dc130ab--- /dev/null+++ b/.agents/skills/nestjs-trpc/references/api-reference.md@@ -0,0 +1,313 @@+# API Reference++Every public symbol exported from `nestjs-trpc`, transcribed from the shipped `.d.ts` files+at **v2.13.0**. When a name is in doubt, this file is authoritative over the published docs —+several documented identifiers don't exist.++Contents:+- [Export surface](#export-surface)+- [Class decorators](#class-decorators)+- [Method decorators](#method-decorators)+- [Parameter decorators](#parameter-decorators)+- [Module](#module)+- [Context types](#context-types)+- [Middleware types](#middleware-types)+- [Error handler types](#error-handler-types)+- [Procedure and parser types](#procedure-and-parser-types)+- [Streaming option types](#streaming-option-types)+- [`AppRouterHost`](#approuterhost)+- [Names the docs use that do not exist](#names-the-docs-use-that-do-not-exist)++## Export surface++`nestjs-trpc` re-exports from four barrels:++```typescript+export * from './trpc.module';+export * from './interfaces';+export * from './decorators';+export * from './app-router.host';+```++Everything below is importable directly from `'nestjs-trpc'`. The package also declares a+`nestjs-trpc/config` subpath export, which is not part of the documented API.++## Class decorators++```typescript+function Router(args?: { alias?: string }): ClassDecorator;+```++```typescript+function UseMiddlewares(+ ...middlewares: Array<Class<TRPCMiddleware> | Constructor<TRPCMiddleware>>+): MethodDecorator & ClassDecorator;++/** @deprecated Use `UseMiddlewares` instead. */+function Middlewares(+ ...middlewares: Array<Class<TRPCMiddleware> | Constructor<TRPCMiddleware>>+): MethodDecorator & ClassDecorator;+```++## Method decorators++All three share one argument shape:++```typescript+function Query(args?: {+ input?: Parser;+ output?: Parser;+ meta?: Record<string, unknown>;+}): MethodDecorator;++function Mutation(args?: {+ input?: Parser;+ output?: Parser;+ meta?: Record<string, unknown>;+}): MethodDecorator;++function Subscription(args?: {+ input?: Parser;+ output?: Parser;+ meta?: Record<string, unknown>;+}): MethodDecorator;+```++## Parameter decorators++```typescript+function Ctx(): ParameterDecorator;+function Input(key?: string): ParameterDecorator;+function Options(): ParameterDecorator;+function RawInput(): ParameterDecorator;+function Type(): ParameterDecorator;+function Path(): ParameterDecorator;+```++The context decorator is **`Ctx`**. There is no exported `Context` decorator.++## Module++```typescript+export declare class TRPCModule implements NestModule, OnModuleInit {+ static forRoot(options?: TRPCModuleOptions): DynamicModule;+ configure(_consumer: MiddlewareConsumer): Promise<void>;+ onModuleInit(): Promise<void>;+}+```++```typescript+export interface TRPCModuleOptions {+ basePath?: string;+ context?: Class<TRPCContext>;+ errorFormatter?: TRPCErrorFormatter<any, TRPCDefaultErrorShape>;+ transformer?: DataTransformer | CombinedDataTransformer;+ logger?: LoggerService;+ onError?: Class<TRPCErrorHandler>;+ globalMiddlewares?: Array<Class<TRPCMiddleware> | Constructor<TRPCMiddleware>>;+ sse?: TRPCSSEOptions;+ jsonl?: TRPCJSONLOptions;+}+```++No `forRootAsync`.++## Context types++```typescript+export type ContextOptions =+ | CreateExpressContextOptions+ | CreateFastifyContextOptions;++export interface TRPCContext {+ create(+ opts: ContextOptions,+ ): Record<string, unknown> | Promise<Record<string, unknown>>;+}+```++## Middleware types++```typescript+export type MiddlewareResponse = Promise<+ | { ok: true; data: unknown }+ | { ok: false; error: unknown }+>;++export type MiddlewareOptions<+ TContext extends object = object,+ TReturnContext = Record<string, unknown>,+ TMeta = unknown,+> = {+ ctx: TContext;+ type: TRPCProcedureType;+ path: string;+ input: unknown;+ getRawInput: () => Promise<unknown>;+ meta: TMeta;+ signal: AbortSignal | undefined;+ next: (opts?: { ctx?: TReturnContext }) => MiddlewareResponse;+};++export interface TRPCMiddleware<TMeta = unknown> {+ use(+ opts: MiddlewareOptions<object, Record<string, unknown>, TMeta>,+ ): MiddlewareResponse | Promise<MiddlewareResponse>;+}+```++The single generic on `TRPCMiddleware` is the **meta** type.++## Error handler types++```typescript+export interface OnErrorOptions {+ error: TRPCError;+ type: TRPCProcedureType | 'unknown';+ path: string | undefined;+ input: unknown;+ ctx: Record<string, unknown> | undefined;+ req: unknown;+}++export interface TRPCErrorHandler {+ onError(opts: OnErrorOptions): void;+}+```++## Procedure and parser types++```typescript+export type ProcedureOptions = {+ ctx: unknown;+ input: unknown;+ type: string;+ path: string;+ rawInput: unknown;+ signal: AbortSignal | undefined;+};+```++`Parser` is a union covering Standard Schema v1 and the common validator shapes:++```typescript+export type Parser =+ | ParserWithInputOutput<any, any> // Zod, Valibot, ArkType, Standard Schema v1+ | ParserWithoutInput<any>; // custom fn, my-zod, scale, superstruct, yup+```++Inlined from `@trpc/server` to avoid depending on its unstable internals.++Also exported from `factory.interface`, mostly internal but occasionally useful:++```typescript+export declare enum ProcedureParamDecoratorType {+ Options = 'options',+ Ctx = 'ctx',+ Input = 'input',+ RawInput = 'rawInput',+ Type = 'type',+ Path = 'path',+}++export interface RouterInstance {+ name: string;+ instance: unknown;+ middlewares: Array<Class<TRPCMiddleware> | Constructor<TRPCMiddleware>>;+ alias?: string;+}++export interface ProcedureFactoryMetadata {+ type: ProcedureType;+ input: Parser | undefined;+ output: Parser | undefined;+ meta: Record<string, unknown> | undefined;+ middlewares: Array<Constructor<TRPCMiddleware> | Class<TRPCMiddleware>>;+ name: string;+ implementation: ProcedureImplementation;+ params: Array<ProcedureParamDecorator> | undefined;+}++export type TRPCRouter = <TProcRouterRecord extends TRPCRouterRecord>(+ procedures: TProcRouterRecord,+) => AnyRouter;++export type TRPCPublicProcedure = TRPCProcedureBuilder<any, any, any, any, any, any, any, any>;+```++## Streaming option types++```typescript+export interface TRPCSSEOptions {+ enabled?: boolean; // default true+ ping?: {+ enabled: boolean; // default false+ intervalMs?: number; // default 1000+ };+ maxDurationMs?: number; // default undefined+ emitAndEndImmediately?: boolean; // default false+ client?: {+ reconnectAfterInactivityMs?: number; // default undefined+ };+}++export interface TRPCJSONLOptions {+ pingMs?: number; // default undefined+}+```++## `AppRouterHost`++```typescript+export declare class AppRouterHost {+ set appRouter(schemaRef: AnyRouter);+ get appRouter(): AnyRouter;+}+```++The getter throws before the app is initialised.++## Names the docs use that do not exist++| In the docs | Actual |+|---|---|+| `@Context()` parameter decorator | `@Ctx()` |+| `TRPCMiddlewareOptions` | `MiddlewareOptions` |+| `TRPCMiddleware<Context>` (context as generic) | `TRPCMiddleware<TMeta>`; context goes on `MiddlewareOptions<TContext, …>` |+| `autoSchemaFile` module option | removed in v2 — use the CLI's `--output` |+| `schemaFileImports` module option | removed in v2 |+| `import … from 'nestjs-trpc/types'` | v1 only — v2 emits `server.ts`; declare context types yourself |+| `@Middlewares()` | deprecated alias of `@UseMiddlewares()` |++## Peer dependencies at v2.13.0++```json+{+ "@nestjs/common": "^9.3.8 || ^10.0.0 || ^11.0.0",+ "@nestjs/core": "^9.3.8 || ^10.0.0 || ^11.0.0",+ "@trpc/server": "^11.0.0",+ "zod": "^3.14.0 || ^4.0.0",+ "rxjs": "7.8.1",+ "reflect-metadata": "^0.1.13 || ^0.2.0"+}+```++CLI binaries ship for darwin x64/arm64, linux x64/arm64 (gnu), and win32 x64.++## Version landmarks++Useful when reading issues or deciding whether an upgrade is needed:++| Version | Change |+|---|---|+| 2.0.1 | Rust CLI replaces the ts-morph generator; watch mode |+| 2.1.0 | procedure `meta` support |+| 2.2.0 | custom logger |+| 2.3.0 | importability-aware schema flattening |+| 2.4.0 | routers sharing an `alias` are merged |+| 2.5.0 | transformer auto-detection during generation |+| 2.8.0 | global middlewares, `@Subscription`, injectable error handler |+| 2.9.0 | Zod 4 support; `TReturnContext` generic on `MiddlewareOptions` |+| 2.11.0 | output type inferred from resolver return type; NestJS 11 |+| 2.12.0 | ESM import-extension auto-detection from tsconfig |+| 2.13.0 | `sse` and `jsonl` options on `forRoot` |diff --git a/.agents/skills/nestjs-trpc/references/codegen-and-client.md b/.agents/skills/nestjs-trpc/references/codegen-and-client.mdnew file mode 100644index 00000000..b003947b--- /dev/null+++ b/.agents/skills/nestjs-trpc/references/codegen-and-client.md@@ -0,0 +1,285 @@+# Code Generation and Client Usage++Contents:+- [What the CLI does](#what-the-cli-does)+- [Commands and flags](#commands-and-flags)+- [Wiring codegen into your scripts](#wiring-codegen-into-your-scripts)+- [ESM and `--import-extension`](#esm-and---import-extension)+- [When schema flattening fails](#when-schema-flattening-fails)+- [Consuming `AppRouter` on the client](#consuming-approuter-on-the-client)+- [Sharing the type across a monorepo](#sharing-the-type-across-a-monorepo)+- [`AppRouterHost`](#approuterhost)+- [E2E testing with AppRouterHost](#e2e-testing-with-approuterhost)+- [trpc-ui and other integrations](#trpc-ui-and-other-integrations)++## What the CLI does++`nestjs-trpc` ships a Rust binary (since v2.0.1) that statically analyses your source,+finds classes decorated with `@Router`, reads their `@Query`/`@Mutation`/`@Subscription`+decorators, inlines the referenced Zod schemas, and writes a `server.ts` ending in:++```typescript+export type AppRouter = typeof appRouter;+```++That file is **types only**. Nothing in it executes at runtime — your procedures still run+through the Nest-managed router. Its only job is to give the client something to infer+against.++Two consequences follow from it being static analysis rather than reflection:++- The CLI never boots your app. It doesn't need a database, environment variables, or a+ successful `NestFactory.create()`.+- It only sees what it can read literally. A schema assembled by a function call at runtime,+ or a router registered dynamically, is invisible to it.++The generator locates your entrypoint automatically — checking `package.json` `source`/`main`+fields, then `src/main.ts`, `src/app.module.ts`, `lib/main.ts`, `lib/app.module.ts`,+`app.module.ts`, `main.module.ts` — and reads configuration out of the `TRPCModule.forRoot()`+call it finds. It also invokes `tsc --noEmit` to typecheck the result, so **`tsc` must be+resolvable** or generation fails with "TypeScript compiler (tsc) not found."++## Commands and flags++```shell+npx nestjs-trpc generate # one-shot generation+npx nestjs-trpc watch # regenerate on file change+npx nestjs-trpc --version+```++`generate` options:++| Flag | Purpose |+|---|---|+| `-e, --entrypoint <PATH>` | Path to the Nest module entrypoint. Auto-discovered if omitted. |+| `-r, --router-pattern <PATTERN>` | Glob for locating router files. |+| `-o, --output <PATH>` | Output directory. Default `./src/@generated`. |+| `--import-extension <js\|none\|auto>` | Whether to append `.js` to local imports. Default `auto`. |+| `--dry-run` | Validate and report without writing. |+| `--json` | Machine-readable output, for tooling and CI. |+| `-v`, `-vv`, `-vvv` | Increasing verbosity (info, debug, trace). |+| `--debug` | Full debug output with file locations, for bug reports. |++Use `-vv` when generation succeeds but a procedure is missing — the debug log names each+router file it found and each procedure it extracted, which usually identifies the one it+skipped.++## Wiring codegen into your scripts++The generated type is a build artifact that can silently go stale. Make that impossible:++```json+{+ "scripts": {+ "dev": "nestjs-trpc watch & nest start --watch",+ "build": "nestjs-trpc generate && nest build",+ "typecheck:trpc": "nestjs-trpc generate --dry-run --json"+ }+}+```++Whether you commit `src/@generated` is a real decision, not a detail:++- **Commit it** if the frontend is a separate repo, or if anything consumes the types+ without running the backend's build. The cost is merge conflicts on the generated file.+- **Gitignore it** if everything lives in one repo and the build always regenerates. Then+ add `nestjs-trpc generate --dry-run` to CI so a PR that changes a router without+ regenerating still fails loudly.++Pick one and be consistent — the failure mode of "sometimes committed" is a client typed+against a router that no longer exists, which typechecks fine and 404s at runtime.++## ESM and `--import-extension`++Node ESM requires explicit `.js` extensions on relative imports. The default `auto` reads+your nearest `tsconfig.json` and enables extensions when `module` or `moduleResolution` is+`NodeNext`/`Node16`.++There's a documented gap: projects on `moduleResolution: bundler` (e.g.+`module: ESNext` + `moduleResolution: bundler`) that nonetheless run on plain Node ESM+**still need the extensions at runtime**, but `auto` reports `false` because bundler mode+doesn't require them at compile time. The symptom is `ERR_MODULE_NOT_FOUND` at startup with+everything typechecking cleanly. Fix it explicitly:++```shell+npx nestjs-trpc generate --import-extension=js+```++CommonJS projects want `none`, which `auto` will infer correctly.++## When schema flattening fails++The generator inlines your Zod schemas into `server.ts`. When a schema references something+it can't inline, it tries to add a relative import instead. That resolution can fail —+typically for schemas from an external package, behind a path alias, or built by a helper+function.++Signals: "Maximum recursion depth reached during schema flattening", an unresolved import in+the generated file, or a procedure typed as `any`.++Fixes, in order of preference:++1. **Define schemas as top-level `const`s in files the CLI scans**, and import them into the+ router by relative path. This is the path the tool is designed for.+2. **Avoid runtime-computed schemas** in decorators. `input: makeSchema(opts)` cannot be+ read statically; `input: z.object({ ... })` or a reference to a module-scope const can.+3. **Watch recursion.** Deeply self-referential Zod schemas (`z.lazy` trees) can blow the+ flattening depth limit. Break the cycle by extracting a sub-schema.+4. Use `-vv` to see exactly which schema it choked on.++Zod 4 is supported (since v2.9.0), as is Zod 3. Other Standard Schema validators satisfy the+`Parser` type at compile time, but the flattening logic is Zod-oriented — expect rougher+edges elsewhere.++## Consuming `AppRouter` on the client++Import the generated type — and only the type:++```typescript+import type { AppRouter } from '../../server/src/@generated/server';+```++**Vanilla client:**++```typescript+import { createTRPCClient, httpBatchLink } from '@trpc/client';+import type { AppRouter } from './generated/server';++const trpc = createTRPCClient<AppRouter>({+ links: [httpBatchLink({ url: 'http://localhost:8080/trpc' })],+});++const user = await trpc.users.getUserById.query({ userId: '1' });+const created = await trpc.users.createUser.mutate({ name: 'Jane' });+```++The `users` segment is the router's `alias`. The `url` must match `basePath` plus any Nest+global prefix.++**React Query:** https://trpc.io/docs/client/react+**Next.js:** https://trpc.io/docs/client/nextjs+**Vanilla:** https://trpc.io/docs/client/vanilla++If you configured a `transformer` on the module, configure the identical one on the client.++For subscriptions, the client needs a link that can stream — `httpSubscriptionLink` for SSE,+usually combined with `splitLink` so only subscriptions take that path.++Import with `import type`, not a plain `import`. A value import of a server-side file will+drag server code into the client bundle, and in a monorepo that's how database drivers end+up in browser builds.++## Sharing the type across a monorepo++In a Turborepo/pnpm-workspaces setup, point the CLI's output at a shared package:++```shell+nestjs-trpc generate --output ../../packages/api-types/src+```++Then have the frontend depend on `@repo/api-types` and re-export `AppRouter` from its index.+This beats deep relative paths into the backend's `src`, because it keeps the dependency+explicit in `package.json` and lets the type-generation step be a proper task in the+dependency graph:++```json+{+ "tasks": {+ "generate:trpc": { "outputs": ["../../packages/api-types/src/**"] },+ "build": { "dependsOn": ["^build", "generate:trpc"] }+ }+}+```++## `AppRouterHost`++For runtime access to the actual `appRouter` object:++```typescript+export declare class AppRouterHost {+ set appRouter(schemaRef: AnyRouter);+ get appRouter(): AnyRouter;+}+```++```typescript+const { appRouter } = app.get(AppRouterHost);+```++The getter throws if read before the app is initialised. The router is assembled during+`onModuleInit`, so call it after `app.listen()` or `app.init()` — or from your own+`onModuleInit`, which is what the trpc-ui controller below does.++## E2E testing with AppRouterHost++`AppRouterHost` gives you the real router, so you can exercise the full pipeline —+validation, middlewares, context — without HTTP:++```typescript+const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();+const app = moduleRef.createNestApplication();+await app.init(); // required before reading appRouter++const { appRouter } = app.get(AppRouterHost);+const caller = appRouter.createCaller({ auth: { userId: 'test-user' } });++const user = await caller.users.getUserById({ userId: '1' });+```++The object you pass to `createCaller` replaces your context class's output, so it must+satisfy whatever your middlewares and procedures read off `ctx`. That's the trade: you skip+the transport, but you take responsibility for constructing a realistic context. If your+context is split inner/outer, reuse the inner one here.++## trpc-ui and other integrations++Anything that accepts a vanilla tRPC router works — `trpc-ui`, `trpc-openapi`,+`trpc-playground`. Get the router from `AppRouterHost` and hand it over.++```shell+npm install trpc-ui+```++```typescript+// trpc-panel.controller.ts+import { All, Controller, Inject, OnModuleInit } from '@nestjs/common';+import { renderTrpcPanel } from 'trpc-ui';+import { AnyRouter } from '@trpc/server';+import { AppRouterHost } from 'nestjs-trpc';++@Controller()+export class TrpcPanelController implements OnModuleInit {+ private appRouter!: AnyRouter;++ constructor(+ @Inject(AppRouterHost) private readonly appRouterHost: AppRouterHost,+ ) {}++ onModuleInit() {+ this.appRouter = this.appRouterHost.appRouter;+ }++ @All('/panel')+ panel(): string {+ return renderTrpcPanel(this.appRouter, { url: 'http://localhost:8080/trpc' });+ }+}+```++```typescript+@Module({+ imports: [TRPCModule.forRoot({ context: AppContext })],+ controllers: [TrpcPanelController],+})+export class AppModule {}+```++Reading `appRouter` in `onModuleInit` rather than the constructor is what keeps this legal —+the router doesn't exist yet at construction time.++The panel then serves at `/panel`. It exposes your entire API surface with a call interface,+so gate it behind an environment check before this reaches production:++```typescript+controllers: process.env.NODE_ENV !== 'production' ? [TrpcPanelController] : [],+```diff --git a/.agents/skills/nestjs-trpc/references/middlewares-and-context.md b/.agents/skills/nestjs-trpc/references/middlewares-and-context.mdnew file mode 100644index 00000000..3e670f86--- /dev/null+++ b/.agents/skills/nestjs-trpc/references/middlewares-and-context.md@@ -0,0 +1,351 @@+# Middlewares and Context++Contents:+- [Middleware anatomy](#middleware-anatomy)+- [The `MiddlewareOptions` generics](#the-middlewareoptions-generics)+- [Applying middlewares](#applying-middlewares)+- [Execution order](#execution-order)+- [Extending the context from a middleware](#extending-the-context-from-a-middleware)+- [Procedure `meta` for authorization](#procedure-meta-for-authorization)+- [Context classes](#context-classes)+- [Typing context on v2](#typing-context-on-v2)++## Middleware anatomy++A middleware is an `@Injectable()` class implementing `TRPCMiddleware`, with a single+`use()` method. It's the tRPC analogue of a Nest guard or interceptor, and it can do both+jobs: reject a request, or wrap it and observe the result.++```typescript+import {+ MiddlewareOptions,+ MiddlewareResponse,+ TRPCMiddleware,+} from 'nestjs-trpc';+import { Inject, Injectable, ConsoleLogger } from '@nestjs/common';++@Injectable()+export class LoggedMiddleware implements TRPCMiddleware {+ constructor(+ @Inject(ConsoleLogger) private readonly logger: ConsoleLogger,+ ) {}++ async use(opts: MiddlewareOptions<object>): Promise<MiddlewareResponse> {+ const start = Date.now();+ const { next, path, type } = opts;++ const result = await next();++ const durationMs = Date.now() - start;+ const meta = { path, type, durationMs };++ result.ok+ ? this.logger.log('OK request timing:', meta)+ : this.logger.error('Non-OK request timing', meta);++ return result;+ }+}+```++Register it in the module's `providers` array like any other provider. Without that, DI+can't construct it.++Two mistakes account for most middleware bugs:++1. **Not returning `next()`'s result.** `use()` must return the `MiddlewareResponse`. Drop+ it and the chain terminates with an undefined result — the procedure appears to hang or+ return nothing, with no error pointing at the middleware.+2. **Assuming `next()` throws on failure.** It doesn't. It resolves to a discriminated union+ — `{ ok: true, data }` or `{ ok: false, error }`. Inspect `result.ok`; a bare `try/catch`+ around `next()` will not see procedure errors.++Note the upstream docs' first middleware example contains a typo (`constructror`) and omits+`async` on a method that awaits. Use the shape above.++## The `MiddlewareOptions` generics++```typescript+export type MiddlewareResponse = Promise<+ | { ok: true; data: unknown }+ | { ok: false; error: unknown }+>;++export type MiddlewareOptions<+ TContext extends object = object,+ TReturnContext = Record<string, unknown>,+ TMeta = unknown,+> = {+ ctx: TContext;+ type: TRPCProcedureType;+ path: string;+ input: unknown;+ getRawInput: () => Promise<unknown>;+ meta: TMeta;+ signal: AbortSignal | undefined;+ next: (opts?: { ctx?: TReturnContext }) => MiddlewareResponse;+};++export interface TRPCMiddleware<TMeta = unknown> {+ use(+ opts: MiddlewareOptions<object, Record<string, unknown>, TMeta>,+ ): MiddlewareResponse | Promise<MiddlewareResponse>;+}+```++The generic positions matter and the docs get them wrong:++- **`TRPCMiddleware<T>` — `T` is the *meta* type**, not the context type. The docs' snippet+ `implements TRPCMiddleware<Context>` is incorrect. If your middleware reads `opts.meta`,+ that's what the class-level generic is for.+- **Context types go on `MiddlewareOptions`**: `TContext` is what you receive, `TReturnContext`+ is what you're allowed to pass to `next({ ctx })`.+- The exported type is **`MiddlewareOptions`**. `TRPCMiddlewareOptions`, used on the+ middlewares docs page, does not exist.+- `signal` is available here too, so a middleware can bail out early on a disconnected+ client.++## Applying middlewares++`@UseMiddlewares()` is both a method and a class decorator:++```typescript+export declare function UseMiddlewares(+ ...middlewares: Array<Class<TRPCMiddleware> | Constructor<TRPCMiddleware>>+): MethodDecorator & ClassDecorator;+```++```typescript+@Router({ alias: 'admin' })+@UseMiddlewares(AuthMiddleware) // every procedure in this router+export class AdminRouter {+ @UseMiddlewares(RolesMiddleware) // this procedure only, after AuthMiddleware+ @Query({ meta: { roles: ['admin'] } })+ async getUser() { ... }+}+```++Pass **classes, not instances** — the DI container constructs them.++`@Middlewares()` is the deprecated alias of the same thing, renamed to match Nest's+`@UseGuards` convention. Use `@UseMiddlewares()`.++Global middlewares go on the module:++```typescript+TRPCModule.forRoot({+ globalMiddlewares: [LoggedMiddleware, ErrorReportingMiddleware],+}),+// ...and still need to be in providers:+providers: [LoggedMiddleware, ErrorReportingMiddleware],+```++## Execution order++```+global middlewares → router middlewares → procedure middlewares → handler+```++Within each tier, the order you listed them in. Since each wraps the next via `next()`, a+middleware's post-`next()` code runs in reverse order on the way back out — so the *first*+global middleware is the outermost, and the best place for timing and error reporting.++Order has security consequences: authentication must precede authorization, because the+roles check reads the user that auth put on the context. Putting `RolesMiddleware` before+`AuthMiddleware` gives you a check against an empty context, which typically fails open or+throws confusingly.++## Extending the context from a middleware++Pass new values through `next()`. Don't mutate `opts.ctx` — the merge is what tRPC tracks+for typing, and in-place mutation is invisible to it.++```typescript+@Injectable()+export class AuthMiddleware implements TRPCMiddleware {+ constructor(@Inject(AuthService) private readonly authService: AuthService) {}++ async use(+ opts: MiddlewareOptions<{ req: Request }, { auth: { userId: string } }>,+ ): Promise<MiddlewareResponse> {+ const userId = await this.authService.verify(opts.ctx.req.headers.authorization);++ if (userId == null) {+ throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not signed in.' });+ }++ return opts.next({ ctx: { auth: { userId } } });+ }+}+```++Throwing `TRPCError` from a middleware is the right way to reject — it short-circuits the+chain and reaches the client with the correct code.++The value passed to `next({ ctx })` is **merged into** the existing context, not swapped for+it, so downstream sees both the base context and your additions.++## Procedure `meta` for authorization++`meta` lets a procedure declare requirements declaratively, and a middleware enforce them+generically — one middleware instead of a bespoke check per procedure:++```typescript+@Router({ alias: 'admin' })+@UseMiddlewares(RolesMiddleware)+export class AdminRouter {+ @Query({+ input: z.object({ userId: z.string() }),+ meta: { roles: ['admin'] },+ })+ async getUser(@Input('userId') userId: string) {+ return this.userService.getUser(userId);+ }++ @Mutation({+ input: z.object({ userId: z.string() }),+ meta: { roles: ['admin', 'moderator'] },+ })+ async deleteUser(@Input('userId') userId: string) {+ return this.userService.deleteUser(userId);+ }+}+```++```typescript+interface RolesMeta {+ roles: string[];+}++@Injectable()+export class RolesMiddleware implements TRPCMiddleware<RolesMeta> {+ async use(+ opts: MiddlewareOptions<AuthContext, Record<string, unknown>, RolesMeta>,+ ): Promise<MiddlewareResponse> {+ const { meta, ctx, next } = opts;++ if (!meta?.roles?.some((role) => ctx.auth.roles.includes(role))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Insufficient permissions.' });+ }++ return next();+ }+}+```++Guard against absent `meta`. A procedure in the same router without a `meta.roles` will+otherwise throw a `TypeError` reading `.includes` of undefined — and depending on where it+lands, that can read as a 500 rather than a denial. Decide deliberately whether missing meta+means "public" or "deny", and write it explicitly.++## Context classes++Context is created once per request, before any middleware runs. It's the natural home for+the request/response objects, the session, and per-request caches or DataLoaders.++```typescript+// app.context.ts+import { Inject, Injectable } from '@nestjs/common';+import { ContextOptions, TRPCContext } from 'nestjs-trpc';++@Injectable()+export class AppContext implements TRPCContext {+ constructor(@Inject(UserService) private readonly userService: UserService) {}++ async create(opts: ContextOptions): Promise<Record<string, unknown>> {+ return {+ req: opts.req,+ res: opts.res,+ auth: { user: await this.userService.fromRequest(opts.req) },+ };+ }+}+```++```typescript+export type ContextOptions = CreateExpressContextOptions | CreateFastifyContextOptions;++export interface TRPCContext {+ create(opts: ContextOptions): Record<string, unknown> | Promise<Record<string, unknown>>;+}+```++`ContextOptions` is a union of the Express and Fastify shapes — the adapter detects your+driver automatically. If you touch driver-specific properties, narrow the type first, or+your code breaks the day someone swaps the platform package.++Wire it up in two places — `providers` and the `context` option:++```typescript+@Module({+ imports: [TRPCModule.forRoot({ context: AppContext })],+ providers: [AppContext],+})+export class AppModule {}+```++Missing it from `providers` is the usual cause of a context that's mysteriously empty.++Keep `create()` cheap. It runs on **every** request including ones that will be rejected, so+a database round-trip here is a per-request tax on your whole API. Prefer putting expensive+lookups in a middleware that only guards the procedures that need them, or return a lazy+loader from the context.++### Inner and outer context++The tRPC convention of splitting "inner" (no request, easy to construct in tests) from+"outer" (request-derived) works here too:++```typescript+@Injectable()+export class AppContext implements TRPCContext {+ constructor(@Inject(InnerContext) private readonly innerContext: InnerContext) {}++ async create(opts: ContextOptions): Promise<Record<string, unknown>> {+ const contextInner = await this.innerContext.create(opts);+ return { ...contextInner, req: opts.req, res: opts.res };+ }+}+```++The payoff is that tests can build the inner context directly without faking an HTTP+request. See https://trpc.io/docs/server/context#inner-and-outer-context.++## Typing context on v2++v1 generated helper types (`Context`, `{MiddlewareName}Context`) importable from+`nestjs-trpc/types`. **v2's Rust CLI does not generate them** — it emits a single `server.ts`+with the `AppRouter` type. Documentation pages that say `import type { Context } from+'nestjs-trpc/types'` are v1 leftovers and will not resolve.++Declare the types yourself and export them alongside the code that produces them:++```typescript+// app.context.ts+export interface AppContextShape {+ req: Request;+ res: Response;+ auth: { user: User | null };+}++// auth.middleware.ts — what the context looks like downstream of this middleware+export interface AuthContext extends AppContextShape {+ auth: { user: User; userId: string };+}+```++Then use them explicitly at the call sites:++```typescript+async use(opts: MiddlewareOptions<AppContextShape, { auth: { userId: string } }>) { ... }++@Query({ output: userSchema })+async getProfile(@Ctx() ctx: AuthContext) {+ return this.userService.getUserById(ctx.auth.userId);+}+```++This is manual, and nothing enforces that the annotation on `@Ctx()` matches what the+middleware chain actually produced — the cast is on trust. Keep the interface definition+next to the middleware that establishes it so the two stay in sync, and be aware this is the+one place in the stack where you lose end-to-end inference.diff --git a/.agents/skills/nestjs-trpc/references/module-config.md b/.agents/skills/nestjs-trpc/references/module-config.mdnew file mode 100644index 00000000..b15bced1--- /dev/null+++ b/.agents/skills/nestjs-trpc/references/module-config.md@@ -0,0 +1,301 @@+# Module Configuration++Contents:+- [`TRPCModuleOptions` in full](#trpcmoduleoptions-in-full)+- [`basePath`](#basepath)+- [`context`](#context)+- [`globalMiddlewares`](#globalmiddlewares)+- [`onError`](#onerror)+- [`errorFormatter`](#errorformatter)+- [`transformer`](#transformer)+- [`logger`](#logger)+- [`sse` — subscription streaming](#sse--subscription-streaming)+- [`jsonl` — batch stream keep-alive](#jsonl--batch-stream-keep-alive)+- [Options that no longer exist](#options-that-no-longer-exist)+- [Express and Fastify](#express-and-fastify)++## `TRPCModuleOptions` in full++Transcribed from the shipped `dist/interfaces/module-options.interface.d.ts` at v2.13.0:++```typescript+export interface TRPCModuleOptions {+ basePath?: string;+ context?: Class<TRPCContext>;+ errorFormatter?: TRPCErrorFormatter<any, TRPCDefaultErrorShape>;+ transformer?: DataTransformer | CombinedDataTransformer;+ logger?: LoggerService;+ onError?: Class<TRPCErrorHandler>;+ globalMiddlewares?: Array<Class<TRPCMiddleware> | Constructor<TRPCMiddleware>>;+ sse?: TRPCSSEOptions;+ jsonl?: TRPCJSONLOptions;+}+```++| Option | Type | Default |+|---|---|---|+| `basePath` | `string` | `"/trpc"` |+| `context` | `Class<TRPCContext>` | — |+| `errorFormatter` | `TRPCErrorFormatter` | — |+| `transformer` | `DataTransformer \| CombinedDataTransformer` | — |+| `logger` | `LoggerService` | `ConsoleLogger` |+| `onError` | `Class<TRPCErrorHandler>` | — |+| `globalMiddlewares` | `Array<Class<TRPCMiddleware>>` | `[]` |+| `sse` | `TRPCSSEOptions` | see below |+| `jsonl` | `TRPCJSONLOptions` | — |++`TRPCModule.forRoot(options?)` returns a `DynamicModule`. There is no `forRootAsync` — if+your configuration depends on runtime values, inject `ConfigService` into the context class+or a middleware rather than trying to await it at module definition time.++Every class you pass here (`context`, `onError`, `globalMiddlewares`) must **also** appear in+the module's `providers` array. `forRoot` records which class to use; `providers` is what+lets Nest build it.++## `basePath`++Where the tRPC handler mounts. Defaults to `/trpc`, so procedures live at+`/trpc/<alias>.<procedure>`.++```typescript+TRPCModule.forRoot({ basePath: '/api/trpc' })+```++This must match the `url` your client's `httpLink` points at, including any global prefix+you set with `app.setGlobalPrefix()` — the two compose, and forgetting that is a common+source of 404s that look like missing procedures.++## `context`++The class implementing `TRPCContext`, created once per request. Covered in+[middlewares-and-context.md](middlewares-and-context.md#context-classes).++## `globalMiddlewares`++Applied to every procedure in the application, before router- and procedure-level+middlewares:++```typescript+@Module({+ imports: [+ TRPCModule.forRoot({+ globalMiddlewares: [LoggedMiddleware, ErrorReportingMiddleware],+ }),+ ],+ providers: [LoggedMiddleware, ErrorReportingMiddleware],+})+export class AppModule {}+```++Good fits: timing, logging, error reporting, rate limiting. Bad fit: authentication —+because a global auth middleware has to special-case every public procedure, and those+exceptions are easy to get wrong. Prefer an explicit `@UseMiddlewares(AuthMiddleware)` on+the routers that need it, so the protected surface is visible in the code.++## `onError`++An injectable handler invoked whenever a procedure throws. Use it for reporting to Sentry+and friends — it observes, it can't rewrite the response.++```typescript+// app.error-handler.ts+import { Inject, Injectable } from '@nestjs/common';+import { OnErrorOptions, TRPCErrorHandler } from 'nestjs-trpc';++@Injectable()+export class AppErrorHandler implements TRPCErrorHandler {+ constructor(@Inject(LogService) private readonly logService: LogService) {}++ onError(opts: OnErrorOptions): void {+ this.logService.error(`[${opts.type}] ${opts.path}: ${opts.error.message}`);+ }+}+```++```typescript+export interface OnErrorOptions {+ error: TRPCError;+ type: TRPCProcedureType | 'unknown';+ path: string | undefined;+ input: unknown;+ ctx: Record<string, unknown> | undefined;+ req: unknown;+}++export interface TRPCErrorHandler {+ onError(opts: OnErrorOptions): void;+}+```++```typescript+@Module({+ imports: [TRPCModule.forRoot({ onError: AppErrorHandler })],+ providers: [AppErrorHandler],+})+export class AppModule {}+```++`onError` returns `void` and is not awaited — don't put slow work on the request path here.+Note also that `opts.input` is the user's payload and `opts.ctx` may hold session data; both+will end up wherever you ship them, so redact before logging if you're subject to+data-handling rules.++To distinguish real bugs from expected rejections, filter on the code — a `NOT_FOUND` from a+mistyped id isn't an incident:++```typescript+onError(opts: OnErrorOptions): void {+ if (opts.error.code === 'INTERNAL_SERVER_ERROR') {+ this.sentry.captureException(opts.error.cause ?? opts.error, { extra: { path: opts.path } });+ }+}+```++## `errorFormatter`++Shapes what the client receives. This is the one that *can* change the payload — use it to+attach structured validation errors, and to make sure internal messages don't escape in+production.++```typescript+TRPCModule.forRoot({+ errorFormatter({ shape, error }) {+ return {+ ...shape,+ data: {+ ...shape.data,+ zodError:+ error.cause instanceof ZodError ? error.cause.flatten() : null,+ },+ };+ },+})+```++Unlike `onError`, this is a plain function on the options object, not an injectable class.++See https://trpc.io/docs/error-formatting.++## `transformer`++A data transformer, for types JSON can't represent — `Date`, `Map`, `Set`, `BigInt`,+`undefined`:++```typescript+import superjson from 'superjson';++TRPCModule.forRoot({ transformer: superjson })+```++The client must be configured with the **same** transformer, or every request fails to+deserialize. Since v2.5.0 the CLI auto-detects the transformer when generating the schema,+so the generated types account for it.++Adding or removing a transformer is a breaking wire-format change — deploy both sides+together.++## `logger`++Any `LoggerService` implementation replaces the default `ConsoleLogger`:++```typescript+import { Module } from '@nestjs/common';+import { TRPCModule } from 'nestjs-trpc';+import { MyLogger } from './my-logger.service';++@Module({+ imports: [TRPCModule.forRoot({ logger: new MyLogger() })],+})+export class AppModule {}+```++This takes an **instance**, not a class — it's the one option that isn't DI-resolved, so a+logger needing injected dependencies has to be constructed manually or obtained from the+app context. Pino and Winston adapters (e.g. `nestjs-pino`) satisfy the interface.++## `sse` — subscription streaming++```typescript+export interface TRPCSSEOptions {+ /** Enable SSE subscriptions. @default true */+ enabled?: boolean;+ ping?: {+ /** @default false */+ enabled: boolean;+ /** Interval in milliseconds. @default 1000 */+ intervalMs?: number;+ };+ /** Max duration in ms before ending the stream. @default undefined */+ maxDurationMs?: number;+ /** End the request immediately after data is sent. @default false */+ emitAndEndImmediately?: boolean;+ client?: {+ /** Client reconnects after this much inactivity, in ms. @default undefined */+ reconnectAfterInactivityMs?: number;+ };+}+```++Added in v2.13.0. A sensible production baseline:++```typescript+TRPCModule.forRoot({+ sse: {+ ping: { enabled: true, intervalMs: 30000 },+ client: { reconnectAfterInactivityMs: 60000 },+ },+})+```++Points worth knowing:++- **Ping defaults to off**, and its `intervalMs` defaults to `1000`. Enabling pings without+ an explicit interval gives one ping per second per open stream — set the interval.+- Pick an interval below your proxy's idle timeout. 30s is safe against the common 60s+ default in nginx, ALB, and Cloudflare.+- `client.reconnectAfterInactivityMs` should be comfortably longer than `ping.intervalMs`,+ or clients will reconnect between healthy pings.+- `emitAndEndImmediately` exists for serverless runtimes that can't hold a streaming+ response open. On a normal long-lived Node server, leave it off — it defeats the point of+ a subscription.+- `maxDurationMs` caps stream lifetime. Useful where an upstream load balancer will sever+ the connection anyway; ending it deliberately produces a cleaner client reconnect than+ being cut off.++## `jsonl` — batch stream keep-alive++```typescript+export interface TRPCJSONLOptions {+ /** Interval in ms between keep-alive pings on streamed batch responses. @default undefined */+ pingMs?: number;+}+```++Applies to `httpBatchStreamLink`, not subscriptions. Set it if you batch requests where one+slow procedure can hold the response open past a proxy's idle timeout:++```typescript+TRPCModule.forRoot({ jsonl: { pingMs: 30000 } })+```++## Options that no longer exist++`autoSchemaFile` and `schemaFileImports` were v1 options and are **not** in the v2+`TRPCModuleOptions` type — passing them is a TypeScript error. Several published docs pages+(context, client, integrations) still show `autoSchemaFile: './src/@generated'`.++In v2, output location is a CLI concern: `nestjs-trpc generate --output ./src/@generated`.+See [codegen-and-client.md](codegen-and-client.md).++(The v2 CLI does still recognise an `autoSchemaFile` literal when scanning your `forRoot`+call, for the benefit of projects migrating from v1. Don't rely on it — it isn't part of the+typed API.)++## Express and Fastify++Both are supported natively; the adapter inspects Nest's `HttpAdapterHost` and picks the+right tRPC adapter. No configuration needed.++The visible consequence is in `ContextOptions`, which is+`CreateExpressContextOptions | CreateFastifyContextOptions`. Narrow before reaching for+driver-specific request properties, and your context stays portable.diff --git a/.agents/skills/nestjs-trpc/references/routers.md b/.agents/skills/nestjs-trpc/references/routers.mdnew file mode 100644index 00000000..719edd0b--- /dev/null+++ b/.agents/skills/nestjs-trpc/references/routers.md@@ -0,0 +1,297 @@+# Routers, Procedures, and Subscriptions++Contents:+- [The `@Router()` decorator](#the-router-decorator)+- [Procedure decorators](#procedure-decorators)+- [Input and output schemas](#input-and-output-schemas)+- [Parameter decorators](#parameter-decorators)+- [Error handling in procedures](#error-handling-in-procedures)+- [Subscriptions](#subscriptions)+- [Merging routers under one alias](#merging-routers-under-one-alias)+- [Testing routers](#testing-routers)++## The `@Router()` decorator++```typescript+export declare function Router(args?: { alias?: string }): ClassDecorator;+```++Marks a class as a tRPC router. The class must also be listed in its module's `providers`+array — `@Router()` records metadata, it does not register the class with Nest.++`alias` sets the namespace the procedures live under on the client. `@Router({ alias: 'users' })`+with a `getUserById` method produces `trpc.users.getUserById`. Without an alias, the class+name is used, which means renaming the class is a breaking API change — prefer an explicit+alias on anything a client depends on.++Routers support constructor injection like any provider:++```typescript+@Router({ alias: 'users' })+export class UserRouter {+ constructor(@Inject(UserService) private readonly userService: UserService) {}+}+```++Only providers visible in the same module (or exported by an imported module) can be+injected — the ordinary Nest resolution rules apply, with the ordinary+`Nest can't resolve dependencies of the UserRouter` error when they don't.++## Procedure decorators++```typescript+function Query(args?: { input?: Parser; output?: Parser; meta?: Record<string, unknown> }): MethodDecorator;+function Mutation(args?: { input?: Parser; output?: Parser; meta?: Record<string, unknown> }): MethodDecorator;+function Subscription(args?: { input?: Parser; output?: Parser; meta?: Record<string, unknown> }): MethodDecorator;+```++| Decorator | Compiles to | Use for |+|---|---|---|+| `@Query` | `publicProcedure.query()` | reads; cacheable, batchable, GET-able |+| `@Mutation` | `publicProcedure.mutation()` | writes and side effects |+| `@Subscription` | `publicProcedure.subscription()` | long-lived SSE streams |++The query/mutation split is a real contract, not decoration — tRPC clients batch and cache+queries, and React Query treats them differently. A "query" that writes will be retried and+deduplicated in ways you don't want.++All three arguments are optional; `@Query()` with no arguments is a valid no-input procedure.++## Input and output schemas++`input` validates the payload before your method body runs. Validation failure produces a+`BAD_REQUEST` tRPC error automatically — you don't write that check.++`output` is optional. Omitted, the return type is inferred from the method's TypeScript+signature (v2.11.0+). Provided, it validates on the way out and — critically — **strips+properties not in the schema**. That makes it the cheapest defence against accidentally+serialising internal fields:++```typescript+// user.schema.ts+export const userSchema = z.object({+ id: z.string(),+ name: z.string(),+ email: z.string(),+ passwordHash: z.string(), // internal+});++export const publicUserSchema = userSchema.omit({ passwordHash: true });++// user.router.ts+@Query({ output: publicUserSchema }) // passwordHash cannot escape+async getProfile(): Promise<User> { ... }+```++The `Parser` type accepts any Standard Schema v1 validator plus the Zod/Valibot/ArkType/Yup/+Superstruct/custom-function shapes. In practice **use Zod**: the CLI's schema flattening —+the step that inlines your schemas into the generated `server.ts` — is written against Zod,+and other libraries are far more likely to hit the "could not flatten" path.++Define schemas at module scope, not inline inside the decorator, when they're shared. The+CLI has to resolve them statically; a schema built by a helper function call at runtime is+something it may not be able to follow.++## Parameter decorators++These destructure the tRPC `opts` object into method parameters.++| Decorator | Signature | Yields |+|---|---|---|+| `@Input(key?)` | `Input(key?: string): ParameterDecorator` | `opts.input`, or `opts.input[key]` when `key` given |+| `@Ctx()` | `Ctx(): ParameterDecorator` | `opts.ctx` |+| `@Options()` | `Options(): ParameterDecorator` | the whole `opts` |+| `@RawInput()` | `RawInput(): ParameterDecorator` | `opts.rawInput` — unvalidated |+| `@Type()` | `Type(): ParameterDecorator` | `opts.type` |+| `@Path()` | `Path(): ParameterDecorator` | `opts.path` |++The decorator is **`@Ctx()`**. The published docs write `@Context()` in the routers and+middlewares examples; that symbol is not exported and the import will fail. The official+`examples/nestjs-express/src/user.router.ts` uses `@Ctx()`.++`@Options()` is typed by `ProcedureOptions`:++```typescript+export type ProcedureOptions = {+ ctx: unknown;+ input: unknown;+ type: string;+ path: string;+ rawInput: unknown;+ signal: AbortSignal | undefined;+};+```++A full example combining them, from the upstream repo:++```typescript+@Query({+ input: z.object({ userId: z.string() }),+ output: userSchema,+})+@UseMiddlewares(ProtectedMiddleware)+async getUserById(+ @Input('userId') userId: string,+ @Ctx() ctx: object,+ @Options() opts: ProcedureOptions,+): Promise<User> {+ return this.userService.getUser(userId);+}+```++`@RawInput()` bypasses validation, so treat whatever it returns as untrusted. It's for+things like webhook signature verification that need the payload exactly as received.++## Error handling in procedures++Throw `TRPCError` from `@trpc/server`:++```typescript+import { TRPCError } from '@trpc/server';++throw new TRPCError({ code: 'NOT_FOUND', message: 'Could not find user.' });+```++Codes are tRPC's, not Nest's: `BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`,+`TIMEOUT`, `CONFLICT`, `PRECONDITION_FAILED`, `PAYLOAD_TOO_LARGE`, `METHOD_NOT_SUPPORTED`,+`UNPROCESSABLE_CONTENT`, `TOO_MANY_REQUESTS`, `CLIENT_CLOSED_REQUEST`,+`INTERNAL_SERVER_ERROR`, `NOT_IMPLEMENTED`, `BAD_GATEWAY`, `SERVICE_UNAVAILABLE`,+`GATEWAY_TIMEOUT`.++Nest's `HttpException` / `NotFoundException` and Nest exception filters do **not** map onto+tRPC's error shape — the client sees an unhelpful `INTERNAL_SERVER_ERROR`. If a shared+service throws Nest exceptions, translate at the router boundary:++```typescript+try {+ return await this.userService.getUser(userId);+} catch (e) {+ if (e instanceof NotFoundException) {+ throw new TRPCError({ code: 'NOT_FOUND', message: e.message });+ }+ throw e;+}+```++Pass `cause` when wrapping so the original stack survives into your `onError` handler:+`new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: e })`.++For centralised reporting, register an `onError` handler on the module — see+[module-config.md](module-config.md).++## Subscriptions++Subscriptions stream over Server-Sent Events. The method is an **async generator** that+yields values:++```typescript+import { Router, Subscription, Input, Options } from 'nestjs-trpc';+import { z } from 'zod';++@Router({ alias: 'events' })+export class EventRouter {+ constructor(@Inject(EventService) private readonly eventService: EventService) {}++ @Subscription({+ input: z.object({ channelId: z.string() }),+ })+ async *onMessage(+ @Input('channelId') channelId: string,+ @Options() opts: { signal?: AbortSignal },+ ) {+ for await (const event of this.eventService.listen(channelId, opts.signal)) {+ yield event;+ }+ }+}+```++`input`, `@UseMiddlewares()`, and DI all work exactly as they do for queries.++### Cleaning up on disconnect++The `AbortSignal` is how you learn the client went away. A generator that ignores it leaks+one live handler per disconnected client, and nothing will tell you it's happening until the+process runs out of memory. Either forward the signal into whatever you're subscribing to+(as above), or check it in your loop condition:++```typescript+async *onMessage(+ @Input('channelId') channelId: string,+ @Options() opts: { signal?: AbortSignal },+) {+ let count = 0;+ while (!opts.signal?.aborted) {+ await new Promise((resolve) => setTimeout(resolve, 1000));+ yield { message: `Event ${count++}`, timestamp: Date.now() };+ }+}+```++If you hold a resource that isn't signal-aware, wrap the body in `try/finally` and release+in the `finally` — it runs when the generator is disposed on disconnect.++### Keep-alive++Idle SSE streams get killed by proxies and load balancers, typically around 30–60s. Enable+server pings in `forRoot`:++```typescript+TRPCModule.forRoot({+ sse: {+ ping: { enabled: true, intervalMs: 30000 },+ client: { reconnectAfterInactivityMs: 60000 },+ },+})+```++Ping is **disabled by default**, and the default `intervalMs` is `1000` — if you enable+pings without setting an interval you get one ping per second, which is almost never what+you want. Full option list in [module-config.md](module-config.md).++### Consuming from the client++```typescript+trpc.events.onMessage.useSubscription(+ { channelId: 'general' },+ {+ onData(event) {+ console.log('Received:', event);+ },+ },+);+```++## Merging routers under one alias++Since v2.4.0, two router classes sharing an `alias` are merged into one namespace. This lets+you split a large surface across files without flattening it on the client:++```typescript+@Router({ alias: 'users' })+export class UserReadRouter { /* getById, list */ }++@Router({ alias: 'users' })+export class UserWriteRouter { /* create, update */ }+```++Both contribute to `trpc.users.*`. Procedure names must still be unique across the merged+set — a collision is a generation-time error, not a runtime one.++## Testing routers++Because a router is a plain provider, unit tests need no tRPC machinery:++```typescript+const module = await Test.createTestingModule({+ providers: [UserRouter, { provide: UserService, useValue: mockUserService }],+}).compile();++const router = module.get(UserRouter);+await expect(router.getUserById('missing')).rejects.toThrow(TRPCError);+```++This calls the method directly, so decorator-driven `input`/`output` validation and+middlewares do **not** run. To exercise the real procedure pipeline, go through+`AppRouterHost` and create a server-side caller — see+[codegen-and-client.md](codegen-and-client.md#e2e-testing-with-approuterhost).diff --git a/.claude/skills/nestjs-trpc b/.claude/skills/nestjs-trpcnew file mode 120000index 00000000..4b4e2d7b--- /dev/null+++ b/.claude/skills/nestjs-trpc@@ -0,0 +1 @@+../../.agents/skills/nestjs-trpc\ No newline at end of file