@trpc/server 10.0.0-alpha.41 → 10.0.0-alpha.44

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 (87) hide show
  1. package/adapters/aws-lambda/dist/trpc-server-adapters-aws-lambda.cjs.dev.js +4 -4
  2. package/adapters/aws-lambda/dist/trpc-server-adapters-aws-lambda.cjs.prod.js +4 -4
  3. package/adapters/aws-lambda/dist/trpc-server-adapters-aws-lambda.esm.js +4 -4
  4. package/adapters/aws-lambda/index.js +1 -1
  5. package/adapters/express/dist/trpc-server-adapters-express.cjs.dev.js +3 -3
  6. package/adapters/express/dist/trpc-server-adapters-express.cjs.prod.js +3 -3
  7. package/adapters/express/dist/trpc-server-adapters-express.esm.js +3 -3
  8. package/adapters/fastify/dist/trpc-server-adapters-fastify.cjs.dev.js +3 -3
  9. package/adapters/fastify/dist/trpc-server-adapters-fastify.cjs.prod.js +3 -3
  10. package/adapters/fastify/dist/trpc-server-adapters-fastify.esm.js +3 -3
  11. package/adapters/lambda/dist/trpc-server-adapters-lambda.cjs.dev.js +4 -4
  12. package/adapters/lambda/dist/trpc-server-adapters-lambda.cjs.prod.js +4 -4
  13. package/adapters/lambda/dist/trpc-server-adapters-lambda.esm.js +4 -4
  14. package/adapters/next/dist/trpc-server-adapters-next.cjs.dev.js +3 -3
  15. package/adapters/next/dist/trpc-server-adapters-next.cjs.prod.js +3 -3
  16. package/adapters/next/dist/trpc-server-adapters-next.esm.js +3 -3
  17. package/adapters/node-http/dist/trpc-server-adapters-node-http.cjs.dev.js +3 -3
  18. package/adapters/node-http/dist/trpc-server-adapters-node-http.cjs.prod.js +3 -3
  19. package/adapters/node-http/dist/trpc-server-adapters-node-http.esm.js +3 -3
  20. package/adapters/standalone/dist/trpc-server-adapters-standalone.cjs.dev.js +3 -3
  21. package/adapters/standalone/dist/trpc-server-adapters-standalone.cjs.prod.js +3 -3
  22. package/adapters/standalone/dist/trpc-server-adapters-standalone.esm.js +3 -3
  23. package/adapters/ws/dist/trpc-server-adapters-ws.cjs.dev.js +2 -2
  24. package/adapters/ws/dist/trpc-server-adapters-ws.cjs.prod.js +2 -2
  25. package/adapters/ws/dist/trpc-server-adapters-ws.esm.js +2 -2
  26. package/dist/{TRPCError-b7fa0c31.mjs → TRPCError-97212592.mjs} +1 -1
  27. package/dist/adapters/aws-lambda/index.js +190 -0
  28. package/dist/adapters/aws-lambda/index.mjs +186 -0
  29. package/dist/adapters/aws-lambda/index.ts.js +1 -0
  30. package/dist/adapters/express.js +3 -3
  31. package/dist/adapters/express.mjs +4 -4
  32. package/dist/adapters/fastify/index.js +2 -2
  33. package/dist/adapters/fastify/index.mjs +3 -3
  34. package/dist/adapters/fetch/index.js +2 -2
  35. package/dist/adapters/fetch/index.mjs +3 -3
  36. package/dist/adapters/next.js +3 -3
  37. package/dist/adapters/next.mjs +4 -4
  38. package/dist/adapters/node-http/index.js +3 -3
  39. package/dist/adapters/node-http/index.mjs +4 -4
  40. package/dist/adapters/standalone.js +3 -3
  41. package/dist/adapters/standalone.mjs +4 -4
  42. package/dist/adapters/ws.mjs +1 -1
  43. package/dist/core/index.d.ts +1 -1
  44. package/dist/core/index.d.ts.map +1 -1
  45. package/dist/core/initTRPC.d.ts +8 -0
  46. package/dist/core/initTRPC.d.ts.map +1 -1
  47. package/dist/core/internals/__generated__/mergeRoutersGeneric.d.ts +20 -0
  48. package/dist/core/internals/__generated__/mergeRoutersGeneric.d.ts.map +1 -1
  49. package/dist/core/internals/procedureBuilder.d.ts +1 -6
  50. package/dist/core/internals/procedureBuilder.d.ts.map +1 -1
  51. package/dist/core/procedure.d.ts +1 -0
  52. package/dist/core/procedure.d.ts.map +1 -1
  53. package/dist/core/router.d.ts +31 -23
  54. package/dist/core/router.d.ts.map +1 -1
  55. package/dist/deprecated/interop.d.ts +29 -2
  56. package/dist/deprecated/interop.d.ts.map +1 -1
  57. package/dist/deprecated/router.d.ts.map +1 -1
  58. package/dist/{envelopes-b6dd0367.js → envelopes-2ae27c9f.js} +1 -4
  59. package/dist/{envelopes-af8c2959.mjs → envelopes-b9f49d4d.mjs} +1 -4
  60. package/dist/error/TRPCError.d.ts +1 -1
  61. package/dist/index.js +22 -1114
  62. package/dist/index.mjs +8 -1101
  63. package/dist/internals/transformTRPCResponse.d.ts +2 -2
  64. package/dist/internals/transformTRPCResponse.d.ts.map +1 -1
  65. package/dist/{nodeHTTPRequestHandler-6b7c8622.js → nodeHTTPRequestHandler-bee7aacc.js} +1 -1
  66. package/dist/{nodeHTTPRequestHandler-174459c5.mjs → nodeHTTPRequestHandler-f1656eba.mjs} +2 -2
  67. package/dist/{resolveHTTPResponse-8657b8de.mjs → resolveHTTPResponse-455f1e51.mjs} +2 -2
  68. package/dist/{resolveHTTPResponse-fcc8f644.js → resolveHTTPResponse-5d90abc5.js} +1 -1
  69. package/dist/router-4e50a6ac.js +1104 -0
  70. package/dist/router-a3db8f3a.mjs +1094 -0
  71. package/dist/rpc/envelopes.d.ts +22 -21
  72. package/dist/rpc/envelopes.d.ts.map +1 -1
  73. package/dist/rpc/index.js +1 -1
  74. package/dist/rpc/index.mjs +1 -1
  75. package/dist/subscription.mjs +1 -1
  76. package/dist/types.d.ts.map +1 -1
  77. package/package.json +6 -5
  78. package/src/core/index.ts +5 -1
  79. package/src/core/initTRPC.ts +0 -1
  80. package/src/core/internals/__generated__/mergeRoutersGeneric.ts +20 -0
  81. package/src/core/internals/procedureBuilder.ts +0 -22
  82. package/src/core/procedure.ts +1 -0
  83. package/src/core/router.ts +29 -44
  84. package/src/deprecated/interop.ts +47 -4
  85. package/src/deprecated/router.ts +0 -2
  86. package/src/rpc/envelopes.ts +32 -25
  87. package/src/types.ts +0 -1
@@ -0,0 +1,1104 @@
1
+ 'use strict';
2
+
3
+ var resolveHTTPResponse = require('./resolveHTTPResponse-5d90abc5.js');
4
+ var envelopes = require('./envelopes-2ae27c9f.js');
5
+ var TRPCError = require('./TRPCError-9050a68d.js');
6
+ var index = require('./index-1a25ccbd.js');
7
+
8
+ resolveHTTPResponse.assertNotBrowser();
9
+
10
+ /* eslint-disable @typescript-eslint/no-explicit-any */
11
+
12
+ /**
13
+ * @public
14
+ */
15
+
16
+ /**
17
+ * @public
18
+ */
19
+
20
+ /**
21
+ * @public
22
+ */
23
+
24
+ /**
25
+ * @public
26
+ */
27
+
28
+ /**
29
+ * @public
30
+ */
31
+
32
+ /**
33
+ * @internal
34
+ */
35
+ function getDataTransformer$1(transformer) {
36
+ if ('input' in transformer) {
37
+ return transformer;
38
+ }
39
+
40
+ return {
41
+ input: transformer,
42
+ output: transformer
43
+ };
44
+ }
45
+ /**
46
+ * @internal
47
+ */
48
+
49
+ /**
50
+ * @internal
51
+ */
52
+ const defaultTransformer = {
53
+ _default: true,
54
+ input: {
55
+ serialize: obj => obj,
56
+ deserialize: obj => obj
57
+ },
58
+ output: {
59
+ serialize: obj => obj,
60
+ deserialize: obj => obj
61
+ }
62
+ };
63
+
64
+ /**
65
+ * @internal
66
+ */
67
+
68
+ /**
69
+ * @internal
70
+ */
71
+
72
+ /**
73
+ * @internal
74
+ */
75
+ const defaultFormatter = ({
76
+ shape
77
+ }) => {
78
+ return shape;
79
+ };
80
+
81
+ /**
82
+ * @deprecated
83
+ */
84
+ const middlewareMarker$1 = 'middlewareMarker';
85
+
86
+ /* eslint-disable @typescript-eslint/no-explicit-any */
87
+ resolveHTTPResponse.assertNotBrowser();
88
+
89
+ function getParseFn$1(procedureParser) {
90
+ const parser = procedureParser;
91
+
92
+ if (typeof parser === 'function') {
93
+ // ProcedureParserCustomValidatorEsque
94
+ return parser;
95
+ }
96
+
97
+ if (typeof parser.parseAsync === 'function') {
98
+ // ProcedureParserZodEsque
99
+ return parser.parseAsync.bind(parser);
100
+ }
101
+
102
+ if (typeof parser.parse === 'function') {
103
+ // ProcedureParserZodEsque
104
+ return parser.parse.bind(parser);
105
+ }
106
+
107
+ if (typeof parser.validateSync === 'function') {
108
+ // ProcedureParserYupEsque
109
+ return parser.validateSync.bind(parser);
110
+ }
111
+
112
+ if (typeof parser.create === 'function') {
113
+ // ProcedureParserSuperstructEsque
114
+ return parser.create.bind(parser);
115
+ }
116
+
117
+ throw new Error('Could not find a validator fn');
118
+ }
119
+ /**
120
+ * @internal
121
+ * @deprecated
122
+ */
123
+
124
+
125
+ class Procedure {
126
+ constructor(opts) {
127
+ this.middlewares = void 0;
128
+ this.resolver = void 0;
129
+ this.inputParser = void 0;
130
+ this.parseInputFn = void 0;
131
+ this.outputParser = void 0;
132
+ this.parseOutputFn = void 0;
133
+ this.meta = void 0;
134
+ this.middlewares = opts.middlewares;
135
+ this.resolver = opts.resolver;
136
+ this.inputParser = opts.inputParser;
137
+ this.parseInputFn = getParseFn$1(this.inputParser);
138
+ this.outputParser = opts.outputParser;
139
+ this.parseOutputFn = getParseFn$1(this.outputParser);
140
+ this.meta = opts.meta;
141
+ }
142
+
143
+ _def() {
144
+ return {
145
+ middlewares: this.middlewares,
146
+ resolver: this.resolver,
147
+ inputParser: this.inputParser,
148
+ outputParser: this.outputParser,
149
+ meta: this.meta
150
+ };
151
+ }
152
+
153
+ async parseInput(rawInput) {
154
+ try {
155
+ return await this.parseInputFn(rawInput);
156
+ } catch (cause) {
157
+ throw new TRPCError.TRPCError({
158
+ code: 'BAD_REQUEST',
159
+ cause: TRPCError.getCauseFromUnknown(cause)
160
+ });
161
+ }
162
+ }
163
+
164
+ async parseOutput(rawOutput) {
165
+ try {
166
+ return await this.parseOutputFn(rawOutput);
167
+ } catch (cause) {
168
+ throw new TRPCError.TRPCError({
169
+ code: 'INTERNAL_SERVER_ERROR',
170
+ cause: TRPCError.getCauseFromUnknown(cause),
171
+ message: 'Output validation failed'
172
+ });
173
+ }
174
+ }
175
+ /**
176
+ * Trigger middlewares in order, parse raw input, call resolver & parse raw output
177
+ * @internal
178
+ */
179
+
180
+
181
+ async call(opts) {
182
+ // wrap the actual resolver and treat as the last "middleware"
183
+ const middlewaresWithResolver = this.middlewares.concat([async ({
184
+ ctx
185
+ }) => {
186
+ const input = await this.parseInput(opts.rawInput);
187
+ const rawOutput = await this.resolver({ ...opts,
188
+ ctx,
189
+ input
190
+ });
191
+ const data = await this.parseOutput(rawOutput);
192
+ return {
193
+ marker: middlewareMarker$1,
194
+ ok: true,
195
+ data,
196
+ ctx
197
+ };
198
+ }]); // run the middlewares recursively with the resolver as the last one
199
+
200
+ const callRecursive = async (callOpts = {
201
+ index: 0,
202
+ ctx: opts.ctx
203
+ }) => {
204
+ try {
205
+ const result = await middlewaresWithResolver[callOpts.index]({
206
+ ctx: callOpts.ctx,
207
+ type: opts.type,
208
+ path: opts.path,
209
+ rawInput: opts.rawInput,
210
+ meta: this.meta,
211
+ next: async nextOpts => {
212
+ return await callRecursive({
213
+ index: callOpts.index + 1,
214
+ ctx: nextOpts ? nextOpts.ctx : callOpts.ctx
215
+ });
216
+ }
217
+ });
218
+ return result;
219
+ } catch (cause) {
220
+ return {
221
+ ctx: callOpts.ctx,
222
+ ok: false,
223
+ error: TRPCError.getErrorFromUnknown(cause),
224
+ marker: middlewareMarker$1
225
+ };
226
+ }
227
+ }; // there's always at least one "next" since we wrap this.resolver in a middleware
228
+
229
+
230
+ const result = await callRecursive();
231
+
232
+ if (!result) {
233
+ throw new TRPCError.TRPCError({
234
+ code: 'INTERNAL_SERVER_ERROR',
235
+ message: 'No result from middlewares - did you forget to `return next()`?'
236
+ });
237
+ }
238
+
239
+ if (!result.ok) {
240
+ // re-throw original error
241
+ throw result.error;
242
+ }
243
+
244
+ return result.data;
245
+ }
246
+ /**
247
+ * Create new procedure with passed middlewares
248
+ * @param middlewares
249
+ */
250
+
251
+
252
+ inheritMiddlewares(middlewares) {
253
+ const Constructor = this.constructor;
254
+ const instance = new Constructor({
255
+ middlewares: [...middlewares, ...this.middlewares],
256
+ resolver: this.resolver,
257
+ inputParser: this.inputParser,
258
+ outputParser: this.outputParser,
259
+ meta: this.meta
260
+ });
261
+ return instance;
262
+ }
263
+
264
+ }
265
+ function createProcedure(opts) {
266
+ const inputParser = 'input' in opts ? opts.input : input => {
267
+ if (input != null) {
268
+ throw new TRPCError.TRPCError({
269
+ code: 'BAD_REQUEST',
270
+ message: 'No input expected'
271
+ });
272
+ }
273
+
274
+ return undefined;
275
+ };
276
+ const outputParser = 'output' in opts && opts.output ? opts.output : output => output;
277
+ return new Procedure({
278
+ inputParser: inputParser,
279
+ resolver: opts.resolve,
280
+ middlewares: [],
281
+ outputParser: outputParser,
282
+ meta: opts.meta
283
+ });
284
+ }
285
+
286
+ function getParseFn(procedureParser) {
287
+ const parser = procedureParser;
288
+
289
+ if (typeof parser === 'function') {
290
+ // ProcedureParserCustomValidatorEsque
291
+ return parser;
292
+ }
293
+
294
+ if (typeof parser.parseAsync === 'function') {
295
+ // ProcedureParserZodEsque
296
+ return parser.parseAsync.bind(parser);
297
+ }
298
+
299
+ if (typeof parser.parse === 'function') {
300
+ // ProcedureParserZodEsque
301
+ return parser.parse.bind(parser);
302
+ }
303
+
304
+ if (typeof parser.validateSync === 'function') {
305
+ // ProcedureParserYupEsque
306
+ return parser.validateSync.bind(parser);
307
+ }
308
+
309
+ if (typeof parser.create === 'function') {
310
+ // ProcedureParserSuperstructEsque
311
+ return parser.create.bind(parser);
312
+ }
313
+
314
+ throw new Error('Could not find a validator fn');
315
+ }
316
+ /**
317
+ * @deprecated only for backwards compat
318
+ * @internal
319
+ */
320
+
321
+ function getParseFnOrPassThrough(procedureParser) {
322
+ if (!procedureParser) {
323
+ return v => v;
324
+ }
325
+
326
+ return getParseFn(procedureParser);
327
+ }
328
+
329
+ /**
330
+ * Ensures there are no duplicate keys when building a procedure.
331
+ */
332
+ function mergeWithoutOverrides(obj1, ...objs) {
333
+ const newObj = Object.assign(Object.create(null), obj1);
334
+
335
+ for (const overrides of objs) {
336
+ for (const key in overrides) {
337
+ if (key in newObj && newObj[key] !== overrides[key]) {
338
+ throw new Error(`Duplicate key ${key}`);
339
+ }
340
+
341
+ newObj[key] = overrides[key];
342
+ }
343
+ }
344
+
345
+ return newObj;
346
+ }
347
+
348
+ /**
349
+ * @internal
350
+ */
351
+
352
+ /**
353
+ * @internal
354
+ */
355
+
356
+ /**
357
+ * @internal
358
+ */
359
+ const middlewareMarker = 'middlewareMarker';
360
+ /**
361
+ * @internal
362
+ */
363
+
364
+ function createNewBuilder(def1, def2) {
365
+ const {
366
+ middlewares = [],
367
+ ...rest
368
+ } = def2; // TODO: maybe have a fn here to warn about calls
369
+
370
+ return createBuilder({ ...mergeWithoutOverrides(def1, rest),
371
+ middlewares: [...def1.middlewares, ...middlewares]
372
+ });
373
+ }
374
+
375
+ function createBuilder(initDef) {
376
+ const _def = initDef || {
377
+ middlewares: []
378
+ };
379
+
380
+ return {
381
+ _def,
382
+
383
+ input(input) {
384
+ const parser = getParseFn(input);
385
+ return createNewBuilder(_def, {
386
+ input,
387
+ middlewares: [createInputMiddleware(parser)]
388
+ });
389
+ },
390
+
391
+ output(output) {
392
+ const parseOutput = getParseFn(output);
393
+ return createNewBuilder(_def, {
394
+ output,
395
+ middlewares: [createOutputMiddleware(parseOutput)]
396
+ });
397
+ },
398
+
399
+ meta(meta) {
400
+ return createNewBuilder(_def, {
401
+ meta: meta
402
+ });
403
+ },
404
+
405
+ unstable_concat(builder) {
406
+ return createNewBuilder(_def, builder._def);
407
+ },
408
+
409
+ use(middleware) {
410
+ return createNewBuilder(_def, {
411
+ middlewares: [middleware]
412
+ });
413
+ },
414
+
415
+ query(resolver) {
416
+ return createResolver({ ..._def,
417
+ query: true
418
+ }, resolver);
419
+ },
420
+
421
+ mutation(resolver) {
422
+ return createResolver({ ..._def,
423
+ mutation: true
424
+ }, resolver);
425
+ },
426
+
427
+ subscription(resolver) {
428
+ return createResolver({ ..._def,
429
+ subscription: true
430
+ }, resolver);
431
+ }
432
+
433
+ };
434
+ }
435
+ function createInputMiddleware(parse) {
436
+ return async function inputMiddleware({
437
+ next,
438
+ rawInput
439
+ }) {
440
+ let input;
441
+
442
+ try {
443
+ input = await parse(rawInput);
444
+ } catch (cause) {
445
+ throw new TRPCError.TRPCError({
446
+ code: 'BAD_REQUEST',
447
+ cause: TRPCError.getCauseFromUnknown(cause)
448
+ });
449
+ } // TODO fix this typing?
450
+
451
+
452
+ return next({
453
+ input
454
+ });
455
+ };
456
+ }
457
+ function createOutputMiddleware(parse) {
458
+ return async function outputMiddleware({
459
+ next
460
+ }) {
461
+ const result = await next();
462
+
463
+ if (!result.ok) {
464
+ // pass through failures without validating
465
+ return result;
466
+ }
467
+
468
+ try {
469
+ const data = await parse(result.data);
470
+ return { ...result,
471
+ data
472
+ };
473
+ } catch (cause) {
474
+ throw new TRPCError.TRPCError({
475
+ message: 'Output validation failed',
476
+ code: 'INTERNAL_SERVER_ERROR',
477
+ cause: TRPCError.getCauseFromUnknown(cause)
478
+ });
479
+ }
480
+ };
481
+ }
482
+
483
+ function createResolver(_def, resolver) {
484
+ const finalBuilder = createNewBuilder(_def, {
485
+ resolver,
486
+ middlewares: [async function resolveMiddleware(opts) {
487
+ const data = await resolver(opts);
488
+ return {
489
+ marker: middlewareMarker,
490
+ ok: true,
491
+ data,
492
+ ctx: opts.ctx
493
+ };
494
+ }]
495
+ });
496
+ return createProcedureCaller(finalBuilder._def);
497
+ }
498
+ /**
499
+ * @internal
500
+ */
501
+
502
+
503
+ const codeblock = /*#__PURE__*/`
504
+ If you want to call this function on the server, you do the following:
505
+ This is a client-only function.
506
+
507
+ const caller = appRouter.createCaller({
508
+ /* ... your context */
509
+ });
510
+
511
+ const result = await caller.call('myProcedure', input);
512
+ `.trim();
513
+
514
+ function createProcedureCaller(_def) {
515
+ const procedure = async function resolve(opts) {
516
+ // is direct server-side call
517
+ if (!opts || !('rawInput' in opts)) {
518
+ throw new Error(codeblock);
519
+ } // run the middlewares recursively with the resolver as the last one
520
+
521
+
522
+ const callRecursive = async (callOpts = {
523
+ index: 0,
524
+ ctx: opts.ctx
525
+ }) => {
526
+ try {
527
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
528
+ const middleware = _def.middlewares[callOpts.index];
529
+ const result = await middleware({
530
+ ctx: callOpts.ctx,
531
+ type: opts.type,
532
+ path: opts.path,
533
+ rawInput: opts.rawInput,
534
+ meta: _def.meta,
535
+ input: callOpts.input,
536
+ next: async nextOpts => {
537
+ return await callRecursive({
538
+ index: callOpts.index + 1,
539
+ ctx: nextOpts && 'ctx' in nextOpts ? { ...callOpts.ctx,
540
+ ...nextOpts.ctx
541
+ } : callOpts.ctx,
542
+ input: nextOpts && 'input' in nextOpts ? nextOpts.input : callOpts.input
543
+ });
544
+ }
545
+ });
546
+ return result;
547
+ } catch (cause) {
548
+ return {
549
+ ok: false,
550
+ error: TRPCError.getErrorFromUnknown(cause),
551
+ marker: middlewareMarker
552
+ };
553
+ }
554
+ }; // there's always at least one "next" since we wrap this.resolver in a middleware
555
+
556
+
557
+ const result = await callRecursive();
558
+
559
+ if (!result) {
560
+ throw new TRPCError.TRPCError({
561
+ code: 'INTERNAL_SERVER_ERROR',
562
+ message: 'No result from middlewares - did you forget to `return next()`?'
563
+ });
564
+ }
565
+
566
+ if (!result.ok) {
567
+ // re-throw original error
568
+ throw result.error;
569
+ }
570
+
571
+ return result.data;
572
+ };
573
+
574
+ procedure._def = _def;
575
+ procedure.meta = _def.meta;
576
+ return procedure;
577
+ }
578
+
579
+ /**
580
+ * Create an object without inheriting anything from `Object.prototype`
581
+ * @internal
582
+ */
583
+ function omitPrototype(obj1) {
584
+ return Object.assign(Object.create(null), obj1);
585
+ }
586
+
587
+ const procedureTypes = ['query', 'mutation', 'subscription'];
588
+ /**
589
+ * @public
590
+ */
591
+
592
+ /** @internal **/
593
+
594
+ function isRouter(procedureOrRouter) {
595
+ return 'router' in procedureOrRouter._def;
596
+ }
597
+
598
+ const emptyRouter = {
599
+ _ctx: null,
600
+ _errorShape: null,
601
+ _meta: null,
602
+ queries: {},
603
+ mutations: {},
604
+ subscriptions: {},
605
+ errorFormatter: defaultFormatter,
606
+ transformer: defaultTransformer
607
+ };
608
+ /**
609
+ *
610
+ * @internal
611
+ */
612
+
613
+ function createRouterFactory(defaults) {
614
+ return function createRouterInner(opts) {
615
+ var _defaults$transformer, _defaults$errorFormat;
616
+
617
+ const routerProcedures = omitPrototype({});
618
+
619
+ function recursiveGetPaths(procedures, path = '') {
620
+ for (const [key, procedureOrRouter] of Object.entries(procedures !== null && procedures !== void 0 ? procedures : {})) {
621
+ const newPath = `${path}${key}`;
622
+
623
+ if (isRouter(procedureOrRouter)) {
624
+ recursiveGetPaths(procedureOrRouter._def.procedures, `${newPath}.`);
625
+ continue;
626
+ }
627
+
628
+ routerProcedures[newPath] = procedureOrRouter;
629
+ }
630
+ }
631
+
632
+ recursiveGetPaths(opts);
633
+ const result = mergeWithoutOverrides({
634
+ transformer: (_defaults$transformer = defaults === null || defaults === void 0 ? void 0 : defaults.transformer) !== null && _defaults$transformer !== void 0 ? _defaults$transformer : defaultTransformer,
635
+ errorFormatter: (_defaults$errorFormat = defaults === null || defaults === void 0 ? void 0 : defaults.errorFormatter) !== null && _defaults$errorFormat !== void 0 ? _defaults$errorFormat : defaultFormatter
636
+ }, {
637
+ procedures: routerProcedures
638
+ });
639
+ const _def = {
640
+ router: true,
641
+ legacy: {},
642
+ procedures: {},
643
+ ...emptyRouter,
644
+ ...result,
645
+ record: opts,
646
+ queries: Object.entries(result.procedures || {}).filter(pair => pair[1]._def.query).reduce((acc, [key, val]) => ({ ...acc,
647
+ [key]: val
648
+ }), {}),
649
+ mutations: Object.entries(result.procedures || {}).filter(pair => pair[1]._def.mutation).reduce((acc, [key, val]) => ({ ...acc,
650
+ [key]: val
651
+ }), {}),
652
+ subscriptions: Object.entries(result.procedures || {}).filter(pair => pair[1]._def.subscription).reduce((acc, [key, val]) => ({ ...acc,
653
+ [key]: val
654
+ }), {}),
655
+ routers: Object.entries(result.procedures || {}).filter(pair => pair[1]._def._router).reduce((acc, [key, val]) => ({ ...acc,
656
+ [key]: val
657
+ }), {})
658
+ };
659
+ const router = { ...opts,
660
+ _def,
661
+ transformer: _def.transformer,
662
+ errorFormatter: _def.errorFormatter,
663
+
664
+ createCaller(ctx) {
665
+ const proxy = index.createProxy(({
666
+ path,
667
+ args
668
+ }) => {
669
+ // interop mode
670
+ if (path.length === 1 && procedureTypes.includes(path[0])) {
671
+ return callProcedure({
672
+ procedures: _def.procedures,
673
+ path: args[0],
674
+ rawInput: args[1],
675
+ ctx,
676
+ type: path[0]
677
+ });
678
+ }
679
+
680
+ const fullPath = path.join('.');
681
+ const procedure = _def.procedures[fullPath];
682
+ let type = 'query';
683
+
684
+ if (procedure._def.mutation) {
685
+ type = 'mutation';
686
+ } else if (procedure._def.subscription) {
687
+ type = 'subscription';
688
+ }
689
+
690
+ return procedure({
691
+ path: fullPath,
692
+ rawInput: args[0],
693
+ ctx,
694
+ type
695
+ });
696
+ });
697
+ return proxy;
698
+ },
699
+
700
+ getErrorShape(opts) {
701
+ const {
702
+ path,
703
+ error
704
+ } = opts;
705
+ const {
706
+ code
707
+ } = opts.error;
708
+ const shape = {
709
+ message: error.message,
710
+ code: envelopes.TRPC_ERROR_CODES_BY_KEY[code],
711
+ data: {
712
+ code,
713
+ httpStatus: resolveHTTPResponse.getHTTPStatusCodeFromError(error)
714
+ }
715
+ };
716
+
717
+ if (process.env.NODE_ENV !== 'production' && typeof opts.error.stack === 'string') {
718
+ shape.data.stack = opts.error.stack;
719
+ }
720
+
721
+ if (typeof path === 'string') {
722
+ shape.data.path = path;
723
+ }
724
+
725
+ return this._def.errorFormatter({ ...opts,
726
+ shape
727
+ });
728
+ }
729
+
730
+ };
731
+ return router;
732
+ };
733
+ }
734
+ /**
735
+ * @internal
736
+ */
737
+
738
+ function callProcedure(opts) {
739
+ var _opts$procedures$path;
740
+
741
+ const {
742
+ type,
743
+ path
744
+ } = opts;
745
+
746
+ if (!(path in opts.procedures) || !((_opts$procedures$path = opts.procedures[path]) !== null && _opts$procedures$path !== void 0 && _opts$procedures$path._def[type])) {
747
+ throw new TRPCError.TRPCError({
748
+ code: 'NOT_FOUND',
749
+ message: `No "${type}"-procedure on path "${path}"`
750
+ });
751
+ }
752
+
753
+ const procedure = opts.procedures[path];
754
+ return procedure(opts);
755
+ }
756
+
757
+ function migrateProcedure(oldProc, type) {
758
+ const def = oldProc._def();
759
+
760
+ const inputParser = getParseFnOrPassThrough(def.inputParser);
761
+ const outputParser = getParseFnOrPassThrough(def.outputParser);
762
+ const inputMiddleware = createInputMiddleware(inputParser);
763
+ const builder = createBuilder({
764
+ input: def.inputParser,
765
+ middlewares: [...def.middlewares, inputMiddleware, createOutputMiddleware(outputParser)],
766
+ meta: def.meta,
767
+ output: def.outputParser,
768
+ mutation: type === 'mutation',
769
+ query: type === 'query',
770
+ subscription: type === 'subscription'
771
+ });
772
+ const proc = builder[type](opts => def.resolver(opts));
773
+ return proc;
774
+ }
775
+
776
+ function migrateRouter(oldRouter) {
777
+ const errorFormatter = oldRouter._def.errorFormatter;
778
+ const transformer = oldRouter._def.transformer;
779
+ const queries = {};
780
+ const mutations = {};
781
+ const subscriptions = {};
782
+
783
+ for (const [name, procedure] of Object.entries(oldRouter._def.queries)) {
784
+ queries[name] = migrateProcedure(procedure, 'query');
785
+ }
786
+
787
+ for (const [name, procedure] of Object.entries(oldRouter._def.mutations)) {
788
+ mutations[name] = migrateProcedure(procedure, 'mutation');
789
+ }
790
+
791
+ for (const [name, procedure] of Object.entries(oldRouter._def.subscriptions)) {
792
+ subscriptions[name] = migrateProcedure(procedure, 'subscription');
793
+ }
794
+
795
+ const procedures = mergeWithoutOverrides(queries, mutations, subscriptions);
796
+ const newRouter = createRouterFactory({
797
+ transformer,
798
+ errorFormatter
799
+ })(procedures);
800
+ return newRouter;
801
+ }
802
+
803
+ /* eslint-disable @typescript-eslint/no-explicit-any */
804
+ resolveHTTPResponse.assertNotBrowser();
805
+
806
+ function getDataTransformer(transformer) {
807
+ if ('input' in transformer) {
808
+ return transformer;
809
+ }
810
+
811
+ return {
812
+ input: transformer,
813
+ output: transformer
814
+ };
815
+ }
816
+ /**
817
+ * @internal
818
+ * @deprecated
819
+ */
820
+
821
+
822
+ const PROCEDURE_DEFINITION_MAP = {
823
+ query: 'queries',
824
+ mutation: 'mutations',
825
+ subscription: 'subscriptions'
826
+ };
827
+ /**
828
+ * @internal
829
+ * @deprecated
830
+ */
831
+
832
+ function safeObject(...args) {
833
+ return Object.assign(Object.create(null), ...args);
834
+ }
835
+
836
+ /**
837
+ * @internal The type signature of this class may change without warning.
838
+ * @deprecated
839
+ */
840
+ class Router {
841
+ constructor(def) {
842
+ var _def$queries, _def$mutations, _def$subscriptions, _def$middlewares, _def$errorFormatter, _def$transformer;
843
+
844
+ this._def = void 0;
845
+ this._def = {
846
+ queries: (_def$queries = def === null || def === void 0 ? void 0 : def.queries) !== null && _def$queries !== void 0 ? _def$queries : safeObject(),
847
+ mutations: (_def$mutations = def === null || def === void 0 ? void 0 : def.mutations) !== null && _def$mutations !== void 0 ? _def$mutations : safeObject(),
848
+ subscriptions: (_def$subscriptions = def === null || def === void 0 ? void 0 : def.subscriptions) !== null && _def$subscriptions !== void 0 ? _def$subscriptions : safeObject(),
849
+ middlewares: (_def$middlewares = def === null || def === void 0 ? void 0 : def.middlewares) !== null && _def$middlewares !== void 0 ? _def$middlewares : [],
850
+ errorFormatter: (_def$errorFormatter = def === null || def === void 0 ? void 0 : def.errorFormatter) !== null && _def$errorFormatter !== void 0 ? _def$errorFormatter : defaultFormatter,
851
+ transformer: (_def$transformer = def === null || def === void 0 ? void 0 : def.transformer) !== null && _def$transformer !== void 0 ? _def$transformer : defaultTransformer
852
+ };
853
+ }
854
+
855
+ static prefixProcedures(procedures, prefix) {
856
+ const eps = safeObject();
857
+
858
+ for (const [key, procedure] of Object.entries(procedures)) {
859
+ eps[prefix + key] = procedure;
860
+ }
861
+
862
+ return eps;
863
+ }
864
+
865
+ query(path, procedure) {
866
+ const router = new Router({
867
+ queries: safeObject({
868
+ [path]: createProcedure(procedure)
869
+ })
870
+ });
871
+ return this.merge(router);
872
+ }
873
+
874
+ mutation(path, procedure) {
875
+ const router = new Router({
876
+ mutations: safeObject({
877
+ [path]: createProcedure(procedure)
878
+ })
879
+ });
880
+ return this.merge(router);
881
+ }
882
+ /**
883
+ * @beta Might change without a major version bump
884
+ */
885
+
886
+
887
+ subscription(path, procedure) {
888
+ const router = new Router({
889
+ subscriptions: safeObject({
890
+ [path]: createProcedure(procedure)
891
+ })
892
+ });
893
+ return this.merge(router);
894
+ }
895
+ /**
896
+ * Merge router with other router
897
+ * @param router
898
+ */
899
+
900
+
901
+ merge(prefixOrRouter, maybeRouter) {
902
+ let prefix = '';
903
+ let childRouter;
904
+
905
+ if (typeof prefixOrRouter === 'string' && maybeRouter instanceof Router) {
906
+ prefix = prefixOrRouter;
907
+ childRouter = maybeRouter;
908
+ } else if (prefixOrRouter instanceof Router) {
909
+ childRouter = prefixOrRouter;
910
+ }
911
+ /* istanbul ignore next */
912
+ else {
913
+ throw new Error('Invalid args');
914
+ }
915
+
916
+ const duplicateQueries = Object.keys(childRouter._def.queries).filter(key => !!this._def['queries'][prefix + key]);
917
+ const duplicateMutations = Object.keys(childRouter._def.mutations).filter(key => !!this._def['mutations'][prefix + key]);
918
+ const duplicateSubscriptions = Object.keys(childRouter._def.subscriptions).filter(key => !!this._def['subscriptions'][prefix + key]);
919
+ const duplicates = [...duplicateQueries, ...duplicateMutations, ...duplicateSubscriptions];
920
+
921
+ if (duplicates.length) {
922
+ throw new Error(`Duplicate endpoint(s): ${duplicates.join(', ')}`);
923
+ }
924
+
925
+ const mergeProcedures = defs => {
926
+ const newDefs = safeObject();
927
+
928
+ for (const [key, procedure] of Object.entries(defs)) {
929
+ const newProcedure = procedure.inheritMiddlewares(this._def.middlewares);
930
+ newDefs[key] = newProcedure;
931
+ }
932
+
933
+ return Router.prefixProcedures(newDefs, prefix);
934
+ };
935
+
936
+ return new Router({ ...this._def,
937
+ queries: safeObject(this._def.queries, mergeProcedures(childRouter._def.queries)),
938
+ mutations: safeObject(this._def.mutations, mergeProcedures(childRouter._def.mutations)),
939
+ subscriptions: safeObject(this._def.subscriptions, mergeProcedures(childRouter._def.subscriptions))
940
+ });
941
+ }
942
+ /**
943
+ * Invoke procedure. Only for internal use within library.
944
+ */
945
+
946
+
947
+ async call(opts) {
948
+ const {
949
+ type,
950
+ path
951
+ } = opts;
952
+ const defTarget = PROCEDURE_DEFINITION_MAP[type];
953
+ const defs = this._def[defTarget];
954
+ const procedure = defs[path];
955
+
956
+ if (!procedure) {
957
+ throw new TRPCError.TRPCError({
958
+ code: 'NOT_FOUND',
959
+ message: `No "${type}"-procedure on path "${path}"`
960
+ });
961
+ }
962
+
963
+ return procedure.call(opts);
964
+ }
965
+
966
+ createCaller(ctx) {
967
+ return {
968
+ query: (path, ...args) => {
969
+ return this.call({
970
+ type: 'query',
971
+ ctx,
972
+ path,
973
+ rawInput: args[0]
974
+ });
975
+ },
976
+ mutation: (path, ...args) => {
977
+ return this.call({
978
+ type: 'mutation',
979
+ ctx,
980
+ path,
981
+ rawInput: args[0]
982
+ });
983
+ },
984
+ subscription: (path, ...args) => {
985
+ return this.call({
986
+ type: 'subscription',
987
+ ctx,
988
+ path,
989
+ rawInput: args[0]
990
+ });
991
+ }
992
+ };
993
+ }
994
+ /**
995
+ * Function to be called before any procedure is invoked
996
+ * @link https://trpc.io/docs/middlewares
997
+ */
998
+
999
+
1000
+ middleware(middleware) {
1001
+ return new Router({ ...this._def,
1002
+ middlewares: [...this._def.middlewares, middleware]
1003
+ });
1004
+ }
1005
+ /**
1006
+ * Format errors
1007
+ * @link https://trpc.io/docs/error-formatting
1008
+ */
1009
+
1010
+
1011
+ formatError(errorFormatter) {
1012
+ if (this._def.errorFormatter !== defaultFormatter) {
1013
+ throw new Error('You seem to have double `formatError()`-calls in your router tree');
1014
+ }
1015
+
1016
+ return new Router({ ...this._def,
1017
+ errorFormatter: errorFormatter
1018
+ });
1019
+ }
1020
+
1021
+ getErrorShape(opts) {
1022
+ const {
1023
+ path,
1024
+ error
1025
+ } = opts;
1026
+ const {
1027
+ code
1028
+ } = opts.error;
1029
+ const shape = {
1030
+ message: error.message,
1031
+ code: envelopes.TRPC_ERROR_CODES_BY_KEY[code],
1032
+ data: {
1033
+ code,
1034
+ httpStatus: resolveHTTPResponse.getHTTPStatusCodeFromError(error)
1035
+ }
1036
+ };
1037
+
1038
+ if (process.env.NODE_ENV !== 'production' && typeof opts.error.stack === 'string') {
1039
+ shape.data.stack = opts.error.stack;
1040
+ }
1041
+
1042
+ if (typeof path === 'string') {
1043
+ shape.data.path = path;
1044
+ }
1045
+
1046
+ return this._def.errorFormatter({ ...opts,
1047
+ shape
1048
+ });
1049
+ }
1050
+ /**
1051
+ * Add data transformer to serialize/deserialize input args + output
1052
+ * @link https://trpc.io/docs/data-transformers
1053
+ */
1054
+
1055
+
1056
+ transformer(_transformer) {
1057
+ const transformer = getDataTransformer(_transformer);
1058
+
1059
+ if (this._def.transformer !== defaultTransformer) {
1060
+ throw new Error('You seem to have double `transformer()`-calls in your router tree');
1061
+ }
1062
+
1063
+ return new Router({ ...this._def,
1064
+ transformer
1065
+ });
1066
+ }
1067
+ /**
1068
+ * Flattens the generics of TQueries/TMutations/TSubscriptions.
1069
+ * ⚠️ Experimental - might disappear. ⚠️
1070
+ *
1071
+ * @alpha
1072
+ */
1073
+
1074
+
1075
+ flat() {
1076
+ return this;
1077
+ }
1078
+ /**
1079
+ * Interop mode for v9.x -> v10.x
1080
+ */
1081
+
1082
+
1083
+ interop() {
1084
+ return migrateRouter(this);
1085
+ }
1086
+
1087
+ }
1088
+ /**
1089
+ * @deprecated
1090
+ */
1091
+
1092
+ function router() {
1093
+ return new Router();
1094
+ }
1095
+
1096
+ exports.callProcedure = callProcedure;
1097
+ exports.createBuilder = createBuilder;
1098
+ exports.createRouterFactory = createRouterFactory;
1099
+ exports.defaultFormatter = defaultFormatter;
1100
+ exports.defaultTransformer = defaultTransformer;
1101
+ exports.getDataTransformer = getDataTransformer$1;
1102
+ exports.mergeWithoutOverrides = mergeWithoutOverrides;
1103
+ exports.procedureTypes = procedureTypes;
1104
+ exports.router = router;