@ts-pf/server 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @ts-pf/server
2
2
 
3
- `createImplementer()`, middleware, `runProcedure`, `lookupProcedure`, `createLocalClient()`, and server call interceptors / `DedupePlugin` for [ts-pf](https://github.com/crobinson42/ts-pf#readme). Implements a contract from `@ts-pf/contract`. No `Request` / `Response` — HTTP is `@ts-pf/server-http`.
3
+ `createImplementer()`, middleware, `mapStreamErrors`, `runProcedure`, `lookupProcedure`, `createLocalClient()`, and server call interceptors / `DedupePlugin` for [ts-pf](https://github.com/crobinson42/ts-pf#readme). Implements a contract from `@ts-pf/contract`. No `Request` / `Response` — HTTP is `@ts-pf/server-http`.
4
4
 
5
5
  ## Install
6
6
 
@@ -49,14 +49,235 @@ await local.planet.find({ id: 1 })
49
49
 
50
50
  `Db`, `User`, `db`, and `auth()` are your app's. `.use()` runs before input validation (`input: unknown`); `.useAfter()` runs after it. Input checks default on; output checks run only with `validation: { output: true }`. Name the implemented router `app`.
51
51
 
52
+ A declared code gets its declared `status` whether you throw `errors.NOT_FOUND(...)` or a hand-built `new PFError({ code: 'NOT_FOUND', data, cause })`: `runProcedure` fills an unset `status` on an error thrown from middleware or the handler from the contract's `.errors()` entry and keeps `cause` (it never fills `message`).
53
+
54
+ `validation: { input: false }` hands the handler the raw value, although its `input` type still says parsed: contract-only narrowing (zod `.omit()`, defaults, transforms) is not applied. A handler that validates on its own reports failures in the built-in shape with `validationError` (this package) and `toValidationIssues` from `@ts-pf/contract`:
55
+
56
+ ```ts
57
+ import { toValidationIssues } from '@ts-pf/contract'
58
+ import { createImplementer, validationError } from '@ts-pf/server'
59
+ import { z } from 'zod'
60
+
61
+ const createInput = z.object({ name: z.string().min(1) })
62
+
63
+ const impl = createImplementer(contract)
64
+ const create = impl.planet.create.handler(async ({ input }) => {
65
+ const result = await createInput['~standard'].validate(input)
66
+ if (result.issues) throw validationError(toValidationIssues(result.issues))
67
+ return { id: 1, name: result.value.name }
68
+ })
69
+ ```
70
+
52
71
  Serve it over HTTP with `FetchHandler` from `@ts-pf/server-http` — `new FetchHandler(app).handle(request, { prefix: '/rpc', context: (req) => ({ db, req }) })` — on Workers, Bun, Deno, Node, Hono, or Next.js: see [Serving FetchHandler](https://github.com/crobinson42/ts-pf#serving-fetchhandler). Message transports are `@ts-pf/message-server`.
53
72
 
54
73
  Server `DedupePlugin` keys every unary call by default, writes included; pass `key` to restrict it to reads.
55
74
 
75
+ ## Keys middleware adds
76
+
77
+ Middleware does not narrow the context type yet: `next({ context: { user } })` merges at runtime, but handlers still see `$context<AppCtx>()`, where `user` is optional. Declare those keys optional, let one `.use()` middleware set them or throw, and narrow in the handler with a helper that checks the key (not with a cast at each call site). The context factory then never needs placeholder keys:
78
+
79
+ ```ts
80
+ import { PFError } from '@ts-pf/protocol'
81
+ import { createImplementer } from '@ts-pf/server'
82
+ import { FetchHandler } from '@ts-pf/server-http'
83
+ import { contract } from './contract.js'
84
+
85
+ type AppCtx = { db: Db; req: Request; user?: User }
86
+
87
+ const impl = createImplementer(contract).$context<AppCtx>()
88
+
89
+ const requireUser = impl.middleware(async ({ context, next }) => {
90
+ const user = await auth(context.req)
91
+ if (!user) throw new PFError({ code: 'UNAUTHORIZED', status: 401 })
92
+ return next({ context: { user } })
93
+ })
94
+
95
+ /** `context` with `user` set by `requireUser`; throws if it is missing. */
96
+ function signedIn(context: AppCtx): AppCtx & { user: User } {
97
+ if (!context.user) throw new PFError({ code: 'UNAUTHORIZED', status: 401 })
98
+ return context as AppCtx & { user: User }
99
+ }
100
+
101
+ export const app = impl.router({
102
+ planet: {
103
+ list: impl.planet.list.handler(async ({ context }) => context.db.planets.all()),
104
+ find: impl.planet.find.handler(async ({ input, context, errors }) => {
105
+ const row = await context.db.planets.get(input.id)
106
+ if (!row) throw errors.NOT_FOUND({ id: input.id })
107
+ return row
108
+ }),
109
+ create: impl.planet.create.use(requireUser).handler(async ({ input, context }) => {
110
+ const { db, user } = signedIn(context)
111
+ console.log(`${user.id} creates ${input.name}`)
112
+ return db.planets.create(input)
113
+ }),
114
+ },
115
+ })
116
+
117
+ // No `user: undefined` placeholder: the key is optional.
118
+ const handler = new FetchHandler(app)
119
+ await handler.handle(request, { prefix: '/rpc', context: (req) => ({ db, req }) })
120
+ ```
121
+
122
+ ## Mapping domain errors
123
+
124
+ A `.use()` middleware that wraps `await next()` in `try` / `catch` maps errors thrown before a procedure returns. A stream procedure returns its `AsyncIterable` first and throws while it is iterated, after that `catch` has finished, so a domain error thrown mid-stream reaches a remote client as `INTERNAL` (an in-process caller gets the raw error). `mapStreamErrors(value, fn)` wraps an async iterable so a throw from its `next()` is replaced by `fn(error)`; any other value is returned unchanged, so one middleware covers unary and stream procedures:
125
+
126
+ ```ts
127
+ import { isPFError, PFError } from '@ts-pf/protocol'
128
+ import { createImplementer, mapStreamErrors } from '@ts-pf/server'
129
+ import { contract } from './contract.js'
130
+
131
+ class QuotaExceeded extends Error {}
132
+
133
+ // Returns the error to throw. Return PFErrors unchanged: input VALIDATION,
134
+ // stream item VALIDATION, and errors.CODE() throws must reach the client as they are.
135
+ // Declare RATE_LIMITED on .errors() so clients can narrow on it.
136
+ function mapError(error: unknown): unknown {
137
+ if (isPFError(error)) return error
138
+ if (error instanceof QuotaExceeded) {
139
+ return new PFError({ code: 'RATE_LIMITED', status: 429 })
140
+ }
141
+ return error
142
+ }
143
+
144
+ const impl = createImplementer(contract).$context<{ db: Db }>()
145
+
146
+ const mapErrors = impl.middleware(async ({ next }) => {
147
+ try {
148
+ return mapStreamErrors(await next(), mapError)
149
+ } catch (error) {
150
+ throw mapError(error)
151
+ }
152
+ })
153
+
154
+ // First, so it sees every throw from the middleware and handler below it.
155
+ export const root = impl.use(mapErrors)
156
+ ```
157
+
158
+ `fn` sees every value the iterable throws. The mapped error is still checked against the contract like any other throw (a declared code's `data` is validated; data that fails is sent as `INTERNAL`), because middleware runs inside the procedure. A declared code without its own `status` also gets the declared one; the declared `message` is not applied, so set it on the `PFError` yourself. `return()` (a client that stops reading) reaches the source iterator, including before the first item. Server call interceptors wrap the whole procedure and see its errors after that check, so an error mapped there skips the `data` validation: map in middleware.
159
+
160
+ ### A domain error catalog
161
+
162
+ When the domain layer owns its errors (and may be shared by more than one server), keep one catalog there and derive the contract's codes from it. Every domain code has a message and a status; `null` means "not exposed to clients", and the mapping sends it as `INTERNAL`. This file needs only `@ts-pf/protocol`:
163
+
164
+ ```ts
165
+ // domain-errors.ts — owned by the domain layer
166
+ import { PFError } from '@ts-pf/protocol'
167
+
168
+ /** Every error the domain raises, with its message. */
169
+ const domainErrors = {
170
+ BOOK_NOT_FOUND: 'Book not found',
171
+ LOAN_LIMIT_REACHED: 'Loan limit reached',
172
+ LEDGER_MISMATCH: 'Ledger totals do not match',
173
+ } as const
174
+
175
+ export type DomainCode = keyof typeof domainErrors
176
+
177
+ export class DomainError extends Error {
178
+ readonly code: DomainCode
179
+ constructor(code: DomainCode, options?: ErrorOptions) {
180
+ super(domainErrors[code], options)
181
+ this.code = code
182
+ }
183
+ }
184
+
185
+ /** HTTP status per code; `null` = not exposed to clients (sent as INTERNAL). */
186
+ const domainStatus = {
187
+ BOOK_NOT_FOUND: 404,
188
+ LOAN_LIMIT_REACHED: 409,
189
+ LEDGER_MISMATCH: null,
190
+ } as const satisfies Record<DomainCode, number | null>
191
+
192
+ type ExposedCode = {
193
+ [K in DomainCode]: (typeof domainStatus)[K] extends number ? K : never
194
+ }[DomainCode]
195
+
196
+ /** The exposed codes as an error map for `procedure.errors()`. */
197
+ export const clientErrors = Object.fromEntries(
198
+ Object.entries(domainStatus).flatMap(([code, status]) =>
199
+ status === null ? [] : [[code, { status, message: domainErrors[code as DomainCode] }]],
200
+ ),
201
+ ) as { [K in ExposedCode]: { status: (typeof domainStatus)[K]; message: string } }
202
+
203
+ /** A DomainError becomes a PFError; anything else (PFErrors included) is returned as is. */
204
+ export function mapDomainError(error: unknown): unknown {
205
+ if (!(error instanceof DomainError)) return error
206
+ if (domainStatus[error.code] === null) {
207
+ return new PFError({ code: 'INTERNAL', message: 'Internal server error', cause: error })
208
+ }
209
+ return new PFError({ code: error.code, message: error.message, cause: error })
210
+ }
211
+ ```
212
+
213
+ The contract declares the exposed codes, and one mapping middleware runs first:
214
+
215
+ ```ts
216
+ // library-contract.ts
217
+ import { procedure, router } from '@ts-pf/contract'
218
+ import { z } from 'zod'
219
+ import { clientErrors } from './domain-errors.js'
220
+
221
+ export const contract = router({
222
+ loan: {
223
+ create: procedure
224
+ .input(z.object({ bookId: z.string() }))
225
+ .output(z.object({ loanId: z.string() }))
226
+ .errors(clientErrors),
227
+ },
228
+ })
229
+ ```
230
+
231
+ ```ts
232
+ // map-domain-errors.ts — server side: mapStreamErrors is a runtime import from @ts-pf/server
233
+ import { type MiddlewareFn, mapStreamErrors } from '@ts-pf/server'
234
+ import { mapDomainError } from './domain-errors.js'
235
+
236
+ export const mapDomainErrors: MiddlewareFn = async ({ next }) => {
237
+ try {
238
+ return mapStreamErrors(await next(), mapDomainError)
239
+ } catch (error) {
240
+ throw mapDomainError(error)
241
+ }
242
+ }
243
+ ```
244
+
245
+ ```ts
246
+ // library-server.ts
247
+ import { createImplementer } from '@ts-pf/server'
248
+ import { DomainError } from './domain-errors.js'
249
+ import { contract } from './library-contract.js'
250
+ import { mapDomainErrors } from './map-domain-errors.js'
251
+
252
+ const impl = createImplementer(contract)
253
+
254
+ export const app = impl.use(mapDomainErrors).router({
255
+ loan: {
256
+ create: impl.loan.create.handler(async ({ input }) => {
257
+ if (input.bookId === '') throw new DomainError('BOOK_NOT_FOUND')
258
+ return { loanId: 'loan-1' }
259
+ }),
260
+ },
261
+ })
262
+ ```
263
+
264
+ - The mapped `PFError` sets no `status`: `runProcedure` fills it from the declared entry (404 for `BOOK_NOT_FOUND`) and keeps `cause`, so your logger still sees the domain error. A code the procedure does not declare is sent with HTTP 400 and is outside the client's type; pass `status` too if a procedure can throw codes it does not declare.
265
+ - Unknown throws pass through unchanged and become `INTERNAL`, as does a `null`-status code. Both are logged by the `FetchHandler` default (`isUnexpectedError`).
266
+ - A code that carries data: give `DomainError` a `data` field, pass it to the `PFError`, and add the schema to that code's entry on the contract (`{ ...clientErrors.BOOK_NOT_FOUND, data: schema }`), where it is checked like any declared `data`.
267
+ - `MiddlewareFn` is a type-only import, so the middleware needs no implementer and fits `impl.use()` and a per-procedure `.use()` on any server. `domain-errors.ts` does not import `@ts-pf/server`; `map-domain-errors.ts` does (for `mapStreamErrors`), so a shared package that ships it lists `@ts-pf/server` as a peer dependency.
268
+ - `.errors(clientErrors)` on every procedure is the simple choice, and it gives up per-procedure client error types. See [Error maps: shared or per procedure](https://github.com/crobinson42/ts-pf/blob/main/docs/evolution.md#error-maps-shared-or-per-procedure) for the trade-off and a base-set-plus-area pattern.
269
+
270
+ ## Middleware and handler notes
271
+
272
+ - Call `next()` at most once in a `.use()` / `.useAfter()` middleware. One call keeps one input and context: a second `next()` runs the rest of the chain on the input the first run already parsed and the context inner middleware already added, and concurrent calls race. For retries or hedging, use a `CallInterceptor`; its `next()` may be called more than once, and each call gets a fresh execution.
273
+ - The handler's `signal` is optional. `FetchHandler` (the request's signal) and the message handlers always pass one; `createLocalClient` without `{ signal }`, a direct `runProcedure`, and `@ts-pf/mcp` without a host signal may not. Guard it: `signal?.throwIfAborted()`, or `signal ?? AbortSignal.timeout(5_000)` when you pass it on.
274
+
56
275
  ## API
57
276
 
58
277
  - `createImplementer`, `createLocalClient`, `runProcedure`, `lookupProcedure`, `ProcedureValidation`
278
+ - `validationError(issues)` — the `VALIDATION` `PFError` the input check throws, for handlers that validate themselves
59
279
  - `applyPlugins`, `CallPlugin`, `CallInterceptor`, `DedupePlugin`
280
+ - `mapStreamErrors`
60
281
  - `onStart` / `onSuccess` / `onError` / `onFinish`
61
282
 
62
283
  ## Agent skills
@@ -1,5 +1,11 @@
1
1
  import { type ErrorMap } from '@ts-pf/contract';
2
2
  import type { ErrorFactory } from './middleware.js';
3
3
  export declare function createErrorFactory(map: ErrorMap): ErrorFactory<ErrorMap>;
4
+ /**
5
+ * A thrown `PFError` whose code the procedure declares leaves with the
6
+ * declared `status` when it has none (the same stamping as `errors.X()`, so a
7
+ * hand-built `new PFError({ code })` matches) and with its `data` parsed by
8
+ * the declared schema. Anything else is rethrown untouched.
9
+ */
4
10
  export declare function finalizeDeclaredError(error: unknown, map: ErrorMap): Promise<never>;
5
11
  //# sourceMappingURL=error-factory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-factory.d.ts","sourceRoot":"","sources":["../src/error-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAkB,MAAM,iBAAiB,CAAA;AAE/D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAQnD,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,CAuBxE;AAED,wBAAsB,qBAAqB,CACzC,KAAK,EAAE,OAAO,EACd,GAAG,EAAE,QAAQ,GACZ,OAAO,CAAC,KAAK,CAAC,CA0BhB"}
1
+ {"version":3,"file":"error-factory.d.ts","sourceRoot":"","sources":["../src/error-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAkB,MAAM,iBAAiB,CAAA;AAE/D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAQnD,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,CAuBxE;AAED;;;;;GAKG;AACH,wBAAsB,qBAAqB,CACzC,KAAK,EAAE,OAAO,EACd,GAAG,EAAE,QAAQ,GACZ,OAAO,CAAC,KAAK,CAAC,CAuBhB"}
@@ -29,14 +29,24 @@ export function createErrorFactory(map) {
29
29
  factories.set(map, factory);
30
30
  return factory;
31
31
  }
32
+ /**
33
+ * A thrown `PFError` whose code the procedure declares leaves with the
34
+ * declared `status` when it has none (the same stamping as `errors.X()`, so a
35
+ * hand-built `new PFError({ code })` matches) and with its `data` parsed by
36
+ * the declared schema. Anything else is rethrown untouched.
37
+ */
32
38
  export async function finalizeDeclaredError(error, map) {
33
39
  if (!isPFError(error)) {
34
40
  throw error;
35
41
  }
36
42
  const def = map[error.code];
37
- if (def?.data === undefined) {
43
+ if (def === undefined) {
38
44
  throw error;
39
45
  }
46
+ const status = error.status ?? def.status;
47
+ if (def.data === undefined) {
48
+ throw status === error.status ? error : rebuild(error, status, error.data);
49
+ }
40
50
  const result = await validateSchema(def.data, error.data);
41
51
  if (!result.success) {
42
52
  // The bad payload never reaches the wire (`toJSON()` omits `cause`); the
@@ -47,13 +57,26 @@ export async function finalizeDeclaredError(error, map) {
47
57
  cause: error,
48
58
  });
49
59
  }
60
+ throw rebuild(error, status, result.value);
61
+ }
62
+ // `PFError` fields are readonly, so a finalized error is a copy that keeps
63
+ // everything the constructor takes (including `cause`). The original stack is
64
+ // not copied: reading `error.stack` makes V8 format it, which costs more than
65
+ // the rest of the failed call (`npm run bench`, declared-error rows).
66
+ function rebuild(error, status, data) {
50
67
  const init = { code: error.code, message: error.message };
51
- if (error.status !== undefined) {
52
- init.status = error.status;
68
+ if (status !== undefined) {
69
+ init.status = status;
70
+ }
71
+ if (data !== undefined) {
72
+ init.data = data;
73
+ }
74
+ if ('cause' in error) {
75
+ init.cause = error.cause;
53
76
  }
54
- if (result.value !== undefined) {
55
- init.data = result.value;
77
+ if (error.local === true) {
78
+ init.local = true;
56
79
  }
57
- throw new PFError(init);
80
+ return new PFError(init);
58
81
  }
59
82
  //# sourceMappingURL=error-factory.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-factory.js","sourceRoot":"","sources":["../src/error-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAC/D,OAAO,EAAE,SAAS,EAAE,OAAO,EAAoB,MAAM,i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CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAA;IACnB,CAAC;IACD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;AAC1B,CAAC"}
package/dist/index.d.ts CHANGED
@@ -3,7 +3,9 @@ export { createLocalClient } from './caller.js';
3
3
  export { DedupePlugin, type DedupePluginOptions } from './dedupe-plugin.js';
4
4
  export { onError, onFinish, onStart, onSuccess } from './events.js';
5
5
  export { createImplementer, type Implementer, type ProcedureBuilder, } from './implement.js';
6
+ export { mapStreamErrors } from './map-stream-errors.js';
6
7
  export type { ErrorFactory, MiddlewareFn, NextFn } from './middleware.js';
7
8
  export { applyPlugins, type CallPlugin } from './plugin.js';
8
9
  export { type ImplementedProcedure, type ImplementedRouter, isImplementedProcedure, lookupProcedure, type ProcedureValidation, type RouterImpl, type RunProcedureOptions, runProcedure, } from './runtime.js';
10
+ export { validationError } from './validation-error.js';
9
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AAC3E,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACnE,OAAO,EACL,iBAAiB,EACjB,KAAK,WAAW,EAChB,KAAK,gBAAgB,GACtB,MAAM,gBAAgB,CAAA;AACvB,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACzE,OAAO,EAAE,YAAY,EAAE,KAAK,UAAU,EAAE,MAAM,aAAa,CAAA;AAC3D,OAAO,EACL,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,sBAAsB,EACtB,eAAe,EACf,KAAK,mBAAmB,EACxB,KAAK,UAAU,EACf,KAAK,mBAAmB,EACxB,YAAY,GACb,MAAM,cAAc,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AAC3E,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACnE,OAAO,EACL,iBAAiB,EACjB,KAAK,WAAW,EAChB,KAAK,gBAAgB,GACtB,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACxD,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACzE,OAAO,EAAE,YAAY,EAAE,KAAK,UAAU,EAAE,MAAM,aAAa,CAAA;AAC3D,OAAO,EACL,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,sBAAsB,EACtB,eAAe,EACf,KAAK,mBAAmB,EACxB,KAAK,UAAU,EACf,KAAK,mBAAmB,EACxB,YAAY,GACb,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA"}
package/dist/index.js CHANGED
@@ -2,6 +2,8 @@ export { createLocalClient } from './caller.js';
2
2
  export { DedupePlugin } from './dedupe-plugin.js';
3
3
  export { onError, onFinish, onStart, onSuccess } from './events.js';
4
4
  export { createImplementer, } from './implement.js';
5
+ export { mapStreamErrors } from './map-stream-errors.js';
5
6
  export { applyPlugins } from './plugin.js';
6
7
  export { isImplementedProcedure, lookupProcedure, runProcedure, } from './runtime.js';
8
+ export { validationError } from './validation-error.js';
7
9
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,YAAY,EAA4B,MAAM,oBAAoB,CAAA;AAC3E,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACnE,OAAO,EACL,iBAAiB,GAGlB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,YAAY,EAAmB,MAAM,aAAa,CAAA;AAC3D,OAAO,EAGL,sBAAsB,EACtB,eAAe,EAIf,YAAY,GACb,MAAM,cAAc,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,YAAY,EAA4B,MAAM,oBAAoB,CAAA;AAC3E,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACnE,OAAO,EACL,iBAAiB,GAGlB,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AAExD,OAAO,EAAE,YAAY,EAAmB,MAAM,aAAa,CAAA;AAC3D,OAAO,EAGL,sBAAsB,EACtB,eAAe,EAIf,YAAY,GACb,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Maps the errors an async iterable throws while it is being iterated.
3
+ * `fn` gets every thrown value and returns the error to throw instead; return
4
+ * the value unchanged to keep it (do that for `PFError`s, so `VALIDATION`
5
+ * failures from `stream()` and errors thrown with `errors.CODE()` reach the
6
+ * client as they are). The result is a plain async iterable (typed as `T`;
7
+ * no generator `throw()`). A value that is not an async iterable is returned
8
+ * unchanged, so one `.use()` middleware covers unary and stream procedures:
9
+ *
10
+ * ```ts no-check
11
+ * impl.use(async ({ next }) => {
12
+ * try {
13
+ * return mapStreamErrors(await next(), mapError)
14
+ * } catch (error) {
15
+ * throw mapError(error)
16
+ * }
17
+ * })
18
+ * ```
19
+ *
20
+ * The mapped error still goes through declared-error finalization (its `data`
21
+ * is checked against the contract), because the middleware runs inside the
22
+ * procedure chain. `return()` reaches the source iterator even before the
23
+ * first `next()`, and at most once.
24
+ */
25
+ export declare function mapStreamErrors<T>(value: T, fn: (error: unknown) => unknown): T;
26
+ //# sourceMappingURL=map-stream-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"map-stream-errors.d.ts","sourceRoot":"","sources":["../src/map-stream-errors.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAC/B,KAAK,EAAE,CAAC,EACR,EAAE,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,GAC9B,CAAC,CAKH"}
@@ -0,0 +1,60 @@
1
+ import { isAsyncIterable } from '@ts-pf/protocol';
2
+ /**
3
+ * Maps the errors an async iterable throws while it is being iterated.
4
+ * `fn` gets every thrown value and returns the error to throw instead; return
5
+ * the value unchanged to keep it (do that for `PFError`s, so `VALIDATION`
6
+ * failures from `stream()` and errors thrown with `errors.CODE()` reach the
7
+ * client as they are). The result is a plain async iterable (typed as `T`;
8
+ * no generator `throw()`). A value that is not an async iterable is returned
9
+ * unchanged, so one `.use()` middleware covers unary and stream procedures:
10
+ *
11
+ * ```ts no-check
12
+ * impl.use(async ({ next }) => {
13
+ * try {
14
+ * return mapStreamErrors(await next(), mapError)
15
+ * } catch (error) {
16
+ * throw mapError(error)
17
+ * }
18
+ * })
19
+ * ```
20
+ *
21
+ * The mapped error still goes through declared-error finalization (its `data`
22
+ * is checked against the contract), because the middleware runs inside the
23
+ * procedure chain. `return()` reaches the source iterator even before the
24
+ * first `next()`, and at most once.
25
+ */
26
+ export function mapStreamErrors(value, fn) {
27
+ if (!isAsyncIterable(value)) {
28
+ return value;
29
+ }
30
+ return mapIterable(value, fn);
31
+ }
32
+ // Hand-written, not an async generator: a generator's `return()` before its
33
+ // first `next()` never reaches the source iterator, so cancelling a stream
34
+ // that was never pulled would leak it.
35
+ function mapIterable(source, fn) {
36
+ return {
37
+ [Symbol.asyncIterator]() {
38
+ const it = source[Symbol.asyncIterator]();
39
+ let returned = false;
40
+ return {
41
+ async next() {
42
+ try {
43
+ return await it.next();
44
+ }
45
+ catch (error) {
46
+ throw fn(error);
47
+ }
48
+ },
49
+ async return() {
50
+ if (returned || !it.return) {
51
+ return { done: true, value: undefined };
52
+ }
53
+ returned = true;
54
+ return it.return();
55
+ },
56
+ };
57
+ },
58
+ };
59
+ }
60
+ //# sourceMappingURL=map-stream-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"map-stream-errors.js","sourceRoot":"","sources":["../src/map-stream-errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAEjD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,eAAe,CAC7B,KAAQ,EACR,EAA+B;IAE/B,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,KAAK,CAAA;IACd,CAAC;IACD,OAAO,WAAW,CAAC,KAAK,EAAE,EAAE,CAAM,CAAA;AACpC,CAAC;AAED,4EAA4E;AAC5E,2EAA2E;AAC3E,uCAAuC;AACvC,SAAS,WAAW,CAClB,MAA8B,EAC9B,EAA+B;IAE/B,OAAO;QACL,CAAC,MAAM,CAAC,aAAa,CAAC;YACpB,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;YACzC,IAAI,QAAQ,GAAG,KAAK,CAAA;YACpB,OAAO;gBACL,KAAK,CAAC,IAAI;oBACR,IAAI,CAAC;wBACH,OAAO,MAAM,EAAE,CAAC,IAAI,EAAE,CAAA;oBACxB,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBACf,MAAM,EAAE,CAAC,KAAK,CAAC,CAAA;oBACjB,CAAC;gBACH,CAAC;gBACD,KAAK,CAAC,MAAM;oBACV,IAAI,QAAQ,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC;wBAC3B,OAAO,EAAE,IAAI,EAAE,IAAa,EAAE,KAAK,EAAE,SAAS,EAAE,CAAA;oBAClD,CAAC;oBACD,QAAQ,GAAG,IAAI,CAAA;oBACf,OAAO,EAAE,CAAC,MAAM,EAAE,CAAA;gBACpB,CAAC;aACF,CAAA;QACH,CAAC;KACF,CAAA;AACH,CAAC"}
package/dist/runtime.d.ts CHANGED
@@ -80,7 +80,11 @@ export type PresentProcedures<T, TCtx, I> = T extends unknown ? {
80
80
  export type RouterImplCheck<T, TCtx, I> = MissingProcedures<T, I> & UnexpectedKeys<T, I> & PresentProcedures<T, TCtx, I>;
81
81
  export declare function isImplementedProcedure(value: unknown): value is ImplementedProcedure;
82
82
  export type ProcedureValidation = {
83
- /** Set false to skip the input schema. Default true. */
83
+ /**
84
+ * Set false to skip the input schema. Default true. When skipped, the
85
+ * handler gets the raw value although `input` is typed as parsed; throw
86
+ * `validationError(...)` from a handler that validates itself.
87
+ */
84
88
  input?: boolean;
85
89
  /** Set true to check the output schema, including stream output items. Default false. */
86
90
  output?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,iBAAiB,EAEtB,KAAK,sBAAsB,EAC3B,KAAK,mBAAmB,EAEzB,MAAM,iBAAiB,CAAA;AAExB,OAAO,EACL,KAAK,eAAe,EAErB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAA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YAAY,CAAC,EAAE,SAAS,eAAe,EAAE,CAAA;IACzC,UAAU,CAAC,EAAE,mBAAmB,CAAA;CACjC,CAAA;AA4BD,wBAAsB,YAAY,CAChC,IAAI,EAAE,oBAAoB,EAC1B,QAAQ,EAAE,OAAO,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC5B,OAAO,CAAC,OAAO,CAAC,CA+BlB;AA8HD,wBAAgB,eAAe,CAC7B,MAAM,EAAE,iBAAiB,EACzB,IAAI,EAAE,MAAM,EAAE,GACb,oBAAoB,GAAG,SAAS,CAWlC"}
package/dist/runtime.js CHANGED
@@ -2,6 +2,7 @@ import { validateSchema, } from '@ts-pf/contract';
2
2
  import { isAsyncIterable, PFError } from '@ts-pf/protocol';
3
3
  import { runCallInterceptors, } from './call-interceptor.js';
4
4
  import { createErrorFactory, finalizeDeclaredError } from './error-factory.js';
5
+ import { validationError } from './validation-error.js';
5
6
  export function isImplementedProcedure(value) {
6
7
  return (typeof value === 'object' &&
7
8
  value !== null &&
@@ -51,11 +52,7 @@ async function runUse(run, index) {
51
52
  if (run.validateInput && inputSchema) {
52
53
  const result = await validateSchema(inputSchema, run.input);
53
54
  if (!result.success) {
54
- throw new PFError({
55
- code: 'VALIDATION',
56
- message: 'Validation failed',
57
- data: { issues: result.issues },
58
- });
55
+ throw validationError(result.issues);
59
56
  }
60
57
  run.input = result.value;
61
58
  }
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,cAAc,GACf,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AAC1D,OAAO,EAEL,mBAAmB,GACpB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAwJ9E,MAAM,UAAU,sBAAsB,CACpC,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AAO,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;IAC1E,CAAC;IACD,OAAO,OAAO,IAAI,sBAAsB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAA;AACzE,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type { ValidationIssue } from '@ts-pf/contract';
2
+ import { PFError } from '@ts-pf/protocol';
3
+ /**
4
+ * The `VALIDATION` error `runProcedure` throws when the input check fails:
5
+ * code `VALIDATION`, message `Validation failed`, `data: { issues }`, no
6
+ * `status` (`httpStatus()` maps it to 422). Throw it from a handler that
7
+ * validates on its own, e.g. under `validation.input: false`, with
8
+ * `toValidationIssues` from `@ts-pf/contract` for Standard Schema issues.
9
+ */
10
+ export declare function validationError(issues: ReadonlyArray<ValidationIssue>): PFError;
11
+ //# sourceMappingURL=validation-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation-error.d.ts","sourceRoot":"","sources":["../src/validation-error.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AAEzC;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,aAAa,CAAC,eAAe,CAAC,GACrC,OAAO,CAMT"}
@@ -0,0 +1,16 @@
1
+ import { PFError } from '@ts-pf/protocol';
2
+ /**
3
+ * The `VALIDATION` error `runProcedure` throws when the input check fails:
4
+ * code `VALIDATION`, message `Validation failed`, `data: { issues }`, no
5
+ * `status` (`httpStatus()` maps it to 422). Throw it from a handler that
6
+ * validates on its own, e.g. under `validation.input: false`, with
7
+ * `toValidationIssues` from `@ts-pf/contract` for Standard Schema issues.
8
+ */
9
+ export function validationError(issues) {
10
+ return new PFError({
11
+ code: 'VALIDATION',
12
+ message: 'Validation failed',
13
+ data: { issues },
14
+ });
15
+ }
16
+ //# sourceMappingURL=validation-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation-error.js","sourceRoot":"","sources":["../src/validation-error.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AAEzC;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,MAAsC;IAEtC,OAAO,IAAI,OAAO,CAAC;QACjB,IAAI,EAAE,YAAY;QAClB,OAAO,EAAE,mBAAmB;QAC5B,IAAI,EAAE,EAAE,MAAM,EAAE;KACjB,CAAC,CAAA;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ts-pf/server",
3
- "version": "0.4.3",
3
+ "version": "0.5.0",
4
4
  "description": "Implementer, middleware, runProcedure, and in-process local client",
5
5
  "keywords": [
6
6
  "ts-pf",
@@ -49,8 +49,8 @@
49
49
  "lint": "biome check src tests"
50
50
  },
51
51
  "dependencies": {
52
- "@ts-pf/contract": "0.2.3",
53
- "@ts-pf/protocol": "0.2.2"
52
+ "@ts-pf/contract": "0.5.0",
53
+ "@ts-pf/protocol": "0.5.0"
54
54
  },
55
55
  "devDependencies": {
56
56
  "zod": "^4.0.0"
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ts-pf-server
3
- description: "Use when implementing a ts-pf contract with createImplementer, middleware, runProcedure, createLocalClient, or server DedupePlugin / CallInterceptor. Triggers: @ts-pf/server, createImplementer, .use(), .useAfter(), createLocalClient, applyPlugins."
3
+ description: "Use when implementing a ts-pf contract with createImplementer, middleware, runProcedure, createLocalClient, or server DedupePlugin / CallInterceptor. Triggers: @ts-pf/server, createImplementer, .use(), .useAfter(), createLocalClient, applyPlugins, validationError, mapStreamErrors."
4
4
  ---
5
5
 
6
6
  # @ts-pf/server
@@ -41,7 +41,7 @@ export const app = impl.use(requireUser).router({
41
41
  })
42
42
  ```
43
43
 
44
- `.use()` runs before input validation (`input: unknown`) and takes the same loose `MiddlewareFn` on `impl.use(mw)` and on a per-procedure `impl.planet.find.use(mw)`, so a middleware from `impl.middleware(fn)` fits both. `.useAfter()` runs after and is typed with that procedure's input and output, so it takes an inline function. Input checks default on, so `.useAfter()` then sees the parsed input. `validation: { input: false }` skips the input schema, including stream input items, and `.useAfter()` sees the raw value. Output checks, including stream output items, run only when `validation: { output: true }`. Unary output failure is `INTERNAL` with no issues. A bad stream output item is `VALIDATION` with issues. Parsed output (strip, defaults, transforms) is applied only when output checks run. Declared error `data` is always checked. `$context<C>()` is the context type source; middleware runtime-merges and does not infer added keys. Pass HTTP `Request` in `FetchHandler.handle(..., { context })`, not via `$context` alone. Name the implemented router `app`. Default `DedupePlugin` keys every unary call — pass `key` to restrict to reads.
44
+ `.use()` runs before input validation (`input: unknown`) and takes the same loose `MiddlewareFn` on `impl.use(mw)` and on a per-procedure `impl.planet.find.use(mw)`, so a middleware from `impl.middleware(fn)` fits both. `.useAfter()` runs after and is typed with that procedure's input and output, so it takes an inline function. Input checks default on, so `.useAfter()` then sees the parsed input. `validation: { input: false }` skips the input schema, including stream input items, and `.useAfter()` and the handler see the raw value even though `input` is still typed as parsed (contract-only narrowing — zod `.omit()`, defaults, transforms — is not applied); validate in the handler and `throw validationError(toValidationIssues(result.issues))` (`toValidationIssues` from `@ts-pf/contract`) to answer in the built-in `VALIDATION` shape. Output checks, including stream output items, run only when `validation: { output: true }`. Unary output failure is `INTERNAL` with no issues. A bad stream output item is `VALIDATION` with issues. Parsed output (strip, defaults, transforms) is applied only when output checks run. Declared error `data` is always checked. A hand-built `new PFError({ code })` for a declared code gets the declared `status` when it has none, exactly like `errors.CODE()`, and keeps its `cause` (`message` is not filled). `$context<C>()` is the context type source; middleware runtime-merges and does not infer added keys. Pass HTTP `Request` in `FetchHandler.handle(..., { context })`, not via `$context` alone. Name the implemented router `app`. Default `DedupePlugin` keys every unary call — pass `key` to restrict to reads.
45
45
 
46
46
  `impl.router()` returns `ImplementedRouter<T, TCtx>`: `TCtx` is the `$context<C>()` type and each handler is an `ImplementedProcedure<typeof contract.planet.find, TCtx>` (type-only brands; the runtime object is unchanged). A missing key, an extra key, a handler built from another procedure under this key, or a slice built with a different `$context` is a type error that names the key. `FetchHandler`, the message handlers, `createLocalClient`, and `@ts-pf/astro` read `TCtx` from `app`, so `context` is checked against it. A tree not produced by `impl.router()` (a plain object of handlers) infers `unknown`; use `impl.router()`, or pick procedures into a second `impl.router()` call, to keep the check.
47
47
 
@@ -52,11 +52,109 @@ runProcedure(proc, input, context, { validation: { input: false } })
52
52
 
53
53
  Nest finished slice apps: `impl.router({ planet: planetApp, star: starApp })`. Each slice is `createImplementer(sliceContract).$context<AppCtx>().router({ ... })` with the same `AppCtx` (a slice that needs less than the root provides also nests; one that needs other keys does not). Root `.use(mw)` prepends onto nested procedures. Procedure `path` is the composed tree (`planet.find`). Pick an implemented procedure into a smaller server: `{ list: usersApp.list }`.
54
54
 
55
+ ### Keys middleware adds
56
+
57
+ Middleware does not narrow context (yet). Declare added keys optional on `$context`, set them in one `.use()` middleware (or throw), and narrow with a checking helper, never a bare cast at call sites. Context factories omit the optional keys (no placeholders):
58
+
59
+ ```ts
60
+ import { PFError } from '@ts-pf/protocol'
61
+ import { createImplementer } from '@ts-pf/server'
62
+
63
+ type AppCtx = { db: Db; req: Request; user?: User }
64
+ const impl = createImplementer(contract).$context<AppCtx>()
65
+
66
+ const requireUser = impl.middleware(async ({ context, next }) => {
67
+ const user = await auth(context.req)
68
+ if (!user) throw new PFError({ code: 'UNAUTHORIZED', status: 401 })
69
+ return next({ context: { user } }) // merges
70
+ })
71
+
72
+ function signedIn(context: AppCtx): AppCtx & { user: User } {
73
+ if (!context.user) throw new PFError({ code: 'UNAUTHORIZED', status: 401 })
74
+ return context as AppCtx & { user: User }
75
+ }
76
+
77
+ const create = impl.planet.create.use(requireUser).handler(async ({ input, context }) => {
78
+ const { db, user } = signedIn(context)
79
+ console.log(user.id)
80
+ return db.planets.create(input)
81
+ })
82
+ // context factory: (req) => ({ db, req })
83
+ ```
84
+
85
+ ### Mapping domain errors
86
+
87
+ `try { await next() } catch` misses throws during stream iteration (the iterable is returned first). Use one mapping middleware, first in the chain; `mapStreamErrors(value, fn)` wraps an async iterable (a throw from the iterator's `next()` becomes `fn(error)`; `return()` reaches the source, even before the first item) and returns anything else unchanged:
88
+
89
+ ```ts
90
+ import { isPFError } from '@ts-pf/protocol'
91
+ import { createImplementer, mapStreamErrors } from '@ts-pf/server'
92
+
93
+ declare function toPFError(error: unknown): unknown // your domain mapping
94
+ const mapError = (error: unknown) => (isPFError(error) ? error : toPFError(error))
95
+
96
+ const impl = createImplementer(contract).$context<{ db: Db }>()
97
+ const root = impl.use(async ({ next }) => {
98
+ try {
99
+ return mapStreamErrors(await next(), mapError)
100
+ } catch (error) {
101
+ throw mapError(error)
102
+ }
103
+ })
104
+ ```
105
+
106
+ `fn` returns the error to throw and sees every thrown value: return `PFError`s unchanged so input / stream-item `VALIDATION` and `errors.CODE()` throws survive. Mapped errors still get the declared-error `data` check (invalid → `INTERNAL`) and the declared `status` when they have none, because middleware runs inside the procedure; set the `message` on the `PFError` you return. Not in a call interceptor: interceptors see errors after that check.
107
+
108
+ Domain error catalog (the domain layer owns its codes): code → message, a status map where `null` = not exposed (sent as `INTERNAL`), `clientErrors` derived from the exposed codes for `.errors(clientErrors)`, and a `mapDomainError` that needs only `@ts-pf/protocol`:
109
+
110
+ ```ts
111
+ import { PFError } from '@ts-pf/protocol'
112
+ import type { MiddlewareFn } from '@ts-pf/server'
113
+ import { mapStreamErrors } from '@ts-pf/server'
114
+
115
+ const messages = { BOOK_NOT_FOUND: 'Book not found', LEDGER_MISMATCH: 'Ledger mismatch' } as const
116
+ type DomainCode = keyof typeof messages
117
+ class DomainError extends Error {
118
+ readonly code: DomainCode
119
+ constructor(code: DomainCode) {
120
+ super(messages[code])
121
+ this.code = code
122
+ }
123
+ }
124
+ const status = { BOOK_NOT_FOUND: 404, LEDGER_MISMATCH: null } as const satisfies Record<DomainCode, number | null>
125
+ export const clientErrors = { BOOK_NOT_FOUND: { status: status.BOOK_NOT_FOUND, message: messages.BOOK_NOT_FOUND } } // derive from `status` in real code
126
+
127
+ function mapDomainError(error: unknown): unknown {
128
+ if (!(error instanceof DomainError)) return error // PFErrors and unknown throws as is
129
+ if (status[error.code] === null) return new PFError({ code: 'INTERNAL', message: 'Internal server error', cause: error })
130
+ return new PFError({ code: error.code, message: error.message, cause: error }) // status filled from the declared entry
131
+ }
132
+
133
+ // MiddlewareFn is type-only; mapStreamErrors is a runtime @ts-pf/server import (peer dep in a shared package).
134
+ export const mapDomainErrors: MiddlewareFn = async ({ next }) => {
135
+ try {
136
+ return mapStreamErrors(await next(), mapDomainError)
137
+ } catch (error) {
138
+ throw mapDomainError(error)
139
+ }
140
+ }
141
+ // impl.use(mapDomainErrors) — first in the chain
142
+ ```
143
+
144
+ A code the procedure does not declare is sent without the declared status (HTTP 400) and is not in the client type. `.errors(clientErrors)` on every procedure is simple but loses per-procedure client error types: a shared base map plus per-area spreads is a good middle ground, `.errors({ ...baseErrors, ...areaErrors })` (a second `.errors()` call replaces the map). Full recipe: `@ts-pf/server` README "A domain error catalog"; trade-off: [Evolving a contract](https://github.com/crobinson42/ts-pf/blob/main/docs/evolution.md#error-maps-shared-or-per-procedure).
145
+
146
+ ### Middleware and handler rules
147
+
148
+ - `next()` at most once per `.use()` / `.useAfter()` call. Execution state (`input`, `context`) is shared: a second call re-runs inner middleware on already-parsed input with the context inner middleware added, and concurrent calls race. Retries / hedging are a `CallInterceptor` (its `next()` may run more than once; each gets a fresh execution).
149
+ - Handler `signal` is optional: `FetchHandler` and message handlers always pass one; `createLocalClient` without `{ signal }`, direct `runProcedure`, and `@ts-pf/mcp` without a host signal may not. Guard: `signal?.throwIfAborted()` / `signal ?? AbortSignal.timeout(ms)`.
150
+
55
151
  ## API
56
152
 
57
153
  - `createImplementer`, `createLocalClient`, `runProcedure`, `lookupProcedure`, `ProcedureValidation`
154
+ - `validationError(issues)` — the `VALIDATION` `PFError` the input check throws (`Validation failed`, `data: { issues }`), for handlers that validate themselves
58
155
  - `ImplementedRouter<T, TCtx>`, `ImplementedProcedure<TContract, TCtx>`, `RouterImpl<T, TCtx>`
59
156
  - `applyPlugins`, `CallPlugin`, `CallInterceptor`, `DedupePlugin`
157
+ - `mapStreamErrors`
60
158
  - `onStart` / `onSuccess` / `onError` / `onFinish`
61
159
 
62
160
  ## Pair with
@@ -72,3 +170,7 @@ Nest finished slice apps: `impl.router({ planet: planetApp, star: starApp })`. E
72
170
  - Attach interceptors or `validation` on `createImplementer` — they attach per caller (`createLocalClient` / handler `{ interceptors, validation }`).
73
171
  - Default `DedupePlugin` on non-idempotent writes.
74
172
  - `mergeRouters` — nest `impl.router({ planet: planetApp })`.
173
+ - Call middleware `next()` twice (retry in a `CallInterceptor`).
174
+ - Map domain errors with only a `catch` around `await next()` — it misses mid-stream throws; add `mapStreamErrors`.
175
+ - Map domain errors in a call interceptor — it skips the declared `data` check.
176
+ - Cast `context as AppCtx & { user: User }` at call sites — narrow with a checking helper.