@trpc/server 11.0.0-rc.348 → 11.0.0-rc.354

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 (160) hide show
  1. package/dist/@trpc/server/http.d.ts +1 -0
  2. package/dist/@trpc/server/http.d.ts.map +1 -1
  3. package/dist/@trpc/server/index.d.ts +1 -2
  4. package/dist/@trpc/server/index.d.ts.map +1 -1
  5. package/dist/adapters/aws-lambda/index.d.ts.map +1 -1
  6. package/dist/adapters/aws-lambda/index.js +9 -19
  7. package/dist/adapters/aws-lambda/index.mjs +9 -19
  8. package/dist/adapters/aws-lambda/utils.d.ts +12 -3
  9. package/dist/adapters/aws-lambda/utils.d.ts.map +1 -1
  10. package/dist/adapters/aws-lambda/utils.js +1 -12
  11. package/dist/adapters/aws-lambda/utils.mjs +2 -12
  12. package/dist/adapters/express.d.ts.map +1 -1
  13. package/dist/adapters/express.js +1 -0
  14. package/dist/adapters/express.mjs +1 -0
  15. package/dist/adapters/fastify/fastifyRequestHandler.d.ts +9 -1
  16. package/dist/adapters/fastify/fastifyRequestHandler.d.ts.map +1 -1
  17. package/dist/adapters/fastify/fastifyRequestHandler.js +2 -10
  18. package/dist/adapters/fastify/fastifyRequestHandler.mjs +2 -10
  19. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts +1 -1
  20. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts.map +1 -1
  21. package/dist/adapters/fetch/fetchRequestHandler.d.ts +5 -1
  22. package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +1 -1
  23. package/dist/adapters/fetch/fetchRequestHandler.js +2 -16
  24. package/dist/adapters/fetch/fetchRequestHandler.mjs +2 -16
  25. package/dist/adapters/fetch/types.d.ts +12 -9
  26. package/dist/adapters/fetch/types.d.ts.map +1 -1
  27. package/dist/adapters/next-app-dir/nextAppDirCaller.d.ts +7 -2
  28. package/dist/adapters/next-app-dir/nextAppDirCaller.d.ts.map +1 -1
  29. package/dist/adapters/next.d.ts.map +1 -1
  30. package/dist/adapters/next.js +1 -0
  31. package/dist/adapters/next.mjs +1 -0
  32. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts +73 -0
  33. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts.map +1 -0
  34. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.js +161 -0
  35. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.mjs +157 -0
  36. package/dist/adapters/node-http/content-type/form-data/index.d.ts +25 -4
  37. package/dist/adapters/node-http/content-type/form-data/index.d.ts.map +1 -1
  38. package/dist/adapters/node-http/content-type/form-data/index.js +128 -25
  39. package/dist/adapters/node-http/content-type/form-data/index.mjs +103 -25
  40. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts +31 -0
  41. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts.map +1 -0
  42. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.js +29 -0
  43. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.mjs +27 -0
  44. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts +16 -0
  45. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts.map +1 -0
  46. package/dist/adapters/node-http/content-type/form-data/streamSlice.js +46 -0
  47. package/dist/adapters/node-http/content-type/form-data/streamSlice.mjs +44 -0
  48. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts +45 -0
  49. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts.map +1 -0
  50. package/dist/adapters/node-http/content-type/form-data/uploadHandler.js +30 -0
  51. package/dist/adapters/node-http/content-type/form-data/uploadHandler.mjs +26 -0
  52. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts.map +1 -1
  53. package/dist/adapters/node-http/content-type/json/getPostBody.js +12 -4
  54. package/dist/adapters/node-http/content-type/json/getPostBody.mjs +12 -4
  55. package/dist/adapters/node-http/content-type/json/index.d.ts +1 -4
  56. package/dist/adapters/node-http/content-type/json/index.d.ts.map +1 -1
  57. package/dist/adapters/node-http/content-type/json/index.js +10 -59
  58. package/dist/adapters/node-http/content-type/json/index.mjs +10 -59
  59. package/dist/adapters/node-http/internals/contentType.d.ts +9 -0
  60. package/dist/adapters/node-http/internals/contentType.d.ts.map +1 -0
  61. package/dist/adapters/node-http/internals/contentType.js +8 -0
  62. package/dist/adapters/node-http/internals/contentType.mjs +6 -0
  63. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
  64. package/dist/adapters/node-http/nodeHTTPRequestHandler.js +21 -19
  65. package/dist/adapters/node-http/nodeHTTPRequestHandler.mjs +22 -20
  66. package/dist/adapters/node-http/types.d.ts +19 -8
  67. package/dist/adapters/node-http/types.d.ts.map +1 -1
  68. package/dist/adapters/standalone.d.ts.map +1 -1
  69. package/dist/adapters/standalone.js +1 -0
  70. package/dist/adapters/standalone.mjs +1 -0
  71. package/dist/adapters/ws.d.ts +12 -2
  72. package/dist/adapters/ws.d.ts.map +1 -1
  73. package/dist/bundle-analysis.json +225 -219
  74. package/dist/http.js +2 -0
  75. package/dist/http.mjs +1 -0
  76. package/dist/index.js +0 -2
  77. package/dist/index.mjs +0 -1
  78. package/dist/unstable-core-do-not-import/http/contentType.d.ts +15 -7
  79. package/dist/unstable-core-do-not-import/http/contentType.d.ts.map +1 -1
  80. package/dist/unstable-core-do-not-import/http/contentType.js +54 -0
  81. package/dist/unstable-core-do-not-import/http/contentType.mjs +52 -0
  82. package/dist/unstable-core-do-not-import/http/index.d.ts +1 -0
  83. package/dist/unstable-core-do-not-import/http/index.d.ts.map +1 -1
  84. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.d.ts +5 -5
  85. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.d.ts.map +1 -1
  86. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.js +22 -25
  87. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.mjs +22 -25
  88. package/dist/unstable-core-do-not-import/http/types.d.ts +2 -0
  89. package/dist/unstable-core-do-not-import/http/types.d.ts.map +1 -1
  90. package/dist/unstable-core-do-not-import/initTRPC.d.ts +1 -1
  91. package/dist/unstable-core-do-not-import/initTRPC.d.ts.map +1 -1
  92. package/dist/unstable-core-do-not-import/rootConfig.d.ts +0 -21
  93. package/dist/unstable-core-do-not-import/rootConfig.d.ts.map +1 -1
  94. package/dist/unstable-core-do-not-import.js +2 -0
  95. package/dist/unstable-core-do-not-import.mjs +1 -0
  96. package/package.json +3 -2
  97. package/src/@trpc/server/http.ts +1 -0
  98. package/src/@trpc/server/index.ts +1 -4
  99. package/src/adapters/aws-lambda/index.ts +9 -24
  100. package/src/adapters/aws-lambda/utils.ts +15 -21
  101. package/src/adapters/express.ts +6 -1
  102. package/src/adapters/fastify/fastifyRequestHandler.ts +21 -15
  103. package/src/adapters/fastify/fastifyTRPCPlugin.ts +1 -1
  104. package/src/adapters/fetch/fetchRequestHandler.ts +10 -22
  105. package/src/adapters/fetch/types.ts +15 -22
  106. package/src/adapters/next-app-dir/nextAppDirCaller.ts +9 -2
  107. package/src/adapters/next.ts +6 -1
  108. package/src/adapters/node-http/content-type/form-data/fileUploadHandler.ts +277 -0
  109. package/src/adapters/node-http/content-type/form-data/index.ts +159 -33
  110. package/src/adapters/node-http/content-type/form-data/memoryUploadHandler.ts +56 -0
  111. package/src/adapters/node-http/content-type/form-data/streamSlice.ts +56 -0
  112. package/src/adapters/node-http/content-type/form-data/uploadHandler.ts +89 -0
  113. package/src/adapters/node-http/content-type/json/getPostBody.ts +18 -9
  114. package/src/adapters/node-http/content-type/json/index.ts +7 -87
  115. package/src/adapters/node-http/{content-type/types.ts → internals/contentType.ts} +14 -2
  116. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +35 -22
  117. package/src/adapters/node-http/types.ts +46 -46
  118. package/src/adapters/standalone.ts +2 -1
  119. package/src/adapters/ws.ts +14 -9
  120. package/src/unstable-core-do-not-import/http/contentType.ts +85 -10
  121. package/src/unstable-core-do-not-import/http/index.ts +1 -0
  122. package/src/unstable-core-do-not-import/http/resolveHTTPResponse.ts +28 -29
  123. package/src/unstable-core-do-not-import/http/types.ts +2 -0
  124. package/src/unstable-core-do-not-import/initTRPC.ts +1 -0
  125. package/src/unstable-core-do-not-import/rootConfig.ts +0 -31
  126. package/dist/adapters/aws-lambda/content-type/json/index.d.ts +0 -10
  127. package/dist/adapters/aws-lambda/content-type/json/index.d.ts.map +0 -1
  128. package/dist/adapters/aws-lambda/content-type/json/index.js +0 -59
  129. package/dist/adapters/aws-lambda/content-type/json/index.mjs +0 -57
  130. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.d.ts +0 -10
  131. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.d.ts.map +0 -1
  132. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.js +0 -33
  133. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.mjs +0 -31
  134. package/dist/adapters/fastify/content-type/json/index.d.ts +0 -8
  135. package/dist/adapters/fastify/content-type/json/index.d.ts.map +0 -1
  136. package/dist/adapters/fastify/content-type/json/index.js +0 -59
  137. package/dist/adapters/fastify/content-type/json/index.mjs +0 -57
  138. package/dist/adapters/fastify/types.d.ts +0 -11
  139. package/dist/adapters/fastify/types.d.ts.map +0 -1
  140. package/dist/adapters/fetch/content-type/json/index.d.ts +0 -9
  141. package/dist/adapters/fetch/content-type/json/index.d.ts.map +0 -1
  142. package/dist/adapters/fetch/content-type/json/index.js +0 -58
  143. package/dist/adapters/fetch/content-type/json/index.mjs +0 -56
  144. package/dist/adapters/node-http/content-type/octet/index.d.ts +0 -5
  145. package/dist/adapters/node-http/content-type/octet/index.d.ts.map +0 -1
  146. package/dist/adapters/node-http/content-type/octet/index.js +0 -19
  147. package/dist/adapters/node-http/content-type/octet/index.mjs +0 -17
  148. package/dist/adapters/node-http/content-type/types.d.ts +0 -8
  149. package/dist/adapters/node-http/content-type/types.d.ts.map +0 -1
  150. package/dist/unstable-core-do-not-import/contentTypeParsers.d.ts +0 -16
  151. package/dist/unstable-core-do-not-import/contentTypeParsers.d.ts.map +0 -1
  152. package/dist/unstable-core-do-not-import/contentTypeParsers.js +0 -23
  153. package/dist/unstable-core-do-not-import/contentTypeParsers.mjs +0 -21
  154. package/src/adapters/aws-lambda/content-type/json/index.ts +0 -99
  155. package/src/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.ts +0 -45
  156. package/src/adapters/fastify/content-type/json/index.ts +0 -97
  157. package/src/adapters/fastify/types.ts +0 -22
  158. package/src/adapters/fetch/content-type/json/index.ts +0 -94
  159. package/src/adapters/node-http/content-type/octet/index.ts +0 -27
  160. package/src/unstable-core-do-not-import/contentTypeParsers.ts +0 -37
@@ -24,8 +24,6 @@ import type {
24
24
  ResolveHTTPRequestOptionsContextFn,
25
25
  } from '../../@trpc/server/http';
26
26
  import { resolveHTTPResponse } from '../../@trpc/server/http';
27
- import { selectContentHandlerOrUnsupportedMediaType } from '../content-handlers/selectContentHandlerOrUnsupportedMediaType';
28
- import { getLambdaHTTPJSONContentTypeHandler } from './content-type/json';
29
27
  import type {
30
28
  APIGatewayEvent,
31
29
  APIGatewayResult,
@@ -52,10 +50,18 @@ function lambdaEventToHTTPRequest(event: APIGatewayEvent): HTTPRequest {
52
50
  }
53
51
  }
54
52
 
53
+ let body: string | null | undefined;
54
+ if (event.body && event.isBase64Encoded) {
55
+ body = Buffer.from(event.body, 'base64').toString('utf8');
56
+ } else {
57
+ body = event.body;
58
+ }
59
+
55
60
  return {
56
61
  method: getHTTPMethod(event),
57
62
  query: query,
58
63
  headers: event.headers,
64
+ body: body,
59
65
  };
60
66
  }
61
67
 
@@ -103,39 +109,18 @@ export function awsLambdaRequestHandler<
103
109
  return async (event, context) => {
104
110
  const req = lambdaEventToHTTPRequest(event);
105
111
  const path = getPath(event);
106
-
107
112
  const createContext: ResolveHTTPRequestOptionsContextFn<TRouter> = async (
108
113
  innerOpts,
109
114
  ) => {
110
115
  return await opts.createContext?.({ event, context, ...innerOpts });
111
116
  };
112
117
 
113
- const [contentTypeHandler, unsupportedMediaTypeError] =
114
- selectContentHandlerOrUnsupportedMediaType(
115
- [getLambdaHTTPJSONContentTypeHandler<TRouter, TEvent>()],
116
- {
117
- ...opts,
118
- event,
119
- req,
120
- },
121
- );
122
-
123
118
  const response = await resolveHTTPResponse({
124
119
  ...opts,
125
120
  createContext,
126
121
  req,
127
122
  path,
128
- error: unsupportedMediaTypeError,
129
- async getInput(info) {
130
- return await contentTypeHandler?.getInputs(
131
- {
132
- ...opts,
133
- event,
134
- req,
135
- },
136
- info,
137
- );
138
- },
123
+ error: null,
139
124
  onError(o) {
140
125
  opts?.onError?.({
141
126
  ...o,
@@ -14,12 +14,7 @@ import type {
14
14
  APIGatewayProxyStructuredResultV2,
15
15
  Context as APIGWContext,
16
16
  } from 'aws-lambda';
17
- import type {
18
- AnyRouter,
19
- CreateContextCallback,
20
- inferRouterContext,
21
- } from '../../@trpc/server';
22
- // import @trpc/server
17
+ import type { AnyRouter, inferRouterContext } from '../../@trpc/server'; // import @trpc/server
23
18
 
24
19
  // @trpc/server
25
20
  import { TRPCError } from '../../@trpc/server';
@@ -55,10 +50,20 @@ export type AWSLambdaOptions<
55
50
  TEvent extends APIGatewayEvent,
56
51
  > =
57
52
  | HTTPBaseHandlerOptions<TRouter, TEvent> &
58
- CreateContextCallback<
59
- inferRouterContext<AnyRouter>,
60
- AWSLambdaCreateContextFn<TRouter, TEvent>
61
- >;
53
+ (
54
+ | {
55
+ /**
56
+ * @link https://trpc.io/docs/v11/context
57
+ **/
58
+ createContext: AWSLambdaCreateContextFn<TRouter, TEvent>;
59
+ }
60
+ | {
61
+ /**
62
+ * @link https://trpc.io/docs/v11/context
63
+ **/
64
+ createContext?: AWSLambdaCreateContextFn<TRouter, TEvent>;
65
+ }
66
+ );
62
67
 
63
68
  export function isPayloadV1(
64
69
  event: APIGatewayEvent,
@@ -157,14 +162,3 @@ export type APIGatewayPayloadFormatVersion =
157
162
  export const UNKNOWN_PAYLOAD_FORMAT_VERSION_ERROR_MESSAGE =
158
163
  'Custom payload format version not handled by this adapter. Please use either 1.0 or 2.0. More information here' +
159
164
  'https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html';
160
-
161
- export function lambdaEventToHTTPBody(event: APIGatewayEvent) {
162
- let body: string | null | undefined;
163
- if (event.body && event.isBase64Encoded) {
164
- body = Buffer.from(event.body, 'base64').toString('utf8');
165
- } else {
166
- body = event.body;
167
- }
168
-
169
- return body;
170
- }
@@ -27,7 +27,12 @@ export function createExpressMiddleware<TRouter extends AnyRouter>(
27
27
  const endpoint = req.path.slice(1);
28
28
 
29
29
  await nodeHTTPRequestHandler({
30
- ...opts,
30
+ // FIXME: no typecasting should be needed here
31
+ ...(opts as NodeHTTPHandlerOptions<
32
+ AnyRouter,
33
+ express.Request,
34
+ express.Response
35
+ >),
31
36
  req,
32
37
  res,
33
38
  path: endpoint,
@@ -7,11 +7,12 @@
7
7
  * import type { HTTPBaseHandlerOptions } from '@trpc/server/http'
8
8
  * ```
9
9
  */
10
- import { Readable } from 'stream';
10
+ import { Readable } from 'node:stream';
11
11
  import type { FastifyReply, FastifyRequest } from 'fastify';
12
12
  // @trpc/server
13
13
  import type { AnyRouter } from '../../@trpc/server';
14
14
  import type {
15
+ HTTPBaseHandlerOptions,
15
16
  HTTPRequest,
16
17
  HTTPResponse,
17
18
  ResolveHTTPRequestOptionsContextFn,
@@ -21,9 +22,24 @@ import {
21
22
  getBatchStreamFormatter,
22
23
  resolveHTTPResponse,
23
24
  } from '../../@trpc/server/http';
24
- import { selectContentHandlerOrUnsupportedMediaType } from '../content-handlers/selectContentHandlerOrUnsupportedMediaType';
25
- import { getFastifyHTTPJSONContentTypeHandler } from './content-type/json';
26
- import type { FastifyRequestHandlerOptions } from './types';
25
+ import type { NodeHTTPCreateContextOption } from '../node-http';
26
+
27
+ export type FastifyHandlerOptions<
28
+ TRouter extends AnyRouter,
29
+ TRequest extends FastifyRequest,
30
+ TResponse extends FastifyReply,
31
+ > = HTTPBaseHandlerOptions<TRouter, TRequest> &
32
+ NodeHTTPCreateContextOption<TRouter, TRequest, TResponse>;
33
+
34
+ type FastifyRequestHandlerOptions<
35
+ TRouter extends AnyRouter,
36
+ TRequest extends FastifyRequest,
37
+ TResponse extends FastifyReply,
38
+ > = FastifyHandlerOptions<TRouter, TRequest, TResponse> & {
39
+ req: TRequest;
40
+ res: TResponse;
41
+ path: string;
42
+ };
27
43
 
28
44
  export async function fastifyRequestHandler<
29
45
  TRouter extends AnyRouter,
@@ -47,6 +63,7 @@ export async function fastifyRequestHandler<
47
63
  query,
48
64
  method: opts.req.method,
49
65
  headers: opts.req.headers,
66
+ body: opts.req.body ?? 'null',
50
67
  };
51
68
 
52
69
  let resolve: (value: FastifyReply) => void;
@@ -91,21 +108,10 @@ export async function fastifyRequestHandler<
91
108
  }
92
109
  };
93
110
 
94
- const [contentTypeHandler, unsupportedMediaTypeError] =
95
- selectContentHandlerOrUnsupportedMediaType(
96
- [getFastifyHTTPJSONContentTypeHandler<TRouter, TRequest, TResponse>()],
97
- opts,
98
- );
99
-
100
111
  resolveHTTPResponse({
101
112
  ...opts,
102
113
  req,
103
- error: unsupportedMediaTypeError,
104
- async getInput(info) {
105
- return await contentTypeHandler?.getInputs(opts, info);
106
- },
107
114
  createContext,
108
-
109
115
  onError(o) {
110
116
  opts?.onError?.({ ...o, req: opts.req });
111
117
  },
@@ -9,13 +9,13 @@
9
9
  */
10
10
  /// <reference types="@fastify/websocket" />
11
11
  import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
12
+ import type { FastifyHandlerOptions } from '.';
12
13
  // @trpc/server
13
14
  import type { AnyRouter } from '../../@trpc/server';
14
15
  import type { NodeHTTPCreateContextFnOptions } from '../node-http';
15
16
  import type { WSSHandlerOptions } from '../ws';
16
17
  import { getWSConnectionHandler } from '../ws';
17
18
  import { fastifyRequestHandler } from './fastifyRequestHandler';
18
- import type { FastifyHandlerOptions } from './types';
19
19
 
20
20
  export interface FastifyTRPCPluginOptions<TRouter extends AnyRouter> {
21
21
  prefix?: string;
@@ -21,10 +21,14 @@ import {
21
21
  resolveHTTPResponse,
22
22
  toURL,
23
23
  } from '../../@trpc/server/http';
24
- import { selectContentHandlerOrUnsupportedMediaType } from '../content-handlers/selectContentHandlerOrUnsupportedMediaType';
25
- import { getFetchHTTPJSONContentTypeHandler } from './content-type/json';
26
24
  import type { FetchHandlerOptions } from './types';
27
25
 
26
+ export type FetchHandlerRequestOptions<TRouter extends AnyRouter> =
27
+ FetchHandlerOptions<TRouter> & {
28
+ req: Request;
29
+ endpoint: string;
30
+ };
31
+
28
32
  const trimSlashes = (path: string): string => {
29
33
  path = path.startsWith('/') ? path.slice(1) : path;
30
34
  path = path.endsWith('/') ? path.slice(0, -1) : path;
@@ -33,7 +37,7 @@ const trimSlashes = (path: string): string => {
33
37
  };
34
38
 
35
39
  export async function fetchRequestHandler<TRouter extends AnyRouter>(
36
- opts: FetchHandlerOptions<TRouter>,
40
+ opts: FetchHandlerRequestOptions<TRouter>,
37
41
  ): Promise<Response> {
38
42
  const resHeaders = new Headers();
39
43
 
@@ -53,6 +57,9 @@ export async function fetchRequestHandler<TRouter extends AnyRouter>(
53
57
  query: url.searchParams,
54
58
  method: opts.req.method,
55
59
  headers: Object.fromEntries(opts.req.headers),
60
+ body: opts.req.headers.get('content-type')?.startsWith('application/json')
61
+ ? await opts.req.text()
62
+ : '',
56
63
  };
57
64
 
58
65
  let resolve: (value: Response) => void;
@@ -110,30 +117,11 @@ export async function fetchRequestHandler<TRouter extends AnyRouter>(
110
117
  }
111
118
  };
112
119
 
113
- const [contentTypeHandler, unsupportedMediaTypeError] =
114
- selectContentHandlerOrUnsupportedMediaType(
115
- [getFetchHTTPJSONContentTypeHandler<TRouter>()],
116
- {
117
- ...opts,
118
- url,
119
- },
120
- );
121
-
122
120
  resolveHTTPResponse({
123
121
  ...opts,
124
122
  req,
125
123
  createContext,
126
124
  path,
127
- error: unsupportedMediaTypeError,
128
- async getInput(info) {
129
- return await contentTypeHandler?.getInputs(
130
- {
131
- ...opts,
132
- url,
133
- },
134
- info,
135
- );
136
- },
137
125
  onError(o) {
138
126
  opts?.onError?.({ ...o, req: opts.req });
139
127
  },
@@ -8,12 +8,7 @@
8
8
  * ```
9
9
  */
10
10
  // @trpc/server
11
- import type {
12
- AnyRouter,
13
- CreateContextCallback,
14
- inferRouterContext,
15
- WrapCreateContext,
16
- } from '../../@trpc/server';
11
+ import type { AnyRouter, inferRouterContext } from '../../@trpc/server';
17
12
  // @trpc/server/http
18
13
  import type {
19
14
  HTTPBaseHandlerOptions,
@@ -31,21 +26,19 @@ export type FetchCreateContextFn<TRouter extends AnyRouter> = (
31
26
  ) => inferRouterContext<TRouter> | Promise<inferRouterContext<TRouter>>;
32
27
 
33
28
  export type FetchCreateContextOption<TRouter extends AnyRouter> =
34
- CreateContextCallback<
35
- inferRouterContext<TRouter>,
36
- FetchCreateContextFn<TRouter>
37
- >;
29
+ unknown extends inferRouterContext<TRouter>
30
+ ? {
31
+ /**
32
+ * @link https://trpc.io/docs/v11/context
33
+ **/
34
+ createContext?: FetchCreateContextFn<TRouter>;
35
+ }
36
+ : {
37
+ /**
38
+ * @link https://trpc.io/docs/v11/context
39
+ **/
40
+ createContext: FetchCreateContextFn<TRouter>;
41
+ };
38
42
 
39
43
  export type FetchHandlerOptions<TRouter extends AnyRouter> =
40
- FetchCreateContextOption<TRouter> &
41
- HTTPBaseHandlerOptions<TRouter, Request> & {
42
- req: Request;
43
- endpoint: string;
44
- };
45
-
46
- export type FetchHandlerRequestOptions<TRouter extends AnyRouter> =
47
- HTTPBaseHandlerOptions<TRouter, Request> &
48
- WrapCreateContext<FetchCreateContextFn<TRouter>> & {
49
- req: Request;
50
- endpoint: string;
51
- };
44
+ FetchCreateContextOption<TRouter> & HTTPBaseHandlerOptions<TRouter, Request>;
@@ -1,4 +1,3 @@
1
- import type { CreateContextCallback } from '../../@trpc/server';
2
1
  import { getTRPCErrorFromUnknown, TRPCError } from '../../@trpc/server';
3
2
  // FIXME: fix lint rule, this is ok
4
3
  // eslint-disable-next-line no-restricted-imports
@@ -16,6 +15,14 @@ import { formDataToObject } from './formDataToObject';
16
15
  import { TRPCRedirectError } from './redirect';
17
16
  import { rethrowNextErrors } from './rethrowNextErrors';
18
17
 
18
+ type ContextCallback<TContext> = object extends TContext
19
+ ? {
20
+ createContext?: () => MaybePromise<TContext>;
21
+ }
22
+ : {
23
+ createContext: () => MaybePromise<TContext>;
24
+ };
25
+
19
26
  /**
20
27
  * Create a caller that works with Next.js React Server Components & Server Actions
21
28
  */
@@ -31,7 +38,7 @@ export function nextAppDirCaller<TContext>(
31
38
  * Called when an error occurs in the handler
32
39
  */
33
40
  onError?: (opts: ErrorHandlerOptions<TContext>) => void;
34
- } & CreateContextCallback<TContext, () => MaybePromise<TContext>>
41
+ } & ContextCallback<TContext>
35
42
  >,
36
43
  ): CallerOverride<TContext> {
37
44
  const {
@@ -65,7 +65,12 @@ export function createNextApiHandler<TRouter extends AnyRouter>(
65
65
  }
66
66
 
67
67
  await nodeHTTPRequestHandler({
68
- ...opts,
68
+ // FIXME: no typecasting should be needed here
69
+ ...(opts as NodeHTTPHandlerOptions<
70
+ AnyRouter,
71
+ NextApiRequest,
72
+ NextApiResponse
73
+ >),
69
74
  req,
70
75
  res,
71
76
  path,
@@ -0,0 +1,277 @@
1
+ /* eslint-disable @typescript-eslint/no-empty-function */
2
+
3
+ /**
4
+ * Copyright 2021 Remix Software Inc.
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8
+ */
9
+
10
+ /**
11
+ * @link https://github.com/remix-run/remix/blob/0bcb4a304dd2f08f6032c3bf0c3aa7eb5b976901/packages/remix-node/upload/fileUploadHandler.ts
12
+ */
13
+ import { randomBytes } from 'node:crypto';
14
+ import { createReadStream, createWriteStream, statSync } from 'node:fs';
15
+ import { mkdir, rm, stat as statAsync, unlink } from 'node:fs/promises';
16
+ import { tmpdir } from 'node:os';
17
+ import { basename, dirname, extname, resolve as resolvePath } from 'node:path';
18
+ import { finished, Readable } from 'node:stream';
19
+ import { promisify } from 'node:util';
20
+ import { streamSlice } from './streamSlice';
21
+ import type { UploadHandler } from './uploadHandler';
22
+ import { MaxPartSizeExceededError } from './uploadHandler';
23
+
24
+ export async function readableStreamToString(
25
+ stream: ReadableStream<Uint8Array>,
26
+ encoding?: BufferEncoding,
27
+ ) {
28
+ const reader = stream.getReader();
29
+ const chunks: Uint8Array[] = [];
30
+
31
+ async function read() {
32
+ const { done, value } = await reader.read();
33
+
34
+ if (done) {
35
+ return;
36
+ } else if (value) {
37
+ chunks.push(value);
38
+ }
39
+
40
+ await read();
41
+ }
42
+
43
+ await read();
44
+
45
+ return Buffer.concat(chunks).toString(encoding);
46
+ }
47
+
48
+ export type FileUploadHandlerFilterArgs = {
49
+ filename: string;
50
+ contentType: string;
51
+ name: string;
52
+ };
53
+
54
+ export type FileUploadHandlerPathResolverArgs = {
55
+ filename: string;
56
+ contentType: string;
57
+ name: string;
58
+ };
59
+
60
+ /**
61
+ * Chooses the path of the file to be uploaded. If a string is not
62
+ * returned the file will not be written.
63
+ */
64
+ export type FileUploadHandlerPathResolver = (
65
+ args: FileUploadHandlerPathResolverArgs,
66
+ ) => string | undefined;
67
+
68
+ export type FileUploadHandlerOptions = {
69
+ /**
70
+ * Avoid file conflicts by appending a count on the end of the filename
71
+ * if it already exists on disk. Defaults to `true`.
72
+ */
73
+ avoidFileConflicts?: boolean;
74
+ /**
75
+ * The directory to write the upload.
76
+ */
77
+ directory?: FileUploadHandlerPathResolver | string;
78
+ /**
79
+ * The name of the file in the directory. Can be a relative path, the directory
80
+ * structure will be created if it does not exist.
81
+ */
82
+ file?: FileUploadHandlerPathResolver;
83
+ /**
84
+ * The maximum upload size allowed. If the size is exceeded an error will be thrown.
85
+ * Defaults to 3000000B (3MB).
86
+ */
87
+ maxPartSize?: number;
88
+ /**
89
+ *
90
+ * @param filename
91
+ * @param contentType
92
+ * @param name
93
+ */
94
+ filter?(args: FileUploadHandlerFilterArgs): Promise<boolean> | boolean;
95
+ };
96
+
97
+ const defaultFilePathResolver: FileUploadHandlerPathResolver = ({
98
+ filename,
99
+ }) => {
100
+ const ext = filename ? extname(filename) : '';
101
+ return 'upload_' + randomBytes(4).readUInt32LE(0) + ext;
102
+ };
103
+
104
+ async function uniqueFile(filepath: string) {
105
+ const ext = extname(filepath);
106
+ let uniqueFilepath = filepath;
107
+
108
+ for (
109
+ let i = 1;
110
+ await statAsync(uniqueFilepath)
111
+ .then(() => true)
112
+ .catch(() => false);
113
+ i++
114
+ ) {
115
+ uniqueFilepath =
116
+ (ext ? filepath.slice(0, -ext.length) : filepath) +
117
+ `-${new Date().getTime()}${ext}`;
118
+ }
119
+
120
+ return uniqueFilepath;
121
+ }
122
+
123
+ export function createFileUploadHandler({
124
+ directory = tmpdir(),
125
+ avoidFileConflicts = true,
126
+ file = defaultFilePathResolver,
127
+ filter,
128
+ maxPartSize = 3000000,
129
+ }: FileUploadHandlerOptions = {}): UploadHandler {
130
+ return async ({ name, filename, contentType, data }) => {
131
+ if (
132
+ !filename ||
133
+ (filter && !(await filter({ name, filename, contentType })))
134
+ ) {
135
+ return undefined;
136
+ }
137
+
138
+ const dir =
139
+ typeof directory === 'string'
140
+ ? directory
141
+ : directory({ name, filename, contentType });
142
+
143
+ if (!dir) {
144
+ return undefined;
145
+ }
146
+
147
+ const filedir = resolvePath(dir);
148
+ const path =
149
+ typeof file === 'string' ? file : file({ name, filename, contentType });
150
+
151
+ if (!path) {
152
+ return undefined;
153
+ }
154
+
155
+ let filepath = resolvePath(filedir, path);
156
+
157
+ if (avoidFileConflicts) {
158
+ filepath = await uniqueFile(filepath);
159
+ }
160
+
161
+ await mkdir(dirname(filepath), { recursive: true }).catch(() => {});
162
+
163
+ const writeFileStream = createWriteStream(filepath);
164
+ let size = 0;
165
+ let deleteFile = false;
166
+ try {
167
+ for await (const chunk of data) {
168
+ size += chunk.byteLength;
169
+ if (size > maxPartSize) {
170
+ deleteFile = true;
171
+ throw new MaxPartSizeExceededError(name, maxPartSize);
172
+ }
173
+ writeFileStream.write(chunk);
174
+ }
175
+ } finally {
176
+ writeFileStream.end();
177
+ await promisify(finished)(writeFileStream);
178
+
179
+ if (deleteFile) {
180
+ await rm(filepath).catch(() => {});
181
+ }
182
+ }
183
+
184
+ return new NodeOnDiskFile(filepath, contentType);
185
+ };
186
+ }
187
+ type NodeJSReadableStreamEsque = {
188
+ on(
189
+ eventName: string | symbol,
190
+ listener: (...args: any[]) => void,
191
+ ): NodeJSReadableStreamEsque;
192
+ };
193
+
194
+ export class NodeOnDiskFile {
195
+ name: string;
196
+ lastModified = 0;
197
+ webkitRelativePath = '';
198
+
199
+ constructor(
200
+ private filepath: string,
201
+ public type: string,
202
+ private slicer?: { start: number; end: number },
203
+ ) {
204
+ this.name = basename(filepath);
205
+ }
206
+
207
+ get size(): number {
208
+ const stats = statSync(this.filepath);
209
+
210
+ if (this.slicer) {
211
+ const slice = this.slicer.end - this.slicer.start;
212
+ return slice < 0 ? 0 : slice > stats.size ? stats.size : slice;
213
+ }
214
+
215
+ return stats.size;
216
+ }
217
+
218
+ slice(start?: number, end?: number, type?: string): NodeOnDiskFile {
219
+ if (typeof start === 'number' && start < 0) start = this.size + start;
220
+ if (typeof end === 'number' && end < 0) end = this.size + end;
221
+
222
+ const startOffset = this.slicer?.start ?? 0;
223
+
224
+ start = startOffset + (start ?? 0);
225
+ end = startOffset + (end ?? this.size);
226
+ return new NodeOnDiskFile(
227
+ this.filepath,
228
+ typeof type === 'string' ? type : this.type,
229
+ {
230
+ start,
231
+ end,
232
+ },
233
+ );
234
+ }
235
+
236
+ async arrayBuffer(): Promise<ArrayBuffer> {
237
+ let stream: Readable = createReadStream(this.filepath);
238
+ if (this.slicer) {
239
+ stream = stream.pipe(streamSlice(this.slicer.start, this.slicer.end));
240
+ }
241
+
242
+ return new Promise((resolve, reject) => {
243
+ const buf: any[] = [];
244
+ stream.on('data', (chunk) => buf.push(chunk));
245
+ stream.on('end', () => {
246
+ resolve(Buffer.concat(buf));
247
+ });
248
+ stream.on('error', (err) => {
249
+ reject(err);
250
+ });
251
+ });
252
+ }
253
+
254
+ stream(): ReadableStream<any>;
255
+ stream(): NodeJSReadableStreamEsque;
256
+ stream(): NodeJSReadableStreamEsque | ReadableStream<any> {
257
+ let stream: Readable = createReadStream(this.filepath);
258
+ if (this.slicer) {
259
+ stream = stream.pipe(streamSlice(this.slicer.start, this.slicer.end));
260
+ }
261
+
262
+ return Readable.toWeb(stream) as ReadableStream<Uint8Array>;
263
+ }
264
+
265
+ async text(): Promise<string> {
266
+ return readableStreamToString(this.stream());
267
+ }
268
+
269
+ public readonly [Symbol.toStringTag] = 'File';
270
+
271
+ remove(): Promise<void> {
272
+ return unlink(this.filepath);
273
+ }
274
+ getFilePath(): string {
275
+ return this.filepath;
276
+ }
277
+ }