@trpc/server 11.23.1-canary.39.58d95db98 → 11.24.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.
Files changed (60) hide show
  1. package/dist/adapters/aws-lambda/index.cjs +1 -1
  2. package/dist/adapters/aws-lambda/index.mjs +1 -1
  3. package/dist/adapters/express.cjs +1 -1
  4. package/dist/adapters/express.mjs +1 -1
  5. package/dist/adapters/fastify/index.cjs +5 -4
  6. package/dist/adapters/fastify/index.d.cts +9 -1
  7. package/dist/adapters/fastify/index.d.cts.map +1 -1
  8. package/dist/adapters/fastify/index.d.mts +9 -1
  9. package/dist/adapters/fastify/index.d.mts.map +1 -1
  10. package/dist/adapters/fastify/index.mjs +5 -4
  11. package/dist/adapters/fastify/index.mjs.map +1 -1
  12. package/dist/adapters/fetch/index.cjs +1 -1
  13. package/dist/adapters/fetch/index.mjs +1 -1
  14. package/dist/adapters/next.cjs +1 -1
  15. package/dist/adapters/next.mjs +1 -1
  16. package/dist/adapters/node-http/index.cjs +1 -1
  17. package/dist/adapters/node-http/index.mjs +1 -1
  18. package/dist/adapters/standalone.cjs +1 -1
  19. package/dist/adapters/standalone.mjs +1 -1
  20. package/dist/adapters/ws.cjs +1 -1
  21. package/dist/adapters/ws.mjs +1 -1
  22. package/dist/http.cjs +1 -1
  23. package/dist/http.mjs +1 -1
  24. package/dist/{node-http-DAPMLW4C.mjs → node-http-BHs4hFcB.mjs} +13 -13
  25. package/dist/node-http-BHs4hFcB.mjs.map +1 -0
  26. package/dist/{node-http-DXyh_vFZ.cjs → node-http-fnRXnfX7.cjs} +12 -12
  27. package/dist/{resolveResponse-BsEeb9S9.mjs → resolveResponse-BDxeIDKz.mjs} +22 -18
  28. package/dist/resolveResponse-BDxeIDKz.mjs.map +1 -0
  29. package/dist/{resolveResponse-C13UI6ip.cjs → resolveResponse-BLSF4Ks0.cjs} +21 -17
  30. package/dist/unstable-core-do-not-import.cjs +1 -1
  31. package/dist/unstable-core-do-not-import.mjs +1 -1
  32. package/dist/{ws-DdyL_3Fm.mjs → ws-BY66ccWn.mjs} +44 -6
  33. package/dist/{ws-DdyL_3Fm.mjs.map → ws-BY66ccWn.mjs.map} +1 -1
  34. package/dist/ws-C6aokjeu.d.cts.map +1 -1
  35. package/dist/ws-CA_yykwZ.d.mts.map +1 -1
  36. package/dist/{ws-CF5HiOtB.cjs → ws-D8h4AHV-.cjs} +43 -5
  37. package/package.json +2 -2
  38. package/skills/adapter-aws-lambda/SKILL.md +11 -3
  39. package/skills/adapter-express/SKILL.md +11 -3
  40. package/skills/adapter-fastify/SKILL.md +11 -3
  41. package/skills/adapter-fetch/SKILL.md +1 -1
  42. package/skills/adapter-standalone/SKILL.md +11 -3
  43. package/skills/auth/SKILL.md +1 -1
  44. package/skills/caching/SKILL.md +1 -1
  45. package/skills/error-handling/SKILL.md +1 -1
  46. package/skills/middlewares/SKILL.md +1 -1
  47. package/skills/non-json-content-types/SKILL.md +1 -1
  48. package/skills/server-setup/SKILL.md +1 -1
  49. package/skills/server-side-calls/SKILL.md +1 -1
  50. package/skills/service-oriented-architecture/SKILL.md +1 -1
  51. package/skills/subscriptions/SKILL.md +1 -1
  52. package/skills/subscriptions/references/server-websockets.md +30 -0
  53. package/skills/trpc-router/SKILL.md +1 -1
  54. package/skills/validators/SKILL.md +1 -1
  55. package/src/adapters/fastify/fastifyRequestHandler.ts +10 -3
  56. package/src/adapters/node-http/incomingMessageToRequest.ts +14 -14
  57. package/src/adapters/ws.ts +50 -0
  58. package/src/unstable-core-do-not-import/stream/jsonl.ts +6 -1
  59. package/dist/node-http-DAPMLW4C.mjs.map +0 -1
  60. package/dist/resolveResponse-BsEeb9S9.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ws-DdyL_3Fm.mjs","names":["callTRPCProcedure"],"sources":["../src/adapters/wsEncoder.ts","../src/adapters/ws.ts"],"sourcesContent":["/**\n * Encodes the messages a WebSocket server sends and decodes the ones it\n * gets. The client's `experimental_encoder` must match.\n *\n * @example\n * ```ts\n * const customEncoder: Encoder = {\n * encode: (data) => myFormat.stringify(data),\n * decode: (data) => myFormat.parse(data),\n * };\n * ```\n */\nexport interface Encoder {\n /** Encodes a message to send. */\n encode(data: unknown): string | Uint8Array<ArrayBuffer>;\n /** Decodes a received message. */\n decode(data: string | ArrayBuffer | Uint8Array): unknown;\n}\n\n/**\n * The default encoder: JSON in text frames.\n */\nexport const jsonEncoder: Encoder = {\n encode: (data) => JSON.stringify(data),\n decode: (data) => {\n if (typeof data !== 'string') {\n throw new Error(\n 'jsonEncoder received binary data. JSON uses text frames. ' +\n 'Use a binary encoder for binary data.',\n );\n }\n return JSON.parse(data);\n },\n};\n","import type { IncomingMessage } from 'http';\nimport type { WebSocketServer, WebSocket as WsWebSocket } from 'ws';\nimport type {\n AnyRouter,\n CreateContextCallback,\n inferRouterContext,\n} from '../@trpc/server';\nimport {\n callTRPCProcedure,\n getErrorShape,\n getTRPCErrorFromUnknown,\n transformTRPCResponse,\n TRPCError,\n} from '../@trpc/server';\nimport type { TRPCRequestInfo } from '../@trpc/server/http';\nimport { type BaseHandlerOptions } from '../@trpc/server/http';\nimport { parseTRPCMessage } from '../@trpc/server/rpc';\n// @trpc/server/rpc\nimport type {\n TRPCClientOutgoingMessage,\n TRPCConnectionParamsMessage,\n TRPCReconnectNotification,\n TRPCResponseMessage,\n TRPCResultMessage,\n} from '../@trpc/server/rpc';\nimport { parseConnectionParamsFromUnknown } from '../http';\nimport { isObservable, observableToAsyncIterable } from '../observable';\n// oxlint-disable-next-line no-restricted-imports\nimport {\n isAsyncIterable,\n isObject,\n isTrackedEnvelope,\n run,\n type MaybePromise,\n} from '../unstable-core-do-not-import';\n// oxlint-disable-next-line no-restricted-imports\nimport type { Result } from '../unstable-core-do-not-import';\n// oxlint-disable-next-line no-restricted-imports\nimport { iteratorResource } from '../unstable-core-do-not-import/stream/utils/asyncIterable';\nimport { Unpromise } from '../vendor/unpromise';\nimport { createURL, type NodeHTTPCreateContextFnOptions } from './node-http';\nimport type { Encoder } from './wsEncoder';\nimport { jsonEncoder } from './wsEncoder';\n\n/**\n * Importing ws causes a build error\n * @see https://github.com/trpc/trpc/pull/5279\n */\nconst WEBSOCKET_OPEN = 1; /* ws.WebSocket.OPEN */\n\n/**\n * What `createContext` gets in the WebSocket adapter: the upgrade request\n * as `req`, the socket as `res`, and `info`. It's called once per\n * connection.\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n * @public\n */\nexport type CreateWSSContextFnOptions = NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n WsWebSocket\n>;\n\n/**\n * The `createContext` function the WebSocket adapter takes.\n * @public\n */\nexport type CreateWSSContextFn<TRouter extends AnyRouter> = (\n opts: CreateWSSContextFnOptions,\n) => MaybePromise<inferRouterContext<TRouter>>;\n\n/** The options of `getWSConnectionHandler`. */\nexport type WSConnectionHandlerOptions<TRouter extends AnyRouter> =\n BaseHandlerOptions<TRouter, IncomingMessage> &\n CreateContextCallback<\n inferRouterContext<TRouter>,\n CreateWSSContextFn<TRouter>\n >;\n\n/**\n * The options of `applyWSSHandler`.\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n */\nexport type WSSHandlerOptions<TRouter extends AnyRouter> =\n WSConnectionHandlerOptions<TRouter> & {\n /** The `ws` server to serve the router on. */\n wss: WebSocketServer;\n /** Only connections whose URL starts with this are served. */\n prefix?: string;\n /**\n * Sends pings to each client and closes connections that stop\n * answering.\n */\n keepAlive?: {\n /**\n * Whether to send pings.\n * @default false\n */\n enabled: boolean;\n /**\n * How long a connection can be quiet before a ping, in milliseconds.\n * @default 30_000\n */\n pingMs?: number;\n /**\n * How long to wait for a pong before closing the connection, in\n * milliseconds.\n * @default 5_000\n */\n pongWaitMs?: number;\n };\n /**\n * Stops answering clients' pings. Meant for tests.\n * @default false\n */\n dangerouslyDisablePong?: boolean;\n /**\n * Encodes and decodes messages, for formats other than JSON.\n * Experimental: it may change in any release.\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n };\n\n/**\n * Returns a `ws` connection listener that serves a router. `applyWSSHandler`\n * uses it; call it to attach tRPC to your own WebSocket server.\n */\nexport function getWSConnectionHandler<TRouter extends AnyRouter>(\n opts: WSSHandlerOptions<TRouter>,\n) {\n const { createContext, router } = opts;\n const { transformer } = router._def._config;\n const encoder = opts.experimental_encoder ?? jsonEncoder;\n\n return (client: WsWebSocket, req: IncomingMessage) => {\n type Context = inferRouterContext<TRouter>;\n type ContextResult = Result<Context>;\n\n const clientSubscriptions = new Map<number | string, AbortController>();\n const abortController = new AbortController();\n\n if (opts.keepAlive?.enabled) {\n const { pingMs, pongWaitMs } = opts.keepAlive;\n handleKeepAlive(client, pingMs, pongWaitMs);\n }\n\n function respond(untransformedJSON: TRPCResponseMessage) {\n client.send(\n encoder.encode(\n transformTRPCResponse(router._def._config, untransformedJSON),\n ),\n );\n }\n\n async function createCtxPromise(\n getConnectionParams: () => TRPCRequestInfo['connectionParams'],\n ): Promise<ContextResult> {\n try {\n return await run(async (): Promise<ContextResult> => {\n ctx = await createContext?.({\n req,\n res: client,\n info: {\n connectionParams: getConnectionParams(),\n calls: [],\n isBatchCall: false,\n accept: null,\n type: 'unknown',\n signal: abortController.signal,\n url: null,\n },\n });\n\n return {\n ok: true,\n value: ctx,\n };\n });\n } catch (cause) {\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n\n // close in next tick\n (globalThis.setImmediate ?? globalThis.setTimeout)(() => {\n client.close();\n });\n return {\n ok: false,\n error,\n };\n }\n }\n\n let ctx: Context | undefined = undefined;\n\n /**\n * promise for initializing the context\n *\n * - the context promise will be created immediately on connection if no connectionParams are expected\n * - if connection params are expected, they will be created once received\n */\n let ctxPromise =\n createURL(req).searchParams.get('connectionParams') === '1'\n ? null\n : createCtxPromise(() => null);\n\n function handleRequest(msg: TRPCClientOutgoingMessage, batchIndex: number) {\n const { id, jsonrpc } = msg;\n\n if (id === null) {\n const error = getTRPCErrorFromUnknown(\n new TRPCError({\n code: 'PARSE_ERROR',\n message: '`id` is required',\n }),\n );\n opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n return;\n }\n if (msg.method === 'subscription.stop') {\n clientSubscriptions.get(id)?.abort();\n return;\n }\n const { path, lastEventId } = msg.params;\n let { input } = msg.params;\n const type = msg.method;\n\n if (lastEventId !== undefined) {\n if (isObject(input)) {\n input = {\n ...input,\n lastEventId: lastEventId,\n };\n } else {\n input ??= {\n lastEventId: lastEventId,\n };\n }\n }\n run(async () => {\n // oxlint-disable-next-line typescript/no-non-null-assertion\n const res = await ctxPromise!; // asserts context has been set\n if (!res.ok) {\n throw res.error;\n }\n\n const abortController = new AbortController();\n const result = await callTRPCProcedure({\n router,\n path,\n getRawInput: async () => input,\n ctx,\n type,\n signal: abortController.signal,\n batchIndex,\n });\n\n const isIterableResult =\n isAsyncIterable(result) || isObservable(result);\n\n if (type !== 'subscription') {\n if (isIterableResult) {\n throw new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message: `Cannot return an async iterable or observable from a ${type} procedure with WebSockets`,\n });\n }\n // send the value as data if the method is not a subscription\n respond({\n id,\n jsonrpc,\n result: {\n type: 'data',\n data: result,\n },\n });\n return;\n }\n\n if (!isIterableResult) {\n throw new TRPCError({\n message: `Subscription ${path} did not return an observable or a AsyncGenerator`,\n code: 'INTERNAL_SERVER_ERROR',\n });\n }\n\n /* istanbul ignore next -- @preserve */\n if (client.readyState !== WEBSOCKET_OPEN) {\n // if the client got disconnected whilst initializing the subscription\n // no need to send stopped message if the client is disconnected\n\n return;\n }\n\n /* istanbul ignore next -- @preserve */\n if (clientSubscriptions.has(id)) {\n // duplicate request ids for client\n\n throw new TRPCError({\n message: `Duplicate id ${id}`,\n code: 'BAD_REQUEST',\n });\n }\n\n const iterable = isObservable(result)\n ? observableToAsyncIterable(result, abortController.signal)\n : result;\n\n run(async () => {\n await using iterator = iteratorResource(iterable);\n\n const abortPromise = new Promise<'abort'>((resolve) => {\n abortController.signal.onabort = () => resolve('abort');\n });\n // We need those declarations outside the loop for garbage collection reasons. If they\n // were declared inside, they would not be freed until the next value is present.\n let next:\n | null\n | TRPCError\n | Awaited<\n typeof abortPromise | ReturnType<(typeof iterator)['next']>\n >;\n let result: null | TRPCResultMessage<unknown>['result'];\n\n while (true) {\n next = await Unpromise.race([\n iterator.next().catch(getTRPCErrorFromUnknown),\n abortPromise,\n ]);\n\n if (next === 'abort') {\n await iterator.return?.();\n break;\n }\n if (next instanceof Error) {\n const error = getTRPCErrorFromUnknown(next);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n break;\n }\n if (next.done) {\n break;\n }\n\n result = {\n type: 'data',\n data: next.value,\n };\n\n if (isTrackedEnvelope(next.value)) {\n const [id, data] = next.value;\n result.id = id;\n result.data = {\n id,\n data,\n };\n }\n\n respond({\n id,\n jsonrpc,\n result,\n });\n\n // free up references for garbage collection\n next = null;\n result = null;\n }\n\n respond({\n id,\n jsonrpc,\n result: {\n type: 'stopped',\n },\n });\n clientSubscriptions.delete(id);\n }).catch((cause) => {\n clientSubscriptions.delete(id);\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n abortController.abort();\n });\n clientSubscriptions.set(id, abortController);\n\n respond({\n id,\n jsonrpc,\n result: {\n type: 'started',\n },\n });\n }).catch((cause) => {\n // procedure threw an error\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n });\n }\n client.on('message', (rawData, isBinary) => {\n // Handle PING/PONG as text regardless of encoder\n if (!isBinary) {\n // oxlint-disable-next-line typescript/no-base-to-string\n const msgStr = rawData.toString();\n if (msgStr === 'PONG') {\n return;\n }\n if (msgStr === 'PING') {\n if (!opts.dangerouslyDisablePong) {\n client.send('PONG');\n }\n return;\n }\n }\n\n // Convert rawData to a format our encoder accepts\n // ws gives us Buffer for both text and binary frames\n if (!Buffer.isBuffer(rawData)) {\n const error = new TRPCError({\n code: 'UNPROCESSABLE_CONTENT',\n message: 'Unexpected WebSocket message format',\n });\n respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n return;\n }\n const data: string | Uint8Array = isBinary\n ? rawData\n : rawData.toString('utf8');\n\n if (!ctxPromise) {\n // If the ctxPromise wasn't created immediately, we're expecting the first message to be a TRPCConnectionParamsMessage\n ctxPromise = createCtxPromise(() => {\n let msg;\n try {\n msg = encoder.decode(data) as TRPCConnectionParamsMessage;\n\n if (!isObject(msg)) {\n throw new Error('Message was not an object');\n }\n } catch (cause) {\n throw new TRPCError({\n code: 'PARSE_ERROR',\n message: `Malformed TRPCConnectionParamsMessage`,\n cause,\n });\n }\n\n const connectionParams = parseConnectionParamsFromUnknown(msg.data);\n\n return connectionParams;\n });\n return;\n }\n\n const parsedMsgs = run(() => {\n try {\n const msgJSON: unknown = encoder.decode(data);\n const msgs: unknown[] = Array.isArray(msgJSON) ? msgJSON : [msgJSON];\n\n return msgs.map((raw) => parseTRPCMessage(raw, transformer));\n } catch (cause) {\n const error = new TRPCError({\n code: 'PARSE_ERROR',\n cause,\n });\n\n respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n\n return [];\n }\n });\n\n parsedMsgs.map((msg, index) => handleRequest(msg, index));\n });\n\n // WebSocket errors should be handled, as otherwise unhandled exceptions will crash Node.js.\n // This line was introduced after the following error brought down production systems:\n // \"RangeError: Invalid WebSocket frame: RSV2 and RSV3 must be clear\"\n // Here is the relevant discussion: https://github.com/websockets/ws/issues/1354#issuecomment-774616962\n client.on('error', (cause) => {\n opts.onError?.({\n ctx,\n error: getTRPCErrorFromUnknown(cause),\n input: undefined,\n path: undefined,\n type: 'unknown',\n req,\n });\n });\n\n client.once('close', () => {\n for (const sub of clientSubscriptions.values()) {\n sub.abort();\n }\n clientSubscriptions.clear();\n abortController.abort();\n });\n };\n}\n\n/**\n * Pings a client after `pingMs` of quiet, and closes the connection if no\n * message comes within `pongWaitMs`.\n */\nexport function handleKeepAlive(\n client: WsWebSocket,\n pingMs = 30_000,\n pongWaitMs = 5_000,\n) {\n let timeout: NodeJS.Timeout | undefined = undefined;\n let ping: NodeJS.Timeout | undefined = undefined;\n\n const schedulePing = () => {\n const scheduleTimeout = () => {\n timeout = setTimeout(() => {\n client.terminate();\n }, pongWaitMs);\n };\n ping = setTimeout(() => {\n client.send('PING');\n\n scheduleTimeout();\n }, pingMs);\n };\n\n const onMessage = () => {\n clearTimeout(ping);\n clearTimeout(timeout);\n\n schedulePing();\n };\n\n client.on('message', onMessage);\n\n client.on('close', () => {\n clearTimeout(ping);\n clearTimeout(timeout);\n });\n\n schedulePing();\n}\n\n/**\n * Serves a router on a `ws` WebSocket server. Returns\n * `broadcastReconnectNotification()`, which tells every client to\n * reconnect, for example before a deploy.\n * @example\n * ```ts\n * const wss = new WebSocketServer({ port: 3001 });\n * const handler = applyWSSHandler({ wss, router: appRouter, createContext });\n * process.on('SIGTERM', () => {\n * handler.broadcastReconnectNotification();\n * wss.close();\n * });\n * ```\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n */\nexport function applyWSSHandler<TRouter extends AnyRouter>(\n opts: WSSHandlerOptions<TRouter>,\n) {\n const encoder = opts.experimental_encoder ?? jsonEncoder;\n const onConnection = getWSConnectionHandler(opts);\n opts.wss.on('connection', (client, req) => {\n if (opts.prefix && !req.url?.startsWith(opts.prefix)) {\n return;\n }\n\n onConnection(client, req);\n });\n\n return {\n broadcastReconnectNotification: () => {\n const response: TRPCReconnectNotification = {\n id: null,\n method: 'reconnect',\n };\n const data = encoder.encode(response);\n for (const client of opts.wss.clients) {\n if (client.readyState === WEBSOCKET_OPEN) {\n client.send(data);\n }\n }\n },\n };\n}\n\nexport type { Encoder } from './wsEncoder';\nexport { jsonEncoder } from './wsEncoder';\n"],"mappings":";;;;;;;;;;;AAsBA,MAAa,cAAuB;CAClC,SAAS,SAAS,KAAK,UAAU,IAAI;CACrC,SAAS,SAAS;EAChB,IAAI,OAAO,SAAS,UAClB,MAAM,IAAI,MACR,gGAEF;EAEF,OAAO,KAAK,MAAM,IAAI;CACxB;AACF;;;;;;;ACeA,MAAM,iBAAiB;;;;;AA+EvB,SAAgB,uBACd,MACA;;CACA,MAAM,EAAE,eAAe,WAAW;CAClC,MAAM,EAAE,gBAAgB,OAAO,KAAK;CACpC,MAAM,WAAA,wBAAU,KAAK,0BAAA,QAAA,0BAAA,KAAA,IAAA,wBAAwB;CAE7C,QAAQ,QAAqB,QAAyB;;EAIpD,MAAM,sCAAsB,IAAI,IAAsC;EACtE,MAAM,kBAAkB,IAAI,gBAAgB;EAE5C,KAAA,kBAAI,KAAK,eAAA,QAAA,oBAAA,KAAA,IAAA,KAAA,IAAA,gBAAW,SAAS;GAC3B,MAAM,EAAE,QAAQ,eAAe,KAAK;GACpC,gBAAgB,QAAQ,QAAQ,UAAU;EAC5C;EAEA,SAAS,QAAQ,mBAAwC;GACvD,OAAO,KACL,QAAQ,OACN,sBAAsB,OAAO,KAAK,SAAS,iBAAiB,CAC9D,CACF;EACF;EAEA,eAAe,iBACb,qBACw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,gBACd,QACA,SAAS,KACT,aAAa,KACb;CACA,IAAI,UAAsC,KAAA;CAC1C,IAAI,OAAmC,KAAA;CAEvC,MAAM,qBAAqB;EACzB,MAAM,wBAAwB;GAC5B,UAAU,iBAAiB;IACzB,OAAO,UAAU;GACnB,GAAG,UAAU;EACf;EACA,OAAO,iBAAiB;GACtB,OAAO,KAAK,MAAM;GAElB,gBAAgB;EAClB,GAAG,MAAM;CACX;CAEA,MAAM,kBAAkB;EACtB,aAAa,IAAI;EACjB,aAAa,OAAO;EAEpB,aAAa;CACf;CAEA,OAAO,GAAG,WAAW,SAAS;CAE9B,OAAO,GAAG,eAAe;EACvB,aAAa,IAAI;EACjB,aAAa,OAAO;CACtB,CAAC;CAED,aAAa;AACf;;;;;;;;;;;;;;;;AAiBA,SAAgB,gBACd,MACA;;CACA,MAAM,WAAA,yBAAU,KAAK,0BAAA,QAAA,2BAAA,KAAA,IAAA,yBAAwB;CAC7C,MAAM,eAAe,uBAAuB,IAAI;CAChD,KAAK,IAAI,GAAG,eAAe,QAAQ,QAAQ;;EACzC,IAAI,KAAK,UAAU,GAAA,WAAC,IAAI,SAAA,QAAA,aAAA,KAAA,IAAA,KAAA,IAAA,SAAK,WAAW,KAAK,MAAM,IACjD;EAGF,aAAa,QAAQ,GAAG;CAC1B,CAAC;CAED,OAAO,EACL,sCAAsC;EAKpC,MAAM,OAAO,QAAQ,OAAO;GAH1B,IAAI;GACJ,QAAQ;EAEyB,CAAC;EACpC,KAAK,MAAM,UAAU,KAAK,IAAI,SAC5B,IAAI,OAAO,eAAe,gBACxB,OAAO,KAAK,IAAI;CAGtB,EACF;AACF"}
1
+ {"version":3,"file":"ws-BY66ccWn.mjs","names":["callTRPCProcedure"],"sources":["../src/adapters/wsEncoder.ts","../src/adapters/ws.ts"],"sourcesContent":["/**\n * Encodes the messages a WebSocket server sends and decodes the ones it\n * gets. The client's `experimental_encoder` must match.\n *\n * @example\n * ```ts\n * const customEncoder: Encoder = {\n * encode: (data) => myFormat.stringify(data),\n * decode: (data) => myFormat.parse(data),\n * };\n * ```\n */\nexport interface Encoder {\n /** Encodes a message to send. */\n encode(data: unknown): string | Uint8Array<ArrayBuffer>;\n /** Decodes a received message. */\n decode(data: string | ArrayBuffer | Uint8Array): unknown;\n}\n\n/**\n * The default encoder: JSON in text frames.\n */\nexport const jsonEncoder: Encoder = {\n encode: (data) => JSON.stringify(data),\n decode: (data) => {\n if (typeof data !== 'string') {\n throw new Error(\n 'jsonEncoder received binary data. JSON uses text frames. ' +\n 'Use a binary encoder for binary data.',\n );\n }\n return JSON.parse(data);\n },\n};\n","import type { IncomingMessage } from 'http';\nimport type { WebSocketServer, WebSocket as WsWebSocket } from 'ws';\nimport type {\n AnyRouter,\n CreateContextCallback,\n inferRouterContext,\n} from '../@trpc/server';\nimport {\n callTRPCProcedure,\n getErrorShape,\n getTRPCErrorFromUnknown,\n transformTRPCResponse,\n TRPCError,\n} from '../@trpc/server';\nimport type { TRPCRequestInfo } from '../@trpc/server/http';\nimport { type BaseHandlerOptions } from '../@trpc/server/http';\nimport { parseTRPCMessage } from '../@trpc/server/rpc';\n// @trpc/server/rpc\nimport type {\n TRPCClientOutgoingMessage,\n TRPCConnectionParamsMessage,\n TRPCReconnectNotification,\n TRPCResponseMessage,\n TRPCResultMessage,\n} from '../@trpc/server/rpc';\nimport { parseConnectionParamsFromUnknown } from '../http';\nimport { isObservable, observableToAsyncIterable } from '../observable';\n// oxlint-disable-next-line no-restricted-imports\nimport {\n isAsyncIterable,\n isObject,\n isTrackedEnvelope,\n run,\n type MaybePromise,\n} from '../unstable-core-do-not-import';\n// oxlint-disable-next-line no-restricted-imports\nimport type { Result } from '../unstable-core-do-not-import';\n// oxlint-disable-next-line no-restricted-imports\nimport { iteratorResource } from '../unstable-core-do-not-import/stream/utils/asyncIterable';\nimport { Unpromise } from '../vendor/unpromise';\nimport { createURL, type NodeHTTPCreateContextFnOptions } from './node-http';\nimport type { Encoder } from './wsEncoder';\nimport { jsonEncoder } from './wsEncoder';\n\n/**\n * Importing ws causes a build error\n * @see https://github.com/trpc/trpc/pull/5279\n */\nconst WEBSOCKET_OPEN = 1; /* ws.WebSocket.OPEN */\n\n/**\n * What `createContext` gets in the WebSocket adapter: the upgrade request\n * as `req`, the socket as `res`, and `info`. It's called once per\n * connection.\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n * @public\n */\nexport type CreateWSSContextFnOptions = NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n WsWebSocket\n>;\n\n/**\n * The `createContext` function the WebSocket adapter takes.\n * @public\n */\nexport type CreateWSSContextFn<TRouter extends AnyRouter> = (\n opts: CreateWSSContextFnOptions,\n) => MaybePromise<inferRouterContext<TRouter>>;\n\n/** The options of `getWSConnectionHandler`. */\nexport type WSConnectionHandlerOptions<TRouter extends AnyRouter> =\n BaseHandlerOptions<TRouter, IncomingMessage> &\n CreateContextCallback<\n inferRouterContext<TRouter>,\n CreateWSSContextFn<TRouter>\n >;\n\n/**\n * The options of `applyWSSHandler`.\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n */\nexport type WSSHandlerOptions<TRouter extends AnyRouter> =\n WSConnectionHandlerOptions<TRouter> & {\n /** The `ws` server to serve the router on. */\n wss: WebSocketServer;\n /** Only connections whose URL starts with this are served. */\n prefix?: string;\n /**\n * Sends pings to each client and closes connections that stop\n * answering.\n */\n keepAlive?: {\n /**\n * Whether to send pings.\n * @default false\n */\n enabled: boolean;\n /**\n * How long a connection can be quiet before a ping, in milliseconds.\n * @default 30_000\n */\n pingMs?: number;\n /**\n * How long to wait for a pong before closing the connection, in\n * milliseconds.\n * @default 5_000\n */\n pongWaitMs?: number;\n };\n /**\n * Stops answering clients' pings. Meant for tests.\n * @default false\n */\n dangerouslyDisablePong?: boolean;\n /**\n * Encodes and decodes messages, for formats other than JSON.\n * Experimental: it may change in any release.\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n };\n\n/**\n * Returns a `ws` connection listener that serves a router. `applyWSSHandler`\n * uses it; call it to attach tRPC to your own WebSocket server.\n */\nexport function getWSConnectionHandler<TRouter extends AnyRouter>(\n opts: WSSHandlerOptions<TRouter>,\n) {\n const { createContext, router } = opts;\n const { transformer } = router._def._config;\n const encoder = opts.experimental_encoder ?? jsonEncoder;\n\n return (client: WsWebSocket, req: IncomingMessage) => {\n type Context = inferRouterContext<TRouter>;\n type ContextResult = Result<Context>;\n\n const clientSubscriptions = new Map<number | string, AbortController>();\n const abortController = new AbortController();\n\n if (opts.keepAlive?.enabled) {\n const { pingMs, pongWaitMs } = opts.keepAlive;\n handleKeepAlive(client, pingMs, pongWaitMs);\n }\n\n function respond(untransformedJSON: TRPCResponseMessage) {\n client.send(\n encoder.encode(\n transformTRPCResponse(router._def._config, untransformedJSON),\n ),\n );\n }\n\n async function createCtxPromise(\n getConnectionParams: () => TRPCRequestInfo['connectionParams'],\n ): Promise<ContextResult> {\n try {\n return await run(async (): Promise<ContextResult> => {\n ctx = await createContext?.({\n req,\n res: client,\n info: {\n connectionParams: getConnectionParams(),\n calls: [],\n isBatchCall: false,\n accept: null,\n type: 'unknown',\n signal: abortController.signal,\n url: null,\n },\n });\n\n return {\n ok: true,\n value: ctx,\n };\n });\n } catch (cause) {\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n\n // close in next tick\n (globalThis.setImmediate ?? globalThis.setTimeout)(() => {\n client.close();\n });\n return {\n ok: false,\n error,\n };\n }\n }\n\n let ctx: Context | undefined = undefined;\n\n /**\n * promise for initializing the context\n *\n * - the context promise will be created immediately on connection if no connectionParams are expected\n * - if connection params are expected, they will be created once received\n */\n let ctxPromise =\n createURL(req).searchParams.get('connectionParams') === '1'\n ? null\n : createCtxPromise(() => null);\n\n function handleRequest(msg: TRPCClientOutgoingMessage, batchIndex: number) {\n const { id, jsonrpc } = msg;\n\n if (id === null) {\n const error = getTRPCErrorFromUnknown(\n new TRPCError({\n code: 'PARSE_ERROR',\n message: '`id` is required',\n }),\n );\n opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n return;\n }\n if (msg.method === 'subscription.stop') {\n clientSubscriptions.get(id)?.abort();\n return;\n }\n const { path, lastEventId } = msg.params;\n let { input } = msg.params;\n const type = msg.method;\n\n if (lastEventId !== undefined) {\n if (isObject(input)) {\n input = {\n ...input,\n lastEventId: lastEventId,\n };\n } else {\n input ??= {\n lastEventId: lastEventId,\n };\n }\n }\n run(async () => {\n // oxlint-disable-next-line typescript/no-non-null-assertion\n const res = await ctxPromise!; // asserts context has been set\n if (!res.ok) {\n throw res.error;\n }\n\n const abortController = new AbortController();\n const result = await callTRPCProcedure({\n router,\n path,\n getRawInput: async () => input,\n ctx,\n type,\n signal: abortController.signal,\n batchIndex,\n });\n\n const isIterableResult =\n isAsyncIterable(result) || isObservable(result);\n\n if (type !== 'subscription') {\n if (isIterableResult) {\n throw new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message: `Cannot return an async iterable or observable from a ${type} procedure with WebSockets`,\n });\n }\n // send the value as data if the method is not a subscription\n respond({\n id,\n jsonrpc,\n result: {\n type: 'data',\n data: result,\n },\n });\n return;\n }\n\n if (!isIterableResult) {\n throw new TRPCError({\n message: `Subscription ${path} did not return an observable or a AsyncGenerator`,\n code: 'INTERNAL_SERVER_ERROR',\n });\n }\n\n /* istanbul ignore next -- @preserve */\n if (client.readyState !== WEBSOCKET_OPEN) {\n // if the client got disconnected whilst initializing the subscription\n // no need to send stopped message if the client is disconnected\n\n return;\n }\n\n /* istanbul ignore next -- @preserve */\n if (clientSubscriptions.has(id)) {\n // duplicate request ids for client\n\n throw new TRPCError({\n message: `Duplicate id ${id}`,\n code: 'BAD_REQUEST',\n });\n }\n\n const iterable = isObservable(result)\n ? observableToAsyncIterable(result, abortController.signal)\n : result;\n\n run(async () => {\n await using iterator = iteratorResource(iterable);\n\n const abortPromise = new Promise<'abort'>((resolve) => {\n abortController.signal.onabort = () => resolve('abort');\n });\n // We need those declarations outside the loop for garbage collection reasons. If they\n // were declared inside, they would not be freed until the next value is present.\n let next:\n | null\n | TRPCError\n | Awaited<\n typeof abortPromise | ReturnType<(typeof iterator)['next']>\n >;\n let result: null | TRPCResultMessage<unknown>['result'];\n\n while (true) {\n next = await Unpromise.race([\n iterator.next().catch(getTRPCErrorFromUnknown),\n abortPromise,\n ]);\n\n if (next === 'abort') {\n await iterator.return?.();\n break;\n }\n if (next instanceof Error) {\n const error = getTRPCErrorFromUnknown(next);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n break;\n }\n if (next.done) {\n break;\n }\n\n result = {\n type: 'data',\n data: next.value,\n };\n\n if (isTrackedEnvelope(next.value)) {\n const [id, data] = next.value;\n result.id = id;\n result.data = {\n id,\n data,\n };\n }\n\n respond({\n id,\n jsonrpc,\n result,\n });\n\n // free up references for garbage collection\n next = null;\n result = null;\n }\n\n respond({\n id,\n jsonrpc,\n result: {\n type: 'stopped',\n },\n });\n clientSubscriptions.delete(id);\n }).catch((cause) => {\n clientSubscriptions.delete(id);\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n abortController.abort();\n });\n clientSubscriptions.set(id, abortController);\n\n respond({\n id,\n jsonrpc,\n result: {\n type: 'started',\n },\n });\n }).catch((cause) => {\n // procedure threw an error\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n });\n }\n client.on('message', (rawData, isBinary) => {\n // Handle PING/PONG as text regardless of encoder\n if (!isBinary) {\n // oxlint-disable-next-line typescript/no-base-to-string\n const msgStr = rawData.toString();\n if (msgStr === 'PONG') {\n return;\n }\n if (msgStr === 'PING') {\n if (!opts.dangerouslyDisablePong) {\n client.send('PONG');\n }\n return;\n }\n }\n\n // Convert rawData to a format our encoder accepts\n // ws gives us Buffer for both text and binary frames\n if (!Buffer.isBuffer(rawData)) {\n const error = new TRPCError({\n code: 'UNPROCESSABLE_CONTENT',\n message: 'Unexpected WebSocket message format',\n });\n respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n return;\n }\n const data: string | Uint8Array = isBinary\n ? rawData\n : rawData.toString('utf8');\n\n if (!ctxPromise) {\n // If the ctxPromise wasn't created immediately, we're expecting the first message to be a TRPCConnectionParamsMessage\n ctxPromise = createCtxPromise(() => {\n let msg;\n try {\n msg = encoder.decode(data) as TRPCConnectionParamsMessage;\n\n if (!isObject(msg)) {\n throw new Error('Message was not an object');\n }\n } catch (cause) {\n throw new TRPCError({\n code: 'PARSE_ERROR',\n message: `Malformed TRPCConnectionParamsMessage`,\n cause,\n });\n }\n\n const connectionParams = parseConnectionParamsFromUnknown(msg.data);\n\n return connectionParams;\n });\n return;\n }\n\n const parsedMsgs = run(() => {\n try {\n const msgJSON: unknown = encoder.decode(data);\n const msgs: unknown[] = Array.isArray(msgJSON) ? msgJSON : [msgJSON];\n\n if (\n Array.isArray(msgJSON) &&\n typeof opts.maxBatchSize === 'number' &&\n msgs.length > opts.maxBatchSize\n ) {\n const error = new TRPCError({\n code: 'BAD_REQUEST',\n message: `Batch call exceeds maximum size`,\n });\n opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n const errorShape = getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n });\n\n // Checked before parsing so that no input is deserialized.\n // Every request in the batch gets the error, as a batched HTTP\n // call does, so that clients do not wait for a response forever.\n let responded = false;\n for (const raw of msgs) {\n if (\n isObject(raw) &&\n raw['method'] !== 'subscription.stop' &&\n (typeof raw['id'] === 'number' || typeof raw['id'] === 'string')\n ) {\n respond({\n id: raw['id'],\n jsonrpc: raw['jsonrpc'] === '2.0' ? '2.0' : undefined,\n error: errorShape,\n });\n responded = true;\n }\n }\n if (!responded) {\n respond({ id: null, error: errorShape });\n }\n return [];\n }\n\n return msgs.map((raw) => parseTRPCMessage(raw, transformer));\n } catch (cause) {\n const error = new TRPCError({\n code: 'PARSE_ERROR',\n cause,\n });\n\n respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n\n return [];\n }\n });\n\n parsedMsgs.map((msg, index) => handleRequest(msg, index));\n });\n\n // WebSocket errors should be handled, as otherwise unhandled exceptions will crash Node.js.\n // This line was introduced after the following error brought down production systems:\n // \"RangeError: Invalid WebSocket frame: RSV2 and RSV3 must be clear\"\n // Here is the relevant discussion: https://github.com/websockets/ws/issues/1354#issuecomment-774616962\n client.on('error', (cause) => {\n opts.onError?.({\n ctx,\n error: getTRPCErrorFromUnknown(cause),\n input: undefined,\n path: undefined,\n type: 'unknown',\n req,\n });\n });\n\n client.once('close', () => {\n for (const sub of clientSubscriptions.values()) {\n sub.abort();\n }\n clientSubscriptions.clear();\n abortController.abort();\n });\n };\n}\n\n/**\n * Pings a client after `pingMs` of quiet, and closes the connection if no\n * message comes within `pongWaitMs`.\n */\nexport function handleKeepAlive(\n client: WsWebSocket,\n pingMs = 30_000,\n pongWaitMs = 5_000,\n) {\n let timeout: NodeJS.Timeout | undefined = undefined;\n let ping: NodeJS.Timeout | undefined = undefined;\n\n const schedulePing = () => {\n const scheduleTimeout = () => {\n timeout = setTimeout(() => {\n client.terminate();\n }, pongWaitMs);\n };\n ping = setTimeout(() => {\n client.send('PING');\n\n scheduleTimeout();\n }, pingMs);\n };\n\n const onMessage = () => {\n clearTimeout(ping);\n clearTimeout(timeout);\n\n schedulePing();\n };\n\n client.on('message', onMessage);\n\n client.on('close', () => {\n clearTimeout(ping);\n clearTimeout(timeout);\n });\n\n schedulePing();\n}\n\n/**\n * Serves a router on a `ws` WebSocket server. Returns\n * `broadcastReconnectNotification()`, which tells every client to\n * reconnect, for example before a deploy.\n * @example\n * ```ts\n * const wss = new WebSocketServer({ port: 3001 });\n * const handler = applyWSSHandler({ wss, router: appRouter, createContext });\n * process.on('SIGTERM', () => {\n * handler.broadcastReconnectNotification();\n * wss.close();\n * });\n * ```\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n */\nexport function applyWSSHandler<TRouter extends AnyRouter>(\n opts: WSSHandlerOptions<TRouter>,\n) {\n const encoder = opts.experimental_encoder ?? jsonEncoder;\n const onConnection = getWSConnectionHandler(opts);\n opts.wss.on('connection', (client, req) => {\n if (opts.prefix && !req.url?.startsWith(opts.prefix)) {\n return;\n }\n\n onConnection(client, req);\n });\n\n return {\n broadcastReconnectNotification: () => {\n const response: TRPCReconnectNotification = {\n id: null,\n method: 'reconnect',\n };\n const data = encoder.encode(response);\n for (const client of opts.wss.clients) {\n if (client.readyState === WEBSOCKET_OPEN) {\n client.send(data);\n }\n }\n },\n };\n}\n\nexport type { Encoder } from './wsEncoder';\nexport { jsonEncoder } from './wsEncoder';\n"],"mappings":";;;;;;;;;;;AAsBA,MAAa,cAAuB;CAClC,SAAS,SAAS,KAAK,UAAU,IAAI;CACrC,SAAS,SAAS;EAChB,IAAI,OAAO,SAAS,UAClB,MAAM,IAAI,MACR,gGAEF;EAEF,OAAO,KAAK,MAAM,IAAI;CACxB;AACF;;;;;;;ACeA,MAAM,iBAAiB;;;;;AA+EvB,SAAg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mBAAmB,gBAAgB,cAC7C,MAAM,8BACH,aAAa,mBAAmB;;KAGzB,2BAA2B,gBAAgB,aACrD,mBAAmB,SAAS,mBAC1B,sBACE,mBAAmB,UACnB,mBAAmB;;;;;KAOb,kBAAkB,gBAAgB,aAC5C,2BAA2B;;EAEzB,KAAK;;EAEL;;;;;EAKA;;;;;IAKE;;;;;IAKA;;;;;;IAMA;;;;;;EAMF;;;;;;EAMA,uBAAuB;;;;;;iBAOX,uBAAuB,gBAAgB,WACrD,MAAM,kBAAkB,YAAQ,QAMhB,WAAW,KAAO;;;;;iBA6cpB,gBACd,QAAQ,WACR,iBACA;;;;;;;;;;;;;;;;iBAkDc,gBAAgB,gBAAgB,WAC9C,MAAM,kBAAkB;EAatB"}
1
+ {"version":3,"file":"ws-C6aokjeu.d.cts","names":[],"sources":["../src/adapters/ws.ts"],"mappings":";;;;;;;;;;;;KAyDY,4BAA4B,+BACtC,iBACA;;;;;KAOU,mBAAmB,gBAAgB,cAC7C,MAAM,8BACH,aAAa,mBAAmB;;KAGzB,2BAA2B,gBAAgB,aACrD,mBAAmB,SAAS,mBAC1B,sBACE,mBAAmB,UACnB,mBAAmB;;;;;KAOb,kBAAkB,gBAAgB,aAC5C,2BAA2B;;EAEzB,KAAK;;EAEL;;;;;EAKA;;;;;IAKE;;;;;IAKA;;;;;;IAMA;;;;;;EAMF;;;;;;EAMA,uBAAuB;;;;;;iBAOX,uBAAuB,gBAAgB,WACrD,MAAM,kBAAkB,YAAQ,QAMhB,WAAW,KAAO;;;;;iBA+fpB,gBACd,QAAQ,WACR,iBACA;;;;;;;;;;;;;;;;iBAkDc,gBAAgB,gBAAgB,WAC9C,MAAM,kBAAkB;EAatB"}
@@ -1 +1 @@
1
- {"version":3,"file":"ws-CA_yykwZ.d.mts","names":[],"sources":["../src/adapters/ws.ts"],"mappings":";;;;;;;;;;;;KAyDY,4BAA4B,+BACtC,iBACA;;;;;KAOU,mBAAmB,gBAAgB,cAC7C,MAAM,8BACH,aAAa,mBAAmB;;KAGzB,2BAA2B,gBAAgB,aACrD,mBAAmB,SAAS,mBAC1B,sBACE,mBAAmB,UACnB,mBAAmB;;;;;KAOb,kBAAkB,gBAAgB,aAC5C,2BAA2B;;EAEzB,KAAK;;EAEL;;;;;EAKA;;;;;IAKE;;;;;IAKA;;;;;;IAMA;;;;;;EAMF;;;;;;EAMA,uBAAuB;;;;;;iBAOX,uBAAuB,gBAAgB,WACrD,MAAM,kBAAkB,YAAQ,QAMhB,WAAW,KAAO;;;;;iBA6cpB,gBACd,QAAQ,WACR,iBACA;;;;;;;;;;;;;;;;iBAkDc,gBAAgB,gBAAgB,WAC9C,MAAM,kBAAkB;EAatB"}
1
+ {"version":3,"file":"ws-CA_yykwZ.d.mts","names":[],"sources":["../src/adapters/ws.ts"],"mappings":";;;;;;;;;;;;KAyDY,4BAA4B,+BACtC,iBACA;;;;;KAOU,mBAAmB,gBAAgB,cAC7C,MAAM,8BACH,aAAa,mBAAmB;;KAGzB,2BAA2B,gBAAgB,aACrD,mBAAmB,SAAS,mBAC1B,sBACE,mBAAmB,UACnB,mBAAmB;;;;;KAOb,kBAAkB,gBAAgB,aAC5C,2BAA2B;;EAEzB,KAAK;;EAEL;;;;;EAKA;;;;;IAKE;;;;;IAKA;;;;;;IAMA;;;;;;EAMF;;;;;;EAMA,uBAAuB;;;;;;iBAOX,uBAAuB,gBAAgB,WACrD,MAAM,kBAAkB,YAAQ,QAMhB,WAAW,KAAO;;;;;iBA+fpB,gBACd,QAAQ,WACR,iBACA;;;;;;;;;;;;;;;;iBAkDc,gBAAgB,gBAAgB,WAC9C,MAAM,kBAAkB;EAatB"}
@@ -2,9 +2,9 @@ const require_codes = require("./codes-Be-DrYMh.cjs");
2
2
  const require_getErrorShape = require("./getErrorShape-BAuHhNuh.cjs");
3
3
  const require_parseTRPCMessage = require("./parseTRPCMessage-BsPr5reh.cjs");
4
4
  const require_asyncGeneratorDelegate = require("./asyncGeneratorDelegate-CMdmcplC.cjs");
5
- const require_resolveResponse = require("./resolveResponse-C13UI6ip.cjs");
5
+ const require_resolveResponse = require("./resolveResponse-BLSF4Ks0.cjs");
6
6
  const require_observable = require("./observable-B8nn0anr.cjs");
7
- const require_node_http = require("./node-http-DXyh_vFZ.cjs");
7
+ const require_node_http = require("./node-http-fnRXnfX7.cjs");
8
8
  //#region src/adapters/wsEncoder.ts
9
9
  /**
10
10
  * The default encoder: JSON in text frames.
@@ -367,7 +367,45 @@ function getWSConnectionHandler(opts) {
367
367
  require_codes.run(() => {
368
368
  try {
369
369
  const msgJSON = encoder.decode(data);
370
- return (Array.isArray(msgJSON) ? msgJSON : [msgJSON]).map((raw) => require_parseTRPCMessage.parseTRPCMessage(raw, transformer));
370
+ const msgs = Array.isArray(msgJSON) ? msgJSON : [msgJSON];
371
+ if (Array.isArray(msgJSON) && typeof opts.maxBatchSize === "number" && msgs.length > opts.maxBatchSize) {
372
+ var _opts$onError6;
373
+ const error = new require_asyncGeneratorDelegate.TRPCError({
374
+ code: "BAD_REQUEST",
375
+ message: `Batch call exceeds maximum size`
376
+ });
377
+ (_opts$onError6 = opts.onError) === null || _opts$onError6 === void 0 || _opts$onError6.call(opts, {
378
+ error,
379
+ path: void 0,
380
+ type: "unknown",
381
+ ctx,
382
+ req,
383
+ input: void 0
384
+ });
385
+ const errorShape = require_getErrorShape.getErrorShape({
386
+ config: router._def._config,
387
+ error,
388
+ type: "unknown",
389
+ path: void 0,
390
+ input: void 0,
391
+ ctx
392
+ });
393
+ let responded = false;
394
+ for (const raw of msgs) if (require_codes.isObject(raw) && raw["method"] !== "subscription.stop" && (typeof raw["id"] === "number" || typeof raw["id"] === "string")) {
395
+ respond({
396
+ id: raw["id"],
397
+ jsonrpc: raw["jsonrpc"] === "2.0" ? "2.0" : void 0,
398
+ error: errorShape
399
+ });
400
+ responded = true;
401
+ }
402
+ if (!responded) respond({
403
+ id: null,
404
+ error: errorShape
405
+ });
406
+ return [];
407
+ }
408
+ return msgs.map((raw) => require_parseTRPCMessage.parseTRPCMessage(raw, transformer));
371
409
  } catch (cause) {
372
410
  const error = new require_asyncGeneratorDelegate.TRPCError({
373
411
  code: "PARSE_ERROR",
@@ -389,8 +427,8 @@ function getWSConnectionHandler(opts) {
389
427
  }).map((msg, index) => handleRequest(msg, index));
390
428
  });
391
429
  client.on("error", (cause) => {
392
- var _opts$onError6;
393
- (_opts$onError6 = opts.onError) === null || _opts$onError6 === void 0 || _opts$onError6.call(opts, {
430
+ var _opts$onError7;
431
+ (_opts$onError7 = opts.onError) === null || _opts$onError7 === void 0 || _opts$onError7.call(opts, {
394
432
  ctx,
395
433
  error: require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause),
396
434
  input: void 0,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@trpc/server",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "11.23.1-canary.39.58d95db98",
5
+ "version": "11.24.0",
6
6
  "description": "The tRPC server library",
7
7
  "author": "KATT",
8
8
  "license": "MIT",
@@ -257,5 +257,5 @@
257
257
  "keywords": [
258
258
  "tanstack-intent"
259
259
  ],
260
- "gitHead": "58d95db9886acc8be38f34e2d4205e5b72015124"
260
+ "gitHead": "b147c52e0a6af43a8d735d24bc3d5ef6c7cd42ed"
261
261
  }
@@ -9,7 +9,7 @@ sources:
9
9
  metadata:
10
10
  type: core
11
11
  library: trpc
12
- library_version: 11.23.1-canary.39.58d95db98
12
+ library_version: 11.24.0
13
13
  ---
14
14
 
15
15
  <!-- Generated from www/v11/docs/server/adapters/aws-lambda.md by www/build/skills.ts. Edit the docs instead. -->
@@ -196,7 +196,7 @@ Every HTTP adapter accepts these options, next to its own (like `endpoint` for F
196
196
 
197
197
  The Node.js adapters (Standalone, Express and Next.js) also accept:
198
198
 
199
- - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`.
199
+ - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`. There's no limit by default; see [Request body size](https://trpc.io/docs/server/adapters#request-body-size).
200
200
  - `middleware`: a connect-style `(req, res, next)` function that runs before tRPC, e.g. [`cors()`](https://trpc.io/docs/server/adapters/standalone#handling-cors--options).
201
201
 
202
202
  ```ts no-check title="server.ts"
@@ -210,10 +210,18 @@ createHTTPServer({
210
210
  console.error(`tRPC error on '${path}':`, error);
211
211
  },
212
212
  maxBatchSize: 10,
213
- maxBodySize: 1_000_000, // 1 MB
213
+ maxBodySize: 1024 * 1024, // 1 MiB
214
214
  }).listen(3000);
215
215
  ```
216
216
 
217
+ ### Request body size
218
+
219
+ The Node.js adapters read the request body into memory, and `maxBodySize` is unset by default, so they accept bodies of any size. On a server that's reachable from the internet, set `maxBodySize` so a single large request can't exhaust the process's memory. A body over the limit is rejected with `413 PAYLOAD_TOO_LARGE` as soon as it passes the limit, before it's parsed.
220
+
221
+ We recommend `1024 * 1024` (1 MiB) for typical JSON inputs, as in the example above. If you accept files or other large inputs, set it a little above the largest one you expect, and keep it under about `10 * 1024 * 1024` (10 MiB).
222
+
223
+ `maxBodySize` only applies to bodies tRPC reads itself. If a body parser such as `express.json()` or the Next.js API routes body parser has already set `req.body`, limit the size in that parser instead. A limit in your reverse proxy (like nginx's `client_max_body_size`) adds another layer.
224
+
217
225
  From https://trpc.io/docs/server/adapters#common-options
218
226
 
219
227
  ## Related skills
@@ -9,7 +9,7 @@ sources:
9
9
  metadata:
10
10
  type: core
11
11
  library: trpc
12
- library_version: 11.23.1-canary.39.58d95db98
12
+ library_version: 11.24.0
13
13
  ---
14
14
 
15
15
  <!-- Generated from www/v11/docs/server/adapters/express.md by www/build/skills.ts. Edit the docs instead. -->
@@ -165,7 +165,7 @@ Every HTTP adapter accepts these options, next to its own (like `endpoint` for F
165
165
 
166
166
  The Node.js adapters (Standalone, Express and Next.js) also accept:
167
167
 
168
- - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`.
168
+ - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`. There's no limit by default; see [Request body size](https://trpc.io/docs/server/adapters#request-body-size).
169
169
  - `middleware`: a connect-style `(req, res, next)` function that runs before tRPC, e.g. [`cors()`](https://trpc.io/docs/server/adapters/standalone#handling-cors--options).
170
170
 
171
171
  ```ts no-check title="server.ts"
@@ -179,10 +179,18 @@ createHTTPServer({
179
179
  console.error(`tRPC error on '${path}':`, error);
180
180
  },
181
181
  maxBatchSize: 10,
182
- maxBodySize: 1_000_000, // 1 MB
182
+ maxBodySize: 1024 * 1024, // 1 MiB
183
183
  }).listen(3000);
184
184
  ```
185
185
 
186
+ ### Request body size
187
+
188
+ The Node.js adapters read the request body into memory, and `maxBodySize` is unset by default, so they accept bodies of any size. On a server that's reachable from the internet, set `maxBodySize` so a single large request can't exhaust the process's memory. A body over the limit is rejected with `413 PAYLOAD_TOO_LARGE` as soon as it passes the limit, before it's parsed.
189
+
190
+ We recommend `1024 * 1024` (1 MiB) for typical JSON inputs, as in the example above. If you accept files or other large inputs, set it a little above the largest one you expect, and keep it under about `10 * 1024 * 1024` (10 MiB).
191
+
192
+ `maxBodySize` only applies to bodies tRPC reads itself. If a body parser such as `express.json()` or the Next.js API routes body parser has already set `req.body`, limit the size in that parser instead. A limit in your reverse proxy (like nginx's `client_max_body_size`) adds another layer.
193
+
186
194
  From https://trpc.io/docs/server/adapters#common-options
187
195
 
188
196
  ## Related skills
@@ -9,7 +9,7 @@ sources:
9
9
  metadata:
10
10
  type: core
11
11
  library: trpc
12
- library_version: 11.23.1-canary.39.58d95db98
12
+ library_version: 11.24.0
13
13
  ---
14
14
 
15
15
  <!-- Generated from www/v11/docs/server/adapters/fastify.md by www/build/skills.ts. Edit the docs instead. -->
@@ -288,7 +288,7 @@ Every HTTP adapter accepts these options, next to its own (like `endpoint` for F
288
288
 
289
289
  The Node.js adapters (Standalone, Express and Next.js) also accept:
290
290
 
291
- - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`.
291
+ - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`. There's no limit by default; see [Request body size](https://trpc.io/docs/server/adapters#request-body-size).
292
292
  - `middleware`: a connect-style `(req, res, next)` function that runs before tRPC, e.g. [`cors()`](https://trpc.io/docs/server/adapters/standalone#handling-cors--options).
293
293
 
294
294
  ```ts no-check title="server.ts"
@@ -302,10 +302,18 @@ createHTTPServer({
302
302
  console.error(`tRPC error on '${path}':`, error);
303
303
  },
304
304
  maxBatchSize: 10,
305
- maxBodySize: 1_000_000, // 1 MB
305
+ maxBodySize: 1024 * 1024, // 1 MiB
306
306
  }).listen(3000);
307
307
  ```
308
308
 
309
+ ### Request body size
310
+
311
+ The Node.js adapters read the request body into memory, and `maxBodySize` is unset by default, so they accept bodies of any size. On a server that's reachable from the internet, set `maxBodySize` so a single large request can't exhaust the process's memory. A body over the limit is rejected with `413 PAYLOAD_TOO_LARGE` as soon as it passes the limit, before it's parsed.
312
+
313
+ We recommend `1024 * 1024` (1 MiB) for typical JSON inputs, as in the example above. If you accept files or other large inputs, set it a little above the largest one you expect, and keep it under about `10 * 1024 * 1024` (10 MiB).
314
+
315
+ `maxBodySize` only applies to bodies tRPC reads itself. If a body parser such as `express.json()` or the Next.js API routes body parser has already set `req.body`, limit the size in that parser instead. A limit in your reverse proxy (like nginx's `client_max_body_size`) adds another layer.
316
+
309
317
  From https://trpc.io/docs/server/adapters#common-options
310
318
 
311
319
  ## Related skills
@@ -8,7 +8,7 @@ sources:
8
8
  metadata:
9
9
  type: core
10
10
  library: trpc
11
- library_version: 11.23.1-canary.39.58d95db98
11
+ library_version: 11.24.0
12
12
  ---
13
13
 
14
14
  <!-- Generated from www/v11/docs/server/adapters/fetch.md by www/build/skills.ts. Edit the docs instead. -->
@@ -9,7 +9,7 @@ sources:
9
9
  metadata:
10
10
  type: core
11
11
  library: trpc
12
- library_version: 11.23.1-canary.39.58d95db98
12
+ library_version: 11.24.0
13
13
  ---
14
14
 
15
15
  <!-- Generated from www/v11/docs/server/adapters/standalone.md by www/build/skills.ts. Edit the docs instead. -->
@@ -263,7 +263,7 @@ Every HTTP adapter accepts these options, next to its own (like `endpoint` for F
263
263
 
264
264
  The Node.js adapters (Standalone, Express and Next.js) also accept:
265
265
 
266
- - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`.
266
+ - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`. There's no limit by default; see [Request body size](https://trpc.io/docs/server/adapters#request-body-size).
267
267
  - `middleware`: a connect-style `(req, res, next)` function that runs before tRPC, e.g. [`cors()`](https://trpc.io/docs/server/adapters/standalone#handling-cors--options).
268
268
 
269
269
  ```ts no-check title="server.ts"
@@ -277,10 +277,18 @@ createHTTPServer({
277
277
  console.error(`tRPC error on '${path}':`, error);
278
278
  },
279
279
  maxBatchSize: 10,
280
- maxBodySize: 1_000_000, // 1 MB
280
+ maxBodySize: 1024 * 1024, // 1 MiB
281
281
  }).listen(3000);
282
282
  ```
283
283
 
284
+ ### Request body size
285
+
286
+ The Node.js adapters read the request body into memory, and `maxBodySize` is unset by default, so they accept bodies of any size. On a server that's reachable from the internet, set `maxBodySize` so a single large request can't exhaust the process's memory. A body over the limit is rejected with `413 PAYLOAD_TOO_LARGE` as soon as it passes the limit, before it's parsed.
287
+
288
+ We recommend `1024 * 1024` (1 MiB) for typical JSON inputs, as in the example above. If you accept files or other large inputs, set it a little above the largest one you expect, and keep it under about `10 * 1024 * 1024` (10 MiB).
289
+
290
+ `maxBodySize` only applies to bodies tRPC reads itself. If a body parser such as `express.json()` or the Next.js API routes body parser has already set `req.body`, limit the size in that parser instead. A limit in your reverse proxy (like nginx's `client_max_body_size`) adds another layer.
291
+
284
292
  From https://trpc.io/docs/server/adapters#common-options
285
293
 
286
294
  ## Related skills
@@ -14,7 +14,7 @@ sources:
14
14
  metadata:
15
15
  type: composition
16
16
  library: trpc
17
- library_version: 11.23.1-canary.39.58d95db98
17
+ library_version: 11.24.0
18
18
  ---
19
19
 
20
20
  <!-- Generated from www/v11/docs/server/authorization.md by www/build/skills.ts. Edit the docs instead. -->
@@ -8,7 +8,7 @@ sources:
8
8
  metadata:
9
9
  type: core
10
10
  library: trpc
11
- library_version: 11.23.1-canary.39.58d95db98
11
+ library_version: 11.24.0
12
12
  ---
13
13
 
14
14
  <!-- Generated from www/v11/docs/server/caching.md by www/build/skills.ts. Edit the docs instead. -->
@@ -9,7 +9,7 @@ sources:
9
9
  metadata:
10
10
  type: core
11
11
  library: trpc
12
- library_version: 11.23.1-canary.39.58d95db98
12
+ library_version: 11.24.0
13
13
  ---
14
14
 
15
15
  <!-- Generated from www/v11/docs/server/error-handling.md by www/build/skills.ts. Edit the docs instead. -->
@@ -8,7 +8,7 @@ sources:
8
8
  metadata:
9
9
  type: core
10
10
  library: trpc
11
- library_version: 11.23.1-canary.39.58d95db98
11
+ library_version: 11.24.0
12
12
  ---
13
13
 
14
14
  <!-- Generated from www/v11/docs/server/middlewares.md by www/build/skills.ts. Edit the docs instead. -->
@@ -10,7 +10,7 @@ sources:
10
10
  metadata:
11
11
  type: core
12
12
  library: trpc
13
- library_version: 11.23.1-canary.39.58d95db98
13
+ library_version: 11.24.0
14
14
  ---
15
15
 
16
16
  <!-- Generated from www/v11/docs/server/non-json-content-types.md by www/build/skills.ts. Edit the docs instead. -->
@@ -11,7 +11,7 @@ sources:
11
11
  metadata:
12
12
  type: core
13
13
  library: trpc
14
- library_version: 11.23.1-canary.39.58d95db98
14
+ library_version: 11.24.0
15
15
  ---
16
16
 
17
17
  <!-- Generated from www/v11/docs/server/overview.md by www/build/skills.ts. Edit the docs instead. -->
@@ -8,7 +8,7 @@ sources:
8
8
  metadata:
9
9
  type: core
10
10
  library: trpc
11
- library_version: 11.23.1-canary.39.58d95db98
11
+ library_version: 11.24.0
12
12
  ---
13
13
 
14
14
  <!-- Generated from www/v11/docs/server/server-side-calls.md by www/build/skills.ts. Edit the docs instead. -->
@@ -10,7 +10,7 @@ sources:
10
10
  metadata:
11
11
  type: composition
12
12
  library: trpc
13
- library_version: 11.23.1-canary.39.58d95db98
13
+ library_version: 11.24.0
14
14
  ---
15
15
 
16
16
  <!-- Generated from www/v11/docs/server/service-oriented-architecture.md by www/build/skills.ts. Edit the docs instead. -->
@@ -12,7 +12,7 @@ sources:
12
12
  metadata:
13
13
  type: core
14
14
  library: trpc
15
- library_version: 11.23.1-canary.39.58d95db98
15
+ library_version: 11.24.0
16
16
  ---
17
17
 
18
18
  <!-- Generated from www/v11/docs/server/subscriptions.md by www/build/skills.ts. Edit the docs instead. -->
@@ -69,6 +69,36 @@ applyWSSHandler({ wss, router: appRouter });
69
69
  server.listen(3000);
70
70
  ```
71
71
 
72
+ ### Limiting batch size
73
+
74
+ `applyWSSHandler` accepts the same `maxBatchSize` option as the [HTTP adapters](https://trpc.io/docs/server/adapters#common-options). A WebSocket message that batches more requests than this is rejected as a whole: no procedure runs, and every request in it, except `subscription.stop` entries, gets a `BAD_REQUEST` error with the message `Batch call exceeds maximum size`.
75
+
76
+ `wsLink` sends all requests made in the same tick as one message and has no `maxItems` option, so pick a limit above the number of calls your client makes at once.
77
+
78
+ ### Rejecting cross-origin connections
79
+
80
+ Browsers don't apply CORS to WebSockets: a page on any origin can open a connection to your server, and the browser sends its cookies with it. If you authenticate with cookies, check the `Origin` header against the origins you trust. With `ws`, do this in `verifyClient`, and pass `403` to its callback so a rejected upgrade gets `403 Forbidden`:
81
+
82
+ ```ts no-check title="server/wsServer.ts"
83
+ import { applyWSSHandler } from '@trpc/server/adapters/ws';
84
+ import { WebSocketServer } from 'ws';
85
+ import { appRouter } from './router';
86
+
87
+ const allowedOrigins = new Set(['https://app.example.com']);
88
+
89
+ const wss = new WebSocketServer({
90
+ port: 3001,
91
+ verifyClient: ({ origin }, callback) => {
92
+ // Browsers always send `Origin`, but other clients may not.
93
+ // Decide whether your app accepts connections without one.
94
+ callback(!origin || allowedOrigins.has(origin), 403);
95
+ },
96
+ });
97
+ applyWSSHandler({ wss, router: appRouter });
98
+ ```
99
+
100
+ If you handle upgrades yourself with `noServer: true`, check `req.headers.origin` in your server's `upgrade` listener instead. For an origin you don't trust, end the socket with a `403` response, such as `socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n')`, rather than calling `wss.handleUpgrade()`.
101
+
72
102
  ### Setting `TRPCClient` to use WebSockets
73
103
 
74
104
  > [!TIP]
@@ -7,7 +7,7 @@ sources:
7
7
  metadata:
8
8
  type: core
9
9
  library: trpc
10
- library_version: 11.23.1-canary.39.58d95db98
10
+ library_version: 11.24.0
11
11
  ---
12
12
 
13
13
  <!-- Generated from www/v11/docs/skills.md by www/build/skills.ts. Edit the docs instead. -->
@@ -8,7 +8,7 @@ sources:
8
8
  metadata:
9
9
  type: core
10
10
  library: trpc
11
- library_version: 11.23.1-canary.39.58d95db98
11
+ library_version: 11.24.0
12
12
  ---
13
13
 
14
14
  <!-- Generated from www/v11/docs/server/validators.md by www/build/skills.ts. Edit the docs instead. -->
@@ -28,8 +28,15 @@ export type FastifyHandlerOptions<
28
28
  TRouter extends AnyRouter,
29
29
  TRequest extends FastifyRequest,
30
30
  TResponse extends FastifyReply,
31
- > = HTTPBaseHandlerOptions<TRouter, TRequest> &
32
- NodeHTTPCreateContextOption<TRouter, TRequest, TResponse>;
31
+ > = HTTPBaseHandlerOptions<TRouter, TRequest> & {
32
+ /**
33
+ * The largest request body, in bytes. A larger one gets a
34
+ * `PAYLOAD_TOO_LARGE` error. It applies to bodies tRPC streams, such as
35
+ * `multipart/form-data`; JSON bodies are read by Fastify, so limit them
36
+ * with Fastify's `bodyLimit`.
37
+ */
38
+ maxBodySize?: number;
39
+ } & NodeHTTPCreateContextOption<TRouter, TRequest, TResponse>;
33
40
 
34
41
  type FastifyRequestHandlerOptions<
35
42
  TRouter extends AnyRouter,
@@ -66,7 +73,7 @@ export async function fastifyRequestHandler<
66
73
  incomingMessage.body = opts.req.body;
67
74
  }
68
75
  const req = incomingMessageToRequest(incomingMessage, opts.res.raw, {
69
- maxBodySize: null,
76
+ maxBodySize: opts.maxBodySize ?? null,
70
77
  });
71
78
 
72
79
  const res = await resolveResponse({