@trpc/server 10.22.0 → 10.23.0
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.
- package/dist/adapters/aws-lambda/index.js +2 -1
- package/dist/adapters/aws-lambda/index.mjs +2 -1
- package/dist/adapters/express.js +5 -2
- package/dist/adapters/express.mjs +5 -2
- package/dist/adapters/fastify/index.js +2 -1
- package/dist/adapters/fastify/index.mjs +2 -1
- package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +1 -1
- package/dist/adapters/fetch/index.js +3 -2
- package/dist/adapters/fetch/index.mjs +3 -2
- package/dist/adapters/next.js +5 -2
- package/dist/adapters/next.mjs +5 -2
- package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts +70 -0
- package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts.map +1 -0
- package/dist/adapters/node-http/content-type/form-data/index.d.ts +24 -0
- package/dist/adapters/node-http/content-type/form-data/index.d.ts.map +1 -0
- package/dist/adapters/node-http/content-type/form-data/index.js +723 -0
- package/dist/adapters/node-http/content-type/form-data/index.mjs +708 -0
- package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts +31 -0
- package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts.map +1 -0
- package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts +11 -0
- package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts.map +1 -0
- package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts +40 -0
- package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts.map +1 -0
- package/dist/adapters/node-http/content-type/json/getPostBody.d.ts +7 -0
- package/dist/adapters/node-http/content-type/json/getPostBody.d.ts.map +1 -0
- package/dist/adapters/node-http/content-type/json/index.d.ts +2 -0
- package/dist/adapters/node-http/content-type/json/index.d.ts.map +1 -0
- package/dist/adapters/node-http/content-type/json/index.js +53 -0
- package/dist/adapters/node-http/content-type/json/index.mjs +49 -0
- package/dist/adapters/node-http/index.js +5 -2
- package/dist/adapters/node-http/index.mjs +5 -2
- package/dist/adapters/node-http/internals/contentType.d.ts +9 -0
- package/dist/adapters/node-http/internals/contentType.d.ts.map +1 -0
- package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts +1 -7
- package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
- package/dist/adapters/node-http/types.d.ts +7 -0
- package/dist/adapters/node-http/types.d.ts.map +1 -1
- package/dist/adapters/standalone.js +5 -2
- package/dist/adapters/standalone.mjs +5 -2
- package/dist/contentType-3194ed5f.mjs +5 -0
- package/dist/contentType-8356d528.js +54 -0
- package/dist/contentType-8c16408e.js +7 -0
- package/dist/contentType-a75c990c.js +58 -0
- package/dist/contentType-acc3be52.mjs +52 -0
- package/dist/contentType-f27e4bfc.js +5 -0
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/middleware.d.ts +3 -0
- package/dist/core/middleware.d.ts.map +1 -1
- package/dist/http/contentType.d.ts +29 -0
- package/dist/http/contentType.d.ts.map +1 -0
- package/dist/http/index.js +2 -1
- package/dist/http/index.mjs +2 -1
- package/dist/http/resolveHTTPResponse.d.ts +2 -0
- package/dist/http/resolveHTTPResponse.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.mjs +6 -4
- package/dist/{nodeHTTPRequestHandler-8bbfaa5c.js → nodeHTTPRequestHandler-953c8f9a.js} +22 -54
- package/dist/{nodeHTTPRequestHandler-9d8156da.js → nodeHTTPRequestHandler-c1dcd256.js} +22 -47
- package/dist/{nodeHTTPRequestHandler-4f6f12f6.mjs → nodeHTTPRequestHandler-fcbe1351.mjs} +22 -54
- package/dist/{resolveHTTPResponse-b413b925.js → resolveHTTPResponse-9a9f3436.js} +10 -56
- package/dist/{resolveHTTPResponse-a2e412ec.js → resolveHTTPResponse-a7abb046.js} +9 -49
- package/dist/{resolveHTTPResponse-24febe05.mjs → resolveHTTPResponse-e1286cb3.mjs} +10 -50
- package/package.json +14 -2
- package/src/adapters/fetch/fetchRequestHandler.ts +4 -1
- package/src/adapters/node-http/content-type/form-data/fileUploadHandler.ts +268 -0
- package/src/adapters/node-http/content-type/form-data/index.ts +105 -0
- package/src/adapters/node-http/content-type/form-data/memoryUploadHandler.ts +59 -0
- package/src/adapters/node-http/content-type/form-data/streamSlice.ts +51 -0
- package/src/adapters/node-http/content-type/form-data/uploadHandler.ts +85 -0
- package/src/adapters/node-http/{internals → content-type/json}/getPostBody.test.ts +6 -2
- package/src/adapters/node-http/{internals → content-type/json}/getPostBody.ts +5 -7
- package/src/adapters/node-http/content-type/json/index.ts +11 -0
- package/src/adapters/node-http/internals/contentType.ts +29 -0
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +34 -35
- package/src/adapters/node-http/types.ts +15 -0
- package/src/core/index.ts +1 -1
- package/src/core/internals/procedureBuilder.ts +21 -4
- package/src/core/middleware.ts +1 -0
- package/src/http/contentType.ts +100 -0
- package/src/http/resolveHTTPResponse.ts +18 -65
- package/dist/adapters/node-http/internals/getPostBody.d.ts +0 -14
- package/dist/adapters/node-http/internals/getPostBody.d.ts.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trpc/server",
|
|
3
|
-
"version": "10.
|
|
3
|
+
"version": "10.23.0",
|
|
4
4
|
"description": "tRPC Server",
|
|
5
5
|
"author": "KATT",
|
|
6
6
|
"license": "MIT",
|
|
@@ -69,6 +69,16 @@
|
|
|
69
69
|
"require": "./dist/adapters/node-http/index.js",
|
|
70
70
|
"default": "./dist/adapters/node-http/index.js"
|
|
71
71
|
},
|
|
72
|
+
"./adapters/node-http/content-type/json": {
|
|
73
|
+
"import": "./dist/adapters/node-http/content-type/json/index.mjs",
|
|
74
|
+
"require": "./dist/adapters/node-http/content-type/json/index.js",
|
|
75
|
+
"default": "./dist/adapters/node-http/content-type/json/index.js"
|
|
76
|
+
},
|
|
77
|
+
"./adapters/node-http/content-type/form-data": {
|
|
78
|
+
"import": "./dist/adapters/node-http/content-type/form-data/index.mjs",
|
|
79
|
+
"require": "./dist/adapters/node-http/content-type/form-data/index.js",
|
|
80
|
+
"default": "./dist/adapters/node-http/content-type/form-data/index.js"
|
|
81
|
+
},
|
|
72
82
|
"./adapters/standalone": {
|
|
73
83
|
"import": "./dist/adapters/standalone.mjs",
|
|
74
84
|
"require": "./dist/adapters/standalone.js",
|
|
@@ -135,6 +145,7 @@
|
|
|
135
145
|
"@types/react": "^18.0.9",
|
|
136
146
|
"@types/react-dom": "^18.0.5",
|
|
137
147
|
"@types/ws": "^8.2.0",
|
|
148
|
+
"@web3-storage/multipart-parser": "^1.0.0",
|
|
138
149
|
"aws-lambda": "^1.0.7",
|
|
139
150
|
"devalue": "^4.0.0",
|
|
140
151
|
"eslint": "^8.30.0",
|
|
@@ -150,6 +161,7 @@
|
|
|
150
161
|
"rollup": "^2.79.1",
|
|
151
162
|
"superjson": "^1.7.4",
|
|
152
163
|
"superstruct": "^1.0.0",
|
|
164
|
+
"tslib": "^2.5.0",
|
|
153
165
|
"tsx": "^3.12.3",
|
|
154
166
|
"typescript": "^4.8.3",
|
|
155
167
|
"vitest": "^0.28.5",
|
|
@@ -157,5 +169,5 @@
|
|
|
157
169
|
"yup": "^1.0.0",
|
|
158
170
|
"zod": "^3.0.0"
|
|
159
171
|
},
|
|
160
|
-
"gitHead": "
|
|
172
|
+
"gitHead": "189f81da3b02beedaf11f09f81526c5df63224b7"
|
|
161
173
|
}
|
|
@@ -23,7 +23,10 @@ export async function fetchRequestHandler<TRouter extends AnyRouter>(
|
|
|
23
23
|
query: url.searchParams,
|
|
24
24
|
method: opts.req.method,
|
|
25
25
|
headers: Object.fromEntries(opts.req.headers),
|
|
26
|
-
body:
|
|
26
|
+
body:
|
|
27
|
+
opts.req.headers.get('content-type') === 'application/json'
|
|
28
|
+
? await opts.req.text()
|
|
29
|
+
: '',
|
|
27
30
|
};
|
|
28
31
|
|
|
29
32
|
const result = await resolveHTTPResponse({
|
|
@@ -0,0 +1,268 @@
|
|
|
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
|
+
* @see 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 { Readable, finished } from 'node:stream';
|
|
19
|
+
import { promisify } from 'node:util';
|
|
20
|
+
import { streamSlice } from './streamSlice';
|
|
21
|
+
import { MaxPartSizeExceededError, UploadHandler } from './uploadHandler';
|
|
22
|
+
|
|
23
|
+
export async function readableStreamToString(
|
|
24
|
+
stream: ReadableStream<Uint8Array>,
|
|
25
|
+
encoding?: BufferEncoding,
|
|
26
|
+
) {
|
|
27
|
+
const reader = stream.getReader();
|
|
28
|
+
const chunks: Uint8Array[] = [];
|
|
29
|
+
|
|
30
|
+
async function read() {
|
|
31
|
+
const { done, value } = await reader.read();
|
|
32
|
+
|
|
33
|
+
if (done) {
|
|
34
|
+
return;
|
|
35
|
+
} else if (value) {
|
|
36
|
+
chunks.push(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
await read();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
await read();
|
|
43
|
+
|
|
44
|
+
return Buffer.concat(chunks).toString(encoding);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type FileUploadHandlerFilterArgs = {
|
|
48
|
+
filename: string;
|
|
49
|
+
contentType: string;
|
|
50
|
+
name: string;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export type FileUploadHandlerPathResolverArgs = {
|
|
54
|
+
filename: string;
|
|
55
|
+
contentType: string;
|
|
56
|
+
name: string;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Chooses the path of the file to be uploaded. If a string is not
|
|
61
|
+
* returned the file will not be written.
|
|
62
|
+
*/
|
|
63
|
+
export type FileUploadHandlerPathResolver = (
|
|
64
|
+
args: FileUploadHandlerPathResolverArgs,
|
|
65
|
+
) => string | undefined;
|
|
66
|
+
|
|
67
|
+
export type FileUploadHandlerOptions = {
|
|
68
|
+
/**
|
|
69
|
+
* Avoid file conflicts by appending a count on the end of the filename
|
|
70
|
+
* if it already exists on disk. Defaults to `true`.
|
|
71
|
+
*/
|
|
72
|
+
avoidFileConflicts?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* The directory to write the upload.
|
|
75
|
+
*/
|
|
76
|
+
directory?: string | FileUploadHandlerPathResolver;
|
|
77
|
+
/**
|
|
78
|
+
* The name of the file in the directory. Can be a relative path, the directory
|
|
79
|
+
* structure will be created if it does not exist.
|
|
80
|
+
*/
|
|
81
|
+
file?: FileUploadHandlerPathResolver;
|
|
82
|
+
/**
|
|
83
|
+
* The maximum upload size allowed. If the size is exceeded an error will be thrown.
|
|
84
|
+
* Defaults to 3000000B (3MB).
|
|
85
|
+
*/
|
|
86
|
+
maxPartSize?: number;
|
|
87
|
+
/**
|
|
88
|
+
*
|
|
89
|
+
* @param filename
|
|
90
|
+
* @param contentType
|
|
91
|
+
* @param name
|
|
92
|
+
*/
|
|
93
|
+
filter?(args: FileUploadHandlerFilterArgs): boolean | Promise<boolean>;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const defaultFilePathResolver: FileUploadHandlerPathResolver = ({
|
|
97
|
+
filename,
|
|
98
|
+
}) => {
|
|
99
|
+
const ext = filename ? extname(filename) : '';
|
|
100
|
+
return 'upload_' + randomBytes(4).readUInt32LE(0) + ext;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
async function uniqueFile(filepath: string) {
|
|
104
|
+
const ext = extname(filepath);
|
|
105
|
+
let uniqueFilepath = filepath;
|
|
106
|
+
|
|
107
|
+
for (
|
|
108
|
+
let i = 1;
|
|
109
|
+
await statAsync(uniqueFilepath)
|
|
110
|
+
.then(() => true)
|
|
111
|
+
.catch(() => false);
|
|
112
|
+
i++
|
|
113
|
+
) {
|
|
114
|
+
uniqueFilepath =
|
|
115
|
+
(ext ? filepath.slice(0, -ext.length) : filepath) +
|
|
116
|
+
`-${new Date().getTime()}${ext}`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return uniqueFilepath;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function createFileUploadHandler({
|
|
123
|
+
directory = tmpdir(),
|
|
124
|
+
avoidFileConflicts = true,
|
|
125
|
+
file = defaultFilePathResolver,
|
|
126
|
+
filter,
|
|
127
|
+
maxPartSize = 3000000,
|
|
128
|
+
}: FileUploadHandlerOptions = {}): UploadHandler {
|
|
129
|
+
return async ({ name, filename, contentType, data }) => {
|
|
130
|
+
if (
|
|
131
|
+
!filename ||
|
|
132
|
+
(filter && !(await filter({ name, filename, contentType })))
|
|
133
|
+
) {
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const dir =
|
|
138
|
+
typeof directory === 'string'
|
|
139
|
+
? directory
|
|
140
|
+
: directory({ name, filename, contentType });
|
|
141
|
+
|
|
142
|
+
if (!dir) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const filedir = resolvePath(dir);
|
|
147
|
+
const path =
|
|
148
|
+
typeof file === 'string' ? file : file({ name, filename, contentType });
|
|
149
|
+
|
|
150
|
+
if (!path) {
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let filepath = resolvePath(filedir, path);
|
|
155
|
+
|
|
156
|
+
if (avoidFileConflicts) {
|
|
157
|
+
filepath = await uniqueFile(filepath);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
await mkdir(dirname(filepath), { recursive: true }).catch(() => {});
|
|
161
|
+
|
|
162
|
+
const writeFileStream = createWriteStream(filepath);
|
|
163
|
+
let size = 0;
|
|
164
|
+
let deleteFile = false;
|
|
165
|
+
try {
|
|
166
|
+
for await (const chunk of data) {
|
|
167
|
+
size += chunk.byteLength;
|
|
168
|
+
if (size > maxPartSize) {
|
|
169
|
+
deleteFile = true;
|
|
170
|
+
throw new MaxPartSizeExceededError(name, maxPartSize);
|
|
171
|
+
}
|
|
172
|
+
writeFileStream.write(chunk);
|
|
173
|
+
}
|
|
174
|
+
} finally {
|
|
175
|
+
writeFileStream.end();
|
|
176
|
+
await promisify(finished)(writeFileStream);
|
|
177
|
+
|
|
178
|
+
if (deleteFile) {
|
|
179
|
+
await rm(filepath).catch(() => {});
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return new NodeOnDiskFile(filepath, contentType);
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export class NodeOnDiskFile implements File {
|
|
188
|
+
name: string;
|
|
189
|
+
lastModified = 0;
|
|
190
|
+
webkitRelativePath = '';
|
|
191
|
+
|
|
192
|
+
constructor(
|
|
193
|
+
private filepath: string,
|
|
194
|
+
public type: string,
|
|
195
|
+
private slicer?: { start: number; end: number },
|
|
196
|
+
) {
|
|
197
|
+
this.name = basename(filepath);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
get size(): number {
|
|
201
|
+
const stats = statSync(this.filepath);
|
|
202
|
+
|
|
203
|
+
if (this.slicer) {
|
|
204
|
+
const slice = this.slicer.end - this.slicer.start;
|
|
205
|
+
return slice < 0 ? 0 : slice > stats.size ? stats.size : slice;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return stats.size;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
slice(start?: number, end?: number, type?: string): Blob {
|
|
212
|
+
if (typeof start === 'number' && start < 0) start = this.size + start;
|
|
213
|
+
if (typeof end === 'number' && end < 0) end = this.size + end;
|
|
214
|
+
|
|
215
|
+
const startOffset = this.slicer?.start || 0;
|
|
216
|
+
|
|
217
|
+
start = startOffset + (start || 0);
|
|
218
|
+
end = startOffset + (end || this.size);
|
|
219
|
+
return new NodeOnDiskFile(
|
|
220
|
+
this.filepath,
|
|
221
|
+
typeof type === 'string' ? type : this.type,
|
|
222
|
+
{
|
|
223
|
+
start,
|
|
224
|
+
end,
|
|
225
|
+
},
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async arrayBuffer(): Promise<ArrayBuffer> {
|
|
230
|
+
let stream: Readable = createReadStream(this.filepath);
|
|
231
|
+
if (this.slicer) {
|
|
232
|
+
stream = stream.pipe(streamSlice(this.slicer.start, this.slicer.end));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return new Promise((resolve, reject) => {
|
|
236
|
+
const buf: any[] = [];
|
|
237
|
+
stream.on('data', (chunk) => buf.push(chunk));
|
|
238
|
+
stream.on('end', () => resolve(Buffer.concat(buf)));
|
|
239
|
+
stream.on('error', (err) => reject(err));
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
stream(): ReadableStream<any>;
|
|
244
|
+
stream(): NodeJS.ReadableStream;
|
|
245
|
+
stream(): ReadableStream<any> | NodeJS.ReadableStream {
|
|
246
|
+
let stream: Readable = createReadStream(this.filepath);
|
|
247
|
+
if (this.slicer) {
|
|
248
|
+
stream = stream.pipe(streamSlice(this.slicer.start, this.slicer.end));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return Readable.toWeb(stream);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async text(): Promise<string> {
|
|
255
|
+
return readableStreamToString(this.stream());
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
public get [Symbol.toStringTag]() {
|
|
259
|
+
return 'File';
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
remove(): Promise<void> {
|
|
263
|
+
return unlink(this.filepath);
|
|
264
|
+
}
|
|
265
|
+
getFilePath(): string {
|
|
266
|
+
return this.filepath;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
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
|
+
* @see https://github.com/remix-run/remix/blob/0bcb4a304dd2f08f6032c3bf0c3aa7eb5b976901/packages/remix-server-runtime/formData.ts
|
|
10
|
+
*/
|
|
11
|
+
import { CombinedDataTransformer } from '@trpc/server/transformer';
|
|
12
|
+
import { streamMultipart } from '@web3-storage/multipart-parser';
|
|
13
|
+
import { Readable } from 'node:stream';
|
|
14
|
+
import { createNodeHTTPContentTypeHandler } from '../../internals/contentType';
|
|
15
|
+
import { NodeHTTPRequest } from '../../types';
|
|
16
|
+
import { UploadHandler, UploadHandlerPart } from './uploadHandler';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Allows you to handle multipart forms (file uploads) for your app.
|
|
20
|
+
*
|
|
21
|
+
* TODO: Update this comment
|
|
22
|
+
* @see https://remix.run/utils/parse-multipart-form-data
|
|
23
|
+
*/
|
|
24
|
+
async function parseMultipartFormData(
|
|
25
|
+
request: NodeHTTPRequest,
|
|
26
|
+
uploadHandler: UploadHandler,
|
|
27
|
+
): Promise<FormData> {
|
|
28
|
+
const contentType = request.headers['content-type'] || '';
|
|
29
|
+
const [type, boundary] = contentType.split(/\s*;\s*boundary=/);
|
|
30
|
+
|
|
31
|
+
if (!boundary || type !== 'multipart/form-data') {
|
|
32
|
+
throw new TypeError('Could not parse content as FormData.');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const formData = new FormData();
|
|
36
|
+
const parts: AsyncIterable<UploadHandlerPart & { done?: true }> =
|
|
37
|
+
streamMultipart(Readable.toWeb(request), boundary);
|
|
38
|
+
|
|
39
|
+
for await (const part of parts) {
|
|
40
|
+
if (part.done) break;
|
|
41
|
+
|
|
42
|
+
if (typeof part.filename === 'string') {
|
|
43
|
+
// only pass basename as the multipart/form-data spec recommends
|
|
44
|
+
// https://datatracker.ietf.org/doc/html/rfc7578#section-4.2
|
|
45
|
+
part.filename = part.filename.split(/[/\\]/).pop();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const value = await uploadHandler(part);
|
|
49
|
+
|
|
50
|
+
if (typeof value !== 'undefined' && value !== null) {
|
|
51
|
+
formData.append(part.name, value as any);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return formData;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isMultipartFormDataRequest(req: NodeHTTPRequest) {
|
|
59
|
+
const contentTypeHeader = req.headers['content-type'];
|
|
60
|
+
return (
|
|
61
|
+
contentTypeHeader?.startsWith('multipart/form-data') ||
|
|
62
|
+
contentTypeHeader === 'application/x-www-form-urlencoded'
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const nodeHTTPFormDataContentTypeHandler =
|
|
67
|
+
createNodeHTTPContentTypeHandler({
|
|
68
|
+
isMatch(opts) {
|
|
69
|
+
return isMultipartFormDataRequest(opts.req);
|
|
70
|
+
},
|
|
71
|
+
async getBody(opts) {
|
|
72
|
+
const fields = Object.fromEntries(opts.query);
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
ok: true,
|
|
76
|
+
data: fields,
|
|
77
|
+
preprocessed: false,
|
|
78
|
+
};
|
|
79
|
+
},
|
|
80
|
+
getInputs(opts) {
|
|
81
|
+
const req = opts.req;
|
|
82
|
+
const unparsedInput = req.query.get('input');
|
|
83
|
+
if (!unparsedInput) {
|
|
84
|
+
return {
|
|
85
|
+
0: undefined,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const transformer = opts.router._def._config
|
|
89
|
+
.transformer as CombinedDataTransformer;
|
|
90
|
+
|
|
91
|
+
const deserializedInput = transformer.input.deserialize(
|
|
92
|
+
JSON.parse(unparsedInput),
|
|
93
|
+
);
|
|
94
|
+
return {
|
|
95
|
+
0: deserializedInput,
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
export { parseMultipartFormData as experimental_parseMultipartFormData };
|
|
101
|
+
export { createMemoryUploadHandler as experimental_createMemoryUploadHandler } from './memoryUploadHandler';
|
|
102
|
+
export { createFileUploadHandler as experimental_createFileUploadHandler } from './fileUploadHandler';
|
|
103
|
+
export { composeUploadHandlers as experimental_composeUploadHandlers } from './uploadHandler';
|
|
104
|
+
export { type UploadHandler } from './uploadHandler';
|
|
105
|
+
export { isMultipartFormDataRequest as experimental_isMultipartFormDataRequest };
|
|
@@ -0,0 +1,59 @@
|
|
|
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
|
+
* @see https://github.com/remix-run/remix/blob/0bcb4a304dd2f08f6032c3bf0c3aa7eb5b976901/packages/remix-server-runtime/upload/memoryUploadHandler.ts
|
|
10
|
+
*/
|
|
11
|
+
import { MaxPartSizeExceededError, UploadHandler } from './uploadHandler';
|
|
12
|
+
|
|
13
|
+
export type MemoryUploadHandlerFilterArgs = {
|
|
14
|
+
filename?: string;
|
|
15
|
+
contentType: string;
|
|
16
|
+
name: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type MemoryUploadHandlerOptions = {
|
|
20
|
+
/**
|
|
21
|
+
* The maximum upload size allowed. If the size is exceeded an error will be thrown.
|
|
22
|
+
* Defaults to 3000000B (3MB).
|
|
23
|
+
*/
|
|
24
|
+
maxPartSize?: number;
|
|
25
|
+
/**
|
|
26
|
+
*
|
|
27
|
+
* @param filename
|
|
28
|
+
* @param mimetype
|
|
29
|
+
* @param encoding
|
|
30
|
+
*/
|
|
31
|
+
filter?(args: MemoryUploadHandlerFilterArgs): boolean | Promise<boolean>;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export function createMemoryUploadHandler({
|
|
35
|
+
filter,
|
|
36
|
+
maxPartSize = 3000000,
|
|
37
|
+
}: MemoryUploadHandlerOptions = {}): UploadHandler {
|
|
38
|
+
return async ({ filename, contentType, name, data }) => {
|
|
39
|
+
if (filter && !(await filter({ filename, contentType, name }))) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let size = 0;
|
|
44
|
+
const chunks = [];
|
|
45
|
+
for await (const chunk of data) {
|
|
46
|
+
size += chunk.byteLength;
|
|
47
|
+
if (size > maxPartSize) {
|
|
48
|
+
throw new MaxPartSizeExceededError(name, maxPartSize);
|
|
49
|
+
}
|
|
50
|
+
chunks.push(chunk);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (typeof filename === 'string') {
|
|
54
|
+
return new File(chunks, filename, { type: contentType });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return await new Blob(chunks, { type: contentType }).text();
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Transform, TransformCallback } from 'node:stream';
|
|
2
|
+
|
|
3
|
+
class SliceStream extends Transform {
|
|
4
|
+
#start: number;
|
|
5
|
+
#end: number;
|
|
6
|
+
#offset = 0;
|
|
7
|
+
#emitUp = false;
|
|
8
|
+
#emitDown = false;
|
|
9
|
+
|
|
10
|
+
constructor(start = 0, end = Infinity) {
|
|
11
|
+
super();
|
|
12
|
+
this.#start = start;
|
|
13
|
+
this.#end = end;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
_transform(chunk: any, _: BufferEncoding, done: TransformCallback): void {
|
|
17
|
+
this.#offset += chunk.length;
|
|
18
|
+
|
|
19
|
+
if (!this.#emitUp && this.#offset >= this.#start) {
|
|
20
|
+
this.#emitUp = true;
|
|
21
|
+
const start = chunk.length - (this.#offset - this.#start);
|
|
22
|
+
|
|
23
|
+
if (this.#offset > this.#end) {
|
|
24
|
+
const end = chunk.length - (this.#offset - this.#end);
|
|
25
|
+
this.#emitDown = true;
|
|
26
|
+
this.push(chunk.slice(start, end));
|
|
27
|
+
} else {
|
|
28
|
+
this.push(chunk.slice(start, chunk.length));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return done();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (this.#emitUp && !this.#emitDown) {
|
|
35
|
+
if (this.#offset >= this.#end) {
|
|
36
|
+
this.#emitDown = true;
|
|
37
|
+
this.push(chunk.slice(0, chunk.length - (this.#offset - this.#end)));
|
|
38
|
+
} else {
|
|
39
|
+
this.push(chunk);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return done();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return done();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function streamSlice(start = 0, end = Infinity): SliceStream {
|
|
50
|
+
return new SliceStream(start, end);
|
|
51
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @see https://github.com/remix-run/remix/blob/0bcb4a304dd2f08f6032c3bf0c3aa7eb5b976901/packages/remix-server-runtime/formData.ts
|
|
3
|
+
*/
|
|
4
|
+
export type UploadHandlerPart = {
|
|
5
|
+
name: string;
|
|
6
|
+
filename?: string;
|
|
7
|
+
contentType: string;
|
|
8
|
+
data: AsyncIterable<Uint8Array>;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export type UploadHandler = (
|
|
12
|
+
part: UploadHandlerPart,
|
|
13
|
+
) => Promise<File | string | null | undefined>;
|
|
14
|
+
|
|
15
|
+
export function composeUploadHandlers(
|
|
16
|
+
...handlers: UploadHandler[]
|
|
17
|
+
): UploadHandler {
|
|
18
|
+
return async (part) => {
|
|
19
|
+
for (const handler of handlers) {
|
|
20
|
+
const value = await handler(part);
|
|
21
|
+
if (typeof value !== 'undefined' && value !== null) {
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return undefined;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class MaxPartSizeExceededError extends Error {
|
|
31
|
+
constructor(public field: string, public maxBytes: number) {
|
|
32
|
+
super(`Field "${field}" exceeded upload size of ${maxBytes} bytes.`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type MemoryUploadHandlerFilterArgs = {
|
|
37
|
+
filename?: string;
|
|
38
|
+
contentType: string;
|
|
39
|
+
name: string;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type MemoryUploadHandlerOptions = {
|
|
43
|
+
/**
|
|
44
|
+
* The maximum upload size allowed. If the size is exceeded an error will be thrown.
|
|
45
|
+
* Defaults to 3000000B (3MB).
|
|
46
|
+
*/
|
|
47
|
+
maxPartSize?: number;
|
|
48
|
+
/**
|
|
49
|
+
*
|
|
50
|
+
* @param filename
|
|
51
|
+
* @param mimetype
|
|
52
|
+
* @param encoding
|
|
53
|
+
*/
|
|
54
|
+
filter?(args: MemoryUploadHandlerFilterArgs): boolean | Promise<boolean>;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @see
|
|
59
|
+
*/
|
|
60
|
+
export function createMemoryUploadHandler({
|
|
61
|
+
filter,
|
|
62
|
+
maxPartSize = 3000000,
|
|
63
|
+
}: MemoryUploadHandlerOptions = {}): UploadHandler {
|
|
64
|
+
return async ({ filename, contentType, name, data }) => {
|
|
65
|
+
if (filter && !(await filter({ filename, contentType, name }))) {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let size = 0;
|
|
70
|
+
const chunks = [];
|
|
71
|
+
for await (const chunk of data) {
|
|
72
|
+
size += chunk.byteLength;
|
|
73
|
+
if (size > maxPartSize) {
|
|
74
|
+
throw new MaxPartSizeExceededError(name, maxPartSize);
|
|
75
|
+
}
|
|
76
|
+
chunks.push(chunk);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (typeof filename === 'string') {
|
|
80
|
+
return new File(chunks, filename, { type: contentType });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return await new Blob(chunks, { type: contentType }).text();
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -3,7 +3,9 @@ import { getPostBody } from './getPostBody';
|
|
|
3
3
|
|
|
4
4
|
test('has body', async () => {
|
|
5
5
|
const body = {};
|
|
6
|
-
const resolvedBody = await getPostBody({
|
|
6
|
+
const resolvedBody = await getPostBody({
|
|
7
|
+
req: { body },
|
|
8
|
+
} as any);
|
|
7
9
|
expect(resolvedBody).toMatchInlineSnapshot(`
|
|
8
10
|
Object {
|
|
9
11
|
"data": Object {},
|
|
@@ -24,7 +26,9 @@ test('req as eventemitter', async () => {
|
|
|
24
26
|
);
|
|
25
27
|
events.emit('end');
|
|
26
28
|
}, 5);
|
|
27
|
-
const result = await getPostBody({
|
|
29
|
+
const result = await getPostBody({
|
|
30
|
+
req: events,
|
|
31
|
+
} as any);
|
|
28
32
|
|
|
29
33
|
expect(result.ok).toBeTruthy();
|
|
30
34
|
expect((result as any).data).toBeTruthy();
|
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
import { TRPCError } from '
|
|
2
|
-
import {
|
|
1
|
+
import { TRPCError } from '../../../../error/TRPCError';
|
|
2
|
+
import { BodyResult } from '../../../../http/contentType';
|
|
3
|
+
import { NodeHTTPRequest } from '../../types';
|
|
3
4
|
|
|
4
5
|
export async function getPostBody(opts: {
|
|
5
6
|
req: NodeHTTPRequest;
|
|
6
7
|
maxBodySize?: number;
|
|
7
|
-
}) {
|
|
8
|
+
}): Promise<BodyResult> {
|
|
8
9
|
const { req, maxBodySize = Infinity } = opts;
|
|
9
|
-
return new Promise
|
|
10
|
-
| { ok: true; data: unknown; preprocessed: boolean }
|
|
11
|
-
| { ok: false; error: TRPCError }
|
|
12
|
-
>((resolve) => {
|
|
10
|
+
return new Promise((resolve) => {
|
|
13
11
|
if ('body' in req) {
|
|
14
12
|
resolve({ ok: true, data: req.body, preprocessed: true });
|
|
15
13
|
return;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { getJsonContentTypeInputs } from '../../../../http/contentType';
|
|
2
|
+
import { createNodeHTTPContentTypeHandler } from '../../internals/contentType';
|
|
3
|
+
import { getPostBody } from './getPostBody';
|
|
4
|
+
|
|
5
|
+
export const nodeHTTPJSONContentTypeHandler = createNodeHTTPContentTypeHandler({
|
|
6
|
+
isMatch(opts) {
|
|
7
|
+
return opts.req.headers['content-type'] === 'application/json';
|
|
8
|
+
},
|
|
9
|
+
getBody: getPostBody,
|
|
10
|
+
getInputs: getJsonContentTypeInputs,
|
|
11
|
+
});
|