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

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