@trpc/server 10.0.0-proxy-beta.13 → 10.0.0-proxy-beta.15

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 (63) hide show
  1. package/dist/{TRPCError-281ac25a.mjs → TRPCError-e99e7cbe.mjs} +1 -1
  2. package/dist/adapters/aws-lambda/index.js +2 -3
  3. package/dist/adapters/aws-lambda/index.mjs +3 -4
  4. package/dist/adapters/express.js +3 -3
  5. package/dist/adapters/express.mjs +4 -4
  6. package/dist/adapters/fastify/fastifyRequestHandler.d.ts.map +1 -1
  7. package/dist/adapters/fastify/index.js +2 -3
  8. package/dist/adapters/fastify/index.mjs +3 -4
  9. package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +1 -1
  10. package/dist/adapters/fetch/index.js +2 -3
  11. package/dist/adapters/fetch/index.mjs +3 -4
  12. package/dist/adapters/next.js +3 -3
  13. package/dist/adapters/next.mjs +4 -4
  14. package/dist/adapters/node-http/index.js +3 -3
  15. package/dist/adapters/node-http/index.mjs +4 -4
  16. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
  17. package/dist/adapters/standalone.js +3 -3
  18. package/dist/adapters/standalone.mjs +4 -4
  19. package/dist/adapters/ws.d.ts.map +1 -1
  20. package/dist/adapters/ws.js +10 -3
  21. package/dist/adapters/ws.mjs +11 -4
  22. package/dist/core/initTRPC.d.ts +16 -4
  23. package/dist/core/initTRPC.d.ts.map +1 -1
  24. package/dist/core/internals/config.d.ts +13 -0
  25. package/dist/core/internals/config.d.ts.map +1 -1
  26. package/dist/core/middleware.d.ts +1 -1
  27. package/dist/core/middleware.d.ts.map +1 -1
  28. package/dist/deprecated/internals/procedure.d.ts.map +1 -1
  29. package/dist/deprecated/router.d.ts.map +1 -1
  30. package/dist/http/index.d.ts.map +1 -1
  31. package/dist/index.d.ts +0 -1
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +739 -25
  34. package/dist/index.mjs +724 -9
  35. package/dist/{nodeHTTPRequestHandler-1bf460cc.mjs → nodeHTTPRequestHandler-205f7545.mjs} +2 -3
  36. package/dist/{nodeHTTPRequestHandler-71717219.js → nodeHTTPRequestHandler-efc38711.js} +1 -2
  37. package/dist/resolveHTTPResponse-4ceb1785.mjs +205 -0
  38. package/dist/resolveHTTPResponse-bf4c6ceb.js +207 -0
  39. package/dist/subscription.mjs +1 -1
  40. package/dist/{resolveHTTPResponse-c6e31b55.js → transformTRPCResponse-05aa84c1.js} +22 -201
  41. package/dist/{resolveHTTPResponse-f2b378b6.mjs → transformTRPCResponse-959de787.mjs} +21 -201
  42. package/dist/types.d.ts +9 -2
  43. package/dist/types.d.ts.map +1 -1
  44. package/package.json +6 -6
  45. package/src/adapters/fastify/fastifyRequestHandler.ts +0 -3
  46. package/src/adapters/fetch/fetchRequestHandler.ts +0 -3
  47. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +0 -3
  48. package/src/adapters/ws.ts +13 -3
  49. package/src/core/initTRPC.ts +12 -0
  50. package/src/core/internals/config.ts +19 -0
  51. package/src/core/middleware.ts +1 -1
  52. package/src/deprecated/internals/procedure.ts +0 -3
  53. package/src/deprecated/router.ts +0 -3
  54. package/src/http/index.ts +0 -4
  55. package/src/index.ts +0 -1
  56. package/src/types.ts +28 -7
  57. package/dist/assertNotBrowser.d.ts +0 -2
  58. package/dist/assertNotBrowser.d.ts.map +0 -1
  59. package/dist/router-15f9618e.js +0 -724
  60. package/dist/router-28a2c129.mjs +0 -718
  61. package/dist/transformTRPCResponse-11ac69cc.js +0 -27
  62. package/dist/transformTRPCResponse-c8138d5f.mjs +0 -25
  63. package/src/assertNotBrowser.ts +0 -12
package/dist/index.js CHANGED
@@ -2,34 +2,98 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var resolveHTTPResponse = require('./resolveHTTPResponse-c6e31b55.js');
6
- var router = require('./router-15f9618e.js');
5
+ var resolveHTTPResponse = require('./resolveHTTPResponse-bf4c6ceb.js');
6
+ var transformTRPCResponse = require('./transformTRPCResponse-05aa84c1.js');
7
7
  var TRPCError = require('./TRPCError-fe9113e5.js');
8
- require('./codes-76c38a34.js');
8
+ var codes = require('./codes-76c38a34.js');
9
9
  require('./index-62d46c97.js');
10
- require('./transformTRPCResponse-11ac69cc.js');
10
+
11
+ /**
12
+ * @internal
13
+ */ // FIXME this should use RootConfig
14
+ function createMiddlewareFactory() {
15
+ return function createMiddleware(fn) {
16
+ return fn;
17
+ };
18
+ }
19
+ function isPlainObject(obj) {
20
+ return obj && typeof obj === 'object' && !Array.isArray(obj);
21
+ }
22
+ /**
23
+ * @internal
24
+ * Please note, `trpc-openapi` uses this function.
25
+ */ function createInputMiddleware(parse) {
26
+ const inputMiddleware = async ({ next , rawInput , input , })=>{
27
+ let parsedInput;
28
+ try {
29
+ parsedInput = await parse(rawInput);
30
+ } catch (cause) {
31
+ throw new TRPCError.TRPCError({
32
+ code: 'BAD_REQUEST',
33
+ cause: TRPCError.getCauseFromUnknown(cause)
34
+ });
35
+ }
36
+ // Multiple input parsers
37
+ const combinedInput = isPlainObject(input) && isPlainObject(parsedInput) ? {
38
+ ...input,
39
+ ...parsedInput
40
+ } : parsedInput;
41
+ // TODO fix this typing?
42
+ return next({
43
+ input: combinedInput
44
+ });
45
+ };
46
+ inputMiddleware._type = 'input';
47
+ return inputMiddleware;
48
+ }
49
+ /**
50
+ * @internal
51
+ */ function createOutputMiddleware(parse) {
52
+ const outputMiddleware = async ({ next })=>{
53
+ const result = await next();
54
+ if (!result.ok) {
55
+ // pass through failures without validating
56
+ return result;
57
+ }
58
+ try {
59
+ const data = await parse(result.data);
60
+ return {
61
+ ...result,
62
+ data
63
+ };
64
+ } catch (cause) {
65
+ throw new TRPCError.TRPCError({
66
+ message: 'Output validation failed',
67
+ code: 'INTERNAL_SERVER_ERROR',
68
+ cause: TRPCError.getCauseFromUnknown(cause)
69
+ });
70
+ }
71
+ };
72
+ outputMiddleware._type = 'output';
73
+ return outputMiddleware;
74
+ }
11
75
 
12
76
  function mergeRouters(...routerList) {
13
- const record = resolveHTTPResponse.mergeWithoutOverrides({}, ...routerList.map((r)=>r._def.record));
77
+ const record = transformTRPCResponse.mergeWithoutOverrides({}, ...routerList.map((r)=>r._def.record));
14
78
  const errorFormatter = routerList.reduce((currentErrorFormatter, nextRouter)=>{
15
- if (nextRouter.errorFormatter && nextRouter.errorFormatter !== resolveHTTPResponse.defaultFormatter) {
16
- if (currentErrorFormatter !== resolveHTTPResponse.defaultFormatter && currentErrorFormatter !== nextRouter.errorFormatter) {
79
+ if (nextRouter.errorFormatter && nextRouter.errorFormatter !== transformTRPCResponse.defaultFormatter) {
80
+ if (currentErrorFormatter !== transformTRPCResponse.defaultFormatter && currentErrorFormatter !== nextRouter.errorFormatter) {
17
81
  throw new Error('You seem to have several error formatters');
18
82
  }
19
83
  return nextRouter.errorFormatter;
20
84
  }
21
85
  return currentErrorFormatter;
22
- }, resolveHTTPResponse.defaultFormatter);
86
+ }, transformTRPCResponse.defaultFormatter);
23
87
  const transformer = routerList.reduce((prev, current)=>{
24
- if (current.transformer && current.transformer !== resolveHTTPResponse.defaultTransformer) {
25
- if (prev !== resolveHTTPResponse.defaultTransformer && prev !== current.transformer) {
88
+ if (current.transformer && current.transformer !== transformTRPCResponse.defaultTransformer) {
89
+ if (prev !== transformTRPCResponse.defaultTransformer && prev !== current.transformer) {
26
90
  throw new Error('You seem to have several transformers');
27
91
  }
28
92
  return current.transformer;
29
93
  }
30
94
  return prev;
31
- }, resolveHTTPResponse.defaultTransformer);
32
- const router = resolveHTTPResponse.createRouterFactory({
95
+ }, transformTRPCResponse.defaultTransformer);
96
+ const router = transformTRPCResponse.createRouterFactory({
33
97
  errorFormatter,
34
98
  transformer
35
99
  })(record);
@@ -40,6 +104,208 @@ function mergeRoutersGeneric(...args) {
40
104
  return mergeRouters(...args);
41
105
  }
42
106
 
107
+ function getParseFn$1(procedureParser) {
108
+ const parser = procedureParser;
109
+ if (typeof parser === 'function') {
110
+ // ProcedureParserCustomValidatorEsque
111
+ return parser;
112
+ }
113
+ if (typeof parser.parseAsync === 'function') {
114
+ // ProcedureParserZodEsque
115
+ return parser.parseAsync.bind(parser);
116
+ }
117
+ if (typeof parser.parse === 'function') {
118
+ // ProcedureParserZodEsque
119
+ return parser.parse.bind(parser);
120
+ }
121
+ if (typeof parser.validateSync === 'function') {
122
+ // ProcedureParserYupEsque
123
+ return parser.validateSync.bind(parser);
124
+ }
125
+ if (typeof parser.create === 'function') {
126
+ // ProcedureParserSuperstructEsque
127
+ return parser.create.bind(parser);
128
+ }
129
+ throw new Error('Could not find a validator fn');
130
+ }
131
+ /**
132
+ * @deprecated only for backwards compat
133
+ * @internal
134
+ */ function getParseFnOrPassThrough(procedureParser) {
135
+ if (!procedureParser) {
136
+ return (v)=>v;
137
+ }
138
+ return getParseFn$1(procedureParser);
139
+ }
140
+
141
+ /**
142
+ * @internal
143
+ */ const middlewareMarker$1 = 'middlewareMarker';
144
+
145
+ function createNewBuilder(def1, def2) {
146
+ const { middlewares =[] , inputs , ...rest } = def2;
147
+ // TODO: maybe have a fn here to warn about calls
148
+ return createBuilder({
149
+ ...transformTRPCResponse.mergeWithoutOverrides(def1, rest),
150
+ inputs: [
151
+ ...def1.inputs,
152
+ ...inputs ?? []
153
+ ],
154
+ middlewares: [
155
+ ...def1.middlewares,
156
+ ...middlewares
157
+ ]
158
+ });
159
+ }
160
+ function createBuilder(initDef) {
161
+ const _def = initDef || {
162
+ inputs: [],
163
+ middlewares: []
164
+ };
165
+ return {
166
+ _def,
167
+ input (input) {
168
+ const parser = getParseFn$1(input);
169
+ return createNewBuilder(_def, {
170
+ inputs: [
171
+ input
172
+ ],
173
+ middlewares: [
174
+ createInputMiddleware(parser)
175
+ ]
176
+ });
177
+ },
178
+ output (output) {
179
+ const parseOutput = getParseFn$1(output);
180
+ return createNewBuilder(_def, {
181
+ output,
182
+ middlewares: [
183
+ createOutputMiddleware(parseOutput)
184
+ ]
185
+ });
186
+ },
187
+ meta (meta) {
188
+ return createNewBuilder(_def, {
189
+ meta: meta
190
+ });
191
+ },
192
+ unstable_concat (builder) {
193
+ return createNewBuilder(_def, builder._def);
194
+ },
195
+ use (middleware) {
196
+ return createNewBuilder(_def, {
197
+ middlewares: [
198
+ middleware
199
+ ]
200
+ });
201
+ },
202
+ query (resolver) {
203
+ return createResolver({
204
+ ..._def,
205
+ query: true
206
+ }, resolver);
207
+ },
208
+ mutation (resolver) {
209
+ return createResolver({
210
+ ..._def,
211
+ mutation: true
212
+ }, resolver);
213
+ },
214
+ subscription (resolver) {
215
+ return createResolver({
216
+ ..._def,
217
+ subscription: true
218
+ }, resolver);
219
+ }
220
+ };
221
+ }
222
+ function createResolver(_def, resolver) {
223
+ const finalBuilder = createNewBuilder(_def, {
224
+ resolver,
225
+ middlewares: [
226
+ async function resolveMiddleware(opts) {
227
+ const data = await resolver(opts);
228
+ return {
229
+ marker: middlewareMarker$1,
230
+ ok: true,
231
+ data,
232
+ ctx: opts.ctx
233
+ };
234
+ }
235
+ ]
236
+ });
237
+ return createProcedureCaller(finalBuilder._def);
238
+ }
239
+ const codeblock = `
240
+ If you want to call this function on the server, you do the following:
241
+ This is a client-only function.
242
+
243
+ const caller = appRouter.createCaller({
244
+ /* ... your context */
245
+ });
246
+
247
+ const result = await caller.call('myProcedure', input);
248
+ `.trim();
249
+ function createProcedureCaller(_def) {
250
+ const procedure = async function resolve(opts) {
251
+ // is direct server-side call
252
+ if (!opts || !('rawInput' in opts)) {
253
+ throw new Error(codeblock);
254
+ }
255
+ // run the middlewares recursively with the resolver as the last one
256
+ const callRecursive = async (callOpts = {
257
+ index: 0,
258
+ ctx: opts.ctx
259
+ })=>{
260
+ try {
261
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
262
+ const middleware = _def.middlewares[callOpts.index];
263
+ const result = await middleware({
264
+ ctx: callOpts.ctx,
265
+ type: opts.type,
266
+ path: opts.path,
267
+ rawInput: opts.rawInput,
268
+ meta: _def.meta,
269
+ input: callOpts.input,
270
+ next: async (nextOpts)=>{
271
+ return await callRecursive({
272
+ index: callOpts.index + 1,
273
+ ctx: nextOpts && 'ctx' in nextOpts ? {
274
+ ...callOpts.ctx,
275
+ ...nextOpts.ctx
276
+ } : callOpts.ctx,
277
+ input: nextOpts && 'input' in nextOpts ? nextOpts.input : callOpts.input
278
+ });
279
+ }
280
+ });
281
+ return result;
282
+ } catch (cause) {
283
+ return {
284
+ ok: false,
285
+ error: TRPCError.getTRPCErrorFromUnknown(cause),
286
+ marker: middlewareMarker$1
287
+ };
288
+ }
289
+ };
290
+ // there's always at least one "next" since we wrap this.resolver in a middleware
291
+ const result = await callRecursive();
292
+ if (!result) {
293
+ throw new TRPCError.TRPCError({
294
+ code: 'INTERNAL_SERVER_ERROR',
295
+ message: 'No result from middlewares - did you forget to `return next()`?'
296
+ });
297
+ }
298
+ if (!result.ok) {
299
+ // re-throw original error
300
+ throw result.error;
301
+ }
302
+ return result.data;
303
+ };
304
+ procedure._def = _def;
305
+ procedure.meta = _def.meta;
306
+ return procedure;
307
+ }
308
+
43
309
  /**
44
310
  * TODO: This can be improved:
45
311
  * - We should be able to chain `.meta()`/`.context()` only once
@@ -61,8 +327,15 @@ function mergeRoutersGeneric(...args) {
61
327
  */ const initTRPC = new TRPCBuilder();
62
328
  function createTRPCInner() {
63
329
  return function initTRPCInner(options) {
64
- const errorFormatter = options?.errorFormatter ?? resolveHTTPResponse.defaultFormatter;
65
- const transformer = resolveHTTPResponse.getDataTransformer(options?.transformer ?? resolveHTTPResponse.defaultTransformer);
330
+ {
331
+ // Server check
332
+ const isServer = options?.isServer ?? transformTRPCResponse.isServerDefault;
333
+ if (!isServer && options?.allowOutsideOfServer !== true) {
334
+ throw new Error(`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`);
335
+ }
336
+ }
337
+ const errorFormatter = options?.errorFormatter ?? transformTRPCResponse.defaultFormatter;
338
+ const transformer = transformTRPCResponse.getDataTransformer(options?.transformer ?? transformTRPCResponse.defaultTransformer);
66
339
  const _config = {
67
340
  transformer,
68
341
  errorShape: null,
@@ -76,13 +349,13 @@ function createTRPCInner() {
76
349
  */ _config,
77
350
  /**
78
351
  * Builder object for creating procedures
79
- */ procedure: router.createBuilder(),
352
+ */ procedure: createBuilder(),
80
353
  /**
81
354
  * Create reusable middlewares
82
- */ middleware: router.createMiddlewareFactory(),
355
+ */ middleware: createMiddlewareFactory(),
83
356
  /**
84
357
  * Create a router
85
- */ router: resolveHTTPResponse.createRouterFactory({
358
+ */ router: transformTRPCResponse.createRouterFactory({
86
359
  errorFormatter,
87
360
  transformer
88
361
  }),
@@ -93,14 +366,455 @@ function createTRPCInner() {
93
366
  };
94
367
  }
95
368
 
96
- exports.assertNotBrowser = resolveHTTPResponse.assertNotBrowser;
97
- exports.callProcedure = resolveHTTPResponse.callProcedure;
98
- exports.defaultTransformer = resolveHTTPResponse.defaultTransformer;
99
- exports.getDataTransformer = resolveHTTPResponse.getDataTransformer;
100
- exports.procedureTypes = resolveHTTPResponse.procedureTypes;
369
+ /**
370
+ * @deprecated
371
+ */ const middlewareMarker = 'middlewareMarker';
372
+
373
+ function getParseFn(procedureParser) {
374
+ const parser = procedureParser;
375
+ if (typeof parser === 'function') {
376
+ // ProcedureParserCustomValidatorEsque
377
+ return parser;
378
+ }
379
+ if (typeof parser.parseAsync === 'function') {
380
+ // ProcedureParserZodEsque
381
+ return parser.parseAsync.bind(parser);
382
+ }
383
+ if (typeof parser.parse === 'function') {
384
+ // ProcedureParserZodEsque
385
+ return parser.parse.bind(parser);
386
+ }
387
+ if (typeof parser.validateSync === 'function') {
388
+ // ProcedureParserYupEsque
389
+ return parser.validateSync.bind(parser);
390
+ }
391
+ if (typeof parser.create === 'function') {
392
+ // ProcedureParserSuperstructEsque
393
+ return parser.create.bind(parser);
394
+ }
395
+ throw new Error('Could not find a validator fn');
396
+ }
397
+ /**
398
+ * @internal
399
+ * @deprecated
400
+ */ class Procedure {
401
+ _def() {
402
+ return {
403
+ middlewares: this.middlewares,
404
+ resolver: this.resolver,
405
+ inputParser: this.inputParser,
406
+ outputParser: this.outputParser,
407
+ meta: this.meta
408
+ };
409
+ }
410
+ async parseInput(rawInput) {
411
+ try {
412
+ return await this.parseInputFn(rawInput);
413
+ } catch (cause) {
414
+ throw new TRPCError.TRPCError({
415
+ code: 'BAD_REQUEST',
416
+ cause: TRPCError.getCauseFromUnknown(cause)
417
+ });
418
+ }
419
+ }
420
+ async parseOutput(rawOutput) {
421
+ try {
422
+ return await this.parseOutputFn(rawOutput);
423
+ } catch (cause) {
424
+ throw new TRPCError.TRPCError({
425
+ code: 'INTERNAL_SERVER_ERROR',
426
+ cause: TRPCError.getCauseFromUnknown(cause),
427
+ message: 'Output validation failed'
428
+ });
429
+ }
430
+ }
431
+ /**
432
+ * Trigger middlewares in order, parse raw input, call resolver & parse raw output
433
+ * @internal
434
+ */ async call(opts) {
435
+ // wrap the actual resolver and treat as the last "middleware"
436
+ const middlewaresWithResolver = this.middlewares.concat([
437
+ async ({ ctx })=>{
438
+ const input = await this.parseInput(opts.rawInput);
439
+ const rawOutput = await this.resolver({
440
+ ...opts,
441
+ ctx,
442
+ input
443
+ });
444
+ const data = await this.parseOutput(rawOutput);
445
+ return {
446
+ marker: middlewareMarker,
447
+ ok: true,
448
+ data,
449
+ ctx
450
+ };
451
+ }
452
+ ]);
453
+ // run the middlewares recursively with the resolver as the last one
454
+ const callRecursive = async (callOpts = {
455
+ index: 0,
456
+ ctx: opts.ctx
457
+ })=>{
458
+ try {
459
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
460
+ const result = await middlewaresWithResolver[callOpts.index]({
461
+ ctx: callOpts.ctx,
462
+ type: opts.type,
463
+ path: opts.path,
464
+ rawInput: opts.rawInput,
465
+ meta: this.meta,
466
+ next: async (nextOpts)=>{
467
+ return await callRecursive({
468
+ index: callOpts.index + 1,
469
+ ctx: nextOpts ? nextOpts.ctx : callOpts.ctx
470
+ });
471
+ }
472
+ });
473
+ return result;
474
+ } catch (cause) {
475
+ return {
476
+ ctx: callOpts.ctx,
477
+ ok: false,
478
+ error: TRPCError.getTRPCErrorFromUnknown(cause),
479
+ marker: middlewareMarker
480
+ };
481
+ }
482
+ };
483
+ // there's always at least one "next" since we wrap this.resolver in a middleware
484
+ const result = await callRecursive();
485
+ if (!result) {
486
+ throw new TRPCError.TRPCError({
487
+ code: 'INTERNAL_SERVER_ERROR',
488
+ message: 'No result from middlewares - did you forget to `return next()`?'
489
+ });
490
+ }
491
+ if (!result.ok) {
492
+ // re-throw original error
493
+ throw result.error;
494
+ }
495
+ return result.data;
496
+ }
497
+ /**
498
+ * Create new procedure with passed middlewares
499
+ * @param middlewares
500
+ */ inheritMiddlewares(middlewares) {
501
+ const Constructor = this.constructor;
502
+ const instance = new Constructor({
503
+ middlewares: [
504
+ ...middlewares,
505
+ ...this.middlewares
506
+ ],
507
+ resolver: this.resolver,
508
+ inputParser: this.inputParser,
509
+ outputParser: this.outputParser,
510
+ meta: this.meta
511
+ });
512
+ return instance;
513
+ }
514
+ constructor(opts){
515
+ this.middlewares = opts.middlewares;
516
+ this.resolver = opts.resolver;
517
+ this.inputParser = opts.inputParser;
518
+ this.parseInputFn = getParseFn(this.inputParser);
519
+ this.outputParser = opts.outputParser;
520
+ this.parseOutputFn = getParseFn(this.outputParser);
521
+ this.meta = opts.meta;
522
+ }
523
+ }
524
+ function createProcedure(opts) {
525
+ const inputParser = 'input' in opts ? opts.input : (input)=>{
526
+ if (input != null) {
527
+ throw new TRPCError.TRPCError({
528
+ code: 'BAD_REQUEST',
529
+ message: 'No input expected'
530
+ });
531
+ }
532
+ return undefined;
533
+ };
534
+ const outputParser = 'output' in opts && opts.output ? opts.output : (output)=>output;
535
+ return new Procedure({
536
+ inputParser: inputParser,
537
+ resolver: opts.resolve,
538
+ middlewares: [],
539
+ outputParser: outputParser,
540
+ meta: opts.meta
541
+ });
542
+ }
543
+
544
+ function migrateProcedure(oldProc, type) {
545
+ const def = oldProc._def();
546
+ const inputParser = getParseFnOrPassThrough(def.inputParser);
547
+ const outputParser = getParseFnOrPassThrough(def.outputParser);
548
+ const inputMiddleware = createInputMiddleware(inputParser);
549
+ const builder = createBuilder({
550
+ inputs: [
551
+ def.inputParser
552
+ ],
553
+ middlewares: [
554
+ ...def.middlewares,
555
+ inputMiddleware,
556
+ createOutputMiddleware(outputParser)
557
+ ],
558
+ meta: def.meta,
559
+ output: def.outputParser,
560
+ mutation: type === 'mutation',
561
+ query: type === 'query',
562
+ subscription: type === 'subscription'
563
+ });
564
+ const proc = builder[type]((opts)=>def.resolver(opts));
565
+ return proc;
566
+ }
567
+ function migrateRouter(oldRouter) {
568
+ const errorFormatter = oldRouter._def.errorFormatter;
569
+ const transformer = oldRouter._def.transformer;
570
+ const queries = {};
571
+ const mutations = {};
572
+ const subscriptions = {};
573
+ for (const [name, procedure] of Object.entries(oldRouter._def.queries)){
574
+ queries[name] = migrateProcedure(procedure, 'query');
575
+ }
576
+ for (const [name1, procedure1] of Object.entries(oldRouter._def.mutations)){
577
+ mutations[name1] = migrateProcedure(procedure1, 'mutation');
578
+ }
579
+ for (const [name2, procedure2] of Object.entries(oldRouter._def.subscriptions)){
580
+ subscriptions[name2] = migrateProcedure(procedure2, 'subscription');
581
+ }
582
+ const procedures = transformTRPCResponse.mergeWithoutOverrides(queries, mutations, subscriptions);
583
+ const newRouter = transformTRPCResponse.createRouterFactory({
584
+ transformer,
585
+ errorFormatter
586
+ })(procedures);
587
+ return newRouter;
588
+ }
589
+
590
+ function getDataTransformer(transformer) {
591
+ if ('input' in transformer) {
592
+ return transformer;
593
+ }
594
+ return {
595
+ input: transformer,
596
+ output: transformer
597
+ };
598
+ }
599
+ const PROCEDURE_DEFINITION_MAP = {
600
+ query: 'queries',
601
+ mutation: 'mutations',
602
+ subscription: 'subscriptions'
603
+ };
604
+ function safeObject(...args) {
605
+ return Object.assign(Object.create(null), ...args);
606
+ }
607
+ /**
608
+ * @internal The type signature of this class may change without warning.
609
+ * @deprecated
610
+ */ class Router {
611
+ static prefixProcedures(procedures, prefix) {
612
+ const eps = safeObject();
613
+ for (const [key, procedure] of Object.entries(procedures)){
614
+ eps[prefix + key] = procedure;
615
+ }
616
+ return eps;
617
+ }
618
+ query(path, procedure) {
619
+ const router = new Router({
620
+ queries: safeObject({
621
+ [path]: createProcedure(procedure)
622
+ })
623
+ });
624
+ return this.merge(router);
625
+ }
626
+ mutation(path, procedure) {
627
+ const router = new Router({
628
+ mutations: safeObject({
629
+ [path]: createProcedure(procedure)
630
+ })
631
+ });
632
+ return this.merge(router);
633
+ }
634
+ subscription(path, procedure) {
635
+ const router = new Router({
636
+ subscriptions: safeObject({
637
+ [path]: createProcedure(procedure)
638
+ })
639
+ });
640
+ return this.merge(router);
641
+ }
642
+ merge(prefixOrRouter, maybeRouter) {
643
+ let prefix = '';
644
+ let childRouter;
645
+ if (typeof prefixOrRouter === 'string' && maybeRouter instanceof Router) {
646
+ prefix = prefixOrRouter;
647
+ childRouter = maybeRouter;
648
+ } else if (prefixOrRouter instanceof Router) {
649
+ childRouter = prefixOrRouter;
650
+ } else {
651
+ throw new Error('Invalid args');
652
+ }
653
+ const duplicateQueries = Object.keys(childRouter._def.queries).filter((key)=>!!this._def['queries'][prefix + key]);
654
+ const duplicateMutations = Object.keys(childRouter._def.mutations).filter((key)=>!!this._def['mutations'][prefix + key]);
655
+ const duplicateSubscriptions = Object.keys(childRouter._def.subscriptions).filter((key)=>!!this._def['subscriptions'][prefix + key]);
656
+ const duplicates = [
657
+ ...duplicateQueries,
658
+ ...duplicateMutations,
659
+ ...duplicateSubscriptions
660
+ ];
661
+ if (duplicates.length) {
662
+ throw new Error(`Duplicate endpoint(s): ${duplicates.join(', ')}`);
663
+ }
664
+ const mergeProcedures = (defs)=>{
665
+ const newDefs = safeObject();
666
+ for (const [key, procedure] of Object.entries(defs)){
667
+ const newProcedure = procedure.inheritMiddlewares(this._def.middlewares);
668
+ newDefs[key] = newProcedure;
669
+ }
670
+ return Router.prefixProcedures(newDefs, prefix);
671
+ };
672
+ return new Router({
673
+ ...this._def,
674
+ queries: safeObject(this._def.queries, mergeProcedures(childRouter._def.queries)),
675
+ mutations: safeObject(this._def.mutations, mergeProcedures(childRouter._def.mutations)),
676
+ subscriptions: safeObject(this._def.subscriptions, mergeProcedures(childRouter._def.subscriptions))
677
+ });
678
+ }
679
+ /**
680
+ * Invoke procedure. Only for internal use within library.
681
+ */ async call(opts) {
682
+ const { type , path } = opts;
683
+ const defTarget = PROCEDURE_DEFINITION_MAP[type];
684
+ const defs = this._def[defTarget];
685
+ const procedure = defs[path];
686
+ if (!procedure) {
687
+ throw new TRPCError.TRPCError({
688
+ code: 'NOT_FOUND',
689
+ message: `No "${type}"-procedure on path "${path}"`
690
+ });
691
+ }
692
+ return procedure.call(opts);
693
+ }
694
+ createCaller(ctx) {
695
+ return {
696
+ query: (path, ...args)=>{
697
+ return this.call({
698
+ type: 'query',
699
+ ctx,
700
+ path,
701
+ rawInput: args[0]
702
+ });
703
+ },
704
+ mutation: (path, ...args)=>{
705
+ return this.call({
706
+ type: 'mutation',
707
+ ctx,
708
+ path,
709
+ rawInput: args[0]
710
+ });
711
+ },
712
+ subscription: (path, ...args)=>{
713
+ return this.call({
714
+ type: 'subscription',
715
+ ctx,
716
+ path,
717
+ rawInput: args[0]
718
+ });
719
+ }
720
+ };
721
+ }
722
+ /**
723
+ * Function to be called before any procedure is invoked
724
+ * @link https://trpc.io/docs/middlewares
725
+ */ middleware(middleware) {
726
+ return new Router({
727
+ ...this._def,
728
+ middlewares: [
729
+ ...this._def.middlewares,
730
+ middleware
731
+ ]
732
+ });
733
+ }
734
+ /**
735
+ * Format errors
736
+ * @link https://trpc.io/docs/error-formatting
737
+ */ formatError(errorFormatter) {
738
+ if (this._def.errorFormatter !== transformTRPCResponse.defaultFormatter) {
739
+ throw new Error('You seem to have double `formatError()`-calls in your router tree');
740
+ }
741
+ return new Router({
742
+ ...this._def,
743
+ errorFormatter: errorFormatter
744
+ });
745
+ }
746
+ getErrorShape(opts) {
747
+ const { path , error } = opts;
748
+ const { code } = opts.error;
749
+ const shape = {
750
+ message: error.message,
751
+ code: codes.TRPC_ERROR_CODES_BY_KEY[code],
752
+ data: {
753
+ code,
754
+ httpStatus: transformTRPCResponse.getHTTPStatusCodeFromError(error)
755
+ }
756
+ };
757
+ if (process.env.NODE_ENV !== 'production' && typeof opts.error.stack === 'string') {
758
+ shape.data.stack = opts.error.stack;
759
+ }
760
+ if (typeof path === 'string') {
761
+ shape.data.path = path;
762
+ }
763
+ return this._def.errorFormatter({
764
+ ...opts,
765
+ shape
766
+ });
767
+ }
768
+ /**
769
+ * Add data transformer to serialize/deserialize input args + output
770
+ * @link https://trpc.io/docs/data-transformers
771
+ */ transformer(_transformer) {
772
+ const transformer = getDataTransformer(_transformer);
773
+ if (this._def.transformer !== transformTRPCResponse.defaultTransformer) {
774
+ throw new Error('You seem to have double `transformer()`-calls in your router tree');
775
+ }
776
+ return new Router({
777
+ ...this._def,
778
+ transformer
779
+ });
780
+ }
781
+ /**
782
+ * Flattens the generics of TQueries/TMutations/TSubscriptions.
783
+ * ⚠️ Experimental - might disappear. ⚠️
784
+ *
785
+ * @alpha
786
+ */ flat() {
787
+ return this;
788
+ }
789
+ /**
790
+ * Interop mode for v9.x -> v10.x
791
+ */ interop() {
792
+ return migrateRouter(this);
793
+ }
794
+ constructor(def){
795
+ this._def = {
796
+ queries: def?.queries ?? safeObject(),
797
+ mutations: def?.mutations ?? safeObject(),
798
+ subscriptions: def?.subscriptions ?? safeObject(),
799
+ middlewares: def?.middlewares ?? [],
800
+ errorFormatter: def?.errorFormatter ?? transformTRPCResponse.defaultFormatter,
801
+ transformer: def?.transformer ?? transformTRPCResponse.defaultTransformer
802
+ };
803
+ }
804
+ }
805
+ /**
806
+ * @deprecated
807
+ */ function router() {
808
+ return new Router();
809
+ }
810
+
101
811
  exports.resolveHTTPResponse = resolveHTTPResponse.resolveHTTPResponse;
102
- exports.createInputMiddleware = router.createInputMiddleware;
103
- exports.createOutputMiddleware = router.createOutputMiddleware;
104
- exports.router = router.router;
812
+ exports.callProcedure = transformTRPCResponse.callProcedure;
813
+ exports.defaultTransformer = transformTRPCResponse.defaultTransformer;
814
+ exports.getDataTransformer = transformTRPCResponse.getDataTransformer;
815
+ exports.procedureTypes = transformTRPCResponse.procedureTypes;
105
816
  exports.TRPCError = TRPCError.TRPCError;
817
+ exports.createInputMiddleware = createInputMiddleware;
818
+ exports.createOutputMiddleware = createOutputMiddleware;
106
819
  exports.initTRPC = initTRPC;
820
+ exports.router = router;