@spfn/core 0.3.0-beta.1 → 0.3.0-beta.11

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.
Files changed (69) hide show
  1. package/README.md +301 -26
  2. package/dist/app-config/index.d.ts +96 -0
  3. package/dist/app-config/index.js +58 -0
  4. package/dist/app-config/index.js.map +1 -0
  5. package/dist/authz/index.js +1 -381
  6. package/dist/authz/index.js.map +1 -1
  7. package/dist/{boss-D16fO2oG.d.ts → boss-BiDCbbAQ.d.ts} +60 -7
  8. package/dist/config/index.d.ts +0 -63
  9. package/dist/config/index.js +12 -12
  10. package/dist/config/index.js.map +1 -1
  11. package/dist/contract/index.d.ts +5 -4
  12. package/dist/db/index.d.ts +201 -34
  13. package/dist/db/index.js +294 -158
  14. package/dist/db/index.js.map +1 -1
  15. package/dist/{define-middleware-DfDP39Nq.d.ts → define-middleware-CVKgqo8S.d.ts} +1 -1
  16. package/dist/env/loader.js +24 -1
  17. package/dist/env/loader.js.map +1 -1
  18. package/dist/errors/index.js +1 -381
  19. package/dist/errors/index.js.map +1 -1
  20. package/dist/event/sse/client.d.ts +15 -2
  21. package/dist/event/sse/client.js +38 -2
  22. package/dist/event/sse/client.js.map +1 -1
  23. package/dist/job/index.d.ts +48 -3
  24. package/dist/job/index.js +118 -40
  25. package/dist/job/index.js.map +1 -1
  26. package/dist/logger/index.js +0 -12
  27. package/dist/logger/index.js.map +1 -1
  28. package/dist/middleware/index.d.ts +6 -2
  29. package/dist/middleware/index.js +7 -388
  30. package/dist/middleware/index.js.map +1 -1
  31. package/dist/nextjs/index.d.ts +73 -6
  32. package/dist/nextjs/index.js +40 -1
  33. package/dist/nextjs/index.js.map +1 -1
  34. package/dist/nextjs/server.d.ts +35 -2
  35. package/dist/nextjs/server.js +14 -0
  36. package/dist/nextjs/server.js.map +1 -1
  37. package/dist/ops/index.d.ts +115 -14
  38. package/dist/ops/index.js +339 -15
  39. package/dist/ops/index.js.map +1 -1
  40. package/dist/route/index.d.ts +5 -3
  41. package/dist/route/index.js +1 -1
  42. package/dist/route/index.js.map +1 -1
  43. package/dist/{router-ukNdAZcN.d.ts → route-builder-2ani2jEI.d.ts} +3 -126
  44. package/dist/router-DJdpwuB6.d.ts +127 -0
  45. package/dist/server/index.d.ts +130 -11
  46. package/dist/server/index.js +714 -70
  47. package/dist/server/index.js.map +1 -1
  48. package/dist/{types-Bvvig_tT.d.ts → types-ClQVomgV.d.ts} +1 -1
  49. package/dist/{types-9oszaJqp.d.ts → types-yv6z_mK7.d.ts} +122 -3
  50. package/docs/file-upload.md +195 -333
  51. package/package.json +14 -8
  52. package/src/cache/README.md +330 -0
  53. package/src/codegen/README.md +516 -0
  54. package/src/config/README.md +326 -0
  55. package/src/contract/README.md +326 -0
  56. package/src/db/README.md +589 -0
  57. package/src/db/manager/README.md +500 -0
  58. package/src/db/schema/README.md +354 -0
  59. package/src/db/transaction/README.md +822 -0
  60. package/src/env/README.md +651 -0
  61. package/src/errors/README.md +429 -0
  62. package/src/event/README.md +741 -0
  63. package/src/job/README.md +613 -0
  64. package/src/logger/README.md +321 -0
  65. package/src/middleware/README.md +634 -0
  66. package/src/nextjs/README.md +649 -0
  67. package/src/route/README.md +744 -0
  68. package/src/security/README.md +100 -0
  69. package/src/server/README.md +704 -0
@@ -0,0 +1,649 @@
1
+ # @spfn/core/nextjs — Type-safe Next.js RPC client + proxy
2
+
3
+ End-to-end type-safe API client (`createApi<AppRouter>()`) and an RPC proxy route handler
4
+ (`createRpcProxy`) that bridges a Next.js App Router app to a SPFN `define-route` backend.
5
+ No per-route metadata codegen is required for the client — method/path resolution happens
6
+ at the proxy from a generated `routeMap`.
7
+
8
+ ```
9
+ Client (browser / RSC) Proxy (Next.js API route) SPFN backend
10
+ api.getUser.call({...}) ──GET/POST──▶ /api/rpc/{routeName} ──HTTP──▶ resolved method+path
11
+ createApi<AppRouter>() createRpcProxy({ routeMap }) define-route handler
12
+ ```
13
+
14
+ ## Import paths
15
+
16
+ There are **two** entry points. Picking the wrong one breaks the build — `/server` pulls in
17
+ `next/headers` + `next/server` and must never reach a Client Component bundle.
18
+
19
+ ```typescript
20
+ // Client-safe (Client Components, Server Components, anywhere). NO next/headers.
21
+ import { createApi, ApiError } from '@spfn/core/nextjs';
22
+
23
+ // Server-only (API routes, Server Components). Uses next/headers + next/server.
24
+ import { createRpcProxy, registerInterceptors } from '@spfn/core/nextjs/server';
25
+ ```
26
+
27
+ `createRpcProxy` and the interceptor registry are **only** exported from
28
+ `@spfn/core/nextjs/server`. `createApi` / `ApiError` are **only** exported from
29
+ `@spfn/core/nextjs`. There is no barrel that re-exports both.
30
+
31
+ | Path | Environment | Exports |
32
+ |------|-------------|---------|
33
+ | `@spfn/core/nextjs` | Client + Server | `createApi`, `ApiError`, all client types |
34
+ | `@spfn/core/nextjs/server` | Server only | `createRpcProxy`, interceptor registry + helpers, interceptor types |
35
+
36
+ ---
37
+
38
+ ## Public API (complete)
39
+
40
+ From `@spfn/core/nextjs` (client-safe):
41
+
42
+ - Values: `createApi`, `ApiError`
43
+ - Types: `Client`, `RouteClient`, `ApiConfig`, `CallOptions`, `InferRouteInput`,
44
+ `InferRouteOutput`, `RouterInput`, `RouterOutput`, `StructuredInput`,
45
+ `RequestInterceptor`, `ResponseInterceptor`, `CookieOptions`, `SetCookie`
46
+
47
+ From `@spfn/core/nextjs/server` (server-only):
48
+
49
+ - Values: `createRpcProxy`, `registerInterceptors`, `interceptorRegistry`, `matchPath`,
50
+ `matchMethod`, `filterMatchingInterceptors`, `executeRequestInterceptors`,
51
+ `executeResponseInterceptors`
52
+ - Types: `RpcProxyConfig`, `RequestInterceptorContext`, `ResponseInterceptorContext`,
53
+ `RequestInterceptor`, `ResponseInterceptor` (the *proxy* `(ctx, next)` shape — distinct
54
+ from the client interceptor types of the same name), `InterceptorRule`, `ProxyConfig`
55
+
56
+ > The client `RequestInterceptor`/`ResponseInterceptor` (`(url, init)` / `(response, body)`)
57
+ > and the proxy `RequestInterceptor`/`ResponseInterceptor` (`(ctx, next) => Promise<void>`)
58
+ > are **different types that share a name** across the two entry points. Don't cross them.
59
+
60
+ ---
61
+
62
+ ## Quick Start
63
+
64
+ ### 1. Define the router (server)
65
+
66
+ ```typescript
67
+ // server/router.ts
68
+ import { defineRouter, route } from '@spfn/core/route';
69
+ import { Type } from '@sinclair/typebox';
70
+
71
+ export const appRouter = defineRouter({
72
+ getUser: route.get('/users/:id')
73
+ .input({ params: Type.Object({ id: Type.String() }) })
74
+ .handler(async (c) => {
75
+ const { params } = await c.data();
76
+ return { id: params.id, name: 'John' };
77
+ }),
78
+
79
+ createUser: route.post('/users')
80
+ .input({ body: Type.Object({ name: Type.String() }) })
81
+ .handler(async (c) => {
82
+ const { body } = await c.data();
83
+ return { id: '2', name: body.name };
84
+ }),
85
+ });
86
+
87
+ export type AppRouter = typeof appRouter;
88
+ ```
89
+
90
+ ### 2. Create the client (no metadata needed)
91
+
92
+ ```typescript
93
+ // lib/api.ts
94
+ import { createApi } from '@spfn/core/nextjs';
95
+ import type { AppRouter } from '@/server/router';
96
+
97
+ export const api = createApi<AppRouter>();
98
+ ```
99
+
100
+ ### 3. Mount the proxy route
101
+
102
+ ```typescript
103
+ // app/api/rpc/[routeName]/route.ts
104
+ import { createRpcProxy } from '@spfn/core/nextjs/server';
105
+ import { routeMap } from '@/generated/route-map';
106
+
107
+ export const { GET, POST } = createRpcProxy({ routeMap });
108
+ ```
109
+
110
+ ### 4. Call it
111
+
112
+ ```typescript
113
+ const user = await api.getUser.call({ params: { id: '123' } }); // GET /api/rpc/getUser?input=...
114
+ const created = await api.createUser.call({ body: { name: 'A' } }); // POST /api/rpc/createUser
115
+ ```
116
+
117
+ ---
118
+
119
+ ## Client — `createApi`
120
+
121
+ ```typescript
122
+ function createApi<TRouter extends Router<any>>(config?: ApiConfig): Client<TRouter>;
123
+ ```
124
+
125
+ Returns a `Proxy`: every property access (`api.getUser`) yields a `RouteClient` builder.
126
+ Calls are made via `.call(input)`.
127
+
128
+ The client is one **flat** namespace, holding exactly the names the server registers. A
129
+ route declared inside a nested `defineRouter` is reached by its own key — `registerRoutes`
130
+ mounts it under that key, the proxy resolves that name against the route map, and
131
+ `RouterOutput` takes the same name:
132
+
133
+ ```typescript
134
+ const appRouter = defineRouter({
135
+ getRoot,
136
+ users: defineRouter({ getUser }),
137
+ });
138
+
139
+ await api.getUser.call({ params: { id: '123' } }); // ✅ GET /api/rpc/getUser
140
+ await api.users.getUser.call({ ... }); // ❌ compile error — `users` is a group
141
+ ```
142
+
143
+ There is no dot notation: a property access never yields another proxy, so a group key
144
+ names nothing on either side. A name two branches both declare is left out of the client
145
+ rather than resolved to one of them, and `.packages()` routes stay out on purpose — call
146
+ them through the package's own client (`authApi`, `cmsApi`).
147
+
148
+ ### Structured input
149
+
150
+ Input mirrors the route's `.input({...})` definition exactly. Empty sections are omitted
151
+ from the type, so you only pass what the route declares:
152
+
153
+ ```typescript
154
+ await api.getUser.call({ params: { id: '123' } });
155
+ await api.getUser.call({ params: { id: '123' }, query: { include: 'posts' } });
156
+ await api.createUser.call({ body: { name: 'John', email: 'a@b.com' } });
157
+ await api.updateUser.call({ params: { id: '123' }, body: { name: 'Jane' } });
158
+
159
+ // Route with no required input → call() with no argument:
160
+ await api.listAll.call();
161
+ ```
162
+
163
+ ### Method detection (client → proxy URL)
164
+
165
+ The client picks the HTTP method to the **proxy** purely from input shape:
166
+
167
+ - Has `body` **or** non-empty `formData` → `POST /api/rpc/{routeName}` (JSON body, or
168
+ `multipart/form-data` when `formData` is present)
169
+ - Otherwise → `GET /api/rpc/{routeName}?input={encoded}` (browser-cacheable)
170
+
171
+ This is the method to the proxy only. The *actual* backend method (PUT/PATCH/DELETE/…) is
172
+ resolved by the proxy from `routeMap` — see below.
173
+
174
+ ### File upload (`formData`)
175
+
176
+ ```typescript
177
+ await api.uploadAvatar.call({
178
+ params: { id: '123' },
179
+ formData: { file: fileInput.files[0], description: 'Profile photo' },
180
+ });
181
+ ```
182
+
183
+ `File` / `File[]` values go into a `FormData`; the other sections (`params`, `query`,
184
+ `headers`, `cookies`) are bundled into a `__metadata` JSON part. The proxy unpacks
185
+ `__metadata` and forwards a clean `multipart/form-data` body to the backend. `Content-Type`
186
+ is left unset so the boundary is generated automatically.
187
+
188
+ ### Options via method chaining
189
+
190
+ Options are set fluently (each returns a cloned builder) and applied on `.call()`:
191
+
192
+ ```typescript
193
+ const user = await api.getUser
194
+ .headers({ 'X-Custom': 'value' })
195
+ .cookies({ session: 'xxx' })
196
+ .fetchOptions({ next: { revalidate: 60 } })
197
+ .onRequest((url, init) => init) // client RequestInterceptor
198
+ .onResponse((res, body) => ({ response: res, body })) // client ResponseInterceptor
199
+ .call({ params: { id: '123' } });
200
+ ```
201
+
202
+ ### `ApiConfig`
203
+
204
+ ```typescript
205
+ interface ApiConfig {
206
+ baseUrl?: string; // default '/api/rpc'
207
+ headers?: Record<string, string>; // default headers on every request
208
+ timeout?: number; // default env.SERVER_TIMEOUT (120000 ms)
209
+ fetch?: typeof fetch; // custom fetch impl
210
+ onRequest?: RequestInterceptor; // global, (url, init) => init
211
+ onResponse?: ResponseInterceptor; // global, (response, body) => { response, body }
212
+ errorRegistry?: ErrorRegistry | ErrorRegistryInput[]; // custom error deserialization
213
+ debug?: boolean; // default false
214
+ }
215
+ ```
216
+
217
+ `errorRegistry`: the core `errorRegistry` is **always** merged in automatically. Pass an
218
+ array to add your app/package error registries on top:
219
+
220
+ ```typescript
221
+ import { errorRegistry } from '@spfn/core/errors';
222
+ const api = createApi<AppRouter>({ errorRegistry: [errorRegistry, authErrorRegistry] });
223
+ ```
224
+
225
+ ### `CallOptions` (per-call, also settable via chaining)
226
+
227
+ ```typescript
228
+ interface CallOptions {
229
+ timeout?: number;
230
+ headers?: Record<string, string>;
231
+ cookies?: Record<string, string>; // override only; cookies are auto-forwarded otherwise
232
+ onRequest?: RequestInterceptor;
233
+ onResponse?: ResponseInterceptor;
234
+ fetchOptions?: RequestInit & { next?: { revalidate?: number | false; tags?: string[] } };
235
+ }
236
+ ```
237
+
238
+ ### Automatic cookie forwarding (SSR)
239
+
240
+ When `createApi` runs **on the server** (RSC / route handler) it auto-detects request
241
+ cookies via `next/headers` `cookies()` and forwards them as the `Cookie` header. In the
242
+ browser, cookies are sent by the browser automatically. You only need `.cookies({...})` /
243
+ `options.cookies` to **override**. Outside a request context (static generation, build) the
244
+ cookie read silently yields none.
245
+
246
+ ### SSR base URL resolution
247
+
248
+ For absolute fetches on the server the client uses `env.SPFN_APP_URL`. If unset, it falls
249
+ back to reconstructing the origin from the incoming request's `host` /
250
+ `x-forwarded-proto` headers (via `next/headers`); failing that, it uses a relative URL.
251
+
252
+ ---
253
+
254
+ ## Proxy — `createRpcProxy`
255
+
256
+ ```typescript
257
+ function createRpcProxy(config: RpcProxyConfig): {
258
+ GET: (req, ctx) => Promise<NextResponse>;
259
+ POST: (req, ctx) => Promise<NextResponse>;
260
+ };
261
+ ```
262
+
263
+ Returns `{ GET, POST }` handlers for an App Router catch-all route. It:
264
+
265
+ 1. Reads `routeName` from the async `params` (`context.params: Promise<{ routeName?: string }>` — Next.js 15).
266
+ 2. Parses `input` from `?input=` (GET) or the JSON / `multipart/form-data` body (POST).
267
+ 3. Resolves `routeMap[routeName]` → `{ method, path }`; **404** if missing.
268
+ 4. Substitutes `:params` into `path`, appends the query string.
269
+ 5. Forwards to `${apiUrl}${path}${query}` with the resolved backend method, running matching
270
+ interceptors before/after.
271
+ 6. Wraps the backend response in a `NextResponse` (special-casing `204`), forwards response
272
+ headers, and appends any `Set-Cookie` pushed by interceptors.
273
+
274
+ ### `RpcProxyConfig`
275
+
276
+ ```typescript
277
+ interface RpcProxyConfig {
278
+ routeMap: RouteMap; // REQUIRED — Record<routeName, { method, path }>
279
+ apiUrl?: string; // default env.SPFN_API_URL || 'http://localhost:8790'
280
+ timeout?: number; // default env.RPC_PROXY_TIMEOUT (120000 ms); AbortController
281
+ debug?: boolean; // default env.NODE_ENV === 'development'
282
+ headers?: Record<string, string>; // added to every forwarded request
283
+ interceptors?: InterceptorRule[]; // inline interceptors (array, NOT { request, response })
284
+ autoDiscoverInterceptors?: boolean; // default true — pull from registry
285
+ disableAutoInterceptors?: string[]; // e.g. ['auth'] — exclude registered packages
286
+ proxySecret?: string; // default env.SPFN_PROXY_SECRET — HMAC-sign forwarded requests (proxy-guard)
287
+ }
288
+
289
+ interface RouteMapEntry { method: HttpMethod; path: string; }
290
+ type RouteMap = Record<string, RouteMapEntry>;
291
+ ```
292
+
293
+ ### `routeMap` — the proxy's source of truth
294
+
295
+ `routeMap` comes from codegen (`@/generated/route-map`). Merge in route maps exported by
296
+ SPFN packages so their endpoints are reachable through the same proxy:
297
+
298
+ ```typescript
299
+ // app/api/rpc/[routeName]/route.ts
300
+ import '@spfn/auth/nextjs/api'; // side-effect: registers auth interceptors
301
+ import { createRpcProxy } from '@spfn/core/nextjs/server';
302
+ import { authRouteMap } from '@spfn/auth';
303
+ import { eventRouteMap } from '@spfn/core/event';
304
+ import { routeMap } from '@/generated/route-map';
305
+
306
+ export const { GET, POST } = createRpcProxy({
307
+ routeMap: { ...routeMap, ...authRouteMap, ...eventRouteMap },
308
+ });
309
+ ```
310
+
311
+ A `routeName` absent from the merged `routeMap` returns **404** from the proxy (not from the
312
+ backend). After adding routes, re-run codegen and clear `.spfn` cache if stale.
313
+
314
+ ### Header forwarding & client IP
315
+
316
+ Request headers are forwarded to the backend by an **allowlist**, not copied wholesale. Only
317
+ `content-type`, `authorization`, `cookie`, `user-agent`, `accept`, `accept-language`, and
318
+ `origin` pass through; everything else on the inbound request is dropped.
319
+
320
+ `X-Forwarded-For` is **not** in that allowlist, so it is not forwarded verbatim. Instead the
321
+ proxy resolves the real client IP from the inbound `X-Forwarded-For` chain — hop-aware, taking
322
+ the rightmost `TRUSTED_PROXY_HOPS` (default `1`) entries as your own trusted infra — and
323
+ re-emits that single address under a dedicated header, `x-spfn-proxy-client-ip`. This avoids
324
+ passing a client-controllable header straight through to the backend.
325
+
326
+ The backend only **trusts** that header on requests it can prove came through this proxy. Set
327
+ the same **`SPFN_PROXY_SECRET`** on the proxy (or `proxySecret` in config) and on the backend:
328
+ the proxy then HMAC-signs each forwarded request and the backend's proxy-guard marks it
329
+ verified (`clientType ≠ 'untrusted'`), so `getClientIp(c)` returns the real visitor IP from
330
+ `x-spfn-proxy-client-ip`. See [@spfn/core/middleware](../middleware/README.md) proxy-guard +
331
+ `getClientIp`.
332
+
333
+ Without a shared secret the request is unsigned, the backend won't trust that header, and
334
+ `getClientIp` falls back to the raw `X-Forwarded-For` first hop — which the proxy didn't
335
+ forward, so the client IP collapses to the TCP peer or `'unknown'`. If your visitor IP is
336
+ missing in production, set `SPFN_PROXY_SECRET` on both sides (and match `TRUSTED_PROXY_HOPS`
337
+ to your LB/nginx depth) rather than widening the header allowlist — forwarding raw
338
+ `X-Forwarded-For` reintroduces a spoofable IP.
339
+
340
+ ### Full config example
341
+
342
+ ```typescript
343
+ export const { GET, POST } = createRpcProxy({
344
+ routeMap: { ...routeMap, ...authRouteMap },
345
+ apiUrl: process.env.SPFN_API_URL,
346
+ timeout: 60000,
347
+ debug: true,
348
+ headers: { 'X-API-Key': process.env.SPFN_API_KEY! },
349
+ interceptors: [
350
+ {
351
+ pathPattern: '/_auth/*',
352
+ method: 'POST',
353
+ response: async (ctx, next) => {
354
+ if (ctx.response.body?.token) {
355
+ ctx.setCookies.push({
356
+ name: 'session',
357
+ value: ctx.response.body.token,
358
+ options: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 86400 },
359
+ });
360
+ }
361
+ await next();
362
+ },
363
+ },
364
+ ],
365
+ autoDiscoverInterceptors: true,
366
+ disableAutoInterceptors: ['analytics'],
367
+ });
368
+ ```
369
+
370
+ ---
371
+
372
+ ## Interceptors (proxy-side)
373
+
374
+ Proxy interceptors run **inside the proxy route**, around the backend fetch. They use a
375
+ middleware `(ctx, next)` signature and are matched by path/method. Do not confuse them with
376
+ the client `onRequest`/`onResponse` hooks (those run in the calling code, on the proxy URL).
377
+
378
+ ### `InterceptorRule`
379
+
380
+ ```typescript
381
+ interface InterceptorRule {
382
+ pathPattern: string | RegExp; // '/_auth/*' | '/users/:id' | /regex/ | '*' (matches the BACKEND path)
383
+ method?: string | string[]; // 'POST' | ['POST','PUT'] | omit = all
384
+ request?: (ctx: RequestInterceptorContext, next: () => Promise<void>) => Promise<void>;
385
+ response?: (ctx: ResponseInterceptorContext, next: () => Promise<void>) => Promise<void>;
386
+ }
387
+ ```
388
+
389
+ Pattern matching: `'*'` matches all; a `RegExp` is tested directly; a string converts `*`→
390
+ `.*` and `:param`→`[^/]+`. The path matched is the **resolved backend path** (e.g.
391
+ `/users/123`), not `/api/rpc/...`.
392
+
393
+ ### Contexts
394
+
395
+ ```typescript
396
+ interface RequestInterceptorContext {
397
+ path: string; method: string;
398
+ headers: Record<string, string>; // mutable — written back to forwarded headers
399
+ body?: any; // mutable — re-stringified if changed
400
+ query: Record<string, string | string[]>;
401
+ cookies: Map<string, string>; // request cookies
402
+ request: NextRequest;
403
+ metadata: Record<string, any>; // shared with the response interceptor
404
+ }
405
+
406
+ interface ResponseInterceptorContext {
407
+ path: string; method: string;
408
+ request: { headers: Record<string, string>; body?: any };
409
+ response: { ok: boolean; status: number; statusText: string; headers: Headers; body: any }; // body mutable
410
+ cookies: Map<string, string>; // read-only
411
+ setCookies: SetCookie[]; // push to emit Set-Cookie on the NextResponse
412
+ metadata: Record<string, any>;
413
+ }
414
+ ```
415
+
416
+ Interceptors chain in registration order; each must `await next()` to continue (skip it to
417
+ short-circuit). Mutating `ctx.headers` / `ctx.body` (request) and `ctx.response.body` /
418
+ `ctx.setCookies` (response) is how you affect the forwarded request and returned response.
419
+
420
+ ### Package auto-registration
421
+
422
+ Packages register interceptors on import; the proxy auto-discovers them
423
+ (`autoDiscoverInterceptors: true`). The registry lives on `globalThis` to survive HMR and
424
+ de-dupes by package name.
425
+
426
+ ```typescript
427
+ // inside a package, on import
428
+ import { registerInterceptors } from '@spfn/core/nextjs/server';
429
+
430
+ registerInterceptors('auth', [
431
+ {
432
+ pathPattern: '/_auth/*',
433
+ request: async (ctx, next) => {
434
+ const session = ctx.cookies.get('session');
435
+ if (session) ctx.headers['Authorization'] = `Bearer ${session}`;
436
+ await next();
437
+ },
438
+ response: async (ctx, next) => {
439
+ if (ctx.path === '/_auth/login' && ctx.response.body?.token) {
440
+ ctx.setCookies.push({
441
+ name: 'session',
442
+ value: ctx.response.body.token,
443
+ options: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 86400 },
444
+ });
445
+ delete ctx.response.body.token;
446
+ }
447
+ await next();
448
+ },
449
+ },
450
+ ]);
451
+ ```
452
+
453
+ Importing the package's side-effect entry (e.g. `import '@spfn/auth/nextjs/api'`) in the
454
+ proxy route is what triggers registration. Use `disableAutoInterceptors: ['auth']` to opt a
455
+ package out.
456
+
457
+ ---
458
+
459
+ ## Type helpers
460
+
461
+ ```typescript
462
+ import type { RouterOutput, RouterInput, InferRouteInput, InferRouteOutput } from '@spfn/core/nextjs';
463
+ import type { AppRouter } from '@/server/router';
464
+
465
+ type ListData = RouterOutput<AppRouter, 'listExamples'>;
466
+ type CreateInput = RouterInput<AppRouter, 'createExample'>;
467
+ type Item = RouterOutput<AppRouter, 'listExamples'>['items'][number];
468
+ type BodyInput = RouterInput<AppRouter, 'createExample'>['body'];
469
+ ```
470
+
471
+ `RouterOutput`/`RouterInput` take the router type + a route-name key. `InferRouteInput`/
472
+ `InferRouteOutput` take a single `RouteDef`. All inference is compile-time only (zero runtime
473
+ cost).
474
+
475
+ The route-name key is the **flat** set of names in the router tree. A route declared inside a
476
+ nested `defineRouter` is named by its own key here, exactly as the server registers it — the
477
+ group key is not part of the name and does not appear:
478
+
479
+ ```typescript
480
+ const appRouter = defineRouter({
481
+ getRoot,
482
+ examples: defineRouter({ listExamples, createExample }),
483
+ });
484
+
485
+ type ListData = RouterOutput<typeof appRouter, 'listExamples'>; // not 'examples.listExamples'
486
+ ```
487
+
488
+ A name two branches both declare is left out of that set rather than resolved to one of them,
489
+ so naming it is a compile error where it is named. Routes mounted with `.packages()` stay out
490
+ of the set on purpose — call them through the package's own client.
491
+
492
+ `Client<AppRouter>` — what `createApi` returns — is built from the same flat set, so a route
493
+ is named identically whether you call it (`api.listExamples`) or take its type
494
+ (`RouterOutput<AppRouter, 'listExamples'>`).
495
+
496
+ ---
497
+
498
+ ## Error handling
499
+
500
+ `ApiError` is thrown for non-2xx responses, network failures, and timeouts:
501
+
502
+ ```typescript
503
+ class ApiError extends Error {
504
+ constructor(
505
+ message: string,
506
+ public readonly status: number, // HTTP status; 0 for network; 408 for timeout
507
+ public readonly url: string,
508
+ public readonly response?: unknown, // parsed error body
509
+ public readonly errorType?: 'http' | 'network' | 'timeout',
510
+ ) {}
511
+ }
512
+ ```
513
+
514
+ ```typescript
515
+ import { ApiError } from '@spfn/core/nextjs';
516
+
517
+ try {
518
+ await api.getUser.call({ params: { id: '123' } });
519
+ } catch (error) {
520
+ if (error instanceof ApiError) {
521
+ if (error.errorType === 'timeout') { /* 408 */ }
522
+ else if (error.errorType === 'network') { /* status 0 */ }
523
+ else { /* error.status, error.response */ }
524
+ }
525
+ }
526
+ ```
527
+
528
+ **Custom errors**: if the backend body carries a `__type` discriminator and a matching entry
529
+ is registered in the client's `errorRegistry`, the client deserializes and throws the
530
+ **original typed error** instead of a generic `ApiError`. Otherwise it falls back to
531
+ `ApiError`.
532
+
533
+ ---
534
+
535
+ ## Next.js integration
536
+
537
+ ### Server Components with caching
538
+
539
+ ```typescript
540
+ // app/users/[id]/page.tsx
541
+ import { api } from '@/lib/api';
542
+
543
+ export default async function UserPage({ params }: { params: Promise<{ id: string }> }) {
544
+ const { id } = await params;
545
+ const user = await api.getUser
546
+ .fetchOptions({ next: { revalidate: 3600 } })
547
+ .call({ params: { id } });
548
+ return <div>{user.name}</div>;
549
+ }
550
+ ```
551
+
552
+ ### Tag-based revalidation
553
+
554
+ ```typescript
555
+ const posts = await api.getPosts
556
+ .fetchOptions({ next: { tags: ['posts'] } })
557
+ .call({ query: { page: 1 } });
558
+
559
+ // later, in a Server Action:
560
+ import { revalidateTag } from 'next/cache';
561
+ revalidateTag('posts');
562
+ ```
563
+
564
+ ### Client Components / Server Actions
565
+
566
+ ```typescript
567
+ 'use client';
568
+ import { api } from '@/lib/api';
569
+ const created = await api.createUser.call({ body: { name, email } });
570
+ ```
571
+
572
+ ```typescript
573
+ // app/actions.ts
574
+ 'use server';
575
+ import { api } from '@/lib/api';
576
+ export async function createUser(formData: FormData) {
577
+ return api.createUser.call({
578
+ body: { name: formData.get('name') as string, email: formData.get('email') as string },
579
+ });
580
+ }
581
+ ```
582
+
583
+ ---
584
+
585
+ ## Pitfalls & anti-patterns
586
+
587
+ - **Never import `@spfn/core/nextjs/server` in a Client Component.** It pulls in
588
+ `next/headers` + `next/server`; bundling it client-side breaks the build. Client code uses
589
+ `@spfn/core/nextjs` only (`createApi`, `ApiError`, types).
590
+ - **`interceptors` is an `InterceptorRule[]`, not `{ request, response }`.** Older docs
591
+ showed `createRpcProxy({ router, interceptors: { request, response } })` — that config
592
+ shape **does not exist**. The current API is `{ routeMap, interceptors: [{ pathPattern,
593
+ method?, request?, response? }] }`. There is **no** `router` option either; the proxy is
594
+ driven entirely by `routeMap`.
595
+ - **The proxy resolves the real HTTP method from `routeMap`, not from the client call.** The
596
+ client only ever sends GET (no body) or POST (body/formData) to `/api/rpc/...`. A PUT /
597
+ PATCH / DELETE route still works — the backend method comes from `routeMap[routeName]`.
598
+ - **A missing `routeName` in `routeMap` is a proxy 404, not a backend 404.** Merge package
599
+ route maps (`authRouteMap`, `eventRouteMap`, …) and re-run codegen after adding routes;
600
+ delete `.spfn` if the map looks stale.
601
+ - **Interceptor `pathPattern` matches the resolved backend path** (e.g. `/users/123`,
602
+ `/_auth/login`) — *not* the `/api/rpc/{routeName}` URL the client hit.
603
+ - **Two same-named interceptor type pairs.** `RequestInterceptor`/`ResponseInterceptor` from
604
+ `@spfn/core/nextjs` are `(url, init)` / `(response, body)` (client hooks);
605
+ from `@spfn/core/nextjs/server` they are `(ctx, next) => Promise<void>` (proxy middleware).
606
+ Import from the right entry point.
607
+ - **Don't pass auth via the client to set HttpOnly cookies.** HttpOnly session cookies are
608
+ set on the proxy response by a response interceptor (`ctx.setCookies.push(...)`), and
609
+ forwarded automatically on subsequent requests. Client code can't read them by design.
610
+ - **Cookies are auto-forwarded on the server** — only use `.cookies({...})` /
611
+ `options.cookies` to override. Calling outside a request context (static generation) yields
612
+ no cookies, silently.
613
+ - **`createApi` needs no codegen; the *proxy* does.** The client is metadata-free. The
614
+ `routeMap` the proxy consumes is the generated artifact.
615
+ - **Raw `X-Forwarded-For` is not forwarded — don't widen the allowlist to "fix" client IP.**
616
+ The proxy re-emits the resolved client IP as `x-spfn-proxy-client-ip`, trusted only on
617
+ HMAC-signed requests. Missing visitor IP in production means `SPFN_PROXY_SECRET` isn't set on
618
+ both sides (and/or `TRUSTED_PROXY_HOPS` is wrong), not that the header allowlist needs
619
+ `x-forwarded-for` — adding it back makes the IP spoofable. See *Header forwarding & client IP*.
620
+ - **Each `.headers()/.cookies()/.fetchOptions()/.onRequest()/.onResponse()` returns a new
621
+ builder.** Chain them in one expression; a dangling builder without `.call()` does nothing.
622
+
623
+ ---
624
+
625
+ ## Types reference
626
+
627
+ ```typescript
628
+ // client (@spfn/core/nextjs)
629
+ type RequestInterceptor = (url: string, init: RequestInit) => Promise<RequestInit> | RequestInit;
630
+ type ResponseInterceptor = (response: Response, body: any)
631
+ => Promise<{ response: Response; body: any }> | { response: Response; body: any };
632
+
633
+ interface CookieOptions { httpOnly?: boolean; secure?: boolean; sameSite?: 'strict'|'lax'|'none'; maxAge?: number; path?: string; domain?: string; }
634
+ interface SetCookie { name: string; value: string; options?: CookieOptions; }
635
+
636
+ // proxy (@spfn/core/nextjs/server)
637
+ type RequestInterceptor = (ctx: RequestInterceptorContext, next: () => Promise<void>) => Promise<void>;
638
+ type ResponseInterceptor = (ctx: ResponseInterceptorContext, next: () => Promise<void>) => Promise<void>;
639
+ interface RouteMapEntry { method: HttpMethod; path: string; }
640
+ type RouteMap = Record<string, RouteMapEntry>;
641
+ ```
642
+
643
+ ## Related
644
+
645
+ - [@spfn/core/route](../route/README.md) — server-side route + router definitions (source of `AppRouter`)
646
+ - [@spfn/core/codegen](../codegen/README.md) — generates the `routeMap` the proxy consumes
647
+ - [@spfn/core/errors](../errors/README.md) — `ErrorRegistry`, custom error deserialization
648
+ - [@spfn/core/config](../config/README.md) — `SPFN_API_URL`, `SPFN_APP_URL`, `RPC_PROXY_TIMEOUT`, `SERVER_TIMEOUT`
649
+ - [@spfn/auth](../../../auth/README.md) — example package: route map + auto-registered interceptors