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

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 (157) 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 +233 -227
  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/rootConfig.d.ts +0 -21
  91. package/dist/unstable-core-do-not-import/rootConfig.d.ts.map +1 -1
  92. package/dist/unstable-core-do-not-import.js +2 -0
  93. package/dist/unstable-core-do-not-import.mjs +1 -0
  94. package/package.json +3 -2
  95. package/src/@trpc/server/http.ts +1 -0
  96. package/src/@trpc/server/index.ts +0 -4
  97. package/src/adapters/aws-lambda/index.ts +9 -24
  98. package/src/adapters/aws-lambda/utils.ts +15 -21
  99. package/src/adapters/express.ts +6 -1
  100. package/src/adapters/fastify/fastifyRequestHandler.ts +21 -15
  101. package/src/adapters/fastify/fastifyTRPCPlugin.ts +1 -1
  102. package/src/adapters/fetch/fetchRequestHandler.ts +10 -22
  103. package/src/adapters/fetch/types.ts +15 -22
  104. package/src/adapters/next-app-dir/nextAppDirCaller.ts +9 -2
  105. package/src/adapters/next.ts +6 -1
  106. package/src/adapters/node-http/content-type/form-data/fileUploadHandler.ts +277 -0
  107. package/src/adapters/node-http/content-type/form-data/index.ts +159 -33
  108. package/src/adapters/node-http/content-type/form-data/memoryUploadHandler.ts +56 -0
  109. package/src/adapters/node-http/content-type/form-data/streamSlice.ts +56 -0
  110. package/src/adapters/node-http/content-type/form-data/uploadHandler.ts +89 -0
  111. package/src/adapters/node-http/content-type/json/getPostBody.ts +18 -9
  112. package/src/adapters/node-http/content-type/json/index.ts +7 -87
  113. package/src/adapters/node-http/{content-type/types.ts → internals/contentType.ts} +14 -2
  114. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +35 -22
  115. package/src/adapters/node-http/types.ts +46 -46
  116. package/src/adapters/standalone.ts +2 -1
  117. package/src/adapters/ws.ts +14 -9
  118. package/src/unstable-core-do-not-import/http/contentType.ts +85 -10
  119. package/src/unstable-core-do-not-import/http/index.ts +1 -0
  120. package/src/unstable-core-do-not-import/http/resolveHTTPResponse.ts +28 -29
  121. package/src/unstable-core-do-not-import/http/types.ts +2 -0
  122. package/src/unstable-core-do-not-import/rootConfig.ts +0 -31
  123. package/dist/adapters/aws-lambda/content-type/json/index.d.ts +0 -10
  124. package/dist/adapters/aws-lambda/content-type/json/index.d.ts.map +0 -1
  125. package/dist/adapters/aws-lambda/content-type/json/index.js +0 -59
  126. package/dist/adapters/aws-lambda/content-type/json/index.mjs +0 -57
  127. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.d.ts +0 -10
  128. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.d.ts.map +0 -1
  129. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.js +0 -33
  130. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.mjs +0 -31
  131. package/dist/adapters/fastify/content-type/json/index.d.ts +0 -8
  132. package/dist/adapters/fastify/content-type/json/index.d.ts.map +0 -1
  133. package/dist/adapters/fastify/content-type/json/index.js +0 -59
  134. package/dist/adapters/fastify/content-type/json/index.mjs +0 -57
  135. package/dist/adapters/fastify/types.d.ts +0 -11
  136. package/dist/adapters/fastify/types.d.ts.map +0 -1
  137. package/dist/adapters/fetch/content-type/json/index.d.ts +0 -9
  138. package/dist/adapters/fetch/content-type/json/index.d.ts.map +0 -1
  139. package/dist/adapters/fetch/content-type/json/index.js +0 -58
  140. package/dist/adapters/fetch/content-type/json/index.mjs +0 -56
  141. package/dist/adapters/node-http/content-type/octet/index.d.ts +0 -5
  142. package/dist/adapters/node-http/content-type/octet/index.d.ts.map +0 -1
  143. package/dist/adapters/node-http/content-type/octet/index.js +0 -19
  144. package/dist/adapters/node-http/content-type/octet/index.mjs +0 -17
  145. package/dist/adapters/node-http/content-type/types.d.ts +0 -8
  146. package/dist/adapters/node-http/content-type/types.d.ts.map +0 -1
  147. package/dist/unstable-core-do-not-import/contentTypeParsers.d.ts +0 -16
  148. package/dist/unstable-core-do-not-import/contentTypeParsers.d.ts.map +0 -1
  149. package/dist/unstable-core-do-not-import/contentTypeParsers.js +0 -23
  150. package/dist/unstable-core-do-not-import/contentTypeParsers.mjs +0 -21
  151. package/src/adapters/aws-lambda/content-type/json/index.ts +0 -99
  152. package/src/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.ts +0 -45
  153. package/src/adapters/fastify/content-type/json/index.ts +0 -97
  154. package/src/adapters/fastify/types.ts +0 -22
  155. package/src/adapters/fetch/content-type/json/index.ts +0 -94
  156. package/src/adapters/node-http/content-type/octet/index.ts +0 -27
  157. package/src/unstable-core-do-not-import/contentTypeParsers.ts +0 -37
@@ -1,37 +1,163 @@
1
- import { Readable } from 'stream';
1
+ /**
2
+ * Copyright 2021 Remix Software Inc.
3
+ * 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:
4
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ * 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.
6
+ */
7
+
8
+ /**
9
+ * @link https://github.com/remix-run/remix/blob/0bcb4a304dd2f08f6032c3bf0c3aa7eb5b976901/packages/remix-server-runtime/formData.ts
10
+ */
11
+ import * as fs from 'fs/promises';
12
+ import { Readable } from 'node:stream';
13
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
14
+ // @ts-ignore the type definitions for this package are borked
15
+ import { streamMultipart } from '@web3-storage/multipart-parser';
2
16
  // @trpc/server
3
- import type { AnyRouter } from '../../../../@trpc/server';
4
- import type { NodeHTTPRequest, NodeHTTPResponse } from '../../types';
5
- import type { NodeHTTPContentTypeHandler } from '../types';
6
-
7
- export const getFormDataContentTypeHandler: <
8
- TRouter extends AnyRouter,
9
- TRequest extends NodeHTTPRequest,
10
- TResponse extends NodeHTTPResponse,
11
- >() => NodeHTTPContentTypeHandler<TRouter, TRequest, TResponse> = () => ({
12
- name: 'node-http-formdata',
13
- isMatch: (headers) => {
14
- return !!headers.get('content-type')?.startsWith('multipart/form-data');
15
- },
16
- async getInputs(opts, inputOpts) {
17
- if (inputOpts.isBatchCall) {
18
- throw new Error('Batch calls not supported for form-data');
19
- }
17
+ import { createNodeHTTPContentTypeHandler } from '../../internals/contentType';
18
+ import type { NodeHTTPRequest } from '../../types';
19
+ import { NodeOnDiskFile } from './fileUploadHandler';
20
+ import type { UploadHandler, UploadHandlerPart } from './uploadHandler';
21
+ import { MaxBodySizeExceededError } from './uploadHandler';
22
+
23
+ const utfTextDecoder = new TextDecoder('utf-8');
24
+
25
+ /**
26
+ * Allows you to handle multipart forms (file uploads) for your app.
27
+ * Request body parts with a 'filename' property will be treated as files.
28
+ * The rest will be treated as text.
29
+ * @param request The incoming Node HTTP request
30
+ * @param uploadHandler A function that handles file uploads and returns a value to be used in the request body. If uploaded to disk, the returned value is a NodeOnDiskFile. If uploaded to memory, the returned value is a File.
31
+ * @param maxBodySize The maximum size of the request body in bytes. Defaults to Infinity.
32
+ *
33
+ * @link https://remix.run/utils/parse-multipart-form-data
34
+ */
35
+ async function parseMultipartFormData(
36
+ request: NodeHTTPRequest,
37
+ uploadHandler: UploadHandler,
38
+ maxBodySize = Infinity,
39
+ ) {
40
+ const contentType = request.headers['content-type'] ?? '';
41
+ const [type, boundary] = contentType.split(/\s*;\s*boundary=/);
42
+
43
+ if (!boundary || type !== 'multipart/form-data') {
44
+ throw new TypeError('Could not parse content as FormData.');
45
+ }
46
+
47
+ const formData = new FormData();
48
+ const parts: AsyncIterable<UploadHandlerPart & { done?: true }> =
49
+ streamMultipart(Readable.toWeb(request), boundary);
50
+
51
+ let currentBodySize = 0;
52
+
53
+ const nodeOnDiskFiles: NodeOnDiskFile[] = [];
54
+
55
+ try {
56
+ for await (const part of parts) {
57
+ if (part.done) break;
20
58
 
21
- const contentType = opts.req.headers['content-type'];
22
- if (!contentType) {
23
- // Should be unreachable given the isMatch check
24
- throw new Error('No content-type header found');
59
+ if (typeof part.filename === 'string') {
60
+ // This is a file, so the uploadHandler function will be called
61
+
62
+ // only pass basename as the multipart/form-data spec recommends
63
+ // https://datatracker.ietf.org/doc/html/rfc7578#section-4.2
64
+ part.filename = part.filename.split(/[/\\]/).pop();
65
+ const value = await uploadHandler(part as Required<typeof part>);
66
+
67
+ if (typeof value === 'undefined' || value === null) {
68
+ continue;
69
+ }
70
+ // add to cleanup array in case of error
71
+ if (value instanceof NodeOnDiskFile) {
72
+ nodeOnDiskFiles.push(value);
73
+ }
74
+
75
+ // if the combined size of the body exceeds the max size, throw an error
76
+ currentBodySize += value.size;
77
+ if (currentBodySize > maxBodySize) {
78
+ throw new MaxBodySizeExceededError(maxBodySize);
79
+ }
80
+ // add the file to the form data
81
+ formData.append(part.name, value as any);
82
+ } else {
83
+ // This is text, so we'll decode it and add it to the form data
84
+ let textualPart = '';
85
+ for await (const chunk of part.data) {
86
+ // if the combined size of the body exceeds the max size, throw an error
87
+ currentBodySize += chunk.length;
88
+ if (currentBodySize > maxBodySize) {
89
+ throw new MaxBodySizeExceededError(maxBodySize);
90
+ }
91
+ textualPart += utfTextDecoder.decode(chunk);
92
+ }
93
+ // add the text to the form data
94
+ formData.append(part.name, textualPart);
95
+ }
25
96
  }
26
97
 
27
- const form = await new Request('https://unused.com', {
28
- method: 'POST',
29
- headers: { 'content-type': contentType },
30
- body: Readable.toWeb(opts.req) as ReadableStream,
31
- // @ts-expect-error - outdated types? this exists
32
- duplex: 'half',
33
- }).formData();
34
-
35
- return form;
36
- },
37
- });
98
+ return formData;
99
+ } catch (e) {
100
+ // clean up any files that were uploaded to disk if an error occurs
101
+ await Promise.all(
102
+ nodeOnDiskFiles.map((file) => fs.unlink(file.getFilePath())),
103
+ );
104
+ throw e;
105
+ }
106
+ }
107
+
108
+ function isMultipartFormDataRequest(req: NodeHTTPRequest) {
109
+ const contentTypeHeader = req.headers['content-type'];
110
+ return (
111
+ contentTypeHeader?.startsWith('multipart/form-data') ??
112
+ contentTypeHeader === 'application/x-www-form-urlencoded'
113
+ );
114
+ }
115
+
116
+ export const nodeHTTPFormDataContentTypeHandler =
117
+ createNodeHTTPContentTypeHandler({
118
+ isMatch(opts) {
119
+ return isMultipartFormDataRequest(opts.req);
120
+ },
121
+ async getBody(opts) {
122
+ const fields = Object.fromEntries(opts.query);
123
+
124
+ return {
125
+ ok: true,
126
+ data: fields,
127
+ preprocessed: false,
128
+ };
129
+ },
130
+ getInputs(opts) {
131
+ const req = opts.req;
132
+ const unparsedInput = req.query.get('input');
133
+ if (!unparsedInput) {
134
+ return {
135
+ 0: undefined,
136
+ };
137
+ }
138
+ const transformer = opts.router._def._config.transformer;
139
+
140
+ const deserializedInput = transformer.input.deserialize(
141
+ JSON.parse(unparsedInput),
142
+ );
143
+ return {
144
+ 0: deserializedInput,
145
+ };
146
+ },
147
+ });
148
+
149
+ export {
150
+ NodeOnDiskFile as experimental_NodeOnDiskFile,
151
+ createFileUploadHandler as experimental_createFileUploadHandler,
152
+ } from './fileUploadHandler';
153
+ export { createMemoryUploadHandler as experimental_createMemoryUploadHandler } from './memoryUploadHandler';
154
+ export {
155
+ MaxBodySizeExceededError,
156
+ MaxPartSizeExceededError,
157
+ composeUploadHandlers as experimental_composeUploadHandlers,
158
+ type UploadHandler,
159
+ } from './uploadHandler';
160
+ export {
161
+ isMultipartFormDataRequest as experimental_isMultipartFormDataRequest,
162
+ parseMultipartFormData as experimental_parseMultipartFormData,
163
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Copyright 2021 Remix Software Inc.
3
+ * 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:
4
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ * 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.
6
+ */
7
+
8
+ /**
9
+ * @link https://github.com/remix-run/remix/blob/0bcb4a304dd2f08f6032c3bf0c3aa7eb5b976901/packages/remix-server-runtime/upload/memoryUploadHandler.ts
10
+ */
11
+ import type { UploadHandler } from './uploadHandler';
12
+ import { MaxPartSizeExceededError } from './uploadHandler';
13
+
14
+ export type MemoryUploadHandlerFilterArgs = {
15
+ filename?: string;
16
+ contentType: string;
17
+ name: string;
18
+ };
19
+
20
+ export type MemoryUploadHandlerOptions = {
21
+ /**
22
+ * The maximum upload size allowed. If the size is exceeded an error will be thrown.
23
+ * Defaults to 3000000B (3MB).
24
+ */
25
+ maxPartSize?: number;
26
+ /**
27
+ *
28
+ * @param filename
29
+ * @param mimetype
30
+ * @param encoding
31
+ */
32
+ filter?(args: MemoryUploadHandlerFilterArgs): Promise<boolean> | boolean;
33
+ };
34
+
35
+ export function createMemoryUploadHandler({
36
+ filter,
37
+ maxPartSize = 3000000,
38
+ }: MemoryUploadHandlerOptions = {}): UploadHandler {
39
+ return async ({ filename, contentType, name, data }) => {
40
+ if (filter && !(await filter({ filename, contentType, name }))) {
41
+ return undefined;
42
+ }
43
+
44
+ let size = 0;
45
+ const chunks = [];
46
+ for await (const chunk of data) {
47
+ size += chunk.byteLength;
48
+ if (size > maxPartSize) {
49
+ throw new MaxPartSizeExceededError(name, maxPartSize);
50
+ }
51
+ chunks.push(chunk);
52
+ }
53
+
54
+ return new File(chunks, filename, { type: contentType });
55
+ };
56
+ }
@@ -0,0 +1,56 @@
1
+ import type { TransformCallback } from 'node:stream';
2
+ import { Transform } from 'node:stream';
3
+
4
+ class SliceStream extends Transform {
5
+ private indexOffset = 0;
6
+ private emitUp = false;
7
+ private emitDown = false;
8
+
9
+ constructor(private startIndex = 0, private endIndex = Infinity) {
10
+ super();
11
+ }
12
+
13
+ override _transform(
14
+ chunk: any,
15
+ _: BufferEncoding,
16
+ done: TransformCallback,
17
+ ): void {
18
+ this.indexOffset += chunk.length;
19
+
20
+ if (!this.emitUp && this.indexOffset >= this.startIndex) {
21
+ this.emitUp = true;
22
+ const start = chunk.length - (this.indexOffset - this.startIndex);
23
+
24
+ if (this.indexOffset > this.endIndex) {
25
+ const end = chunk.length - (this.indexOffset - this.endIndex);
26
+ this.emitDown = true;
27
+ this.push(chunk.slice(start, end));
28
+ } else {
29
+ this.push(chunk.slice(start, chunk.length));
30
+ }
31
+
32
+ done();
33
+ return;
34
+ }
35
+
36
+ if (this.emitUp && !this.emitDown) {
37
+ if (this.indexOffset >= this.endIndex) {
38
+ this.emitDown = true;
39
+ this.push(
40
+ chunk.slice(0, chunk.length - (this.indexOffset - this.endIndex)),
41
+ );
42
+ } else {
43
+ this.push(chunk);
44
+ }
45
+
46
+ done();
47
+ return;
48
+ }
49
+
50
+ done();
51
+ }
52
+ }
53
+
54
+ export function streamSlice(startIndex = 0, endIndex = Infinity): SliceStream {
55
+ return new SliceStream(startIndex, endIndex);
56
+ }
@@ -0,0 +1,89 @@
1
+ import type { NodeOnDiskFile } from './fileUploadHandler';
2
+
3
+ /**
4
+ * @link https://github.com/remix-run/remix/blob/0bcb4a304dd2f08f6032c3bf0c3aa7eb5b976901/packages/remix-server-runtime/formData.ts
5
+ */
6
+ export type UploadHandlerPart = {
7
+ name: string;
8
+ filename?: string;
9
+ contentType: string;
10
+ data: AsyncIterable<Uint8Array>;
11
+ };
12
+
13
+ export type UploadHandler = (
14
+ part: Required<UploadHandlerPart>,
15
+ ) => Promise<File | NodeOnDiskFile | null | undefined>;
16
+
17
+ export function composeUploadHandlers(
18
+ ...handlers: UploadHandler[]
19
+ ): UploadHandler {
20
+ return async (part) => {
21
+ for (const handler of handlers) {
22
+ const value = await handler(part);
23
+ if (typeof value !== 'undefined' && value !== null) {
24
+ return value;
25
+ }
26
+ }
27
+
28
+ return undefined;
29
+ };
30
+ }
31
+
32
+ export class MaxPartSizeExceededError extends Error {
33
+ constructor(public field: string, public maxBytes: number) {
34
+ super(`Field "${field}" exceeded upload size of ${maxBytes} bytes.`);
35
+ }
36
+ }
37
+
38
+ export class MaxBodySizeExceededError extends Error {
39
+ constructor(public maxBytes: number) {
40
+ super(`Body exceeded upload size of ${maxBytes} bytes.`);
41
+ }
42
+ }
43
+
44
+ export type MemoryUploadHandlerFilterArgs = {
45
+ filename?: string;
46
+ contentType: string;
47
+ name: string;
48
+ };
49
+
50
+ export type MemoryUploadHandlerOptions = {
51
+ /**
52
+ * The maximum upload size allowed. If the size is exceeded an error will be thrown.
53
+ * Defaults to 3000000B (3MB).
54
+ */
55
+ maxPartSize?: number;
56
+ /**
57
+ *
58
+ * @param filename
59
+ * @param mimetype
60
+ * @param encoding
61
+ */
62
+ filter?(args: MemoryUploadHandlerFilterArgs): Promise<boolean> | boolean;
63
+ };
64
+
65
+ /**
66
+ * @see
67
+ */
68
+ export function createMemoryUploadHandler({
69
+ filter,
70
+ maxPartSize = 3000000,
71
+ }: MemoryUploadHandlerOptions = {}): UploadHandler {
72
+ return async ({ filename, contentType, name, data }) => {
73
+ if (filter && !(await filter({ filename, contentType, name }))) {
74
+ return undefined;
75
+ }
76
+
77
+ let size = 0;
78
+ const chunks = [];
79
+ for await (const chunk of data) {
80
+ size += chunk.byteLength;
81
+ if (size > maxPartSize) {
82
+ throw new MaxPartSizeExceededError(name, maxPartSize);
83
+ }
84
+ chunks.push(chunk);
85
+ }
86
+
87
+ return new File(chunks, filename, { type: contentType });
88
+ };
89
+ }
@@ -9,6 +9,22 @@ export async function getPostBody(opts: {
9
9
  }): Promise<BodyResult> {
10
10
  const { req, maxBodySize = Infinity } = opts;
11
11
  return new Promise((resolve) => {
12
+ if (
13
+ !req.headers['content-type']?.startsWith('application/json') &&
14
+ (!req.method ||
15
+ (req.method !== 'GET' &&
16
+ req.method !== 'OPTIONS' &&
17
+ req.method !== 'HEAD'))
18
+ ) {
19
+ resolve({
20
+ ok: false,
21
+ error: new TRPCError({
22
+ code: 'UNSUPPORTED_MEDIA_TYPE',
23
+ message: 'Invalid Content-Type header (expected application/json)',
24
+ }),
25
+ });
26
+ return;
27
+ }
12
28
  if ('body' in req) {
13
29
  resolve({
14
30
  ok: true,
@@ -19,25 +35,18 @@ export async function getPostBody(opts: {
19
35
  });
20
36
  return;
21
37
  }
22
-
23
38
  let body = '';
24
39
  let hasBody = false;
25
-
26
- function onData(data: any) {
40
+ req.on('data', function (data) {
27
41
  body += data;
28
42
  hasBody = true;
29
43
  if (body.length > maxBodySize) {
30
- req.off('data', onData);
31
-
32
44
  resolve({
33
45
  ok: false,
34
46
  error: new TRPCError({ code: 'PAYLOAD_TOO_LARGE' }),
35
47
  });
36
48
  }
37
- }
38
-
39
- req.on('data', onData);
40
-
49
+ });
41
50
  req.on('end', () => {
42
51
  resolve({
43
52
  ok: true,
@@ -1,91 +1,11 @@
1
- // @trpc/server
2
- import { TRPCError } from '../../../../@trpc/server';
3
- import type {
4
- AnyRouter,
5
- CombinedDataTransformer,
6
- } from '../../../../@trpc/server';
7
- import type { NodeHTTPRequest, NodeHTTPResponse } from '../../types';
8
- import type { NodeHTTPContentTypeHandler } from '../types';
1
+ import { getJsonContentTypeInputs } from '../../../../@trpc/server/http';
2
+ import { createNodeHTTPContentTypeHandler } from '../../internals/contentType';
9
3
  import { getPostBody } from './getPostBody';
10
4
 
11
- export const getNodeHTTPJSONContentTypeHandler: <
12
- TRouter extends AnyRouter,
13
- TRequest extends NodeHTTPRequest,
14
- TResponse extends NodeHTTPResponse,
15
- >() => NodeHTTPContentTypeHandler<TRouter, TRequest, TResponse> = () => ({
16
- name: 'node-http-json',
17
- isMatch: (headers) => {
18
- return !!headers.get('content-type')?.startsWith('application/json');
19
- },
20
- getInputs: async (opts, info) => {
21
- const bodyResult = await getPostBody(opts);
22
- if (!bodyResult.ok) {
23
- throw bodyResult.error;
24
- }
25
-
26
- const preprocessedBody = bodyResult.preprocessed;
27
- const body = bodyResult.data;
28
-
29
- function getRawProcedureInputOrThrow() {
30
- try {
31
- if (opts.req.method === 'GET') {
32
- const input = opts.query.get('input');
33
- if (!input) {
34
- return undefined;
35
- }
36
-
37
- return JSON.parse(input);
38
- }
39
-
40
- if (preprocessedBody || typeof body !== 'string') {
41
- // Some tools like nextjs may parse json
42
- // requests before they reach us. So we just use them as is
43
- return body;
44
- } else {
45
- return JSON.parse(body);
46
- }
47
- } catch (cause) {
48
- throw new TRPCError({
49
- code: 'PARSE_ERROR',
50
- cause,
51
- });
52
- }
53
- }
54
-
55
- const deserializeInputValue = (
56
- rawValue: unknown,
57
- transformer: CombinedDataTransformer,
58
- ) => {
59
- return typeof rawValue !== 'undefined'
60
- ? transformer.input.deserialize(rawValue)
61
- : rawValue;
62
- };
63
-
64
- const rawInput = getRawProcedureInputOrThrow();
65
- if (rawInput === undefined) {
66
- return undefined;
67
- }
68
-
69
- const transformer = opts.router._def._config.transformer;
70
-
71
- if (!info.isBatchCall) {
72
- return deserializeInputValue(rawInput, transformer);
73
- }
74
-
75
- /* istanbul ignore if */
76
- if (
77
- rawInput == null ||
78
- typeof rawInput !== 'object' ||
79
- Array.isArray(rawInput)
80
- ) {
81
- throw new TRPCError({
82
- code: 'BAD_REQUEST',
83
- message: '"input" needs to be an object when doing a batch call',
84
- });
85
- }
86
-
87
- const rawValue = rawInput[info.batch];
88
-
89
- return deserializeInputValue(rawValue, transformer);
5
+ export const nodeHTTPJSONContentTypeHandler = createNodeHTTPContentTypeHandler({
6
+ isMatch(opts) {
7
+ return !!opts.req.headers['content-type']?.startsWith('application/json');
90
8
  },
9
+ getBody: getPostBody,
10
+ getInputs: getJsonContentTypeInputs,
91
11
  });
@@ -9,11 +9,23 @@ import type {
9
9
  } from '../types';
10
10
 
11
11
  export interface NodeHTTPContentTypeHandler<
12
- TRouter extends AnyRouter,
13
12
  TRequest extends NodeHTTPRequest,
14
13
  TResponse extends NodeHTTPResponse,
15
14
  > extends BaseContentTypeHandler<
16
- NodeHTTPRequestHandlerOptions<TRouter, TRequest, TResponse> & {
15
+ NodeHTTPRequestHandlerOptions<AnyRouter, TRequest, TResponse> & {
17
16
  query: URLSearchParams;
18
17
  }
19
18
  > {}
19
+
20
+ export function createNodeHTTPContentTypeHandler(
21
+ contentTypeHandler: NodeHTTPContentTypeHandler<
22
+ NodeHTTPRequest,
23
+ NodeHTTPResponse
24
+ >,
25
+ ) {
26
+ return <
27
+ TRequest extends NodeHTTPRequest,
28
+ TResponse extends NodeHTTPResponse,
29
+ >(): NodeHTTPContentTypeHandler<TRequest, TResponse> =>
30
+ contentTypeHandler as any;
31
+ }
@@ -8,7 +8,6 @@
8
8
  * ```
9
9
  */
10
10
  /* eslint-disable @typescript-eslint/no-non-null-assertion */
11
-
12
11
  // @trpc/server
13
12
  import type { AnyRouter } from '../../@trpc/server';
14
13
  import type {
@@ -21,16 +20,16 @@ import {
21
20
  getBatchStreamFormatter,
22
21
  resolveHTTPResponse,
23
22
  } from '../../@trpc/server/http';
24
- import { selectContentHandlerOrUnsupportedMediaType } from '../content-handlers/selectContentHandlerOrUnsupportedMediaType';
25
- import { getFormDataContentTypeHandler } from './content-type/form-data';
26
- import { getNodeHTTPJSONContentTypeHandler } from './content-type/json';
27
- import { getOctetContentTypeHandler } from './content-type/octet';
23
+ import { nodeHTTPJSONContentTypeHandler } from './content-type/json';
24
+ import type { NodeHTTPContentTypeHandler } from './internals/contentType';
28
25
  import type {
29
26
  NodeHTTPRequest,
30
27
  NodeHTTPRequestHandlerOptions,
31
28
  NodeHTTPResponse,
32
29
  } from './types';
33
30
 
31
+ const defaultJSONContentTypeHandler = nodeHTTPJSONContentTypeHandler();
32
+
34
33
  export async function nodeHTTPRequestHandler<
35
34
  TRouter extends AnyRouter,
36
35
  TRequest extends NodeHTTPRequest,
@@ -57,10 +56,38 @@ export async function nodeHTTPRequestHandler<
57
56
  ? new URLSearchParams(opts.req.query as any)
58
57
  : new URLSearchParams(opts.req.url!.split('?')[1]);
59
58
 
59
+ const jsonContentTypeHandler =
60
+ defaultJSONContentTypeHandler as unknown as NodeHTTPContentTypeHandler<
61
+ TRequest,
62
+ TResponse
63
+ >;
64
+
65
+ const contentTypeHandlers = opts.experimental_contentTypeHandlers ?? [
66
+ jsonContentTypeHandler,
67
+ ];
68
+
69
+ const contentTypeHandler =
70
+ contentTypeHandlers.find((handler) =>
71
+ handler.isMatch({
72
+ // FIXME: no typecasting should be needed here
73
+ ...(opts as any),
74
+ query,
75
+ }),
76
+ ) ??
77
+ // fallback to json
78
+ jsonContentTypeHandler;
79
+
80
+ const bodyResult = await contentTypeHandler.getBody({
81
+ // FIXME: no typecasting should be needed here
82
+ ...(opts as any),
83
+ query,
84
+ });
85
+
60
86
  const req: HTTPRequest = {
61
87
  method: opts.req.method!,
62
88
  headers: opts.req.headers,
63
89
  query,
90
+ body: bodyResult.ok ? bodyResult.data : undefined,
64
91
  };
65
92
 
66
93
  let isStream = false;
@@ -106,33 +133,19 @@ export async function nodeHTTPRequestHandler<
106
133
  }
107
134
  };
108
135
 
109
- const [contentTypeHandler, unsupportedMediaTypeError] =
110
- selectContentHandlerOrUnsupportedMediaType(
111
- [
112
- getNodeHTTPJSONContentTypeHandler<TRouter, TRequest, TResponse>(),
113
- getFormDataContentTypeHandler<TRouter, TRequest, TResponse>(),
114
- getOctetContentTypeHandler<TRouter, TRequest, TResponse>(),
115
- ],
116
- { ...opts, query },
117
- );
118
-
119
136
  await resolveHTTPResponse<TRouter, HTTPRequest>({
120
137
  ...opts,
121
138
  req,
122
139
  createContext,
123
- error: unsupportedMediaTypeError,
140
+ error: bodyResult.ok ? null : bodyResult.error,
141
+ preprocessedBody: bodyResult.ok ? bodyResult.preprocessed : false,
124
142
  onError(o) {
125
143
  opts?.onError?.({
126
144
  ...o,
127
145
  req: opts.req,
128
146
  });
129
147
  },
130
- async getInput(inputsOpts) {
131
- return await contentTypeHandler?.getInputs(
132
- { ...opts, query },
133
- inputsOpts,
134
- );
135
- },
148
+ contentTypeHandler,
136
149
  unstable_onHead,
137
150
  unstable_onChunk,
138
151
  });