@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.
Files changed (83) hide show
  1. package/dist/adapters/aws-lambda/index.js +2 -1
  2. package/dist/adapters/aws-lambda/index.mjs +2 -1
  3. package/dist/adapters/express.js +5 -2
  4. package/dist/adapters/express.mjs +5 -2
  5. package/dist/adapters/fastify/index.js +2 -1
  6. package/dist/adapters/fastify/index.mjs +2 -1
  7. package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +1 -1
  8. package/dist/adapters/fetch/index.js +3 -2
  9. package/dist/adapters/fetch/index.mjs +3 -2
  10. package/dist/adapters/next.js +5 -2
  11. package/dist/adapters/next.mjs +5 -2
  12. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts +70 -0
  13. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts.map +1 -0
  14. package/dist/adapters/node-http/content-type/form-data/index.d.ts +24 -0
  15. package/dist/adapters/node-http/content-type/form-data/index.d.ts.map +1 -0
  16. package/dist/adapters/node-http/content-type/form-data/index.js +723 -0
  17. package/dist/adapters/node-http/content-type/form-data/index.mjs +708 -0
  18. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts +31 -0
  19. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts.map +1 -0
  20. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts +11 -0
  21. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts.map +1 -0
  22. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts +40 -0
  23. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts.map +1 -0
  24. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts +7 -0
  25. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts.map +1 -0
  26. package/dist/adapters/node-http/content-type/json/index.d.ts +2 -0
  27. package/dist/adapters/node-http/content-type/json/index.d.ts.map +1 -0
  28. package/dist/adapters/node-http/content-type/json/index.js +53 -0
  29. package/dist/adapters/node-http/content-type/json/index.mjs +49 -0
  30. package/dist/adapters/node-http/index.js +5 -2
  31. package/dist/adapters/node-http/index.mjs +5 -2
  32. package/dist/adapters/node-http/internals/contentType.d.ts +9 -0
  33. package/dist/adapters/node-http/internals/contentType.d.ts.map +1 -0
  34. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts +1 -7
  35. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
  36. package/dist/adapters/node-http/types.d.ts +7 -0
  37. package/dist/adapters/node-http/types.d.ts.map +1 -1
  38. package/dist/adapters/standalone.js +5 -2
  39. package/dist/adapters/standalone.mjs +5 -2
  40. package/dist/contentType-3194ed5f.mjs +5 -0
  41. package/dist/contentType-8356d528.js +54 -0
  42. package/dist/contentType-8c16408e.js +7 -0
  43. package/dist/contentType-a75c990c.js +58 -0
  44. package/dist/contentType-acc3be52.mjs +52 -0
  45. package/dist/contentType-f27e4bfc.js +5 -0
  46. package/dist/core/index.d.ts +1 -0
  47. package/dist/core/index.d.ts.map +1 -1
  48. package/dist/core/middleware.d.ts +3 -0
  49. package/dist/core/middleware.d.ts.map +1 -1
  50. package/dist/http/contentType.d.ts +29 -0
  51. package/dist/http/contentType.d.ts.map +1 -0
  52. package/dist/http/index.js +2 -1
  53. package/dist/http/index.mjs +2 -1
  54. package/dist/http/resolveHTTPResponse.d.ts +2 -0
  55. package/dist/http/resolveHTTPResponse.d.ts.map +1 -1
  56. package/dist/index.js +6 -4
  57. package/dist/index.mjs +6 -4
  58. package/dist/{nodeHTTPRequestHandler-8bbfaa5c.js → nodeHTTPRequestHandler-953c8f9a.js} +22 -54
  59. package/dist/{nodeHTTPRequestHandler-9d8156da.js → nodeHTTPRequestHandler-c1dcd256.js} +22 -47
  60. package/dist/{nodeHTTPRequestHandler-4f6f12f6.mjs → nodeHTTPRequestHandler-fcbe1351.mjs} +22 -54
  61. package/dist/{resolveHTTPResponse-b413b925.js → resolveHTTPResponse-9a9f3436.js} +10 -56
  62. package/dist/{resolveHTTPResponse-a2e412ec.js → resolveHTTPResponse-a7abb046.js} +9 -49
  63. package/dist/{resolveHTTPResponse-24febe05.mjs → resolveHTTPResponse-e1286cb3.mjs} +10 -50
  64. package/package.json +14 -2
  65. package/src/adapters/fetch/fetchRequestHandler.ts +4 -1
  66. package/src/adapters/node-http/content-type/form-data/fileUploadHandler.ts +268 -0
  67. package/src/adapters/node-http/content-type/form-data/index.ts +105 -0
  68. package/src/adapters/node-http/content-type/form-data/memoryUploadHandler.ts +59 -0
  69. package/src/adapters/node-http/content-type/form-data/streamSlice.ts +51 -0
  70. package/src/adapters/node-http/content-type/form-data/uploadHandler.ts +85 -0
  71. package/src/adapters/node-http/{internals → content-type/json}/getPostBody.test.ts +6 -2
  72. package/src/adapters/node-http/{internals → content-type/json}/getPostBody.ts +5 -7
  73. package/src/adapters/node-http/content-type/json/index.ts +11 -0
  74. package/src/adapters/node-http/internals/contentType.ts +29 -0
  75. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +34 -35
  76. package/src/adapters/node-http/types.ts +15 -0
  77. package/src/core/index.ts +1 -1
  78. package/src/core/internals/procedureBuilder.ts +21 -4
  79. package/src/core/middleware.ts +1 -0
  80. package/src/http/contentType.ts +100 -0
  81. package/src/http/resolveHTTPResponse.ts +18 -65
  82. package/dist/adapters/node-http/internals/getPostBody.d.ts +0 -14
  83. package/dist/adapters/node-http/internals/getPostBody.d.ts.map +0 -1
@@ -0,0 +1,708 @@
1
+ import { Transform, finished, Readable } from 'node:stream';
2
+ import { c as createNodeHTTPContentTypeHandler } from '../../../../contentType-3194ed5f.mjs';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { createWriteStream, statSync, createReadStream } from 'node:fs';
5
+ import { mkdir, rm, unlink, stat } from 'node:fs/promises';
6
+ import { tmpdir } from 'node:os';
7
+ import { resolve, dirname, basename, extname } from 'node:path';
8
+ import { promisify } from 'node:util';
9
+ import _class_private_field_get from '@swc/helpers/src/_class_private_field_get.mjs';
10
+ import _class_private_field_init from '@swc/helpers/src/_class_private_field_init.mjs';
11
+ import _class_private_field_set from '@swc/helpers/src/_class_private_field_set.mjs';
12
+
13
+ function stringToArray(s) {
14
+ const utf8 = unescape(encodeURIComponent(s));
15
+ return Uint8Array.from(utf8, (_, i) => utf8.charCodeAt(i));
16
+ }
17
+ function arrayToString(a) {
18
+ const utf8 = String.fromCharCode.apply(null, a);
19
+ return decodeURIComponent(escape(utf8));
20
+ }
21
+ function mergeArrays(...arrays) {
22
+ const out = new Uint8Array(arrays.reduce((total, arr) => total + arr.length, 0));
23
+ let offset = 0;
24
+ for (const arr of arrays) {
25
+ out.set(arr, offset);
26
+ offset += arr.length;
27
+ }
28
+ return out;
29
+ }
30
+ function arraysEqual(a, b) {
31
+ if (a.length !== b.length) {
32
+ return false;
33
+ }
34
+ for (let i = 0; i < a.length; i++) {
35
+ if (a[i] !== b[i]) {
36
+ return false;
37
+ }
38
+ }
39
+ return true;
40
+ }
41
+
42
+ function coerce(a) {
43
+ if (a instanceof Uint8Array) {
44
+ return index => a[index];
45
+ }
46
+ return a;
47
+ }
48
+ function jsmemcmp(buf1, pos1, buf2, pos2, len) {
49
+ const fn1 = coerce(buf1);
50
+ const fn2 = coerce(buf2);
51
+ for (let i = 0; i < len; ++i) {
52
+ if (fn1(pos1 + i) !== fn2(pos2 + i)) {
53
+ return false;
54
+ }
55
+ }
56
+ return true;
57
+ }
58
+ function createOccurenceTable(s) {
59
+ const table = new Array(256).fill(s.length);
60
+ if (s.length > 1) {
61
+ for (let i = 0; i < s.length - 1; i++) {
62
+ table[s[i]] = s.length - 1 - i;
63
+ }
64
+ }
65
+ return table;
66
+ }
67
+ const MATCH = Symbol('Match');
68
+ class StreamSearch {
69
+ constructor(needle) {
70
+ this._lookbehind = new Uint8Array();
71
+ if (typeof needle === 'string') {
72
+ this._needle = needle = stringToArray(needle);
73
+ } else {
74
+ this._needle = needle;
75
+ }
76
+ this._lastChar = needle[needle.length - 1];
77
+ this._occ = createOccurenceTable(needle);
78
+ }
79
+ feed(chunk) {
80
+ let pos = 0;
81
+ let tokens;
82
+ const allTokens = [];
83
+ while (pos !== chunk.length) {
84
+ [pos, ...tokens] = this._feed(chunk, pos);
85
+ allTokens.push(...tokens);
86
+ }
87
+ return allTokens;
88
+ }
89
+ end() {
90
+ const tail = this._lookbehind;
91
+ this._lookbehind = new Uint8Array();
92
+ return tail;
93
+ }
94
+ _feed(data, bufPos) {
95
+ const tokens = [];
96
+ let pos = -this._lookbehind.length;
97
+ if (pos < 0) {
98
+ while (pos < 0 && pos <= data.length - this._needle.length) {
99
+ const ch = this._charAt(data, pos + this._needle.length - 1);
100
+ if (ch === this._lastChar && this._memcmp(data, pos, this._needle.length - 1)) {
101
+ if (pos > -this._lookbehind.length) {
102
+ tokens.push(this._lookbehind.slice(0, this._lookbehind.length + pos));
103
+ }
104
+ tokens.push(MATCH);
105
+ this._lookbehind = new Uint8Array();
106
+ return [
107
+ pos + this._needle.length,
108
+ ...tokens
109
+ ];
110
+ } else {
111
+ pos += this._occ[ch];
112
+ }
113
+ }
114
+ if (pos < 0) {
115
+ while (pos < 0 && !this._memcmp(data, pos, data.length - pos)) {
116
+ pos++;
117
+ }
118
+ }
119
+ if (pos >= 0) {
120
+ tokens.push(this._lookbehind);
121
+ this._lookbehind = new Uint8Array();
122
+ } else {
123
+ const bytesToCutOff = this._lookbehind.length + pos;
124
+ if (bytesToCutOff > 0) {
125
+ tokens.push(this._lookbehind.slice(0, bytesToCutOff));
126
+ this._lookbehind = this._lookbehind.slice(bytesToCutOff);
127
+ }
128
+ this._lookbehind = Uint8Array.from(new Array(this._lookbehind.length + data.length), (_, i) => this._charAt(data, i - this._lookbehind.length));
129
+ return [
130
+ data.length,
131
+ ...tokens
132
+ ];
133
+ }
134
+ }
135
+ pos += bufPos;
136
+ while (pos <= data.length - this._needle.length) {
137
+ const ch = data[pos + this._needle.length - 1];
138
+ if (ch === this._lastChar && data[pos] === this._needle[0] && jsmemcmp(this._needle, 0, data, pos, this._needle.length - 1)) {
139
+ if (pos > bufPos) {
140
+ tokens.push(data.slice(bufPos, pos));
141
+ }
142
+ tokens.push(MATCH);
143
+ return [
144
+ pos + this._needle.length,
145
+ ...tokens
146
+ ];
147
+ } else {
148
+ pos += this._occ[ch];
149
+ }
150
+ }
151
+ if (pos < data.length) {
152
+ while (pos < data.length && (data[pos] !== this._needle[0] || !jsmemcmp(data, pos, this._needle, 0, data.length - pos))) {
153
+ ++pos;
154
+ }
155
+ if (pos < data.length) {
156
+ this._lookbehind = data.slice(pos);
157
+ }
158
+ }
159
+ if (pos > 0) {
160
+ tokens.push(data.slice(bufPos, pos < data.length ? pos : data.length));
161
+ }
162
+ return [
163
+ data.length,
164
+ ...tokens
165
+ ];
166
+ }
167
+ _charAt(data, pos) {
168
+ if (pos < 0) {
169
+ return this._lookbehind[this._lookbehind.length + pos];
170
+ }
171
+ return data[pos];
172
+ }
173
+ _memcmp(data, pos, len) {
174
+ return jsmemcmp(this._charAt.bind(this, data), pos, this._needle, 0, len);
175
+ }
176
+ }
177
+ class ReadableStreamSearch {
178
+ constructor(needle, _readableStream) {
179
+ this._readableStream = _readableStream;
180
+ this._search = new StreamSearch(needle);
181
+ }
182
+ async *[Symbol.asyncIterator]() {
183
+ const reader = this._readableStream.getReader();
184
+ try {
185
+ while (true) {
186
+ const result = await reader.read();
187
+ if (result.done) {
188
+ break;
189
+ }
190
+ yield* this._search.feed(result.value);
191
+ }
192
+ const tail = this._search.end();
193
+ if (tail.length) {
194
+ yield tail;
195
+ }
196
+ } finally {
197
+ reader.releaseLock();
198
+ }
199
+ }
200
+ }
201
+
202
+ const mergeArrays2 = Function.prototype.apply.bind(mergeArrays, undefined);
203
+ const dash = stringToArray('--');
204
+ const CRLF = stringToArray('\r\n');
205
+ function parseContentDisposition(header) {
206
+ const parts = header.split(';').map(part => part.trim());
207
+ if (parts.shift() !== 'form-data') {
208
+ throw new Error('malformed content-disposition header: missing "form-data" in `' + JSON.stringify(parts) + '`');
209
+ }
210
+ const out = {};
211
+ for (const part of parts) {
212
+ const kv = part.split('=', 2);
213
+ if (kv.length !== 2) {
214
+ throw new Error('malformed content-disposition header: key-value pair not found - ' + part + ' in `' + header + '`');
215
+ }
216
+ const [name, value] = kv;
217
+ if (value[0] === '"' && value[value.length - 1] === '"') {
218
+ out[name] = value.slice(1, -1).replace(/\\"/g, '"');
219
+ } else if (value[0] !== '"' && value[value.length - 1] !== '"') {
220
+ out[name] = value;
221
+ } else if (value[0] === '"' && value[value.length - 1] !== '"' || value[0] !== '"' && value[value.length - 1] === '"') {
222
+ throw new Error('malformed content-disposition header: mismatched quotations in `' + header + '`');
223
+ }
224
+ }
225
+ if (!out.name) {
226
+ throw new Error('malformed content-disposition header: missing field name in `' + header + '`');
227
+ }
228
+ return out;
229
+ }
230
+ function parsePartHeaders(lines) {
231
+ const entries = [];
232
+ let disposition = false;
233
+ let line;
234
+ while (typeof (line = lines.shift()) !== 'undefined') {
235
+ const colon = line.indexOf(':');
236
+ if (colon === -1) {
237
+ throw new Error('malformed multipart-form header: missing colon');
238
+ }
239
+ const header = line.slice(0, colon).trim().toLowerCase();
240
+ const value = line.slice(colon + 1).trim();
241
+ switch (header) {
242
+ case 'content-disposition':
243
+ disposition = true;
244
+ entries.push(...Object.entries(parseContentDisposition(value)));
245
+ break;
246
+ case 'content-type':
247
+ entries.push([
248
+ 'contentType',
249
+ value
250
+ ]);
251
+ }
252
+ }
253
+ if (!disposition) {
254
+ throw new Error('malformed multipart-form header: missing content-disposition');
255
+ }
256
+ return Object.fromEntries(entries);
257
+ }
258
+ async function readHeaderLines(it, needle) {
259
+ let firstChunk = true;
260
+ let lastTokenWasMatch = false;
261
+ const headerLines = [[]];
262
+ const crlfSearch = new StreamSearch(CRLF);
263
+ for (;;) {
264
+ const result = await it.next();
265
+ if (result.done) {
266
+ throw new Error('malformed multipart-form data: unexpected end of stream');
267
+ }
268
+ if (firstChunk && result.value !== MATCH && arraysEqual(result.value.slice(0, 2), dash)) {
269
+ return [
270
+ undefined,
271
+ new Uint8Array()
272
+ ];
273
+ }
274
+ let chunk;
275
+ if (result.value !== MATCH) {
276
+ chunk = result.value;
277
+ } else if (!lastTokenWasMatch) {
278
+ chunk = needle;
279
+ } else {
280
+ throw new Error('malformed multipart-form data: unexpected boundary');
281
+ }
282
+ if (!chunk.length) {
283
+ continue;
284
+ }
285
+ if (firstChunk) {
286
+ firstChunk = false;
287
+ }
288
+ const tokens = crlfSearch.feed(chunk);
289
+ for (const [i, token] of tokens.entries()) {
290
+ const isMatch = token === MATCH;
291
+ if (!isMatch && !token.length) {
292
+ continue;
293
+ }
294
+ if (lastTokenWasMatch && isMatch) {
295
+ tokens.push(crlfSearch.end());
296
+ return [
297
+ headerLines.filter(chunks => chunks.length).map(mergeArrays2).map(arrayToString),
298
+ mergeArrays(...tokens.slice(i + 1).map(token => token === MATCH ? CRLF : token))
299
+ ];
300
+ }
301
+ if (lastTokenWasMatch = isMatch) {
302
+ headerLines.push([]);
303
+ } else {
304
+ headerLines[headerLines.length - 1].push(token);
305
+ }
306
+ }
307
+ }
308
+ }
309
+ async function* streamMultipart(body, boundary) {
310
+ const needle = mergeArrays(dash, stringToArray(boundary));
311
+ const it = new ReadableStreamSearch(needle, body)[Symbol.asyncIterator]();
312
+ for (;;) {
313
+ const result = await it.next();
314
+ if (result.done) {
315
+ return;
316
+ }
317
+ if (result.value === MATCH) {
318
+ break;
319
+ }
320
+ }
321
+ const crlfSearch = new StreamSearch(CRLF);
322
+ for (;;) {
323
+ const [headerLines, tail] = await readHeaderLines(it, needle);
324
+ if (!headerLines) {
325
+ return;
326
+ }
327
+ async function nextToken() {
328
+ const result = await it.next();
329
+ if (result.done) {
330
+ throw new Error('malformed multipart-form data: unexpected end of stream');
331
+ }
332
+ return result;
333
+ }
334
+ let trailingCRLF = false;
335
+ function feedChunk(chunk) {
336
+ const chunks = [];
337
+ for (const token of crlfSearch.feed(chunk)) {
338
+ if (trailingCRLF) {
339
+ chunks.push(CRLF);
340
+ }
341
+ if (!(trailingCRLF = token === MATCH)) {
342
+ chunks.push(token);
343
+ }
344
+ }
345
+ return mergeArrays(...chunks);
346
+ }
347
+ let done = false;
348
+ async function nextChunk() {
349
+ const result = await nextToken();
350
+ let chunk;
351
+ if (result.value !== MATCH) {
352
+ chunk = result.value;
353
+ } else if (!trailingCRLF) {
354
+ chunk = CRLF;
355
+ } else {
356
+ done = true;
357
+ return { value: crlfSearch.end() };
358
+ }
359
+ return { value: feedChunk(chunk) };
360
+ }
361
+ const bufferedChunks = [{ value: feedChunk(tail) }];
362
+ yield {
363
+ ...parsePartHeaders(headerLines),
364
+ data: {
365
+ [Symbol.asyncIterator]() {
366
+ return this;
367
+ },
368
+ async next() {
369
+ for (;;) {
370
+ const result = bufferedChunks.shift();
371
+ if (!result) {
372
+ break;
373
+ }
374
+ if (result.value.length > 0) {
375
+ return result;
376
+ }
377
+ }
378
+ for (;;) {
379
+ if (done) {
380
+ return {
381
+ done,
382
+ value: undefined
383
+ };
384
+ }
385
+ const result = await nextChunk();
386
+ if (result.value.length > 0) {
387
+ return result;
388
+ }
389
+ }
390
+ }
391
+ }
392
+ };
393
+ while (!done) {
394
+ bufferedChunks.push(await nextChunk());
395
+ }
396
+ }
397
+ }
398
+
399
+ /**
400
+ * @see https://github.com/remix-run/remix/blob/0bcb4a304dd2f08f6032c3bf0c3aa7eb5b976901/packages/remix-server-runtime/formData.ts
401
+ */ function composeUploadHandlers(...handlers) {
402
+ return async (part)=>{
403
+ for (const handler of handlers){
404
+ const value = await handler(part);
405
+ if (typeof value !== 'undefined' && value !== null) {
406
+ return value;
407
+ }
408
+ }
409
+ return undefined;
410
+ };
411
+ }
412
+ class MaxPartSizeExceededError extends Error {
413
+ constructor(field, maxBytes){
414
+ super(`Field "${field}" exceeded upload size of ${maxBytes} bytes.`);
415
+ this.field = field;
416
+ this.maxBytes = maxBytes;
417
+ }
418
+ }
419
+
420
+ function createMemoryUploadHandler({ filter , maxPartSize =3000000 } = {}) {
421
+ return async ({ filename , contentType , name , data })=>{
422
+ if (filter && !await filter({
423
+ filename,
424
+ contentType,
425
+ name
426
+ })) {
427
+ return undefined;
428
+ }
429
+ let size = 0;
430
+ const chunks = [];
431
+ for await (const chunk of data){
432
+ size += chunk.byteLength;
433
+ if (size > maxPartSize) {
434
+ throw new MaxPartSizeExceededError(name, maxPartSize);
435
+ }
436
+ chunks.push(chunk);
437
+ }
438
+ if (typeof filename === 'string') {
439
+ return new File(chunks, filename, {
440
+ type: contentType
441
+ });
442
+ }
443
+ return await new Blob(chunks, {
444
+ type: contentType
445
+ }).text();
446
+ };
447
+ }
448
+
449
+ var _start = /*#__PURE__*/ new WeakMap(), _end = /*#__PURE__*/ new WeakMap(), _offset = /*#__PURE__*/ new WeakMap(), _emitUp = /*#__PURE__*/ new WeakMap(), _emitDown = /*#__PURE__*/ new WeakMap();
450
+ class SliceStream extends Transform {
451
+ _transform(chunk, _, done) {
452
+ _class_private_field_set(this, _offset, _class_private_field_get(this, _offset) + chunk.length);
453
+ if (!_class_private_field_get(this, _emitUp) && _class_private_field_get(this, _offset) >= _class_private_field_get(this, _start)) {
454
+ _class_private_field_set(this, _emitUp, true);
455
+ const start = chunk.length - (_class_private_field_get(this, _offset) - _class_private_field_get(this, _start));
456
+ if (_class_private_field_get(this, _offset) > _class_private_field_get(this, _end)) {
457
+ const end = chunk.length - (_class_private_field_get(this, _offset) - _class_private_field_get(this, _end));
458
+ _class_private_field_set(this, _emitDown, true);
459
+ this.push(chunk.slice(start, end));
460
+ } else {
461
+ this.push(chunk.slice(start, chunk.length));
462
+ }
463
+ return done();
464
+ }
465
+ if (_class_private_field_get(this, _emitUp) && !_class_private_field_get(this, _emitDown)) {
466
+ if (_class_private_field_get(this, _offset) >= _class_private_field_get(this, _end)) {
467
+ _class_private_field_set(this, _emitDown, true);
468
+ this.push(chunk.slice(0, chunk.length - (_class_private_field_get(this, _offset) - _class_private_field_get(this, _end))));
469
+ } else {
470
+ this.push(chunk);
471
+ }
472
+ return done();
473
+ }
474
+ return done();
475
+ }
476
+ constructor(start = 0, end = Infinity){
477
+ super();
478
+ _class_private_field_init(this, _start, {
479
+ writable: true,
480
+ value: void 0
481
+ });
482
+ _class_private_field_init(this, _end, {
483
+ writable: true,
484
+ value: void 0
485
+ });
486
+ _class_private_field_init(this, _offset, {
487
+ writable: true,
488
+ value: 0
489
+ });
490
+ _class_private_field_init(this, _emitUp, {
491
+ writable: true,
492
+ value: false
493
+ });
494
+ _class_private_field_init(this, _emitDown, {
495
+ writable: true,
496
+ value: false
497
+ });
498
+ _class_private_field_set(this, _start, start);
499
+ _class_private_field_set(this, _end, end);
500
+ }
501
+ }
502
+ function streamSlice(start = 0, end = Infinity) {
503
+ return new SliceStream(start, end);
504
+ }
505
+
506
+ async function readableStreamToString(stream, encoding) {
507
+ const reader = stream.getReader();
508
+ const chunks = [];
509
+ async function read() {
510
+ const { done , value } = await reader.read();
511
+ if (done) {
512
+ return;
513
+ } else if (value) {
514
+ chunks.push(value);
515
+ }
516
+ await read();
517
+ }
518
+ await read();
519
+ return Buffer.concat(chunks).toString(encoding);
520
+ }
521
+ const defaultFilePathResolver = ({ filename })=>{
522
+ const ext = filename ? extname(filename) : '';
523
+ return 'upload_' + randomBytes(4).readUInt32LE(0) + ext;
524
+ };
525
+ async function uniqueFile(filepath) {
526
+ const ext = extname(filepath);
527
+ let uniqueFilepath = filepath;
528
+ for(let i = 1; await stat(uniqueFilepath).then(()=>true).catch(()=>false); i++){
529
+ uniqueFilepath = (ext ? filepath.slice(0, -ext.length) : filepath) + `-${new Date().getTime()}${ext}`;
530
+ }
531
+ return uniqueFilepath;
532
+ }
533
+ function createFileUploadHandler({ directory =tmpdir() , avoidFileConflicts =true , file =defaultFilePathResolver , filter , maxPartSize =3000000 } = {}) {
534
+ return async ({ name , filename , contentType , data })=>{
535
+ if (!filename || filter && !await filter({
536
+ name,
537
+ filename,
538
+ contentType
539
+ })) {
540
+ return undefined;
541
+ }
542
+ const dir = typeof directory === 'string' ? directory : directory({
543
+ name,
544
+ filename,
545
+ contentType
546
+ });
547
+ if (!dir) {
548
+ return undefined;
549
+ }
550
+ const filedir = resolve(dir);
551
+ const path = typeof file === 'string' ? file : file({
552
+ name,
553
+ filename,
554
+ contentType
555
+ });
556
+ if (!path) {
557
+ return undefined;
558
+ }
559
+ let filepath = resolve(filedir, path);
560
+ if (avoidFileConflicts) {
561
+ filepath = await uniqueFile(filepath);
562
+ }
563
+ await mkdir(dirname(filepath), {
564
+ recursive: true
565
+ }).catch(()=>{});
566
+ const writeFileStream = createWriteStream(filepath);
567
+ let size = 0;
568
+ let deleteFile = false;
569
+ try {
570
+ for await (const chunk of data){
571
+ size += chunk.byteLength;
572
+ if (size > maxPartSize) {
573
+ deleteFile = true;
574
+ throw new MaxPartSizeExceededError(name, maxPartSize);
575
+ }
576
+ writeFileStream.write(chunk);
577
+ }
578
+ } finally{
579
+ writeFileStream.end();
580
+ await promisify(finished)(writeFileStream);
581
+ if (deleteFile) {
582
+ await rm(filepath).catch(()=>{});
583
+ }
584
+ }
585
+ return new NodeOnDiskFile(filepath, contentType);
586
+ };
587
+ }
588
+ class NodeOnDiskFile {
589
+ get size() {
590
+ const stats = statSync(this.filepath);
591
+ if (this.slicer) {
592
+ const slice = this.slicer.end - this.slicer.start;
593
+ return slice < 0 ? 0 : slice > stats.size ? stats.size : slice;
594
+ }
595
+ return stats.size;
596
+ }
597
+ slice(start, end, type) {
598
+ if (typeof start === 'number' && start < 0) start = this.size + start;
599
+ if (typeof end === 'number' && end < 0) end = this.size + end;
600
+ const startOffset = this.slicer?.start || 0;
601
+ start = startOffset + (start || 0);
602
+ end = startOffset + (end || this.size);
603
+ return new NodeOnDiskFile(this.filepath, typeof type === 'string' ? type : this.type, {
604
+ start,
605
+ end
606
+ });
607
+ }
608
+ async arrayBuffer() {
609
+ let stream = createReadStream(this.filepath);
610
+ if (this.slicer) {
611
+ stream = stream.pipe(streamSlice(this.slicer.start, this.slicer.end));
612
+ }
613
+ return new Promise((resolve, reject)=>{
614
+ const buf = [];
615
+ stream.on('data', (chunk)=>buf.push(chunk));
616
+ stream.on('end', ()=>resolve(Buffer.concat(buf)));
617
+ stream.on('error', (err)=>reject(err));
618
+ });
619
+ }
620
+ stream() {
621
+ let stream = createReadStream(this.filepath);
622
+ if (this.slicer) {
623
+ stream = stream.pipe(streamSlice(this.slicer.start, this.slicer.end));
624
+ }
625
+ return Readable.toWeb(stream);
626
+ }
627
+ async text() {
628
+ return readableStreamToString(this.stream());
629
+ }
630
+ get [Symbol.toStringTag]() {
631
+ return 'File';
632
+ }
633
+ remove() {
634
+ return unlink(this.filepath);
635
+ }
636
+ getFilePath() {
637
+ return this.filepath;
638
+ }
639
+ constructor(filepath, type, slicer){
640
+ this.filepath = filepath;
641
+ this.type = type;
642
+ this.slicer = slicer;
643
+ this.lastModified = 0;
644
+ this.webkitRelativePath = '';
645
+ this.name = basename(filepath);
646
+ }
647
+ }
648
+
649
+ /**
650
+ * Allows you to handle multipart forms (file uploads) for your app.
651
+ *
652
+ * TODO: Update this comment
653
+ * @see https://remix.run/utils/parse-multipart-form-data
654
+ */ async function parseMultipartFormData(request, uploadHandler) {
655
+ const contentType = request.headers['content-type'] || '';
656
+ const [type, boundary] = contentType.split(/\s*;\s*boundary=/);
657
+ if (!boundary || type !== 'multipart/form-data') {
658
+ throw new TypeError('Could not parse content as FormData.');
659
+ }
660
+ const formData = new FormData();
661
+ const parts = streamMultipart(Readable.toWeb(request), boundary);
662
+ for await (const part of parts){
663
+ if (part.done) break;
664
+ if (typeof part.filename === 'string') {
665
+ // only pass basename as the multipart/form-data spec recommends
666
+ // https://datatracker.ietf.org/doc/html/rfc7578#section-4.2
667
+ part.filename = part.filename.split(/[/\\]/).pop();
668
+ }
669
+ const value = await uploadHandler(part);
670
+ if (typeof value !== 'undefined' && value !== null) {
671
+ formData.append(part.name, value);
672
+ }
673
+ }
674
+ return formData;
675
+ }
676
+ function isMultipartFormDataRequest(req) {
677
+ const contentTypeHeader = req.headers['content-type'];
678
+ return contentTypeHeader?.startsWith('multipart/form-data') || contentTypeHeader === 'application/x-www-form-urlencoded';
679
+ }
680
+ const nodeHTTPFormDataContentTypeHandler = createNodeHTTPContentTypeHandler({
681
+ isMatch (opts) {
682
+ return isMultipartFormDataRequest(opts.req);
683
+ },
684
+ async getBody (opts) {
685
+ const fields = Object.fromEntries(opts.query);
686
+ return {
687
+ ok: true,
688
+ data: fields,
689
+ preprocessed: false
690
+ };
691
+ },
692
+ getInputs (opts) {
693
+ const req = opts.req;
694
+ const unparsedInput = req.query.get('input');
695
+ if (!unparsedInput) {
696
+ return {
697
+ 0: undefined
698
+ };
699
+ }
700
+ const transformer = opts.router._def._config.transformer;
701
+ const deserializedInput = transformer.input.deserialize(JSON.parse(unparsedInput));
702
+ return {
703
+ 0: deserializedInput
704
+ };
705
+ }
706
+ });
707
+
708
+ export { composeUploadHandlers as experimental_composeUploadHandlers, createFileUploadHandler as experimental_createFileUploadHandler, createMemoryUploadHandler as experimental_createMemoryUploadHandler, isMultipartFormDataRequest as experimental_isMultipartFormDataRequest, parseMultipartFormData as experimental_parseMultipartFormData, nodeHTTPFormDataContentTypeHandler };