@trpc/server 11.14.1 → 11.15.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 (73) hide show
  1. package/dist/adapters/aws-lambda/index.cjs +1 -1
  2. package/dist/adapters/aws-lambda/index.d.cts +1 -1
  3. package/dist/adapters/aws-lambda/index.d.mts +1 -1
  4. package/dist/adapters/aws-lambda/index.mjs +1 -1
  5. package/dist/adapters/express.cjs +2 -2
  6. package/dist/adapters/express.d.cts +2 -2
  7. package/dist/adapters/express.d.mts +2 -2
  8. package/dist/adapters/express.mjs +2 -2
  9. package/dist/adapters/fastify/index.cjs +3 -3
  10. package/dist/adapters/fastify/index.d.cts +2 -2
  11. package/dist/adapters/fastify/index.d.mts +2 -2
  12. package/dist/adapters/fastify/index.mjs +3 -3
  13. package/dist/adapters/fetch/index.cjs +1 -1
  14. package/dist/adapters/fetch/index.d.cts +1 -1
  15. package/dist/adapters/fetch/index.d.mts +1 -1
  16. package/dist/adapters/fetch/index.mjs +1 -1
  17. package/dist/adapters/next-app-dir.cjs +77 -77
  18. package/dist/adapters/next-app-dir.d.cts +1 -1
  19. package/dist/adapters/next-app-dir.d.mts +1 -1
  20. package/dist/adapters/next-app-dir.mjs +77 -77
  21. package/dist/adapters/next-app-dir.mjs.map +1 -1
  22. package/dist/adapters/next.cjs +2 -2
  23. package/dist/adapters/next.d.cts +2 -2
  24. package/dist/adapters/next.d.mts +2 -2
  25. package/dist/adapters/next.mjs +2 -2
  26. package/dist/adapters/node-http/index.cjs +2 -2
  27. package/dist/adapters/node-http/index.d.cts +2 -2
  28. package/dist/adapters/node-http/index.d.mts +2 -2
  29. package/dist/adapters/node-http/index.mjs +2 -2
  30. package/dist/adapters/standalone.cjs +2 -2
  31. package/dist/adapters/standalone.d.cts +2 -2
  32. package/dist/adapters/standalone.d.mts +2 -2
  33. package/dist/adapters/standalone.mjs +2 -2
  34. package/dist/adapters/ws.cjs +3 -3
  35. package/dist/adapters/ws.d.cts +2 -2
  36. package/dist/adapters/ws.d.mts +2 -2
  37. package/dist/adapters/ws.mjs +3 -3
  38. package/dist/http.cjs +1 -1
  39. package/dist/http.d.cts +1 -1
  40. package/dist/http.d.mts +1 -1
  41. package/dist/http.mjs +1 -1
  42. package/dist/{index.d-D2tfkeVL.d.cts → index.d-C8CpwWZN.d.cts} +2 -2
  43. package/dist/{index.d-D2tfkeVL.d.cts.map → index.d-C8CpwWZN.d.cts.map} +1 -1
  44. package/dist/{index.d-l03toeY5.d.mts → index.d-Ch63NO6Z.d.mts} +2 -2
  45. package/dist/{index.d-l03toeY5.d.mts.map → index.d-Ch63NO6Z.d.mts.map} +1 -1
  46. package/dist/index.d.cts +1 -1
  47. package/dist/index.d.mts +1 -1
  48. package/dist/{node-http-DZiUEwuh.mjs → node-http-BAkZnlij.mjs} +2 -2
  49. package/dist/{node-http-DZiUEwuh.mjs.map → node-http-BAkZnlij.mjs.map} +1 -1
  50. package/dist/{node-http-DOrt4Pjb.cjs → node-http-qIM6subj.cjs} +1 -1
  51. package/dist/{resolveResponse-0xxAjZaH.cjs → resolveResponse-Ck4MWy4N.cjs} +7 -1
  52. package/dist/{resolveResponse-DbcCY-yX.mjs → resolveResponse-O0k3XIo_.mjs} +8 -2
  53. package/dist/resolveResponse-O0k3XIo_.mjs.map +1 -0
  54. package/dist/rpc.d.cts +1 -1
  55. package/dist/rpc.d.mts +1 -1
  56. package/dist/shared.d.cts +1 -1
  57. package/dist/shared.d.mts +1 -1
  58. package/dist/unstable-core-do-not-import.cjs +1 -1
  59. package/dist/{unstable-core-do-not-import.d-DJljFxtY.d.mts → unstable-core-do-not-import.d-Bl-_61JQ.d.mts} +9 -1
  60. package/dist/{unstable-core-do-not-import.d-Hlj_hEnF.d.cts.map → unstable-core-do-not-import.d-Bl-_61JQ.d.mts.map} +1 -1
  61. package/dist/{unstable-core-do-not-import.d-Hlj_hEnF.d.cts → unstable-core-do-not-import.d-Dm2ii-ih.d.cts} +9 -1
  62. package/dist/{unstable-core-do-not-import.d-DJljFxtY.d.mts.map → unstable-core-do-not-import.d-Dm2ii-ih.d.cts.map} +1 -1
  63. package/dist/unstable-core-do-not-import.d.cts +1 -1
  64. package/dist/unstable-core-do-not-import.d.mts +1 -1
  65. package/dist/unstable-core-do-not-import.mjs +1 -1
  66. package/dist/{ws-Dmi9HHSk.mjs → ws-bG-XhXoQ.mjs} +3 -3
  67. package/dist/{ws-Dmi9HHSk.mjs.map → ws-bG-XhXoQ.mjs.map} +1 -1
  68. package/dist/{ws-D0ZoX7-1.cjs → ws-vP42F1N-.cjs} +2 -2
  69. package/package.json +3 -3
  70. package/src/unstable-core-do-not-import/http/contentType.ts +13 -0
  71. package/src/unstable-core-do-not-import/http/resolveResponse.ts +1 -0
  72. package/src/unstable-core-do-not-import/http/types.ts +7 -0
  73. package/dist/resolveResponse-DbcCY-yX.mjs.map +0 -1
@@ -1,3 +1,3 @@
1
1
  import "./index.d-BiUz7kM_.cjs";
2
- import { AnyClientTypes, AnyMiddlewareBuilder, AnyMiddlewareFunction, AnyMutationProcedure, AnyProcedure, AnyProcedureBuilder, AnyQueryProcedure, AnyRootTypes, AnyRouter, AnySubscriptionProcedure, BaseHandlerOptions, BuiltRouter, CallerOverride, CombinedDataTransformer, CombinedDataTransformerClient, ConsumerOnError, CreateContextCallback, CreateRootTypes, CreateRouterOptions, DataTransformer, DataTransformerOptions, DecorateCreateRouterOptions, DecorateRouterRecord, DeepPartial, DefaultErrorData, DefaultErrorShape, Deferred, Dict, DistributiveOmit, ErrorFormatter, ErrorHandlerOptions, ErrorSymbol, EventSourceLike, FileLike, Filter, FilterKeys, GetInferenceHelpers, GetRawInputFn, HTTPBaseHandlerOptions, HTTPErrorHandler, HTTP_CODE_TO_JSONRPC2, InferrableClientTypes, IntersectionError, InvertKeyValue, JSONLProducerOptions, JSONRPC2, JSONRPC2_TO_HTTP_CODE, KeyFromValue, Lazy, LegacyObservableSubscriptionProcedure, Maybe, MaybePromise, MergeRouters, MiddlewareBuilder, MiddlewareFunction, MiddlewareResult, MutationProcedure, NodeJSReadableStreamEsque, OctetInput, Overwrite, ParseFn, Parser, ParserArkTypeEsque, ParserCustomValidatorEsque, ParserMyZodEsque, ParserScaleEsque, ParserStandardSchemaEsque, ParserSuperstructEsque, ParserValibotEsque, ParserWithInputOutput, ParserWithoutInput, ParserYupEsque, ParserZodEsque, PickFirstDefined, Procedure, ProcedureBuilder, ProcedureCallOptions, ProcedureResolverOptions, ProcedureType, ProducerOnError, PromiseExecutor, PromiseWithResolvers, ProtectedIntersection, ProxyPromise, QueryProcedure, ResolveHTTPRequestOptionsContextFn, ResponseMeta, ResponseMetaFn, Result, RootConfig, RootTypes, Router, RouterBuilder, RouterCaller, RouterCallerErrorHandler, RouterCallerFactory, RouterDef, RouterRecord, RuntimeConfigOptions, SSEClientOptions, SSEPingOptions, SSEStreamConsumerOptions, SSEStreamProducerOptions, Serialize, SerializeObject, Simplify, StandardSchemaV1, StandardSchemaV1Error, SubscribedPromise, SubscriptionProcedure, TRPCAcceptHeader, TRPCBuilder, TRPCClientIncomingMessage, TRPCClientIncomingRequest, TRPCClientOutgoingMessage, TRPCClientOutgoingRequest, TRPCConnectionParamsMessage, TRPCError, TRPCErrorResponse, TRPCErrorShape, TRPCReconnectNotification, TRPCRequest, TRPCRequestInfo, TRPCRequestInfoProcedureCall, TRPCRequestMessage, TRPCResponse, TRPCResponseMessage, TRPCResult, TRPCResultMessage, TRPCRootObject, TRPCSubscriptionStopNotification, TRPCSuccessResponse, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, TRPC_ERROR_CODE_KEY, TRPC_ERROR_CODE_NUMBER, TrackedData, TrackedEnvelope, TypeError, Unpromise, UnsetMarker, Unwrap, UtilityParser, ValidateShape, ValueOf, WebReadableStreamEsque, WithoutIndexSignature, abortSignalsAnyPonyfill, assert, callProcedure, coerceAsyncIterableToArray, createBuilder, createCallerFactory, createDeferred, createFlatProxy, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, createRecursiveProxy, createRouterFactory, defaultFormatter, defaultTransformer, emptyObject, experimental_standaloneMiddleware, formDataToObject, getAcceptHeader, getCauseFromUnknown, getDataTransformer, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getParseFn, getProcedureAtPath, getRequestInfo, getStatusCodeFromKey, getStatusKeyFromCode, getTRPCErrorFromUnknown, identity, inferAsyncIterableYield, inferClientTypes, inferParser, inferProcedureBuilderResolverOptions, inferProcedureInput, inferProcedureOutput, inferProcedureParams, inferRouterContext, inferRouterError, inferRouterInputs, inferRouterMeta, inferRouterOutputs, inferRouterRootTypes, inferTrackedOutput, inferTransformedProcedureOutput, inferTransformedSubscriptionOutput, initTRPC, isAbortError, isAsyncIterable, isFunction, isObject, isPromise, isServerDefault, isTrackedEnvelope, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, lazy, makeAsyncResource, makeResource, mergeRouters, mergeWithoutOverrides, middlewareMarker, noop, octetInputParser, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, parseTRPCMessage, procedureTypes, resolveResponse, retryableRpcCodes, run, sleep, sse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, tracked, transformResult, transformTRPCResponse } from "./unstable-core-do-not-import.d-Hlj_hEnF.cjs";
2
+ import { AnyClientTypes, AnyMiddlewareBuilder, AnyMiddlewareFunction, AnyMutationProcedure, AnyProcedure, AnyProcedureBuilder, AnyQueryProcedure, AnyRootTypes, AnyRouter, AnySubscriptionProcedure, BaseHandlerOptions, BuiltRouter, CallerOverride, CombinedDataTransformer, CombinedDataTransformerClient, ConsumerOnError, CreateContextCallback, CreateRootTypes, CreateRouterOptions, DataTransformer, DataTransformerOptions, DecorateCreateRouterOptions, DecorateRouterRecord, DeepPartial, DefaultErrorData, DefaultErrorShape, Deferred, Dict, DistributiveOmit, ErrorFormatter, ErrorHandlerOptions, ErrorSymbol, EventSourceLike, FileLike, Filter, FilterKeys, GetInferenceHelpers, GetRawInputFn, HTTPBaseHandlerOptions, HTTPErrorHandler, HTTP_CODE_TO_JSONRPC2, InferrableClientTypes, IntersectionError, InvertKeyValue, JSONLProducerOptions, JSONRPC2, JSONRPC2_TO_HTTP_CODE, KeyFromValue, Lazy, LegacyObservableSubscriptionProcedure, Maybe, MaybePromise, MergeRouters, MiddlewareBuilder, MiddlewareFunction, MiddlewareResult, MutationProcedure, NodeJSReadableStreamEsque, OctetInput, Overwrite, ParseFn, Parser, ParserArkTypeEsque, ParserCustomValidatorEsque, ParserMyZodEsque, ParserScaleEsque, ParserStandardSchemaEsque, ParserSuperstructEsque, ParserValibotEsque, ParserWithInputOutput, ParserWithoutInput, ParserYupEsque, ParserZodEsque, PickFirstDefined, Procedure, ProcedureBuilder, ProcedureCallOptions, ProcedureResolverOptions, ProcedureType, ProducerOnError, PromiseExecutor, PromiseWithResolvers, ProtectedIntersection, ProxyPromise, QueryProcedure, ResolveHTTPRequestOptionsContextFn, ResponseMeta, ResponseMetaFn, Result, RootConfig, RootTypes, Router, RouterBuilder, RouterCaller, RouterCallerErrorHandler, RouterCallerFactory, RouterDef, RouterRecord, RuntimeConfigOptions, SSEClientOptions, SSEPingOptions, SSEStreamConsumerOptions, SSEStreamProducerOptions, Serialize, SerializeObject, Simplify, StandardSchemaV1, StandardSchemaV1Error, SubscribedPromise, SubscriptionProcedure, TRPCAcceptHeader, TRPCBuilder, TRPCClientIncomingMessage, TRPCClientIncomingRequest, TRPCClientOutgoingMessage, TRPCClientOutgoingRequest, TRPCConnectionParamsMessage, TRPCError, TRPCErrorResponse, TRPCErrorShape, TRPCReconnectNotification, TRPCRequest, TRPCRequestInfo, TRPCRequestInfoProcedureCall, TRPCRequestMessage, TRPCResponse, TRPCResponseMessage, TRPCResult, TRPCResultMessage, TRPCRootObject, TRPCSubscriptionStopNotification, TRPCSuccessResponse, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, TRPC_ERROR_CODE_KEY, TRPC_ERROR_CODE_NUMBER, TrackedData, TrackedEnvelope, TypeError, Unpromise, UnsetMarker, Unwrap, UtilityParser, ValidateShape, ValueOf, WebReadableStreamEsque, WithoutIndexSignature, abortSignalsAnyPonyfill, assert, callProcedure, coerceAsyncIterableToArray, createBuilder, createCallerFactory, createDeferred, createFlatProxy, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, createRecursiveProxy, createRouterFactory, defaultFormatter, defaultTransformer, emptyObject, experimental_standaloneMiddleware, formDataToObject, getAcceptHeader, getCauseFromUnknown, getDataTransformer, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getParseFn, getProcedureAtPath, getRequestInfo, getStatusCodeFromKey, getStatusKeyFromCode, getTRPCErrorFromUnknown, identity, inferAsyncIterableYield, inferClientTypes, inferParser, inferProcedureBuilderResolverOptions, inferProcedureInput, inferProcedureOutput, inferProcedureParams, inferRouterContext, inferRouterError, inferRouterInputs, inferRouterMeta, inferRouterOutputs, inferRouterRootTypes, inferTrackedOutput, inferTransformedProcedureOutput, inferTransformedSubscriptionOutput, initTRPC, isAbortError, isAsyncIterable, isFunction, isObject, isPromise, isServerDefault, isTrackedEnvelope, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, lazy, makeAsyncResource, makeResource, mergeRouters, mergeWithoutOverrides, middlewareMarker, noop, octetInputParser, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, parseTRPCMessage, procedureTypes, resolveResponse, retryableRpcCodes, run, sleep, sse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, tracked, transformResult, transformTRPCResponse } from "./unstable-core-do-not-import.d-Dm2ii-ih.cjs";
3
3
  export { AnyClientTypes, AnyMiddlewareBuilder, AnyMiddlewareFunction, AnyMutationProcedure, AnyProcedure, AnyProcedureBuilder, AnyQueryProcedure, AnyRootTypes, AnyRouter, AnySubscriptionProcedure, BaseHandlerOptions, BuiltRouter, CallerOverride, CombinedDataTransformer, CombinedDataTransformerClient, ConsumerOnError, CreateContextCallback, CreateRootTypes, CreateRouterOptions, DataTransformer, DataTransformerOptions, DecorateCreateRouterOptions, DecorateRouterRecord, DeepPartial, DefaultErrorData, DefaultErrorShape, Deferred, Dict, DistributiveOmit, ErrorFormatter, ErrorHandlerOptions, ErrorSymbol, EventSourceLike, FileLike, Filter, FilterKeys, GetInferenceHelpers, GetRawInputFn, HTTPBaseHandlerOptions, HTTPErrorHandler, HTTP_CODE_TO_JSONRPC2, InferrableClientTypes, IntersectionError, InvertKeyValue, JSONLProducerOptions, JSONRPC2, JSONRPC2_TO_HTTP_CODE, KeyFromValue, Lazy, LegacyObservableSubscriptionProcedure, Maybe, MaybePromise, MergeRouters, MiddlewareBuilder, MiddlewareFunction, MiddlewareResult, MutationProcedure, NodeJSReadableStreamEsque, OctetInput, Overwrite, ParseFn, Parser, ParserArkTypeEsque, ParserCustomValidatorEsque, ParserMyZodEsque, ParserScaleEsque, ParserStandardSchemaEsque, ParserSuperstructEsque, ParserValibotEsque, ParserWithInputOutput, ParserWithoutInput, ParserYupEsque, ParserZodEsque, PickFirstDefined, Procedure, ProcedureBuilder, ProcedureCallOptions, ProcedureResolverOptions, ProcedureType, ProducerOnError, PromiseExecutor, PromiseWithResolvers, ProtectedIntersection, ProxyPromise, QueryProcedure, ResolveHTTPRequestOptionsContextFn, ResponseMeta, ResponseMetaFn, Result, RootConfig, RootTypes, Router, RouterBuilder, RouterCaller, RouterCallerErrorHandler, RouterCallerFactory, RouterDef, RouterRecord, RuntimeConfigOptions, SSEClientOptions, SSEPingOptions, SSEStreamConsumerOptions, SSEStreamProducerOptions, Serialize, SerializeObject, Simplify, StandardSchemaV1, StandardSchemaV1Error, SubscribedPromise, SubscriptionProcedure, TRPCAcceptHeader, TRPCBuilder, TRPCClientIncomingMessage, TRPCClientIncomingRequest, TRPCClientOutgoingMessage, TRPCClientOutgoingRequest, TRPCConnectionParamsMessage, TRPCError, TRPCErrorResponse, TRPCErrorShape, TRPCReconnectNotification, TRPCRequest, TRPCRequestInfo, TRPCRequestInfoProcedureCall, TRPCRequestMessage, TRPCResponse, TRPCResponseMessage, TRPCResult, TRPCResultMessage, TRPCRootObject, TRPCSubscriptionStopNotification, TRPCSuccessResponse, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, TRPC_ERROR_CODE_KEY, TRPC_ERROR_CODE_NUMBER, TrackedData, TrackedEnvelope, TypeError, Unpromise, UnsetMarker, Unwrap, UtilityParser, ValidateShape, ValueOf, WebReadableStreamEsque, WithoutIndexSignature, abortSignalsAnyPonyfill, assert, callProcedure, coerceAsyncIterableToArray, createBuilder, createCallerFactory, createDeferred, createFlatProxy, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, createRecursiveProxy, createRouterFactory, defaultFormatter, defaultTransformer, emptyObject, experimental_standaloneMiddleware, formDataToObject, getAcceptHeader, getCauseFromUnknown, getDataTransformer, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getParseFn, getProcedureAtPath, getRequestInfo, getStatusCodeFromKey, getStatusKeyFromCode, getTRPCErrorFromUnknown, identity, inferAsyncIterableYield, inferClientTypes, inferParser, inferProcedureBuilderResolverOptions, inferProcedureInput, inferProcedureOutput, inferProcedureParams, inferRouterContext, inferRouterError, inferRouterInputs, inferRouterMeta, inferRouterOutputs, inferRouterRootTypes, inferTrackedOutput, inferTransformedProcedureOutput, inferTransformedSubscriptionOutput, initTRPC, isAbortError, isAsyncIterable, isFunction, isObject, isPromise, isServerDefault, isTrackedEnvelope, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, lazy, makeAsyncResource, makeResource, mergeRouters, mergeWithoutOverrides, middlewareMarker, noop, octetInputParser, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, parseTRPCMessage, procedureTypes, resolveResponse, retryableRpcCodes, run, sleep, sse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, tracked, transformResult, transformTRPCResponse };
@@ -1,3 +1,3 @@
1
1
  import "./index.d-D4qZxQJh.mjs";
2
- import { AnyClientTypes, AnyMiddlewareBuilder, AnyMiddlewareFunction, AnyMutationProcedure, AnyProcedure, AnyProcedureBuilder, AnyQueryProcedure, AnyRootTypes, AnyRouter, AnySubscriptionProcedure, BaseHandlerOptions, BuiltRouter, CallerOverride, CombinedDataTransformer, CombinedDataTransformerClient, ConsumerOnError, CreateContextCallback, CreateRootTypes, CreateRouterOptions, DataTransformer, DataTransformerOptions, DecorateCreateRouterOptions, DecorateRouterRecord, DeepPartial, DefaultErrorData, DefaultErrorShape, Deferred, Dict, DistributiveOmit, ErrorFormatter, ErrorHandlerOptions, ErrorSymbol, EventSourceLike, FileLike, Filter, FilterKeys, GetInferenceHelpers, GetRawInputFn, HTTPBaseHandlerOptions, HTTPErrorHandler, HTTP_CODE_TO_JSONRPC2, InferrableClientTypes, IntersectionError, InvertKeyValue, JSONLProducerOptions, JSONRPC2, JSONRPC2_TO_HTTP_CODE, KeyFromValue, Lazy, LegacyObservableSubscriptionProcedure, Maybe, MaybePromise, MergeRouters, MiddlewareBuilder, MiddlewareFunction, MiddlewareResult, MutationProcedure, NodeJSReadableStreamEsque, OctetInput, Overwrite, ParseFn, Parser, ParserArkTypeEsque, ParserCustomValidatorEsque, ParserMyZodEsque, ParserScaleEsque, ParserStandardSchemaEsque, ParserSuperstructEsque, ParserValibotEsque, ParserWithInputOutput, ParserWithoutInput, ParserYupEsque, ParserZodEsque, PickFirstDefined, Procedure, ProcedureBuilder, ProcedureCallOptions, ProcedureResolverOptions, ProcedureType, ProducerOnError, PromiseExecutor, PromiseWithResolvers, ProtectedIntersection, ProxyPromise, QueryProcedure, ResolveHTTPRequestOptionsContextFn, ResponseMeta, ResponseMetaFn, Result, RootConfig, RootTypes, Router, RouterBuilder, RouterCaller, RouterCallerErrorHandler, RouterCallerFactory, RouterDef, RouterRecord, RuntimeConfigOptions, SSEClientOptions, SSEPingOptions, SSEStreamConsumerOptions, SSEStreamProducerOptions, Serialize, SerializeObject, Simplify, StandardSchemaV1, StandardSchemaV1Error, SubscribedPromise, SubscriptionProcedure, TRPCAcceptHeader, TRPCBuilder, TRPCClientIncomingMessage, TRPCClientIncomingRequest, TRPCClientOutgoingMessage, TRPCClientOutgoingRequest, TRPCConnectionParamsMessage, TRPCError, TRPCErrorResponse, TRPCErrorShape, TRPCReconnectNotification, TRPCRequest, TRPCRequestInfo, TRPCRequestInfoProcedureCall, TRPCRequestMessage, TRPCResponse, TRPCResponseMessage, TRPCResult, TRPCResultMessage, TRPCRootObject, TRPCSubscriptionStopNotification, TRPCSuccessResponse, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, TRPC_ERROR_CODE_KEY, TRPC_ERROR_CODE_NUMBER, TrackedData, TrackedEnvelope, TypeError, Unpromise, UnsetMarker, Unwrap, UtilityParser, ValidateShape, ValueOf, WebReadableStreamEsque, WithoutIndexSignature, abortSignalsAnyPonyfill, assert, callProcedure, coerceAsyncIterableToArray, createBuilder, createCallerFactory, createDeferred, createFlatProxy, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, createRecursiveProxy, createRouterFactory, defaultFormatter, defaultTransformer, emptyObject, experimental_standaloneMiddleware, formDataToObject, getAcceptHeader, getCauseFromUnknown, getDataTransformer, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getParseFn, getProcedureAtPath, getRequestInfo, getStatusCodeFromKey, getStatusKeyFromCode, getTRPCErrorFromUnknown, identity, inferAsyncIterableYield, inferClientTypes, inferParser, inferProcedureBuilderResolverOptions, inferProcedureInput, inferProcedureOutput, inferProcedureParams, inferRouterContext, inferRouterError, inferRouterInputs, inferRouterMeta, inferRouterOutputs, inferRouterRootTypes, inferTrackedOutput, inferTransformedProcedureOutput, inferTransformedSubscriptionOutput, initTRPC, isAbortError, isAsyncIterable, isFunction, isObject, isPromise, isServerDefault, isTrackedEnvelope, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, lazy, makeAsyncResource, makeResource, mergeRouters, mergeWithoutOverrides, middlewareMarker, noop, octetInputParser, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, parseTRPCMessage, procedureTypes, resolveResponse, retryableRpcCodes, run, sleep, sse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, tracked, transformResult, transformTRPCResponse } from "./unstable-core-do-not-import.d-DJljFxtY.mjs";
2
+ import { AnyClientTypes, AnyMiddlewareBuilder, AnyMiddlewareFunction, AnyMutationProcedure, AnyProcedure, AnyProcedureBuilder, AnyQueryProcedure, AnyRootTypes, AnyRouter, AnySubscriptionProcedure, BaseHandlerOptions, BuiltRouter, CallerOverride, CombinedDataTransformer, CombinedDataTransformerClient, ConsumerOnError, CreateContextCallback, CreateRootTypes, CreateRouterOptions, DataTransformer, DataTransformerOptions, DecorateCreateRouterOptions, DecorateRouterRecord, DeepPartial, DefaultErrorData, DefaultErrorShape, Deferred, Dict, DistributiveOmit, ErrorFormatter, ErrorHandlerOptions, ErrorSymbol, EventSourceLike, FileLike, Filter, FilterKeys, GetInferenceHelpers, GetRawInputFn, HTTPBaseHandlerOptions, HTTPErrorHandler, HTTP_CODE_TO_JSONRPC2, InferrableClientTypes, IntersectionError, InvertKeyValue, JSONLProducerOptions, JSONRPC2, JSONRPC2_TO_HTTP_CODE, KeyFromValue, Lazy, LegacyObservableSubscriptionProcedure, Maybe, MaybePromise, MergeRouters, MiddlewareBuilder, MiddlewareFunction, MiddlewareResult, MutationProcedure, NodeJSReadableStreamEsque, OctetInput, Overwrite, ParseFn, Parser, ParserArkTypeEsque, ParserCustomValidatorEsque, ParserMyZodEsque, ParserScaleEsque, ParserStandardSchemaEsque, ParserSuperstructEsque, ParserValibotEsque, ParserWithInputOutput, ParserWithoutInput, ParserYupEsque, ParserZodEsque, PickFirstDefined, Procedure, ProcedureBuilder, ProcedureCallOptions, ProcedureResolverOptions, ProcedureType, ProducerOnError, PromiseExecutor, PromiseWithResolvers, ProtectedIntersection, ProxyPromise, QueryProcedure, ResolveHTTPRequestOptionsContextFn, ResponseMeta, ResponseMetaFn, Result, RootConfig, RootTypes, Router, RouterBuilder, RouterCaller, RouterCallerErrorHandler, RouterCallerFactory, RouterDef, RouterRecord, RuntimeConfigOptions, SSEClientOptions, SSEPingOptions, SSEStreamConsumerOptions, SSEStreamProducerOptions, Serialize, SerializeObject, Simplify, StandardSchemaV1, StandardSchemaV1Error, SubscribedPromise, SubscriptionProcedure, TRPCAcceptHeader, TRPCBuilder, TRPCClientIncomingMessage, TRPCClientIncomingRequest, TRPCClientOutgoingMessage, TRPCClientOutgoingRequest, TRPCConnectionParamsMessage, TRPCError, TRPCErrorResponse, TRPCErrorShape, TRPCReconnectNotification, TRPCRequest, TRPCRequestInfo, TRPCRequestInfoProcedureCall, TRPCRequestMessage, TRPCResponse, TRPCResponseMessage, TRPCResult, TRPCResultMessage, TRPCRootObject, TRPCSubscriptionStopNotification, TRPCSuccessResponse, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, TRPC_ERROR_CODE_KEY, TRPC_ERROR_CODE_NUMBER, TrackedData, TrackedEnvelope, TypeError, Unpromise, UnsetMarker, Unwrap, UtilityParser, ValidateShape, ValueOf, WebReadableStreamEsque, WithoutIndexSignature, abortSignalsAnyPonyfill, assert, callProcedure, coerceAsyncIterableToArray, createBuilder, createCallerFactory, createDeferred, createFlatProxy, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, createRecursiveProxy, createRouterFactory, defaultFormatter, defaultTransformer, emptyObject, experimental_standaloneMiddleware, formDataToObject, getAcceptHeader, getCauseFromUnknown, getDataTransformer, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getParseFn, getProcedureAtPath, getRequestInfo, getStatusCodeFromKey, getStatusKeyFromCode, getTRPCErrorFromUnknown, identity, inferAsyncIterableYield, inferClientTypes, inferParser, inferProcedureBuilderResolverOptions, inferProcedureInput, inferProcedureOutput, inferProcedureParams, inferRouterContext, inferRouterError, inferRouterInputs, inferRouterMeta, inferRouterOutputs, inferRouterRootTypes, inferTrackedOutput, inferTransformedProcedureOutput, inferTransformedSubscriptionOutput, initTRPC, isAbortError, isAsyncIterable, isFunction, isObject, isPromise, isServerDefault, isTrackedEnvelope, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, lazy, makeAsyncResource, makeResource, mergeRouters, mergeWithoutOverrides, middlewareMarker, noop, octetInputParser, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, parseTRPCMessage, procedureTypes, resolveResponse, retryableRpcCodes, run, sleep, sse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, tracked, transformResult, transformTRPCResponse } from "./unstable-core-do-not-import.d-Bl-_61JQ.mjs";
3
3
  export { AnyClientTypes, AnyMiddlewareBuilder, AnyMiddlewareFunction, AnyMutationProcedure, AnyProcedure, AnyProcedureBuilder, AnyQueryProcedure, AnyRootTypes, AnyRouter, AnySubscriptionProcedure, BaseHandlerOptions, BuiltRouter, CallerOverride, CombinedDataTransformer, CombinedDataTransformerClient, ConsumerOnError, CreateContextCallback, CreateRootTypes, CreateRouterOptions, DataTransformer, DataTransformerOptions, DecorateCreateRouterOptions, DecorateRouterRecord, DeepPartial, DefaultErrorData, DefaultErrorShape, Deferred, Dict, DistributiveOmit, ErrorFormatter, ErrorHandlerOptions, ErrorSymbol, EventSourceLike, FileLike, Filter, FilterKeys, GetInferenceHelpers, GetRawInputFn, HTTPBaseHandlerOptions, HTTPErrorHandler, HTTP_CODE_TO_JSONRPC2, InferrableClientTypes, IntersectionError, InvertKeyValue, JSONLProducerOptions, JSONRPC2, JSONRPC2_TO_HTTP_CODE, KeyFromValue, Lazy, LegacyObservableSubscriptionProcedure, Maybe, MaybePromise, MergeRouters, MiddlewareBuilder, MiddlewareFunction, MiddlewareResult, MutationProcedure, NodeJSReadableStreamEsque, OctetInput, Overwrite, ParseFn, Parser, ParserArkTypeEsque, ParserCustomValidatorEsque, ParserMyZodEsque, ParserScaleEsque, ParserStandardSchemaEsque, ParserSuperstructEsque, ParserValibotEsque, ParserWithInputOutput, ParserWithoutInput, ParserYupEsque, ParserZodEsque, PickFirstDefined, Procedure, ProcedureBuilder, ProcedureCallOptions, ProcedureResolverOptions, ProcedureType, ProducerOnError, PromiseExecutor, PromiseWithResolvers, ProtectedIntersection, ProxyPromise, QueryProcedure, ResolveHTTPRequestOptionsContextFn, ResponseMeta, ResponseMetaFn, Result, RootConfig, RootTypes, Router, RouterBuilder, RouterCaller, RouterCallerErrorHandler, RouterCallerFactory, RouterDef, RouterRecord, RuntimeConfigOptions, SSEClientOptions, SSEPingOptions, SSEStreamConsumerOptions, SSEStreamProducerOptions, Serialize, SerializeObject, Simplify, StandardSchemaV1, StandardSchemaV1Error, SubscribedPromise, SubscriptionProcedure, TRPCAcceptHeader, TRPCBuilder, TRPCClientIncomingMessage, TRPCClientIncomingRequest, TRPCClientOutgoingMessage, TRPCClientOutgoingRequest, TRPCConnectionParamsMessage, TRPCError, TRPCErrorResponse, TRPCErrorShape, TRPCReconnectNotification, TRPCRequest, TRPCRequestInfo, TRPCRequestInfoProcedureCall, TRPCRequestMessage, TRPCResponse, TRPCResponseMessage, TRPCResult, TRPCResultMessage, TRPCRootObject, TRPCSubscriptionStopNotification, TRPCSuccessResponse, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, TRPC_ERROR_CODE_KEY, TRPC_ERROR_CODE_NUMBER, TrackedData, TrackedEnvelope, TypeError, Unpromise, UnsetMarker, Unwrap, UtilityParser, ValidateShape, ValueOf, WebReadableStreamEsque, WithoutIndexSignature, abortSignalsAnyPonyfill, assert, callProcedure, coerceAsyncIterableToArray, createBuilder, createCallerFactory, createDeferred, createFlatProxy, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, createRecursiveProxy, createRouterFactory, defaultFormatter, defaultTransformer, emptyObject, experimental_standaloneMiddleware, formDataToObject, getAcceptHeader, getCauseFromUnknown, getDataTransformer, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getParseFn, getProcedureAtPath, getRequestInfo, getStatusCodeFromKey, getStatusKeyFromCode, getTRPCErrorFromUnknown, identity, inferAsyncIterableYield, inferClientTypes, inferParser, inferProcedureBuilderResolverOptions, inferProcedureInput, inferProcedureOutput, inferProcedureParams, inferRouterContext, inferRouterError, inferRouterInputs, inferRouterMeta, inferRouterOutputs, inferRouterRootTypes, inferTrackedOutput, inferTransformedProcedureOutput, inferTransformedSubscriptionOutput, initTRPC, isAbortError, isAsyncIterable, isFunction, isObject, isPromise, isServerDefault, isTrackedEnvelope, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, lazy, makeAsyncResource, makeResource, mergeRouters, mergeWithoutOverrides, middlewareMarker, noop, octetInputParser, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, parseTRPCMessage, procedureTypes, resolveResponse, retryableRpcCodes, run, sleep, sse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, tracked, transformResult, transformTRPCResponse };
@@ -2,7 +2,7 @@ import { HTTP_CODE_TO_JSONRPC2, JSONRPC2_TO_HTTP_CODE, createFlatProxy, createRe
2
2
  import { TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, abortSignalsAnyPonyfill, assert, emptyObject, identity, isAsyncIterable, isFunction, isObject, mergeWithoutOverrides, noop, retryableRpcCodes, run, sleep } from "./codes-DagpWZLc.mjs";
3
3
  import { TRPCError, callProcedure, createCallerFactory, createRouterFactory, defaultFormatter, defaultTransformer, getCauseFromUnknown, getDataTransformer, getProcedureAtPath, getTRPCErrorFromUnknown, isTrackedEnvelope, lazy, mergeRouters, sse, tracked, transformResult, transformTRPCResponse } from "./tracked-Bjtgv3wJ.mjs";
4
4
  import { parseTRPCMessage, procedureTypes } from "./parseTRPCMessage-CTow-umk.mjs";
5
- import { Unpromise, createDeferred, getAcceptHeader, getRequestInfo, isAbortError, isPromise, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, makeAsyncResource, makeResource, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, resolveResponse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError } from "./resolveResponse-DbcCY-yX.mjs";
5
+ import { Unpromise, createDeferred, getAcceptHeader, getRequestInfo, isAbortError, isPromise, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, makeAsyncResource, makeResource, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, resolveResponse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError } from "./resolveResponse-O0k3XIo_.mjs";
6
6
  import { octetInputParser } from "./contentTypeParsers-SN4WL9ze.mjs";
7
7
  import { formDataToObject } from "./unstable-core-do-not-import-9NNw8uQM.mjs";
8
8
  import "./observable-UMO3vUa_.mjs";
@@ -2,9 +2,9 @@ import { __toESM, getErrorShape, require_objectSpread2 } from "./getErrorShape-v
2
2
  import { isAsyncIterable, isObject, run } from "./codes-DagpWZLc.mjs";
3
3
  import { TRPCError, callProcedure, getTRPCErrorFromUnknown, isTrackedEnvelope, transformTRPCResponse } from "./tracked-Bjtgv3wJ.mjs";
4
4
  import { parseTRPCMessage } from "./parseTRPCMessage-CTow-umk.mjs";
5
- import { Unpromise, iteratorResource, parseConnectionParamsFromUnknown, require_usingCtx } from "./resolveResponse-DbcCY-yX.mjs";
5
+ import { Unpromise, iteratorResource, parseConnectionParamsFromUnknown, require_usingCtx } from "./resolveResponse-O0k3XIo_.mjs";
6
6
  import { isObservable, observableToAsyncIterable } from "./observable-UMO3vUa_.mjs";
7
- import { createURL } from "./node-http-DZiUEwuh.mjs";
7
+ import { createURL } from "./node-http-BAkZnlij.mjs";
8
8
 
9
9
  //#region src/adapters/wsEncoder.ts
10
10
  /**
@@ -457,4 +457,4 @@ function applyWSSHandler(opts) {
457
457
 
458
458
  //#endregion
459
459
  export { applyWSSHandler, getWSConnectionHandler, handleKeepAlive, jsonEncoder };
460
- //# sourceMappingURL=ws-Dmi9HHSk.mjs.map
460
+ //# sourceMappingURL=ws-bG-XhXoQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ws-Dmi9HHSk.mjs","names":["jsonEncoder: Encoder","opts: WSSHandlerOptions<TRouter>","client: ws.WebSocket","req: IncomingMessage","untransformedJSON: TRPCResponseMessage","getConnectionParams: () => TRPCRequestInfo['connectionParams']","ctx: Context | undefined","msg: TRPCClientOutgoingMessage","batchIndex: number","abortController","next:\n | null\n | TRPCError\n | Awaited<\n typeof abortPromise | ReturnType<(typeof iterator)['next']>\n >","result: null | TRPCResultMessage<unknown>['result']","id","data: string | Uint8Array","msgJSON: unknown","msgs: unknown[]","timeout: NodeJS.Timeout | undefined","ping: NodeJS.Timeout | undefined","response: TRPCReconnectNotification"],"sources":["../src/adapters/wsEncoder.ts","../src/adapters/ws.ts"],"sourcesContent":["/**\n * Encoder for WebSocket wire format.\n * Encodes outgoing messages and decodes incoming messages.\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 /** Encode data for transmission over the wire */\n encode(data: unknown): string | Uint8Array;\n /** Decode data received from the wire */\n decode(data: string | ArrayBuffer | Uint8Array): unknown;\n}\n\n/**\n * Default JSON encoder - used when no encoder is specified.\n * This maintains backwards compatibility with existing behavior.\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 ws 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// eslint-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// eslint-disable-next-line no-restricted-imports\nimport type { Result } from '../unstable-core-do-not-import';\n// eslint-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 * @public\n */\nexport type CreateWSSContextFnOptions = NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n ws.WebSocket\n>;\n\n/**\n * @public\n */\nexport type CreateWSSContextFn<TRouter extends AnyRouter> = (\n opts: CreateWSSContextFnOptions,\n) => MaybePromise<inferRouterContext<TRouter>>;\n\nexport type WSConnectionHandlerOptions<TRouter extends AnyRouter> =\n BaseHandlerOptions<TRouter, IncomingMessage> &\n CreateContextCallback<\n inferRouterContext<TRouter>,\n CreateWSSContextFn<TRouter>\n >;\n\n/**\n * Web socket server handler\n */\nexport type WSSHandlerOptions<TRouter extends AnyRouter> =\n WSConnectionHandlerOptions<TRouter> & {\n wss: ws.WebSocketServer;\n prefix?: string;\n keepAlive?: {\n /**\n * Enable heartbeat messages\n * @default false\n */\n enabled: boolean;\n /**\n * Heartbeat interval in milliseconds\n * @default 30_000\n */\n pingMs?: number;\n /**\n * Terminate the WebSocket if no pong is received after this many milliseconds\n * @default 5_000\n */\n pongWaitMs?: number;\n };\n /**\n * Disable responding to ping messages from the client\n * **Not recommended** - this is mainly used for testing\n * @default false\n */\n dangerouslyDisablePong?: boolean;\n /**\n * Custom encoder for wire encoding (e.g. custom binary formats)\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n };\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: ws.WebSocket, 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 // eslint-disable-next-line @typescript-eslint/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 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 // eslint-disable-next-line @typescript-eslint/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 * Handle WebSocket keep-alive messages\n */\nexport function handleKeepAlive(\n client: ws.WebSocket,\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) as any;\n };\n ping = setTimeout(() => {\n client.send('PING');\n\n scheduleTimeout();\n }, pingMs) as any;\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\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":";;;;;;;;;;;;;AAuBA,MAAaA,cAAuB;CAClC,QAAQ,CAAC,SAAS,KAAK,UAAU,KAAK;CACtC,QAAQ,CAAC,SAAS;AAChB,aAAW,SAAS,SAClB,OAAM,IAAI,MACR;AAIJ,SAAO,KAAK,MAAM,KAAK;CACxB;AACF;;;;;;;;;;ACcD,MAAM,iBAAiB;AA6DvB,SAAgB,uBACdC,MACA;;CACA,MAAM,EAAE,eAAe,QAAQ,GAAG;CAClC,MAAM,EAAE,aAAa,GAAG,OAAO,KAAK;CACpC,MAAM,mCAAU,KAAK,6FAAwB;AAE7C,QAAO,CAACC,QAAsBC,QAAyB;;EAIrD,MAAM,sCAAsB,IAAI;EAChC,MAAM,kBAAkB,IAAI;AAE5B,yBAAI,KAAK,6EAAW,SAAS;GAC3B,MAAM,EAAE,QAAQ,YAAY,GAAG,KAAK;AACpC,mBAAgB,QAAQ,QAAQ,WAAW;EAC5C;EAED,SAAS,QAAQC,mBAAwC;AACvD,UAAO,KACL,QAAQ,OACN,sBAAsB,OAAO,KAAK,SAAS,kBAAkB,CAC9D,CACF;EACF;EAED,eAAe,iBACbC,qBACwB;AACxB,OAAI;AACF,WAAO,MAAM,IAAI,YAAoC;AACnD,WAAM,qEAAM,cAAgB;MAC1B;MACA,KAAK;MACL,MAAM;OACJ,kBAAkB,qBAAqB;OACvC,OAAO,CAAE;OACT,aAAa;OACb,QAAQ;OACR,MAAM;OACN,QAAQ,gBAAgB;OACxB,KAAK;MACN;KACF,EAAC;AAEF,YAAO;MACL,IAAI;MACJ,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ws.WebSocket","req: IncomingMessage","untransformedJSON: TRPCResponseMessage","getConnectionParams: () => TRPCRequestInfo['connectionParams']","ctx: Context | undefined","msg: TRPCClientOutgoingMessage","batchIndex: number","abortController","next:\n | null\n | TRPCError\n | Awaited<\n typeof abortPromise | ReturnType<(typeof iterator)['next']>\n >","result: null | TRPCResultMessage<unknown>['result']","id","data: string | Uint8Array","msgJSON: unknown","msgs: unknown[]","timeout: NodeJS.Timeout | undefined","ping: NodeJS.Timeout | undefined","response: TRPCReconnectNotification"],"sources":["../src/adapters/wsEncoder.ts","../src/adapters/ws.ts"],"sourcesContent":["/**\n * Encoder for WebSocket wire format.\n * Encodes outgoing messages and decodes incoming messages.\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 /** Encode data for transmission over the wire */\n encode(data: unknown): string | Uint8Array;\n /** Decode data received from the wire */\n decode(data: string | ArrayBuffer | Uint8Array): unknown;\n}\n\n/**\n * Default JSON encoder - used when no encoder is specified.\n * This maintains backwards compatibility with existing behavior.\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 ws 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// eslint-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// eslint-disable-next-line no-restricted-imports\nimport type { Result } from '../unstable-core-do-not-import';\n// eslint-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 * @public\n */\nexport type CreateWSSContextFnOptions = NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n ws.WebSocket\n>;\n\n/**\n * @public\n */\nexport type CreateWSSContextFn<TRouter extends AnyRouter> = (\n opts: CreateWSSContextFnOptions,\n) => MaybePromise<inferRouterContext<TRouter>>;\n\nexport type WSConnectionHandlerOptions<TRouter extends AnyRouter> =\n BaseHandlerOptions<TRouter, IncomingMessage> &\n CreateContextCallback<\n inferRouterContext<TRouter>,\n CreateWSSContextFn<TRouter>\n >;\n\n/**\n * Web socket server handler\n */\nexport type WSSHandlerOptions<TRouter extends AnyRouter> =\n WSConnectionHandlerOptions<TRouter> & {\n wss: ws.WebSocketServer;\n prefix?: string;\n keepAlive?: {\n /**\n * Enable heartbeat messages\n * @default false\n */\n enabled: boolean;\n /**\n * Heartbeat interval in milliseconds\n * @default 30_000\n */\n pingMs?: number;\n /**\n * Terminate the WebSocket if no pong is received after this many milliseconds\n * @default 5_000\n */\n pongWaitMs?: number;\n };\n /**\n * Disable responding to ping messages from the client\n * **Not recommended** - this is mainly used for testing\n * @default false\n */\n dangerouslyDisablePong?: boolean;\n /**\n * Custom encoder for wire encoding (e.g. custom binary formats)\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n };\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: ws.WebSocket, 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 // eslint-disable-next-line @typescript-eslint/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 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 // eslint-disable-next-line @typescript-eslint/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 * Handle WebSocket keep-alive messages\n */\nexport function handleKeepAlive(\n client: ws.WebSocket,\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) as any;\n };\n ping = setTimeout(() => {\n client.send('PING');\n\n scheduleTimeout();\n }, pingMs) as any;\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\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":";;;;;;;;;;;;;AAuBA,MAAaA,cAAuB;CAClC,QAAQ,CAAC,SAAS,KAAK,UAAU,KAAK;CACtC,QAAQ,CAAC,SAAS;AAChB,aAAW,SAAS,SAClB,OAAM,IAAI,MACR;AAIJ,SAAO,KAAK,MAAM,KAAK;CACxB;AACF;;;;;;;;;;ACcD,MAAM,iBAAiB;AA6DvB,SAAgB,uBACdC,MACA;;CACA,MAAM,EAAE,eAAe,QAAQ,GAAG;CAClC,MAAM,EAAE,aAAa,GAAG,OAAO,KAAK;CACpC,MAAM,mCAAU,KAAK,6FAAwB;AAE7C,QAAO,CAACC,QAAsBC,QAAyB;;EAIrD,MAAM,sCAAsB,IAAI;EAChC,MAAM,kBAAkB,IAAI;AAE5B,yBAAI,KAAK,6EAAW,SAAS;GAC3B,MAAM,EAAE,QAAQ,YAAY,GAAG,KAAK;AACpC,mBAAgB,QAAQ,QAAQ,WAAW;EAC5C;EAED,SAAS,QAAQC,mBAAwC;AACvD,UAAO,KACL,QAAQ,OACN,sBAAsB,OAAO,KAAK,SAAS,kBAAkB,CAC9D,CACF;EACF;EAED,eAAe,iBACbC,qBACwB;AACxB,OAAI;AACF,WAAO,MAAM,IAAI,YAAoC;AACnD,WAAM,qEAAM,cAAgB;MAC1B;MACA,KAAK;MACL,MAAM;OACJ,kBAAkB,qBAAqB;OACvC,OAAO,CAAE;OACT,aAAa;OACb,QAAQ;OACR,MAAM;OACN,QAAQ,gBAAgB;OACxB,KAAK;MACN;KACF,EAAC;AAEF,YAAO;MACL,IAAI;MACJ,OAAO;KACR;IACF,EAAC;GACH,SAAQ,OAAO;;IACd,MAAM,QAAQ,wBAAwB,MAAM;AAC5C,0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,OAAO,oBAAoB,QAAQ,CAC5C,KAAI,OAAO;AAEb,uBAAoB,OAAO;AAC3B,mBAAgB,OAAO;EACxB,EAAC;CACH;AACF;;;;AAKD,SAAgB,gBACdb,QACA,SAAS,KACT,aAAa,KACb;CACA,IAAIc;CACJ,IAAIC;CAEJ,MAAM,eAAe,MAAM;EACzB,MAAM,kBAAkB,MAAM;AAC5B,aAAU,WAAW,MAAM;AACzB,WAAO,WAAW;GACnB,GAAE,WAAW;EACf;AACD,SAAO,WAAW,MAAM;AACtB,UAAO,KAAK,OAAO;AAEnB,oBAAiB;EAClB,GAAE,OAAO;CACX;CAED,MAAM,YAAY,MAAM;AACtB,eAAa,KAAK;AAClB,eAAa,QAAQ;AAErB,gBAAc;CACf;AAED,QAAO,GAAG,WAAW,UAAU;AAE/B,QAAO,GAAG,SAAS,MAAM;AACvB,eAAa,KAAK;AAClB,eAAa,QAAQ;CACtB,EAAC;AAEF,eAAc;AACf;AAED,SAAgB,gBACdhB,MACA;;CACA,MAAM,oCAAU,KAAK,+FAAwB;CAC7C,MAAM,eAAe,uBAAuB,KAAK;AACjD,MAAK,IAAI,GAAG,cAAc,CAAC,QAAQ,QAAQ;;AACzC,MAAI,KAAK,wBAAW,IAAI,gDAAJ,SAAS,WAAW,KAAK,OAAO,EAClD;AAGF,eAAa,QAAQ,IAAI;CAC1B,EAAC;AAEF,QAAO,EACL,gCAAgC,MAAM;EACpC,MAAMiB,WAAsC;GAC1C,IAAI;GACJ,QAAQ;EACT;EACD,MAAM,OAAO,QAAQ,OAAO,SAAS;AACrC,OAAK,MAAM,UAAU,KAAK,IAAI,QAC5B,KAAI,OAAO,eAAe,eACxB,QAAO,KAAK,KAAK;CAGtB,EACF;AACF"}
@@ -2,9 +2,9 @@ const require_getErrorShape = require('./getErrorShape-MR4DZeb7.cjs');
2
2
  const require_codes = require('./codes-BfZsPdy-.cjs');
3
3
  const require_tracked = require('./tracked-DX1GMBVX.cjs');
4
4
  const require_parseTRPCMessage = require('./parseTRPCMessage-7Ltmq-Fb.cjs');
5
- const require_resolveResponse = require('./resolveResponse-0xxAjZaH.cjs');
5
+ const require_resolveResponse = require('./resolveResponse-Ck4MWy4N.cjs');
6
6
  const require_observable = require('./observable-B1Nk6r1H.cjs');
7
- const require_node_http = require('./node-http-DOrt4Pjb.cjs');
7
+ const require_node_http = require('./node-http-qIM6subj.cjs');
8
8
 
9
9
  //#region src/adapters/wsEncoder.ts
10
10
  /**
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@trpc/server",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "11.14.1",
5
+ "version": "11.15.0",
6
6
  "description": "The tRPC server library",
7
7
  "author": "KATT",
8
8
  "license": "MIT",
@@ -198,7 +198,7 @@
198
198
  "devDependencies": {
199
199
  "@fastify/websocket": "^11.0.0",
200
200
  "@oxc-project/runtime": "0.115.0",
201
- "@tanstack/intent": "^0.0.20",
201
+ "@tanstack/intent": "^0.0.23",
202
202
  "@tanstack/react-query": "^5.80.3",
203
203
  "@types/aws-lambda": "^8.10.149",
204
204
  "@types/express": "^5.0.0",
@@ -238,5 +238,5 @@
238
238
  "bin": {
239
239
  "intent": "./bin/intent.js"
240
240
  },
241
- "gitHead": "e896259af491fc4b1c9e8fc320817e2222bae869"
241
+ "gitHead": "25b97f51ee4ee57da0da3c63cf54a50c6c8627d5"
242
242
  }
@@ -24,6 +24,7 @@ type GetRequestInfoOptions = {
24
24
  searchParams: URLSearchParams;
25
25
  headers: Headers;
26
26
  router: AnyRouter;
27
+ maxBatchSize?: number;
27
28
  };
28
29
 
29
30
  type ContentTypeHandler = {
@@ -81,7 +82,19 @@ const jsonContentTypeHandler: ContentTypeHandler = {
81
82
  async parse(opts) {
82
83
  const { req } = opts;
83
84
  const isBatchCall = opts.searchParams.get('batch') === '1';
85
+ const maxBatchSize = opts.maxBatchSize;
86
+
84
87
  const paths = isBatchCall ? opts.path.split(',') : [opts.path];
88
+ if (
89
+ isBatchCall &&
90
+ typeof maxBatchSize === 'number' &&
91
+ paths.length > maxBatchSize
92
+ ) {
93
+ throw new TRPCError({
94
+ code: 'BAD_REQUEST',
95
+ message: `Batch call exceeds maximum size`,
96
+ });
97
+ }
85
98
 
86
99
  type InputRecord = Record<number, unknown>;
87
100
  const getInputs = memo(async (): Promise<InputRecord> => {
@@ -248,6 +248,7 @@ export async function resolveResponse<TRouter extends AnyRouter>(
248
248
  searchParams: url.searchParams,
249
249
  headers: opts.req.headers,
250
250
  url,
251
+ maxBatchSize: opts.maxBatchSize,
251
252
  }),
252
253
  ];
253
254
  } catch (cause) {
@@ -158,4 +158,11 @@ export interface BaseHandlerOptions<TRouter extends AnyRouter, TRequest> {
158
158
  * @default true
159
159
  */
160
160
  allowBatching?: boolean;
161
+ /**
162
+ * Restrict the maximum size of a batch call, invalid requests will be rejected with a 400 error
163
+ *
164
+ * @important Ensure you set the same or lower limit on your client batch link
165
+ * @default unlimited
166
+ */
167
+ maxBatchSize?: number;
161
168
  }