@trpc/server 11.0.0-alpha-tmp-export-from-main.221 → 11.0.0-alpha-tmp-export-from-main.222

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 (136) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +68 -0
  2. package/dist/adapters/aws-lambda/index.d.ts +54 -6
  3. package/dist/adapters/aws-lambda/index.js +110 -20
  4. package/dist/adapters/aws-lambda/index.mjs +94 -4
  5. package/dist/adapters/express.d.mts +19 -0
  6. package/dist/adapters/express.d.ts +9 -6
  7. package/dist/adapters/express.js +3 -3
  8. package/dist/adapters/express.mjs +1 -1
  9. package/dist/adapters/fastify/index.d.mts +33 -0
  10. package/dist/adapters/fastify/index.d.ts +33 -3
  11. package/dist/adapters/fastify/index.js +124 -5
  12. package/dist/adapters/fastify/index.mjs +125 -2
  13. package/dist/adapters/fetch/index.d.mts +51 -0
  14. package/dist/adapters/fetch/index.d.ts +51 -3
  15. package/dist/adapters/fetch/index.js +115 -4
  16. package/dist/adapters/fetch/index.mjs +116 -1
  17. package/dist/adapters/next.d.mts +21 -0
  18. package/dist/adapters/next.d.ts +11 -7
  19. package/dist/adapters/next.js +6 -6
  20. package/dist/adapters/next.mjs +2 -2
  21. package/dist/adapters/node-http/content-type/form-data/index.d.mts +219 -0
  22. package/dist/adapters/node-http/content-type/form-data/index.d.ts +201 -10
  23. package/dist/adapters/node-http/content-type/form-data/index.js +662 -23
  24. package/dist/adapters/node-http/content-type/form-data/index.mjs +646 -10
  25. package/dist/adapters/node-http/{types.d.ts → content-type/json/index.d.mts} +21 -15
  26. package/dist/adapters/node-http/content-type/json/index.d.ts +89 -2
  27. package/dist/adapters/node-http/content-type/json/index.js +48 -7
  28. package/dist/adapters/node-http/content-type/json/index.mjs +44 -3
  29. package/dist/adapters/node-http/index.d.mts +100 -0
  30. package/dist/adapters/node-http/index.d.ts +100 -3
  31. package/dist/adapters/node-http/index.js +106 -4
  32. package/dist/adapters/node-http/index.mjs +107 -1
  33. package/dist/adapters/standalone.d.mts +21 -0
  34. package/dist/adapters/standalone.d.ts +11 -9
  35. package/dist/adapters/standalone.js +9 -5
  36. package/dist/adapters/standalone.mjs +2 -2
  37. package/dist/adapters/ws.d.mts +36 -0
  38. package/dist/adapters/ws.d.ts +12 -13
  39. package/dist/adapters/ws.js +30 -28
  40. package/dist/adapters/ws.mjs +12 -10
  41. package/dist/http.d.mts +1 -0
  42. package/dist/http.d.ts +1 -7
  43. package/dist/http.js +7 -7
  44. package/dist/http.mjs +1 -1
  45. package/dist/index.d.mts +9 -0
  46. package/dist/index.d.ts +5 -65
  47. package/dist/index.js +809 -46
  48. package/dist/index.mjs +798 -1
  49. package/dist/observable.d.mts +1 -0
  50. package/dist/observable.d.ts +1 -3
  51. package/dist/observable.js +8 -8
  52. package/dist/observable.mjs +1 -1
  53. package/dist/rpc.d.mts +1 -0
  54. package/dist/rpc.d.ts +1 -3
  55. package/dist/rpc.js +5 -5
  56. package/dist/rpc.mjs +1 -1
  57. package/dist/shared.d.mts +1 -0
  58. package/dist/shared.d.ts +1 -26
  59. package/dist/shared.js +4 -4
  60. package/dist/shared.mjs +1 -1
  61. package/dist/unstableDontImportMe.d.mts +1 -0
  62. package/dist/unstableDontImportMe.d.ts +1 -10
  63. package/dist/unstableDontImportMe.js +1549 -142
  64. package/dist/unstableDontImportMe.mjs +1514 -1
  65. package/package.json +6 -4
  66. package/dist/@trpc-server/http.d.ts +0 -2
  67. package/dist/@trpc-server/http.d.ts.map +0 -1
  68. package/dist/adapters/aws-lambda/index.d.ts.map +0 -1
  69. package/dist/adapters/aws-lambda/utils.d.ts +0 -48
  70. package/dist/adapters/aws-lambda/utils.d.ts.map +0 -1
  71. package/dist/adapters/aws-lambda/utils.js +0 -100
  72. package/dist/adapters/aws-lambda/utils.mjs +0 -93
  73. package/dist/adapters/express.d.ts.map +0 -1
  74. package/dist/adapters/fastify/fastifyRequestHandler.d.ts +0 -13
  75. package/dist/adapters/fastify/fastifyRequestHandler.d.ts.map +0 -1
  76. package/dist/adapters/fastify/fastifyRequestHandler.js +0 -81
  77. package/dist/adapters/fastify/fastifyRequestHandler.mjs +0 -79
  78. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts +0 -22
  79. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts.map +0 -1
  80. package/dist/adapters/fastify/fastifyTRPCPlugin.js +0 -51
  81. package/dist/adapters/fastify/fastifyTRPCPlugin.mjs +0 -49
  82. package/dist/adapters/fastify/index.d.ts.map +0 -1
  83. package/dist/adapters/fetch/fetchRequestHandler.d.ts +0 -18
  84. package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +0 -1
  85. package/dist/adapters/fetch/fetchRequestHandler.js +0 -118
  86. package/dist/adapters/fetch/fetchRequestHandler.mjs +0 -116
  87. package/dist/adapters/fetch/index.d.ts.map +0 -1
  88. package/dist/adapters/fetch/types.d.ts +0 -31
  89. package/dist/adapters/fetch/types.d.ts.map +0 -1
  90. package/dist/adapters/next.d.ts.map +0 -1
  91. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts +0 -70
  92. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts.map +0 -1
  93. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.js +0 -161
  94. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.mjs +0 -157
  95. package/dist/adapters/node-http/content-type/form-data/index.d.ts.map +0 -1
  96. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts +0 -31
  97. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts.map +0 -1
  98. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.js +0 -29
  99. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.mjs +0 -27
  100. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts +0 -16
  101. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts.map +0 -1
  102. package/dist/adapters/node-http/content-type/form-data/streamSlice.js +0 -46
  103. package/dist/adapters/node-http/content-type/form-data/streamSlice.mjs +0 -44
  104. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts +0 -45
  105. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts.map +0 -1
  106. package/dist/adapters/node-http/content-type/form-data/uploadHandler.js +0 -30
  107. package/dist/adapters/node-http/content-type/form-data/uploadHandler.mjs +0 -26
  108. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts +0 -7
  109. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts.map +0 -1
  110. package/dist/adapters/node-http/content-type/json/getPostBody.js +0 -42
  111. package/dist/adapters/node-http/content-type/json/getPostBody.mjs +0 -40
  112. package/dist/adapters/node-http/content-type/json/index.d.ts.map +0 -1
  113. package/dist/adapters/node-http/index.d.ts.map +0 -1
  114. package/dist/adapters/node-http/internals/contentType.d.ts +0 -9
  115. package/dist/adapters/node-http/internals/contentType.d.ts.map +0 -1
  116. package/dist/adapters/node-http/internals/contentType.js +0 -8
  117. package/dist/adapters/node-http/internals/contentType.mjs +0 -6
  118. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts +0 -14
  119. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +0 -1
  120. package/dist/adapters/node-http/nodeHTTPRequestHandler.js +0 -109
  121. package/dist/adapters/node-http/nodeHTTPRequestHandler.mjs +0 -107
  122. package/dist/adapters/node-http/types.d.ts.map +0 -1
  123. package/dist/adapters/standalone.d.ts.map +0 -1
  124. package/dist/adapters/ws.d.ts.map +0 -1
  125. package/dist/http.d.ts.map +0 -1
  126. package/dist/index.d.ts.map +0 -1
  127. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/index.js +0 -203
  128. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/index.mjs +0 -201
  129. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/search.js +0 -167
  130. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/search.mjs +0 -163
  131. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/utils.js +0 -35
  132. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/utils.mjs +0 -30
  133. package/dist/observable.d.ts.map +0 -1
  134. package/dist/rpc.d.ts.map +0 -1
  135. package/dist/shared.d.ts.map +0 -1
  136. package/dist/unstableDontImportMe.d.ts.map +0 -1
@@ -1 +1,1514 @@
1
- export { TRPCError, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, callProcedure, createBuilder, createFlatProxy, createInputMiddleware, createOutputMiddleware, createRecursiveProxy, createRouterFactory, experimental_standaloneMiddleware, getBatchStreamFormatter, getCauseFromUnknown, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getJsonContentTypeInputs, getTRPCErrorFromUnknown, initTRPC, isObject, isObservable, map, mergeRouters, middlewareMarker, observable, observableToPromise, parseTRPCMessage, procedureTypes, resolveHTTPResponse, share, tap, transformResult, transformTRPCResponse, unsetMarker } from '@trpc/core';
1
+ /**
2
+ * @internal
3
+ */ function invert(obj) {
4
+ const newObj = Object.create(null);
5
+ for(const key in obj){
6
+ const v = obj[key];
7
+ newObj[v] = key;
8
+ }
9
+ return newObj;
10
+ }
11
+ /**
12
+ * Ensures there are no duplicate keys when building a procedure.
13
+ * @internal
14
+ */ function mergeWithoutOverrides(obj1, ...objs) {
15
+ const newObj = Object.assign(Object.create(null), obj1);
16
+ for (const overrides of objs){
17
+ for(const key in overrides){
18
+ if (key in newObj && newObj[key] !== overrides[key]) {
19
+ throw new Error(`Duplicate key ${key}`);
20
+ }
21
+ newObj[key] = overrides[key];
22
+ }
23
+ }
24
+ return newObj;
25
+ }
26
+ /**
27
+ * Check that value is object
28
+ * @internal
29
+ */ function isObject(value) {
30
+ return !!value && !Array.isArray(value) && typeof value === 'object';
31
+ }
32
+ /**
33
+ * Create an object without inheriting anything from `Object.prototype`
34
+ * @internal
35
+ */ function omitPrototype(obj) {
36
+ return Object.assign(Object.create(null), obj);
37
+ }
38
+ /**
39
+ * @internal
40
+ */ function identity(x) {
41
+ return x;
42
+ }
43
+
44
+ // reference: https://www.jsonrpc.org/specification
45
+ /**
46
+ * JSON-RPC 2.0 Error codes
47
+ *
48
+ * `-32000` to `-32099` are reserved for implementation-defined server-errors.
49
+ * For tRPC we're copying the last digits of HTTP 4XX errors.
50
+ */ const TRPC_ERROR_CODES_BY_KEY = {
51
+ /**
52
+ * Invalid JSON was received by the server.
53
+ * An error occurred on the server while parsing the JSON text.
54
+ */ PARSE_ERROR: -32700,
55
+ /**
56
+ * The JSON sent is not a valid Request object.
57
+ */ BAD_REQUEST: -32600,
58
+ // Internal JSON-RPC error
59
+ INTERNAL_SERVER_ERROR: -32603,
60
+ NOT_IMPLEMENTED: -32603,
61
+ // Implementation specific errors
62
+ UNAUTHORIZED: -32001,
63
+ FORBIDDEN: -32003,
64
+ NOT_FOUND: -32004,
65
+ METHOD_NOT_SUPPORTED: -32005,
66
+ TIMEOUT: -32008,
67
+ CONFLICT: -32009,
68
+ PRECONDITION_FAILED: -32012,
69
+ PAYLOAD_TOO_LARGE: -32013,
70
+ UNPROCESSABLE_CONTENT: -32022,
71
+ TOO_MANY_REQUESTS: -32029,
72
+ CLIENT_CLOSED_REQUEST: -32099
73
+ };
74
+ const TRPC_ERROR_CODES_BY_NUMBER = invert(TRPC_ERROR_CODES_BY_KEY);
75
+
76
+ const procedureTypes = [
77
+ 'query',
78
+ 'mutation',
79
+ 'subscription'
80
+ ];
81
+
82
+ /* istanbul ignore next -- @preserve */ function assertIsObject(obj) {
83
+ if (!isObject(obj)) {
84
+ throw new Error('Not an object');
85
+ }
86
+ }
87
+ /* istanbul ignore next -- @preserve */ function assertIsProcedureType(obj) {
88
+ if (!procedureTypes.includes(obj)) {
89
+ throw new Error('Invalid procedure type');
90
+ }
91
+ }
92
+ /* istanbul ignore next -- @preserve */ function assertIsRequestId(obj) {
93
+ if (obj !== null && typeof obj === 'number' && isNaN(obj) && typeof obj !== 'string') {
94
+ throw new Error('Invalid request id');
95
+ }
96
+ }
97
+ /* istanbul ignore next -- @preserve */ function assertIsString(obj) {
98
+ if (typeof obj !== 'string') {
99
+ throw new Error('Invalid string');
100
+ }
101
+ }
102
+ /* istanbul ignore next -- @preserve */ function assertIsJSONRPC2OrUndefined(obj) {
103
+ if (typeof obj !== 'undefined' && obj !== '2.0') {
104
+ throw new Error('Must be JSONRPC 2.0');
105
+ }
106
+ }
107
+ /** @public */ function parseTRPCMessage(obj, transformer) {
108
+ assertIsObject(obj);
109
+ const { id, jsonrpc, method, params } = obj;
110
+ assertIsRequestId(id);
111
+ assertIsJSONRPC2OrUndefined(jsonrpc);
112
+ if (method === 'subscription.stop') {
113
+ return {
114
+ id,
115
+ jsonrpc,
116
+ method
117
+ };
118
+ }
119
+ assertIsProcedureType(method);
120
+ assertIsObject(params);
121
+ const { input: rawInput, path } = params;
122
+ assertIsString(path);
123
+ const input = transformer.input.deserialize(rawInput);
124
+ return {
125
+ id,
126
+ jsonrpc,
127
+ method,
128
+ params: {
129
+ input,
130
+ path
131
+ }
132
+ };
133
+ }
134
+
135
+ const JSONRPC2_TO_HTTP_CODE = {
136
+ PARSE_ERROR: 400,
137
+ BAD_REQUEST: 400,
138
+ UNAUTHORIZED: 401,
139
+ NOT_FOUND: 404,
140
+ FORBIDDEN: 403,
141
+ METHOD_NOT_SUPPORTED: 405,
142
+ TIMEOUT: 408,
143
+ CONFLICT: 409,
144
+ PRECONDITION_FAILED: 412,
145
+ PAYLOAD_TOO_LARGE: 413,
146
+ UNPROCESSABLE_CONTENT: 422,
147
+ TOO_MANY_REQUESTS: 429,
148
+ CLIENT_CLOSED_REQUEST: 499,
149
+ INTERNAL_SERVER_ERROR: 500,
150
+ NOT_IMPLEMENTED: 501
151
+ };
152
+ function getStatusCodeFromKey(code) {
153
+ return JSONRPC2_TO_HTTP_CODE[code] ?? 500;
154
+ }
155
+ function getHTTPStatusCode(json) {
156
+ const arr = Array.isArray(json) ? json : [
157
+ json
158
+ ];
159
+ const httpStatuses = new Set(arr.map((res)=>{
160
+ if ('error' in res) {
161
+ const data = res.error.data;
162
+ if (typeof data['httpStatus'] === 'number') {
163
+ return data['httpStatus'];
164
+ }
165
+ const code = TRPC_ERROR_CODES_BY_NUMBER[res.error.code];
166
+ return getStatusCodeFromKey(code);
167
+ }
168
+ return 200;
169
+ }));
170
+ if (httpStatuses.size !== 1) {
171
+ return 207;
172
+ }
173
+ const httpStatus = httpStatuses.values().next().value;
174
+ return httpStatus;
175
+ }
176
+ function getHTTPStatusCodeFromError(error) {
177
+ return getStatusCodeFromKey(error.code);
178
+ }
179
+
180
+ /**
181
+ * @internal
182
+ */ function getErrorShape(opts) {
183
+ const { path, error, config } = opts;
184
+ const { code } = opts.error;
185
+ const shape = {
186
+ message: error.message,
187
+ code: TRPC_ERROR_CODES_BY_KEY[code],
188
+ data: {
189
+ code,
190
+ httpStatus: getHTTPStatusCodeFromError(error)
191
+ }
192
+ };
193
+ if (config.isDev && typeof opts.error.stack === 'string') {
194
+ shape.data.stack = opts.error.stack;
195
+ }
196
+ if (typeof path === 'string') {
197
+ shape.data.path = path;
198
+ }
199
+ return config.errorFormatter({
200
+ ...opts,
201
+ shape
202
+ });
203
+ }
204
+
205
+ class UnknownCauseError extends Error {
206
+ }
207
+ function getCauseFromUnknown(cause) {
208
+ if (cause instanceof Error) {
209
+ return cause;
210
+ }
211
+ const type = typeof cause;
212
+ if (type === 'undefined' || type === 'function' || cause === null) {
213
+ return undefined;
214
+ }
215
+ // Primitive types just get wrapped in an error
216
+ if (type !== 'object') {
217
+ return new Error(String(cause));
218
+ }
219
+ // If it's an object, we'll create a synthetic error
220
+ if (isObject(cause)) {
221
+ const err = new UnknownCauseError();
222
+ for(const key in cause){
223
+ err[key] = cause[key];
224
+ }
225
+ return err;
226
+ }
227
+ return undefined;
228
+ }
229
+ function getTRPCErrorFromUnknown(cause) {
230
+ if (cause instanceof TRPCError) {
231
+ return cause;
232
+ }
233
+ if (cause instanceof Error && cause.name === 'TRPCError') {
234
+ // https://github.com/trpc/trpc/pull/4848
235
+ return cause;
236
+ }
237
+ const trpcError = new TRPCError({
238
+ code: 'INTERNAL_SERVER_ERROR',
239
+ cause
240
+ });
241
+ // Inherit stack from error
242
+ if (cause instanceof Error && cause.stack) {
243
+ trpcError.stack = cause.stack;
244
+ }
245
+ return trpcError;
246
+ }
247
+ class TRPCError extends Error {
248
+ constructor(opts){
249
+ const cause = getCauseFromUnknown(opts.cause);
250
+ const message = opts.message ?? cause?.message ?? opts.code;
251
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
252
+ // @ts-ignore https://github.com/tc39/proposal-error-cause
253
+ super(message, {
254
+ cause
255
+ });
256
+ this.code = opts.code;
257
+ this.name = 'TRPCError';
258
+ if (!this.cause) {
259
+ // < ES2022 / < Node 16.9.0 compatability
260
+ this.cause = cause;
261
+ }
262
+ }
263
+ }
264
+
265
+ const noop = ()=>{
266
+ // noop
267
+ };
268
+ function createInnerProxy(callback, path) {
269
+ const proxy = new Proxy(noop, {
270
+ get (_obj, key) {
271
+ if (typeof key !== 'string' || key === 'then') {
272
+ // special case for if the proxy is accidentally treated
273
+ // like a PromiseLike (like in `Promise.resolve(proxy)`)
274
+ return undefined;
275
+ }
276
+ return createInnerProxy(callback, [
277
+ ...path,
278
+ key
279
+ ]);
280
+ },
281
+ apply (_1, _2, args) {
282
+ const isApply = path[path.length - 1] === 'apply';
283
+ return callback({
284
+ args: isApply ? args.length >= 2 ? args[1] : [] : args,
285
+ path: isApply ? path.slice(0, -1) : path
286
+ });
287
+ }
288
+ });
289
+ return proxy;
290
+ }
291
+ /**
292
+ * Creates a proxy that calls the callback with the path and arguments
293
+ *
294
+ * @internal
295
+ */ const createRecursiveProxy = (callback)=>createInnerProxy(callback, []);
296
+ /**
297
+ * Used in place of `new Proxy` where each handler will map 1 level deep to another value.
298
+ *
299
+ * @internal
300
+ */ const createFlatProxy = (callback)=>{
301
+ return new Proxy(noop, {
302
+ get (_obj, name) {
303
+ if (typeof name !== 'string' || name === 'then') {
304
+ // special case for if the proxy is accidentally treated
305
+ // like a PromiseLike (like in `Promise.resolve(proxy)`)
306
+ return undefined;
307
+ }
308
+ return callback(name);
309
+ }
310
+ });
311
+ };
312
+
313
+ const defaultFormatter = ({ shape })=>{
314
+ return shape;
315
+ };
316
+
317
+ /** @internal */ const middlewareMarker = 'middlewareMarker';
318
+ /**
319
+ * @internal
320
+ */ function createMiddlewareFactory() {
321
+ function createMiddlewareInner(middlewares) {
322
+ return {
323
+ _middlewares: middlewares,
324
+ unstable_pipe (middlewareBuilderOrFn) {
325
+ const pipedMiddleware = '_middlewares' in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [
326
+ middlewareBuilderOrFn
327
+ ];
328
+ return createMiddlewareInner([
329
+ ...middlewares,
330
+ ...pipedMiddleware
331
+ ]);
332
+ }
333
+ };
334
+ }
335
+ function createMiddleware(fn) {
336
+ return createMiddlewareInner([
337
+ fn
338
+ ]);
339
+ }
340
+ return createMiddleware;
341
+ }
342
+ /**
343
+ * Create a standalone middleware
344
+ * @link https://trpc.io/docs/v11/server/middlewares#experimental-standalone-middlewares
345
+ */ const experimental_standaloneMiddleware = ()=>({
346
+ create: createMiddlewareFactory()
347
+ });
348
+ /**
349
+ * @internal
350
+ * Please note, `trpc-openapi` uses this function.
351
+ */ function createInputMiddleware(parse) {
352
+ const inputMiddleware = async function inputValidatorMiddleware(opts) {
353
+ let parsedInput;
354
+ const rawInput = await opts.getRawInput();
355
+ try {
356
+ parsedInput = await parse(rawInput);
357
+ } catch (cause) {
358
+ throw new TRPCError({
359
+ code: 'BAD_REQUEST',
360
+ cause
361
+ });
362
+ }
363
+ // Multiple input parsers
364
+ const combinedInput = isObject(opts.input) && isObject(parsedInput) ? {
365
+ ...opts.input,
366
+ ...parsedInput
367
+ } : parsedInput;
368
+ return opts.next({
369
+ input: combinedInput
370
+ });
371
+ };
372
+ inputMiddleware._type = 'input';
373
+ return inputMiddleware;
374
+ }
375
+ /**
376
+ * @internal
377
+ */ function createOutputMiddleware(parse) {
378
+ const outputMiddleware = async function outputValidatorMiddleware({ next }) {
379
+ const result = await next();
380
+ if (!result.ok) {
381
+ // pass through failures without validating
382
+ return result;
383
+ }
384
+ try {
385
+ const data = await parse(result.data);
386
+ return {
387
+ ...result,
388
+ data
389
+ };
390
+ } catch (cause) {
391
+ throw new TRPCError({
392
+ message: 'Output validation failed',
393
+ code: 'INTERNAL_SERVER_ERROR',
394
+ cause
395
+ });
396
+ }
397
+ };
398
+ outputMiddleware._type = 'output';
399
+ return outputMiddleware;
400
+ }
401
+
402
+ // zod / @decs/typeschema
403
+ function getParseFn(procedureParser) {
404
+ const parser = procedureParser;
405
+ if (typeof parser === 'function') {
406
+ // ParserCustomValidatorEsque
407
+ return parser;
408
+ }
409
+ if (typeof parser.parseAsync === 'function') {
410
+ // ParserZodEsque
411
+ return parser.parseAsync.bind(parser);
412
+ }
413
+ if (typeof parser.parse === 'function') {
414
+ // ParserZodEsque
415
+ // ParserValibotEsque (<= v0.12.X)
416
+ return parser.parse.bind(parser);
417
+ }
418
+ if (typeof parser.validateSync === 'function') {
419
+ // ParserYupEsque
420
+ return parser.validateSync.bind(parser);
421
+ }
422
+ if (typeof parser.create === 'function') {
423
+ // ParserSuperstructEsque
424
+ return parser.create.bind(parser);
425
+ }
426
+ if (typeof parser.assert === 'function') {
427
+ // ParserScaleEsque
428
+ return (value)=>{
429
+ parser.assert(value);
430
+ return value;
431
+ };
432
+ }
433
+ throw new Error('Could not find a validator fn');
434
+ }
435
+
436
+ /** @internal */ const unsetMarker = Symbol('unsetMarker');
437
+ function createNewBuilder(def1, def2) {
438
+ const { middlewares = [], inputs, meta, ...rest } = def2;
439
+ // TODO: maybe have a fn here to warn about calls
440
+ return createBuilder({
441
+ ...mergeWithoutOverrides(def1, rest),
442
+ inputs: [
443
+ ...def1.inputs,
444
+ ...inputs ?? []
445
+ ],
446
+ middlewares: [
447
+ ...def1.middlewares,
448
+ ...middlewares
449
+ ],
450
+ meta: def1.meta && meta ? {
451
+ ...def1.meta,
452
+ ...meta
453
+ } : meta ?? def1.meta
454
+ });
455
+ }
456
+ function createBuilder(initDef = {}) {
457
+ const _def = {
458
+ procedure: true,
459
+ inputs: [],
460
+ middlewares: [],
461
+ ...initDef
462
+ };
463
+ const builder = {
464
+ _def,
465
+ input (input) {
466
+ const parser = getParseFn(input);
467
+ return createNewBuilder(_def, {
468
+ inputs: [
469
+ input
470
+ ],
471
+ middlewares: [
472
+ createInputMiddleware(parser)
473
+ ]
474
+ });
475
+ },
476
+ output (output) {
477
+ const parser = getParseFn(output);
478
+ return createNewBuilder(_def, {
479
+ output,
480
+ middlewares: [
481
+ createOutputMiddleware(parser)
482
+ ]
483
+ });
484
+ },
485
+ meta (meta) {
486
+ return createNewBuilder(_def, {
487
+ meta
488
+ });
489
+ },
490
+ use (middlewareBuilderOrFn) {
491
+ // Distinguish between a middleware builder and a middleware function
492
+ const middlewares = '_middlewares' in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [
493
+ middlewareBuilderOrFn
494
+ ];
495
+ return createNewBuilder(_def, {
496
+ middlewares: middlewares
497
+ });
498
+ },
499
+ query (resolver) {
500
+ return createResolver({
501
+ ..._def,
502
+ type: 'query'
503
+ }, resolver);
504
+ },
505
+ mutation (resolver) {
506
+ return createResolver({
507
+ ..._def,
508
+ type: 'mutation'
509
+ }, resolver);
510
+ },
511
+ subscription (resolver) {
512
+ return createResolver({
513
+ ..._def,
514
+ type: 'subscription'
515
+ }, resolver);
516
+ }
517
+ };
518
+ return builder;
519
+ }
520
+ function createResolver(_def, resolver) {
521
+ const finalBuilder = createNewBuilder(_def, {
522
+ resolver,
523
+ middlewares: [
524
+ async function resolveMiddleware(opts) {
525
+ const data = await resolver(opts);
526
+ return {
527
+ marker: middlewareMarker,
528
+ ok: true,
529
+ data,
530
+ ctx: opts.ctx
531
+ };
532
+ }
533
+ ]
534
+ });
535
+ return createProcedureCaller(finalBuilder._def);
536
+ }
537
+ const codeblock = `
538
+ This is a client-only function.
539
+ If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls
540
+ `.trim();
541
+ function createProcedureCaller(_def) {
542
+ async function procedure(opts) {
543
+ // is direct server-side call
544
+ if (!opts || !('getRawInput' in opts)) {
545
+ throw new Error(codeblock);
546
+ }
547
+ // run the middlewares recursively with the resolver as the last one
548
+ async function callRecursive(callOpts = {
549
+ index: 0,
550
+ ctx: opts.ctx
551
+ }) {
552
+ try {
553
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
554
+ const middleware = _def.middlewares[callOpts.index];
555
+ const result = await middleware({
556
+ ctx: callOpts.ctx,
557
+ type: opts.type,
558
+ path: opts.path,
559
+ getRawInput: callOpts.getRawInput ?? opts.getRawInput,
560
+ meta: _def.meta,
561
+ input: callOpts.input,
562
+ next (_nextOpts) {
563
+ const nextOpts = _nextOpts;
564
+ return callRecursive({
565
+ index: callOpts.index + 1,
566
+ ctx: nextOpts && 'ctx' in nextOpts ? {
567
+ ...callOpts.ctx,
568
+ ...nextOpts.ctx
569
+ } : callOpts.ctx,
570
+ input: nextOpts && 'input' in nextOpts ? nextOpts.input : callOpts.input,
571
+ getRawInput: nextOpts && 'getRawInput' in nextOpts ? nextOpts.getRawInput : callOpts.getRawInput
572
+ });
573
+ }
574
+ });
575
+ return result;
576
+ } catch (cause) {
577
+ return {
578
+ ok: false,
579
+ error: getTRPCErrorFromUnknown(cause),
580
+ marker: middlewareMarker
581
+ };
582
+ }
583
+ }
584
+ // there's always at least one "next" since we wrap this.resolver in a middleware
585
+ const result = await callRecursive();
586
+ if (!result) {
587
+ throw new TRPCError({
588
+ code: 'INTERNAL_SERVER_ERROR',
589
+ message: 'No result from middlewares - did you forget to `return next()`?'
590
+ });
591
+ }
592
+ if (!result.ok) {
593
+ // re-throw original error
594
+ throw result.error;
595
+ }
596
+ return result.data;
597
+ }
598
+ procedure._def = _def;
599
+ // FIXME typecast shouldn't be needed - fixittt
600
+ return procedure;
601
+ }
602
+
603
+ /**
604
+ * The default check to see if we're in a server
605
+ */ const isServerDefault = typeof window === 'undefined' || 'Deno' in window || // eslint-disable-next-line @typescript-eslint/dot-notation
606
+ globalThis.process?.env?.['NODE_ENV'] === 'test' || !!globalThis.process?.env?.['JEST_WORKER_ID'] || !!globalThis.process?.env?.['VITEST_WORKER_ID'];
607
+
608
+ /**
609
+ * @internal
610
+ */ function getDataTransformer(transformer) {
611
+ if ('input' in transformer) {
612
+ return transformer;
613
+ }
614
+ return {
615
+ input: transformer,
616
+ output: transformer
617
+ };
618
+ }
619
+ /**
620
+ * @internal
621
+ */ const defaultTransformer = {
622
+ _default: true,
623
+ input: {
624
+ serialize: (obj)=>obj,
625
+ deserialize: (obj)=>obj
626
+ },
627
+ output: {
628
+ serialize: (obj)=>obj,
629
+ deserialize: (obj)=>obj
630
+ }
631
+ };
632
+ function transformTRPCResponseItem(config, item) {
633
+ if ('error' in item) {
634
+ return {
635
+ ...item,
636
+ error: config.transformer.output.serialize(item.error)
637
+ };
638
+ }
639
+ if ('data' in item.result) {
640
+ return {
641
+ ...item,
642
+ result: {
643
+ ...item.result,
644
+ data: config.transformer.output.serialize(item.result.data)
645
+ }
646
+ };
647
+ }
648
+ return item;
649
+ }
650
+ /**
651
+ * Takes a unserialized `TRPCResponse` and serializes it with the router's transformers
652
+ **/ function transformTRPCResponse(config, itemOrItems) {
653
+ return Array.isArray(itemOrItems) ? itemOrItems.map((item)=>transformTRPCResponseItem(config, item)) : transformTRPCResponseItem(config, itemOrItems);
654
+ }
655
+ // FIXME:
656
+ // - the generics here are probably unnecessary
657
+ // - the RPC-spec could probably be simplified to combine HTTP + WS
658
+ /** @internal */ function transformResultInner(response, transformer) {
659
+ if ('error' in response) {
660
+ const error = transformer.deserialize(response.error);
661
+ return {
662
+ ok: false,
663
+ error: {
664
+ ...response,
665
+ error
666
+ }
667
+ };
668
+ }
669
+ const result = {
670
+ ...response.result,
671
+ ...(!response.result.type || response.result.type === 'data') && {
672
+ type: 'data',
673
+ data: transformer.deserialize(response.result.data)
674
+ }
675
+ };
676
+ return {
677
+ ok: true,
678
+ result
679
+ };
680
+ }
681
+ class TransformResultError extends Error {
682
+ constructor(){
683
+ super('Unable to transform response from server');
684
+ }
685
+ }
686
+ /**
687
+ * Transforms and validates that the result is a valid TRPCResponse
688
+ * @internal
689
+ */ function transformResult(response, transformer) {
690
+ let result;
691
+ try {
692
+ // Use the data transformers on the JSON-response
693
+ result = transformResultInner(response, transformer);
694
+ } catch (err) {
695
+ throw new TransformResultError();
696
+ }
697
+ // check that output of the transformers is a valid TRPCResponse
698
+ if (!result.ok && (!isObject(result.error.error) || typeof result.error.error['code'] !== 'number')) {
699
+ throw new TransformResultError();
700
+ }
701
+ if (result.ok && !isObject(result.result)) {
702
+ throw new TransformResultError();
703
+ }
704
+ return result;
705
+ }
706
+
707
+ function isRouter(procedureOrRouter) {
708
+ return 'router' in procedureOrRouter._def;
709
+ }
710
+ const emptyRouter = {
711
+ _ctx: null,
712
+ _errorShape: null,
713
+ _meta: null,
714
+ queries: {},
715
+ mutations: {},
716
+ subscriptions: {},
717
+ errorFormatter: defaultFormatter,
718
+ transformer: defaultTransformer
719
+ };
720
+ /**
721
+ * Reserved words that can't be used as router or procedure names
722
+ */ const reservedWords = [
723
+ /**
724
+ * Then is a reserved word because otherwise we can't return a promise that returns a Proxy
725
+ * since JS will think that `.then` is something that exists
726
+ */ 'then'
727
+ ];
728
+ /**
729
+ * @internal
730
+ */ function createRouterFactory(config) {
731
+ return function createRouterInner(procedures) {
732
+ const reservedWordsUsed = new Set(Object.keys(procedures).filter((v)=>reservedWords.includes(v)));
733
+ if (reservedWordsUsed.size > 0) {
734
+ throw new Error('Reserved words used in `router({})` call: ' + Array.from(reservedWordsUsed).join(', '));
735
+ }
736
+ const routerProcedures = omitPrototype({});
737
+ function recursiveGetPaths(procedures, path = '') {
738
+ for (const [key, procedureOrRouter] of Object.entries(procedures ?? {})){
739
+ const newPath = `${path}${key}`;
740
+ if (isRouter(procedureOrRouter)) {
741
+ recursiveGetPaths(procedureOrRouter._def.procedures, `${newPath}.`);
742
+ continue;
743
+ }
744
+ if (routerProcedures[newPath]) {
745
+ throw new Error(`Duplicate key: ${newPath}`);
746
+ }
747
+ routerProcedures[newPath] = procedureOrRouter;
748
+ }
749
+ }
750
+ recursiveGetPaths(procedures);
751
+ const _def = {
752
+ _config: config,
753
+ router: true,
754
+ procedures: routerProcedures,
755
+ ...emptyRouter,
756
+ record: procedures
757
+ };
758
+ const router = {
759
+ ...procedures,
760
+ _def,
761
+ createCaller (ctx) {
762
+ const proxy = createRecursiveProxy(({ path, args })=>{
763
+ const fullPath = path.join('.');
764
+ const procedure = _def.procedures[fullPath];
765
+ return procedure({
766
+ path: fullPath,
767
+ getRawInput: async ()=>args[0],
768
+ ctx,
769
+ type: procedure._def.type
770
+ });
771
+ });
772
+ return proxy;
773
+ }
774
+ };
775
+ return router;
776
+ };
777
+ }
778
+ function isProcedure(procedureOrRouter) {
779
+ return !!procedureOrRouter._def.procedure;
780
+ }
781
+ /**
782
+ * @internal
783
+ */ function callProcedure(opts) {
784
+ const { type, path } = opts;
785
+ const proc = opts.procedures[path];
786
+ if (!proc || !isProcedure(proc) || proc._def.type !== type) {
787
+ throw new TRPCError({
788
+ code: 'NOT_FOUND',
789
+ message: `No "${type}"-procedure on path "${path}"`
790
+ });
791
+ }
792
+ return proc(opts);
793
+ }
794
+ function createCallerFactory() {
795
+ return function createCallerInner(router) {
796
+ const _def = router._def;
797
+ return function createCaller(maybeContext) {
798
+ const proxy = createRecursiveProxy(({ path, args })=>{
799
+ const fullPath = path.join('.');
800
+ const procedure = _def.procedures[fullPath];
801
+ const callProc = (ctx)=>procedure({
802
+ path: fullPath,
803
+ getRawInput: async ()=>args[0],
804
+ ctx,
805
+ type: procedure._def.type
806
+ });
807
+ if (typeof maybeContext === 'function') {
808
+ const context = maybeContext();
809
+ if (context instanceof Promise) {
810
+ return context.then(callProc);
811
+ }
812
+ return callProc(context);
813
+ }
814
+ return callProc(maybeContext);
815
+ });
816
+ return proxy;
817
+ };
818
+ };
819
+ }
820
+ function mergeRouters(...routerList) {
821
+ const record = mergeWithoutOverrides({}, ...routerList.map((r)=>r._def.record));
822
+ const errorFormatter = routerList.reduce((currentErrorFormatter, nextRouter)=>{
823
+ if (nextRouter._def._config.errorFormatter && nextRouter._def._config.errorFormatter !== defaultFormatter) {
824
+ if (currentErrorFormatter !== defaultFormatter && currentErrorFormatter !== nextRouter._def._config.errorFormatter) {
825
+ throw new Error('You seem to have several error formatters');
826
+ }
827
+ return nextRouter._def._config.errorFormatter;
828
+ }
829
+ return currentErrorFormatter;
830
+ }, defaultFormatter);
831
+ const transformer = routerList.reduce((prev, current)=>{
832
+ if (current._def._config.transformer && current._def._config.transformer !== defaultTransformer) {
833
+ if (prev !== defaultTransformer && prev !== current._def._config.transformer) {
834
+ throw new Error('You seem to have several transformers');
835
+ }
836
+ return current._def._config.transformer;
837
+ }
838
+ return prev;
839
+ }, defaultTransformer);
840
+ const router = createRouterFactory({
841
+ errorFormatter,
842
+ transformer,
843
+ isDev: routerList.some((r)=>r._def._config.isDev),
844
+ allowOutsideOfServer: routerList.some((r)=>r._def._config.allowOutsideOfServer),
845
+ isServer: routerList.some((r)=>r._def._config.isServer),
846
+ $types: routerList[0]?._def._config.$types
847
+ })(record);
848
+ return router;
849
+ }
850
+
851
+ /**
852
+ * TODO: This can be improved:
853
+ * - We should be able to chain `.meta()`/`.context()` only once
854
+ * - Simplify typings
855
+ * - Doesn't need to be a class but it doesn't really hurt either
856
+ */ class TRPCBuilder {
857
+ /**
858
+ * Add a context shape as a generic to the root object
859
+ * @link https://trpc.io/docs/v11/server/context
860
+ */ context() {
861
+ return new TRPCBuilder();
862
+ }
863
+ /**
864
+ * Add a meta shape as a generic to the root object
865
+ * @link https://trpc.io/docs/v11/quickstart
866
+ */ meta() {
867
+ return new TRPCBuilder();
868
+ }
869
+ /**
870
+ * Create the root object
871
+ * @link https://trpc.io/docs/v11/server/routers#initialize-trpc
872
+ */ create(options) {
873
+ return createTRPCInner()(options);
874
+ }
875
+ }
876
+ /**
877
+ * Builder to initialize the tRPC root object - use this exactly once per backend
878
+ * @link https://trpc.io/docs/v11/quickstart
879
+ */ const initTRPC = new TRPCBuilder();
880
+ function createTRPCInner() {
881
+ return function initTRPCInner(runtime) {
882
+ const errorFormatter = runtime?.errorFormatter ?? defaultFormatter;
883
+ const transformer = getDataTransformer(runtime?.transformer ?? defaultTransformer);
884
+ const config = {
885
+ transformer,
886
+ isDev: runtime?.isDev ?? // eslint-disable-next-line @typescript-eslint/dot-notation
887
+ globalThis.process?.env?.['NODE_ENV'] !== 'production',
888
+ allowOutsideOfServer: runtime?.allowOutsideOfServer ?? false,
889
+ errorFormatter,
890
+ isServer: runtime?.isServer ?? isServerDefault,
891
+ /**
892
+ * @internal
893
+ */ $types: createFlatProxy((key)=>{
894
+ throw new Error(`Tried to access "$types.${key}" which is not available at runtime`);
895
+ })
896
+ };
897
+ {
898
+ // Server check
899
+ const isServer = runtime?.isServer ?? isServerDefault;
900
+ if (!isServer && runtime?.allowOutsideOfServer !== true) {
901
+ throw new Error(`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`);
902
+ }
903
+ }
904
+ return {
905
+ /**
906
+ * These are just types, they can't be used
907
+ * @internal
908
+ */ _config: config,
909
+ /**
910
+ * Builder object for creating procedures
911
+ * @link https://trpc.io/docs/v11/server/procedures
912
+ */ procedure: createBuilder({
913
+ meta: runtime?.defaultMeta
914
+ }),
915
+ /**
916
+ * Create reusable middlewares
917
+ * @link https://trpc.io/docs/v11/server/middlewares
918
+ */ middleware: createMiddlewareFactory(),
919
+ /**
920
+ * Create a router
921
+ * @link https://trpc.io/docs/v11/server/routers
922
+ */ router: createRouterFactory(config),
923
+ /**
924
+ * Merge Routers
925
+ * @link https://trpc.io/docs/v11/server/merging-routers
926
+ */ mergeRouters,
927
+ /**
928
+ * Create a server-side caller for a router
929
+ * @link https://trpc.io/docs/v11/server/server-side-calls
930
+ */ createCallerFactory: createCallerFactory()
931
+ };
932
+ };
933
+ }
934
+
935
+ /** @public */ function isObservable(x) {
936
+ return typeof x === 'object' && x !== null && 'subscribe' in x;
937
+ }
938
+ /** @public */ function observable(subscribe) {
939
+ const self = {
940
+ subscribe (observer) {
941
+ let teardownRef = null;
942
+ let isDone = false;
943
+ let unsubscribed = false;
944
+ let teardownImmediately = false;
945
+ function unsubscribe() {
946
+ if (teardownRef === null) {
947
+ teardownImmediately = true;
948
+ return;
949
+ }
950
+ if (unsubscribed) {
951
+ return;
952
+ }
953
+ unsubscribed = true;
954
+ if (typeof teardownRef === 'function') {
955
+ teardownRef();
956
+ } else if (teardownRef) {
957
+ teardownRef.unsubscribe();
958
+ }
959
+ }
960
+ teardownRef = subscribe({
961
+ next (value) {
962
+ if (isDone) {
963
+ return;
964
+ }
965
+ observer.next?.(value);
966
+ },
967
+ error (err) {
968
+ if (isDone) {
969
+ return;
970
+ }
971
+ isDone = true;
972
+ observer.error?.(err);
973
+ unsubscribe();
974
+ },
975
+ complete () {
976
+ if (isDone) {
977
+ return;
978
+ }
979
+ isDone = true;
980
+ observer.complete?.();
981
+ unsubscribe();
982
+ }
983
+ });
984
+ if (teardownImmediately) {
985
+ unsubscribe();
986
+ }
987
+ return {
988
+ unsubscribe
989
+ };
990
+ },
991
+ pipe (...operations) {
992
+ return pipeFromArray(operations)(self);
993
+ }
994
+ };
995
+ return self;
996
+ }
997
+ function pipeFromArray(fns) {
998
+ if (fns.length === 0) {
999
+ return identity;
1000
+ }
1001
+ if (fns.length === 1) {
1002
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1003
+ return fns[0];
1004
+ }
1005
+ return function piped(input) {
1006
+ return fns.reduce((prev, fn)=>fn(prev), input);
1007
+ };
1008
+ }
1009
+ class ObservableAbortError extends Error {
1010
+ constructor(message){
1011
+ super(message);
1012
+ this.name = 'ObservableAbortError';
1013
+ Object.setPrototypeOf(this, ObservableAbortError.prototype);
1014
+ }
1015
+ }
1016
+ /** @internal */ function observableToPromise(observable) {
1017
+ let abort;
1018
+ const promise = new Promise((resolve, reject)=>{
1019
+ let isDone = false;
1020
+ function onDone() {
1021
+ if (isDone) {
1022
+ return;
1023
+ }
1024
+ isDone = true;
1025
+ reject(new ObservableAbortError('This operation was aborted.'));
1026
+ obs$.unsubscribe();
1027
+ }
1028
+ const obs$ = observable.subscribe({
1029
+ next (data) {
1030
+ isDone = true;
1031
+ resolve(data);
1032
+ onDone();
1033
+ },
1034
+ error (data) {
1035
+ isDone = true;
1036
+ reject(data);
1037
+ onDone();
1038
+ },
1039
+ complete () {
1040
+ isDone = true;
1041
+ onDone();
1042
+ }
1043
+ });
1044
+ abort = onDone;
1045
+ });
1046
+ return {
1047
+ promise,
1048
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1049
+ abort: abort
1050
+ };
1051
+ }
1052
+
1053
+ function map(project) {
1054
+ return (originalObserver)=>{
1055
+ return {
1056
+ subscribe (observer) {
1057
+ let index = 0;
1058
+ const subscription = originalObserver.subscribe({
1059
+ next (value) {
1060
+ observer.next?.(project(value, index++));
1061
+ },
1062
+ error (error) {
1063
+ observer.error?.(error);
1064
+ },
1065
+ complete () {
1066
+ observer.complete?.();
1067
+ }
1068
+ });
1069
+ return subscription;
1070
+ }
1071
+ };
1072
+ };
1073
+ }
1074
+ function share(_opts) {
1075
+ return (originalObserver)=>{
1076
+ let refCount = 0;
1077
+ let subscription = null;
1078
+ const observers = [];
1079
+ function startIfNeeded() {
1080
+ if (subscription) {
1081
+ return;
1082
+ }
1083
+ subscription = originalObserver.subscribe({
1084
+ next (value) {
1085
+ for (const observer of observers){
1086
+ observer.next?.(value);
1087
+ }
1088
+ },
1089
+ error (error) {
1090
+ for (const observer of observers){
1091
+ observer.error?.(error);
1092
+ }
1093
+ },
1094
+ complete () {
1095
+ for (const observer of observers){
1096
+ observer.complete?.();
1097
+ }
1098
+ }
1099
+ });
1100
+ }
1101
+ function resetIfNeeded() {
1102
+ // "resetOnRefCountZero"
1103
+ if (refCount === 0 && subscription) {
1104
+ const _sub = subscription;
1105
+ subscription = null;
1106
+ _sub.unsubscribe();
1107
+ }
1108
+ }
1109
+ return {
1110
+ subscribe (observer) {
1111
+ refCount++;
1112
+ observers.push(observer);
1113
+ startIfNeeded();
1114
+ return {
1115
+ unsubscribe () {
1116
+ refCount--;
1117
+ resetIfNeeded();
1118
+ const index = observers.findIndex((v)=>v === observer);
1119
+ if (index > -1) {
1120
+ observers.splice(index, 1);
1121
+ }
1122
+ }
1123
+ };
1124
+ }
1125
+ };
1126
+ };
1127
+ }
1128
+ function tap(observer) {
1129
+ return (originalObserver)=>{
1130
+ return {
1131
+ subscribe (observer2) {
1132
+ return originalObserver.subscribe({
1133
+ next (v) {
1134
+ observer.next?.(v);
1135
+ observer2.next?.(v);
1136
+ },
1137
+ error (v) {
1138
+ observer.error?.(v);
1139
+ observer2.error?.(v);
1140
+ },
1141
+ complete () {
1142
+ observer.complete?.();
1143
+ observer2.complete?.();
1144
+ }
1145
+ });
1146
+ }
1147
+ };
1148
+ };
1149
+ }
1150
+
1151
+ function getRawProcedureInputOrThrow(opts) {
1152
+ const { req } = opts;
1153
+ try {
1154
+ if (req.method === 'GET') {
1155
+ if (!req.query.has('input')) {
1156
+ return undefined;
1157
+ }
1158
+ const raw = req.query.get('input');
1159
+ return JSON.parse(raw);
1160
+ }
1161
+ if (!opts.preprocessedBody && typeof req.body === 'string') {
1162
+ // A mutation with no inputs will have req.body === ''
1163
+ return req.body.length === 0 ? undefined : JSON.parse(req.body);
1164
+ }
1165
+ return req.body;
1166
+ } catch (cause) {
1167
+ throw new TRPCError({
1168
+ code: 'PARSE_ERROR',
1169
+ cause
1170
+ });
1171
+ }
1172
+ }
1173
+ const deserializeInputValue = (rawValue, transformer)=>{
1174
+ return typeof rawValue !== 'undefined' ? transformer.input.deserialize(rawValue) : rawValue;
1175
+ };
1176
+ const getJsonContentTypeInputs = (opts)=>{
1177
+ const rawInput = getRawProcedureInputOrThrow(opts);
1178
+ const transformer = opts.router._def._config.transformer;
1179
+ if (!opts.isBatchCall) {
1180
+ return {
1181
+ 0: deserializeInputValue(rawInput, transformer)
1182
+ };
1183
+ }
1184
+ /* istanbul ignore if */ if (rawInput == null || typeof rawInput !== 'object' || Array.isArray(rawInput)) {
1185
+ throw new TRPCError({
1186
+ code: 'BAD_REQUEST',
1187
+ message: '"input" needs to be an object when doing a batch call'
1188
+ });
1189
+ }
1190
+ const input = {};
1191
+ for(const key in rawInput){
1192
+ const k = key;
1193
+ const rawValue = rawInput[k];
1194
+ const value = deserializeInputValue(rawValue, transformer);
1195
+ input[k] = value;
1196
+ }
1197
+ return input;
1198
+ };
1199
+
1200
+ const HTTP_METHOD_PROCEDURE_TYPE_MAP = {
1201
+ GET: 'query',
1202
+ POST: 'mutation'
1203
+ };
1204
+ const fallbackContentTypeHandler = {
1205
+ getInputs: getJsonContentTypeInputs
1206
+ };
1207
+ function initResponse(initOpts) {
1208
+ const { ctx, paths, type, responseMeta, untransformedJSON, errors = [] } = initOpts;
1209
+ let status = untransformedJSON ? getHTTPStatusCode(untransformedJSON) : 200;
1210
+ const headers = {
1211
+ 'Content-Type': 'application/json'
1212
+ };
1213
+ const eagerGeneration = !untransformedJSON;
1214
+ const data = eagerGeneration ? [] : Array.isArray(untransformedJSON) ? untransformedJSON : [
1215
+ untransformedJSON
1216
+ ];
1217
+ const meta = responseMeta?.({
1218
+ ctx,
1219
+ paths,
1220
+ type,
1221
+ data,
1222
+ errors,
1223
+ eagerGeneration
1224
+ }) ?? {};
1225
+ for (const [key, value] of Object.entries(meta.headers ?? {})){
1226
+ headers[key] = value;
1227
+ }
1228
+ if (meta.status) {
1229
+ status = meta.status;
1230
+ }
1231
+ return {
1232
+ status,
1233
+ headers
1234
+ };
1235
+ }
1236
+ async function inputToProcedureCall(procedureOpts) {
1237
+ const { opts, ctx, type, input, path } = procedureOpts;
1238
+ try {
1239
+ const data = await callProcedure({
1240
+ procedures: opts.router._def.procedures,
1241
+ path,
1242
+ getRawInput: async ()=>input,
1243
+ ctx,
1244
+ type
1245
+ });
1246
+ return {
1247
+ result: {
1248
+ data
1249
+ }
1250
+ };
1251
+ } catch (cause) {
1252
+ const error = getTRPCErrorFromUnknown(cause);
1253
+ opts.onError?.({
1254
+ error,
1255
+ path,
1256
+ input,
1257
+ ctx,
1258
+ type: type,
1259
+ req: opts.req
1260
+ });
1261
+ return {
1262
+ error: getErrorShape({
1263
+ config: opts.router._def._config,
1264
+ error,
1265
+ type,
1266
+ path,
1267
+ input,
1268
+ ctx
1269
+ })
1270
+ };
1271
+ }
1272
+ }
1273
+ function caughtErrorToData(cause, errorOpts) {
1274
+ const { router, req, onError } = errorOpts.opts;
1275
+ const error = getTRPCErrorFromUnknown(cause);
1276
+ onError?.({
1277
+ error,
1278
+ path: errorOpts.path,
1279
+ input: errorOpts.input,
1280
+ ctx: errorOpts.ctx,
1281
+ type: errorOpts.type,
1282
+ req
1283
+ });
1284
+ const untransformedJSON = {
1285
+ error: getErrorShape({
1286
+ config: router._def._config,
1287
+ error,
1288
+ type: errorOpts.type,
1289
+ path: errorOpts.path,
1290
+ input: errorOpts.input,
1291
+ ctx: errorOpts.ctx
1292
+ })
1293
+ };
1294
+ const transformedJSON = transformTRPCResponse(router._def._config, untransformedJSON);
1295
+ const body = JSON.stringify(transformedJSON);
1296
+ return {
1297
+ error,
1298
+ untransformedJSON,
1299
+ body
1300
+ };
1301
+ }
1302
+ // implementation
1303
+ async function resolveHTTPResponse(opts) {
1304
+ const { router, req, unstable_onHead, unstable_onChunk } = opts;
1305
+ if (req.method === 'HEAD') {
1306
+ // can be used for lambda warmup
1307
+ const headResponse = {
1308
+ status: 204
1309
+ };
1310
+ unstable_onHead?.(headResponse, false);
1311
+ unstable_onChunk?.([
1312
+ -1,
1313
+ ''
1314
+ ]);
1315
+ return headResponse;
1316
+ }
1317
+ const contentTypeHandler = opts.contentTypeHandler ?? fallbackContentTypeHandler;
1318
+ const batchingEnabled = opts.batching?.enabled ?? true;
1319
+ const type = HTTP_METHOD_PROCEDURE_TYPE_MAP[req.method] ?? 'unknown';
1320
+ let ctx = undefined;
1321
+ let paths;
1322
+ const isBatchCall = !!req.query.get('batch');
1323
+ const isStreamCall = isBatchCall && unstable_onHead && unstable_onChunk && req.headers['trpc-batch-mode'] === 'stream';
1324
+ try {
1325
+ if (opts.error) {
1326
+ throw opts.error;
1327
+ }
1328
+ if (isBatchCall && !batchingEnabled) {
1329
+ throw new Error(`Batching is not enabled on the server`);
1330
+ }
1331
+ /* istanbul ignore if -- @preserve */ if (type === 'subscription') {
1332
+ throw new TRPCError({
1333
+ message: 'Subscriptions should use wsLink',
1334
+ code: 'METHOD_NOT_SUPPORTED'
1335
+ });
1336
+ }
1337
+ if (type === 'unknown') {
1338
+ throw new TRPCError({
1339
+ message: `Unexpected request method ${req.method}`,
1340
+ code: 'METHOD_NOT_SUPPORTED'
1341
+ });
1342
+ }
1343
+ const inputs = await contentTypeHandler.getInputs({
1344
+ isBatchCall,
1345
+ req,
1346
+ router,
1347
+ preprocessedBody: opts.preprocessedBody ?? false
1348
+ });
1349
+ paths = isBatchCall ? decodeURIComponent(opts.path).split(',') : [
1350
+ opts.path
1351
+ ];
1352
+ const info = {
1353
+ isBatchCall,
1354
+ calls: paths.map((path, idx)=>({
1355
+ path,
1356
+ type,
1357
+ input: inputs[idx] ?? undefined
1358
+ }))
1359
+ };
1360
+ ctx = await opts.createContext({
1361
+ info
1362
+ });
1363
+ const promises = paths.map((path, index)=>inputToProcedureCall({
1364
+ opts,
1365
+ ctx,
1366
+ type,
1367
+ input: inputs[index],
1368
+ path
1369
+ }));
1370
+ if (!isStreamCall) {
1371
+ /**
1372
+ * Non-streaming response:
1373
+ * - await all responses in parallel, blocking on the slowest one
1374
+ * - create headers with known response body
1375
+ * - return a complete HTTPResponse
1376
+ */ const untransformedJSON = await Promise.all(promises);
1377
+ const errors = untransformedJSON.flatMap((response)=>'error' in response ? [
1378
+ response.error
1379
+ ] : []);
1380
+ const headResponse = initResponse({
1381
+ ctx,
1382
+ paths,
1383
+ type,
1384
+ responseMeta: opts.responseMeta,
1385
+ untransformedJSON,
1386
+ errors
1387
+ });
1388
+ unstable_onHead?.(headResponse, false);
1389
+ // return body stuff
1390
+ const result = isBatchCall ? untransformedJSON : untransformedJSON[0]; // eslint-disable-line @typescript-eslint/no-non-null-assertion -- `untransformedJSON` should be the length of `paths` which should be at least 1 otherwise there wouldn't be a request at all
1391
+ const transformedJSON = transformTRPCResponse(router._def._config, result);
1392
+ const body = JSON.stringify(transformedJSON);
1393
+ unstable_onChunk?.([
1394
+ -1,
1395
+ body
1396
+ ]);
1397
+ return {
1398
+ status: headResponse.status,
1399
+ headers: headResponse.headers,
1400
+ body
1401
+ };
1402
+ }
1403
+ /**
1404
+ * Streaming response:
1405
+ * - block on none, call `onChunk` as soon as each response is ready
1406
+ * - create headers with minimal data (cannot know the response body in advance)
1407
+ * - return void
1408
+ */ const headResponse = initResponse({
1409
+ ctx,
1410
+ paths,
1411
+ type,
1412
+ responseMeta: opts.responseMeta
1413
+ });
1414
+ unstable_onHead(headResponse, true);
1415
+ const indexedPromises = new Map(promises.map((promise, index)=>[
1416
+ index,
1417
+ promise.then((r)=>[
1418
+ index,
1419
+ r
1420
+ ])
1421
+ ]));
1422
+ for (const _ of paths){
1423
+ const [index, untransformedJSON] = await Promise.race(indexedPromises.values());
1424
+ indexedPromises.delete(index);
1425
+ try {
1426
+ const transformedJSON = transformTRPCResponse(router._def._config, untransformedJSON);
1427
+ const body = JSON.stringify(transformedJSON);
1428
+ unstable_onChunk([
1429
+ index,
1430
+ body
1431
+ ]);
1432
+ } catch (cause) {
1433
+ const path = paths[index];
1434
+ const input = inputs[index];
1435
+ const { body } = caughtErrorToData(cause, {
1436
+ opts,
1437
+ ctx,
1438
+ type,
1439
+ path,
1440
+ input
1441
+ });
1442
+ unstable_onChunk([
1443
+ index,
1444
+ body
1445
+ ]);
1446
+ }
1447
+ }
1448
+ return;
1449
+ } catch (cause) {
1450
+ // we get here if
1451
+ // - batching is called when it's not enabled
1452
+ // - `createContext()` throws
1453
+ // - `router._def._config.transformer.output.serialize()` throws
1454
+ // - post body is too large
1455
+ // - input deserialization fails
1456
+ // - `errorFormatter` return value is malformed
1457
+ const { error, untransformedJSON, body } = caughtErrorToData(cause, {
1458
+ opts,
1459
+ ctx,
1460
+ type
1461
+ });
1462
+ const headResponse = initResponse({
1463
+ ctx,
1464
+ paths,
1465
+ type,
1466
+ responseMeta: opts.responseMeta,
1467
+ untransformedJSON,
1468
+ errors: [
1469
+ error
1470
+ ]
1471
+ });
1472
+ unstable_onHead?.(headResponse, false);
1473
+ unstable_onChunk?.([
1474
+ -1,
1475
+ body
1476
+ ]);
1477
+ return {
1478
+ status: headResponse.status,
1479
+ headers: headResponse.headers,
1480
+ body
1481
+ };
1482
+ }
1483
+ }
1484
+
1485
+ /**
1486
+ * Format a batch response as a line-delimited JSON stream
1487
+ * that the `unstable_httpBatchStreamLink` can parse:
1488
+ *
1489
+ * @example
1490
+ * ```ts
1491
+ * const formatter = getBatchStreamFormatter();
1492
+ * res.send(formatter(1, 'response #2'));
1493
+ * res.send(formatter(0, 'response #1'));
1494
+ * res.send(formatter.end());
1495
+ * ```
1496
+ *
1497
+ * Expected format:
1498
+ * ```json
1499
+ * {"1":"response #2"
1500
+ * ,"0":"response #1"
1501
+ * }
1502
+ * ```
1503
+ */ function getBatchStreamFormatter() {
1504
+ let first = true;
1505
+ function format(index, string) {
1506
+ const prefix = first ? '{' : ',';
1507
+ first = false;
1508
+ return `${prefix}"${index}":${string}\n`;
1509
+ }
1510
+ format.end = ()=>'}';
1511
+ return format;
1512
+ }
1513
+
1514
+ export { TRPCError, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, callProcedure, createBuilder, createFlatProxy, createInputMiddleware, createOutputMiddleware, createRecursiveProxy, createRouterFactory, experimental_standaloneMiddleware, getBatchStreamFormatter, getCauseFromUnknown, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getJsonContentTypeInputs, getTRPCErrorFromUnknown, initTRPC, isObject, isObservable, map, mergeRouters, middlewareMarker, observable, observableToPromise, parseTRPCMessage, procedureTypes, resolveHTTPResponse, share, tap, transformResult, transformTRPCResponse, unsetMarker };