@orpc/node 2.0.0-beta.47 → 2.0.0-beta.48
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/README.md +2 -3
- package/dist/batch-response-compression-handler-plugin.d.mts +46 -0
- package/dist/batch-response-compression-handler-plugin.mjs +88 -0
- package/dist/index.d.mts +3 -316
- package/dist/index.mjs +3 -927
- package/dist/multipart.d.mts +60 -0
- package/dist/multipart.mjs +179 -0
- package/dist/static-file-handler-plugin.d.mts +133 -0
- package/dist/static-file-handler-plugin.mjs +354 -0
- package/dist/tmp-file-upload-handler-plugin.d.mts +133 -0
- package/dist/tmp-file-upload-handler-plugin.mjs +364 -0
- package/package.json +8 -8
- package/dist/index.d.ts +0 -316
package/dist/index.mjs
CHANGED
|
@@ -1,927 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { toArray, mergeHttpPath, safeDecodeURIComponent, matchesHttpPathPrefix, safeEncodeURIComponent, isCompressibleContentType, parseAcceptEncodingQualities, isAcceptableEncoding, getTracer, value, isAsyncIteratorObject, override, wrapAsyncIterator, wrapReadableStream } from '@orpc/shared';
|
|
5
|
-
import { flattenStandardHeader, parseStandardUrl, resolveStandardBodyHint, getFilenameFromContentDisposition } from '@standard-server/core';
|
|
6
|
-
import { toFetchBody, toFetchHeaders, toStandardBody } from '@standard-server/fetch';
|
|
7
|
-
import { createReadStream, openAsBlob } from 'node:fs';
|
|
8
|
-
import { realpath, stat, mkdtemp, appendFile, rm } from 'node:fs/promises';
|
|
9
|
-
import path from 'node:path';
|
|
10
|
-
import { toWebReadableStream } from '@standard-server/node';
|
|
11
|
-
import mime from 'mime';
|
|
12
|
-
import { Buffer } from 'node:buffer';
|
|
13
|
-
import { tmpdir } from 'node:os';
|
|
14
|
-
import { ORPCError } from '@orpc/server';
|
|
15
|
-
|
|
16
|
-
class BatchResponseCompressionHandlerPlugin {
|
|
17
|
-
name = "~batch-response-compression";
|
|
18
|
-
/**
|
|
19
|
-
* Compression should be done after batching, to compress the assembled batch response
|
|
20
|
-
* rather than each subresponse inside it.
|
|
21
|
-
*/
|
|
22
|
-
after = ["~batch"];
|
|
23
|
-
encodings;
|
|
24
|
-
threshold;
|
|
25
|
-
constructor(options = {}) {
|
|
26
|
-
this.encodings = options.encodings ?? ["gzip", "deflate"];
|
|
27
|
-
this.threshold = options.threshold ?? 1024;
|
|
28
|
-
}
|
|
29
|
-
init(options) {
|
|
30
|
-
const routingInterceptor = async ({ next, ...interceptorOptions }) => {
|
|
31
|
-
const result = await next();
|
|
32
|
-
if (!result.matched) {
|
|
33
|
-
return result;
|
|
34
|
-
}
|
|
35
|
-
if (flattenStandardHeader(interceptorOptions.request.headers[BATCH_HEADER]) === void 0) {
|
|
36
|
-
return result;
|
|
37
|
-
}
|
|
38
|
-
const response = result.response;
|
|
39
|
-
const headers = response.headers;
|
|
40
|
-
const body = response.body;
|
|
41
|
-
if (response.status >= 400) {
|
|
42
|
-
return result;
|
|
43
|
-
}
|
|
44
|
-
const encoding = negotiateResponseCompressionEncoding(response, interceptorOptions.request.headers, this.encodings);
|
|
45
|
-
if (encoding === void 0) {
|
|
46
|
-
return result;
|
|
47
|
-
}
|
|
48
|
-
let stream;
|
|
49
|
-
let bodyHeaders;
|
|
50
|
-
if (Array.isArray(body)) {
|
|
51
|
-
const [string, jsonHeaders] = toFetchBody(body, headers);
|
|
52
|
-
const json = new Blob([string]);
|
|
53
|
-
if (json.size < this.threshold) {
|
|
54
|
-
return result;
|
|
55
|
-
}
|
|
56
|
-
stream = json.stream();
|
|
57
|
-
bodyHeaders = {
|
|
58
|
-
"content-type": jsonHeaders["content-type"],
|
|
59
|
-
// An empty hint rather than none, so the adapter does not hint the compressed stream as `octet-stream`
|
|
60
|
-
"standard-server": jsonHeaders["standard-server"] ?? []
|
|
61
|
-
};
|
|
62
|
-
} else if (body instanceof Blob || body instanceof ReadableStream) {
|
|
63
|
-
if (body instanceof Blob && Number.isFinite(body.size) && body.size < this.threshold) {
|
|
64
|
-
return result;
|
|
65
|
-
}
|
|
66
|
-
stream = body instanceof Blob ? body.stream() : body;
|
|
67
|
-
bodyHeaders = { "standard-server": "octet-stream" };
|
|
68
|
-
} else {
|
|
69
|
-
return result;
|
|
70
|
-
}
|
|
71
|
-
return {
|
|
72
|
-
...result,
|
|
73
|
-
response: {
|
|
74
|
-
...response,
|
|
75
|
-
body: stream.pipeThrough(createFlushingCompressionStream(encoding)),
|
|
76
|
-
headers: {
|
|
77
|
-
...toCompressedHeaders(headers, encoding),
|
|
78
|
-
...bodyHeaders
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
};
|
|
82
|
-
};
|
|
83
|
-
return {
|
|
84
|
-
...options,
|
|
85
|
-
routingInterceptors: [
|
|
86
|
-
routingInterceptor,
|
|
87
|
-
...toArray(options.routingInterceptors)
|
|
88
|
-
]
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
function createFlushingCompressionStream(encoding) {
|
|
93
|
-
const zlibOptions = { flush: constants.Z_SYNC_FLUSH };
|
|
94
|
-
const compressor = encoding === "gzip" ? createGzip(zlibOptions) : encoding === "deflate" ? createDeflate(zlibOptions) : createDeflateRaw(zlibOptions);
|
|
95
|
-
return Duplex.toWeb(compressor);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
const TEXT_CONTENT_TYPE_REGEX = /^text\//;
|
|
99
|
-
const SHORT_NAME_ALIAS_REGEX = /^[^.]{0,6}~\d/;
|
|
100
|
-
const PRECOMPRESSED_ENCODINGS = [
|
|
101
|
-
["br", ".br"],
|
|
102
|
-
["zstd", ".zst"],
|
|
103
|
-
["gzip", ".gz"]
|
|
104
|
-
];
|
|
105
|
-
class StaticFileHandlerPlugin {
|
|
106
|
-
name = "~static-file";
|
|
107
|
-
/**
|
|
108
|
-
* Ensure the request span is available when the interceptor renames it.
|
|
109
|
-
*/
|
|
110
|
-
after = ["~tracing"];
|
|
111
|
-
rootDir;
|
|
112
|
-
/** `rootDir` with a trailing separator, precomputed for the lexical containment check. */
|
|
113
|
-
rootDirPrefix;
|
|
114
|
-
/**
|
|
115
|
-
* `rootDir` with its own symbolic links resolved, paired with its trailing separator form.
|
|
116
|
-
* Resolved once, so a symlinked `rootDir` keeps working and platform links like the macOS
|
|
117
|
-
* `/var` to `/private/var` do not reject every file.
|
|
118
|
-
*/
|
|
119
|
-
rootDirRealPaths;
|
|
120
|
-
path;
|
|
121
|
-
indexFile;
|
|
122
|
-
fallbackFile;
|
|
123
|
-
cacheControl;
|
|
124
|
-
dotfiles;
|
|
125
|
-
precompressed;
|
|
126
|
-
allowSymlinks;
|
|
127
|
-
mimeTypes;
|
|
128
|
-
constructor(options) {
|
|
129
|
-
this.rootDir = path.resolve(options.rootDir);
|
|
130
|
-
this.rootDirPrefix = this.rootDir.endsWith(path.sep) ? this.rootDir : this.rootDir + path.sep;
|
|
131
|
-
this.rootDirRealPaths = realpath(this.rootDir).catch(() => this.rootDir).then((rootDirReal) => [rootDirReal, rootDirReal.endsWith(path.sep) ? rootDirReal : rootDirReal + path.sep]);
|
|
132
|
-
this.path = stripTrailingSlash(options.path ?? "/");
|
|
133
|
-
this.indexFile = options.indexFile ?? "index.html";
|
|
134
|
-
this.fallbackFile = options.fallbackFile;
|
|
135
|
-
this.cacheControl = options.cacheControl ?? "public, max-age=0";
|
|
136
|
-
this.dotfiles = options.dotfiles ?? false;
|
|
137
|
-
this.precompressed = options.precompressed ?? false;
|
|
138
|
-
this.allowSymlinks = options.allowSymlinks ?? false;
|
|
139
|
-
this.mimeTypes = Object.assign(/* @__PURE__ */ Object.create(null), options.mimeTypes);
|
|
140
|
-
}
|
|
141
|
-
init(options) {
|
|
142
|
-
const routingInterceptor = async ({ next, request, prefix }) => {
|
|
143
|
-
const result = await next();
|
|
144
|
-
if (result.matched || request.method !== "GET" && request.method !== "HEAD") {
|
|
145
|
-
return result;
|
|
146
|
-
}
|
|
147
|
-
const base = this.resolveBasePath(prefix);
|
|
148
|
-
const response = await this.serve(request, base);
|
|
149
|
-
if (response === void 0) {
|
|
150
|
-
return result;
|
|
151
|
-
}
|
|
152
|
-
getTracer()?.getActiveSpan()?.updateName(`${request.method} ${base === "/" ? "" : base}/* (static file)`);
|
|
153
|
-
return { matched: true, response };
|
|
154
|
-
};
|
|
155
|
-
return {
|
|
156
|
-
...options,
|
|
157
|
-
// Run after user-provided routing interceptors so they can capture file responses
|
|
158
|
-
routingInterceptors: [...toArray(options.routingInterceptors), routingInterceptor]
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
/**
|
|
162
|
-
* Joins segments under `rootDir` and guarantees the result cannot escape it,
|
|
163
|
-
* as a second layer of defense after URL segment validation.
|
|
164
|
-
*/
|
|
165
|
-
resolveWithinRoot(segments) {
|
|
166
|
-
const resolved = path.join(this.rootDir, ...segments);
|
|
167
|
-
if (resolved !== this.rootDir && !resolved.startsWith(this.rootDirPrefix)) {
|
|
168
|
-
return void 0;
|
|
169
|
-
}
|
|
170
|
-
return resolved;
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Resolves symbolic links and confirms the target is still inside the root,
|
|
174
|
-
* which the lexical `resolveWithinRoot` check cannot see.
|
|
175
|
-
*/
|
|
176
|
-
async resolveContainedRealPath(filePath) {
|
|
177
|
-
if (this.allowSymlinks) {
|
|
178
|
-
return filePath;
|
|
179
|
-
}
|
|
180
|
-
const [rootDirReal, rootDirRealPrefix] = await this.rootDirRealPaths;
|
|
181
|
-
const realPath = await realpath(filePath).catch(() => "");
|
|
182
|
-
return realPath === rootDirReal || realPath.startsWith(rootDirRealPrefix) ? realPath : void 0;
|
|
183
|
-
}
|
|
184
|
-
resolveContentType(filePath) {
|
|
185
|
-
const extension = path.extname(filePath).slice(1).toLowerCase();
|
|
186
|
-
const configured = this.mimeTypes[extension];
|
|
187
|
-
if (configured !== void 0) {
|
|
188
|
-
return configured;
|
|
189
|
-
}
|
|
190
|
-
const contentType = mime.getType(extension);
|
|
191
|
-
if (contentType === null) {
|
|
192
|
-
return "application/octet-stream";
|
|
193
|
-
}
|
|
194
|
-
return TEXT_CONTENT_TYPE_REGEX.test(contentType) ? `${contentType}; charset=utf-8` : contentType;
|
|
195
|
-
}
|
|
196
|
-
resolveBasePath(prefix) {
|
|
197
|
-
return prefix === void 0 ? this.path : stripTrailingSlash(mergeHttpPath(prefix, this.path));
|
|
198
|
-
}
|
|
199
|
-
/**
|
|
200
|
-
* Resolves segments under `rootDir` and stats the result, rejecting anything that
|
|
201
|
-
* escapes the root either lexically or by following a symbolic link.
|
|
202
|
-
*/
|
|
203
|
-
async lookup(segments) {
|
|
204
|
-
const filePath = this.resolveWithinRoot(segments);
|
|
205
|
-
if (filePath === void 0) {
|
|
206
|
-
return void 0;
|
|
207
|
-
}
|
|
208
|
-
const [stats, containedRealPath] = await Promise.all([
|
|
209
|
-
stat(filePath).catch(() => void 0),
|
|
210
|
-
this.resolveContainedRealPath(filePath)
|
|
211
|
-
]);
|
|
212
|
-
if (stats === void 0 || containedRealPath === void 0) {
|
|
213
|
-
return void 0;
|
|
214
|
-
}
|
|
215
|
-
return [filePath, stats];
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Normalizes the url path into filesystem segments,
|
|
219
|
-
* returning `undefined` when the request can never map to a servable file.
|
|
220
|
-
*/
|
|
221
|
-
resolveSegments(pathname, base) {
|
|
222
|
-
const segments = [];
|
|
223
|
-
for (const rawSegment of pathname.slice(base.length).split("/")) {
|
|
224
|
-
const segment = safeDecodeURIComponent(rawSegment);
|
|
225
|
-
if (segment === "" || segment === ".") {
|
|
226
|
-
continue;
|
|
227
|
-
}
|
|
228
|
-
if (segment === "..") {
|
|
229
|
-
if (segments.length === 0) {
|
|
230
|
-
return void 0;
|
|
231
|
-
}
|
|
232
|
-
segments.pop();
|
|
233
|
-
continue;
|
|
234
|
-
}
|
|
235
|
-
if (segment.includes("\0") || segment.includes("/") || segment.includes("\\")) {
|
|
236
|
-
return void 0;
|
|
237
|
-
}
|
|
238
|
-
if (!this.dotfiles && (segment.startsWith(".") || SHORT_NAME_ALIAS_REGEX.test(segment))) {
|
|
239
|
-
return void 0;
|
|
240
|
-
}
|
|
241
|
-
segments.push(segment);
|
|
242
|
-
}
|
|
243
|
-
return segments;
|
|
244
|
-
}
|
|
245
|
-
async serve(request, base) {
|
|
246
|
-
const [pathname, search] = parseStandardUrl(request.url);
|
|
247
|
-
if (base !== "/" && !matchesHttpPathPrefix(pathname, base)) {
|
|
248
|
-
return void 0;
|
|
249
|
-
}
|
|
250
|
-
const segments = this.resolveSegments(pathname, base);
|
|
251
|
-
if (segments === void 0) {
|
|
252
|
-
return void 0;
|
|
253
|
-
}
|
|
254
|
-
let found;
|
|
255
|
-
if (pathname.endsWith("/")) {
|
|
256
|
-
found = this.indexFile === false ? void 0 : await this.lookup([...segments, this.indexFile]);
|
|
257
|
-
} else {
|
|
258
|
-
found = await this.lookup(segments);
|
|
259
|
-
if (found?.[1].isDirectory()) {
|
|
260
|
-
if (this.indexFile === false) {
|
|
261
|
-
found = void 0;
|
|
262
|
-
} else {
|
|
263
|
-
const location = `${base === "/" ? "" : base}${segments.map((segment) => `/${safeEncodeURIComponent(segment)}`).join("")}/`;
|
|
264
|
-
return {
|
|
265
|
-
status: 301,
|
|
266
|
-
headers: {
|
|
267
|
-
location: `${location}${search ?? ""}`,
|
|
268
|
-
...this.cacheControl === false ? {} : { "cache-control": this.cacheControl }
|
|
269
|
-
}
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
if (found === void 0 || !found[1].isFile()) {
|
|
275
|
-
if (this.fallbackFile === void 0) {
|
|
276
|
-
return void 0;
|
|
277
|
-
}
|
|
278
|
-
found = await this.lookup([this.fallbackFile]);
|
|
279
|
-
if (found === void 0 || !found[1].isFile()) {
|
|
280
|
-
return void 0;
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
let [filePath, stats] = found;
|
|
284
|
-
const contentType = this.resolveContentType(filePath);
|
|
285
|
-
const negotiatesEncoding = this.precompressed && isCompressibleContentType(contentType);
|
|
286
|
-
let contentEncoding;
|
|
287
|
-
if (negotiatesEncoding) {
|
|
288
|
-
const qualities = parseAcceptEncodingQualities(flattenStandardHeader(request.headers["accept-encoding"]));
|
|
289
|
-
const variants = await Promise.all(PRECOMPRESSED_ENCODINGS.filter(([encoding]) => isAcceptableEncoding(qualities, encoding)).map(async ([encoding, extension]) => {
|
|
290
|
-
const candidatePath = filePath + extension;
|
|
291
|
-
const [candidateStats, containedRealPath] = await Promise.all([
|
|
292
|
-
stat(candidatePath).catch(() => void 0),
|
|
293
|
-
this.resolveContainedRealPath(candidatePath)
|
|
294
|
-
]);
|
|
295
|
-
return candidateStats?.isFile() && containedRealPath !== void 0 ? { encoding, extension, stats: candidateStats } : void 0;
|
|
296
|
-
}));
|
|
297
|
-
const variant = variants.find((variant2) => variant2 !== void 0);
|
|
298
|
-
if (variant !== void 0) {
|
|
299
|
-
filePath += variant.extension;
|
|
300
|
-
stats = variant.stats;
|
|
301
|
-
contentEncoding = variant.encoding;
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
const size = stats.size;
|
|
305
|
-
const etag = `"${size.toString(16)}-${stats.mtime.getTime().toString(16)}"`;
|
|
306
|
-
const lastModifiedTime = Math.floor(stats.mtime.getTime() / 1e3) * 1e3;
|
|
307
|
-
const headers = {
|
|
308
|
-
"etag": etag,
|
|
309
|
-
"last-modified": stats.mtime.toUTCString(),
|
|
310
|
-
"accept-ranges": "bytes"
|
|
311
|
-
};
|
|
312
|
-
if (negotiatesEncoding) {
|
|
313
|
-
headers.vary = "accept-encoding";
|
|
314
|
-
}
|
|
315
|
-
if (this.cacheControl !== false) {
|
|
316
|
-
headers["cache-control"] = this.cacheControl;
|
|
317
|
-
}
|
|
318
|
-
if (isPreconditionFailed(request.headers, etag, lastModifiedTime)) {
|
|
319
|
-
return { status: 412, headers };
|
|
320
|
-
}
|
|
321
|
-
if (isRequestFresh(request.headers, etag, lastModifiedTime)) {
|
|
322
|
-
return { status: 304, headers };
|
|
323
|
-
}
|
|
324
|
-
let status = 200;
|
|
325
|
-
let start = 0;
|
|
326
|
-
let end = size - 1;
|
|
327
|
-
const range = request.method === "GET" ? flattenStandardHeader(request.headers.range) : void 0;
|
|
328
|
-
if (range !== void 0 && isRangeApplicable(request.headers, etag, lastModifiedTime)) {
|
|
329
|
-
const parsed = parseByteRange(range, size);
|
|
330
|
-
if (parsed === "unsatisfiable") {
|
|
331
|
-
return { status: 416, headers: { ...headers, "content-range": `bytes */${size}` } };
|
|
332
|
-
}
|
|
333
|
-
if (parsed !== void 0) {
|
|
334
|
-
status = 206;
|
|
335
|
-
[start, end] = parsed;
|
|
336
|
-
headers["content-range"] = `bytes ${start}-${end}/${size}`;
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
if (contentEncoding !== void 0) {
|
|
340
|
-
headers["content-encoding"] = contentEncoding;
|
|
341
|
-
}
|
|
342
|
-
headers["content-type"] = contentType;
|
|
343
|
-
headers["content-length"] = `${end - start + 1}`;
|
|
344
|
-
const body = request.method === "HEAD" ? new ReadableStream({ start: (controller) => controller.close() }) : toWebReadableStream(status === 206 ? createReadStream(filePath, { start, end }) : createReadStream(filePath));
|
|
345
|
-
return { status, headers, body };
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
function stripTrailingSlash(path2) {
|
|
349
|
-
return path2.length > 1 && path2.endsWith("/") ? path2.slice(0, -1) : path2;
|
|
350
|
-
}
|
|
351
|
-
function stripWeakEtagPrefix(etag) {
|
|
352
|
-
return etag.startsWith("W/") ? etag.slice(2) : etag;
|
|
353
|
-
}
|
|
354
|
-
function isPreconditionFailed(requestHeaders, etag, lastModifiedTime) {
|
|
355
|
-
const ifMatch = flattenStandardHeader(requestHeaders["if-match"])?.trim();
|
|
356
|
-
if (ifMatch !== void 0 && ifMatch !== "") {
|
|
357
|
-
if (ifMatch === "*") {
|
|
358
|
-
return false;
|
|
359
|
-
}
|
|
360
|
-
return !ifMatch.split(",").some((tag) => tag.trim() === etag);
|
|
361
|
-
}
|
|
362
|
-
const ifUnmodifiedSince = flattenStandardHeader(requestHeaders["if-unmodified-since"]);
|
|
363
|
-
if (ifUnmodifiedSince !== void 0) {
|
|
364
|
-
const sinceTime = Date.parse(ifUnmodifiedSince);
|
|
365
|
-
return !Number.isNaN(sinceTime) && lastModifiedTime > sinceTime;
|
|
366
|
-
}
|
|
367
|
-
return false;
|
|
368
|
-
}
|
|
369
|
-
function isRequestFresh(requestHeaders, etag, lastModifiedTime) {
|
|
370
|
-
const ifNoneMatch = flattenStandardHeader(requestHeaders["if-none-match"]);
|
|
371
|
-
if (ifNoneMatch !== void 0) {
|
|
372
|
-
if (ifNoneMatch.trim() === "*") {
|
|
373
|
-
return true;
|
|
374
|
-
}
|
|
375
|
-
const bareEtag = stripWeakEtagPrefix(etag);
|
|
376
|
-
return ifNoneMatch.split(",").some((tag) => stripWeakEtagPrefix(tag.trim()) === bareEtag);
|
|
377
|
-
}
|
|
378
|
-
const ifModifiedSince = flattenStandardHeader(requestHeaders["if-modified-since"]);
|
|
379
|
-
if (ifModifiedSince !== void 0) {
|
|
380
|
-
const sinceTime = Date.parse(ifModifiedSince);
|
|
381
|
-
return !Number.isNaN(sinceTime) && lastModifiedTime <= sinceTime;
|
|
382
|
-
}
|
|
383
|
-
return false;
|
|
384
|
-
}
|
|
385
|
-
function isRangeApplicable(requestHeaders, etag, lastModifiedTime) {
|
|
386
|
-
const ifRange = flattenStandardHeader(requestHeaders["if-range"]);
|
|
387
|
-
if (ifRange === void 0) {
|
|
388
|
-
return true;
|
|
389
|
-
}
|
|
390
|
-
if (ifRange.startsWith('"') || ifRange.startsWith("W/")) {
|
|
391
|
-
return ifRange === etag;
|
|
392
|
-
}
|
|
393
|
-
return Date.parse(ifRange) === lastModifiedTime;
|
|
394
|
-
}
|
|
395
|
-
function parseByteRange(range, size) {
|
|
396
|
-
const match = range.match(/^bytes=\s*(\d*)-(\d*)$/i);
|
|
397
|
-
if (match === null || match[1] === "" && match[2] === "") {
|
|
398
|
-
return void 0;
|
|
399
|
-
}
|
|
400
|
-
if (match[1] === "") {
|
|
401
|
-
const suffixLength = Number(match[2]);
|
|
402
|
-
if (suffixLength === 0 || size === 0) {
|
|
403
|
-
return "unsatisfiable";
|
|
404
|
-
}
|
|
405
|
-
return [Math.max(0, size - suffixLength), size - 1];
|
|
406
|
-
}
|
|
407
|
-
const start = Number(match[1]);
|
|
408
|
-
if (start >= size) {
|
|
409
|
-
return "unsatisfiable";
|
|
410
|
-
}
|
|
411
|
-
const end = match[2] === "" ? size - 1 : Math.min(Number(match[2]), size - 1);
|
|
412
|
-
if (end < start) {
|
|
413
|
-
return void 0;
|
|
414
|
-
}
|
|
415
|
-
return [start, end];
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
const MAX_PART_HEADER_SIZE = 16 * 1024;
|
|
419
|
-
const CRLF = Buffer.from("\r\n");
|
|
420
|
-
const HEADER_BLOCK_END = Buffer.from("\r\n\r\n");
|
|
421
|
-
async function parseMultipart(source, boundary, onPart) {
|
|
422
|
-
const delimiter = Buffer.from(`\r
|
|
423
|
-
--${boundary}`);
|
|
424
|
-
let buffer = CRLF;
|
|
425
|
-
let state = "preamble";
|
|
426
|
-
let writer;
|
|
427
|
-
let done = false;
|
|
428
|
-
const process = async () => {
|
|
429
|
-
while (true) {
|
|
430
|
-
if (state === "preamble" || state === "body") {
|
|
431
|
-
const index = buffer.indexOf(delimiter);
|
|
432
|
-
if (index === -1) {
|
|
433
|
-
const settledLength = buffer.length - delimiter.length + 1;
|
|
434
|
-
if (settledLength > 0) {
|
|
435
|
-
if (state === "body") {
|
|
436
|
-
await writer.write(buffer.subarray(0, settledLength));
|
|
437
|
-
}
|
|
438
|
-
buffer = buffer.subarray(settledLength);
|
|
439
|
-
}
|
|
440
|
-
return;
|
|
441
|
-
}
|
|
442
|
-
if (state === "body") {
|
|
443
|
-
if (index > 0) {
|
|
444
|
-
await writer.write(buffer.subarray(0, index));
|
|
445
|
-
}
|
|
446
|
-
await writer.end();
|
|
447
|
-
writer = void 0;
|
|
448
|
-
}
|
|
449
|
-
buffer = buffer.subarray(index + delimiter.length);
|
|
450
|
-
state = "delimiter-end";
|
|
451
|
-
continue;
|
|
452
|
-
}
|
|
453
|
-
if (state === "delimiter-end") {
|
|
454
|
-
if (buffer.length < 2) {
|
|
455
|
-
return;
|
|
456
|
-
}
|
|
457
|
-
if (buffer[0] === 45 && buffer[1] === 45) {
|
|
458
|
-
done = true;
|
|
459
|
-
buffer = Buffer.alloc(0);
|
|
460
|
-
return;
|
|
461
|
-
}
|
|
462
|
-
state = "transport-padding";
|
|
463
|
-
continue;
|
|
464
|
-
}
|
|
465
|
-
if (state === "transport-padding") {
|
|
466
|
-
let index = 0;
|
|
467
|
-
while (index < buffer.length && (buffer[index] === 32 || buffer[index] === 9)) {
|
|
468
|
-
index++;
|
|
469
|
-
}
|
|
470
|
-
buffer = buffer.subarray(index);
|
|
471
|
-
if (buffer.length < 2) {
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
if (buffer[0] !== 13 || buffer[1] !== 10) {
|
|
475
|
-
throw new TypeError("Invalid multipart body: expected CRLF after a boundary delimiter");
|
|
476
|
-
}
|
|
477
|
-
buffer = buffer.subarray(2);
|
|
478
|
-
state = "headers";
|
|
479
|
-
continue;
|
|
480
|
-
}
|
|
481
|
-
if (buffer[0] === 13 && buffer[1] === 10) {
|
|
482
|
-
throw new TypeError("Invalid multipart body: part is missing the content-disposition header");
|
|
483
|
-
}
|
|
484
|
-
const headerWindow = MAX_PART_HEADER_SIZE + HEADER_BLOCK_END.length;
|
|
485
|
-
const headerEnd = buffer.subarray(0, headerWindow).indexOf(HEADER_BLOCK_END);
|
|
486
|
-
if (headerEnd === -1) {
|
|
487
|
-
if (buffer.length >= headerWindow) {
|
|
488
|
-
throw new TypeError("Invalid multipart body: part headers exceed the maximum allowed size");
|
|
489
|
-
}
|
|
490
|
-
return;
|
|
491
|
-
}
|
|
492
|
-
const headerSize = headerEnd + HEADER_BLOCK_END.length;
|
|
493
|
-
const part = parsePartHeaders(buffer.subarray(0, headerEnd).toString(), headerSize);
|
|
494
|
-
buffer = buffer.subarray(headerSize);
|
|
495
|
-
writer = await onPart(part);
|
|
496
|
-
state = "body";
|
|
497
|
-
}
|
|
498
|
-
};
|
|
499
|
-
for await (const chunk of source) {
|
|
500
|
-
if (done) {
|
|
501
|
-
continue;
|
|
502
|
-
}
|
|
503
|
-
buffer = buffer.length === 0 ? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) : Buffer.concat([buffer, chunk]);
|
|
504
|
-
await process();
|
|
505
|
-
}
|
|
506
|
-
if (!done) {
|
|
507
|
-
throw new TypeError("Invalid multipart body: unexpected end of body");
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
function parsePartHeaders(block, headerSize) {
|
|
511
|
-
let contentDisposition;
|
|
512
|
-
let contentType;
|
|
513
|
-
for (const line of block.split("\r\n")) {
|
|
514
|
-
const colon = line.indexOf(":");
|
|
515
|
-
if (colon === -1) {
|
|
516
|
-
throw new TypeError("Invalid multipart body: malformed part header");
|
|
517
|
-
}
|
|
518
|
-
const name2 = line.slice(0, colon).trim().toLowerCase();
|
|
519
|
-
if (name2 === "content-disposition") {
|
|
520
|
-
contentDisposition = line.slice(colon + 1).trim();
|
|
521
|
-
} else if (name2 === "content-type") {
|
|
522
|
-
contentType = line.slice(colon + 1).trim();
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
if (contentDisposition === void 0) {
|
|
526
|
-
throw new TypeError("Invalid multipart body: part is missing the content-disposition header");
|
|
527
|
-
}
|
|
528
|
-
const semicolon = contentDisposition.indexOf(";");
|
|
529
|
-
const dispositionType = (semicolon === -1 ? contentDisposition : contentDisposition.slice(0, semicolon)).trim().toLowerCase();
|
|
530
|
-
if (dispositionType !== "form-data") {
|
|
531
|
-
throw new TypeError("Invalid multipart body: content-disposition must be form-data");
|
|
532
|
-
}
|
|
533
|
-
const parameters = parseHeaderParameters(contentDisposition);
|
|
534
|
-
const name = parameters.get("name");
|
|
535
|
-
if (name === void 0) {
|
|
536
|
-
throw new TypeError("Invalid multipart body: content-disposition header is missing the name parameter");
|
|
537
|
-
}
|
|
538
|
-
const filename = parameters.get("filename");
|
|
539
|
-
return {
|
|
540
|
-
name: decodeContentDispositionParameter(name),
|
|
541
|
-
filename: filename === void 0 ? void 0 : decodeContentDispositionParameter(filename),
|
|
542
|
-
type: contentType,
|
|
543
|
-
headerSize
|
|
544
|
-
};
|
|
545
|
-
}
|
|
546
|
-
function decodeContentDispositionParameter(value) {
|
|
547
|
-
return value.replaceAll("%22", '"').replaceAll("%0D", "\r").replaceAll("%0A", "\n");
|
|
548
|
-
}
|
|
549
|
-
function parseHeaderParameters(header) {
|
|
550
|
-
const parameters = /* @__PURE__ */ new Map();
|
|
551
|
-
let index = header.indexOf(";");
|
|
552
|
-
while (index !== -1 && index < header.length) {
|
|
553
|
-
index++;
|
|
554
|
-
while (index < header.length && (header[index] === " " || header[index] === " ")) {
|
|
555
|
-
index++;
|
|
556
|
-
}
|
|
557
|
-
let equals = index;
|
|
558
|
-
while (equals < header.length && header[equals] !== "=" && header[equals] !== ";") {
|
|
559
|
-
equals++;
|
|
560
|
-
}
|
|
561
|
-
if (equals === header.length) {
|
|
562
|
-
break;
|
|
563
|
-
}
|
|
564
|
-
if (header[equals] === ";") {
|
|
565
|
-
index = equals;
|
|
566
|
-
continue;
|
|
567
|
-
}
|
|
568
|
-
const key = header.slice(index, equals).trim().toLowerCase();
|
|
569
|
-
index = equals + 1;
|
|
570
|
-
let value;
|
|
571
|
-
if (header[index] === '"') {
|
|
572
|
-
const closing = header.indexOf('"', index + 1);
|
|
573
|
-
value = closing === -1 ? header.slice(index + 1) : header.slice(index + 1, closing);
|
|
574
|
-
index = closing === -1 ? -1 : header.indexOf(";", closing + 1);
|
|
575
|
-
} else {
|
|
576
|
-
const semicolon = header.indexOf(";", index);
|
|
577
|
-
value = (semicolon === -1 ? header.slice(index) : header.slice(index, semicolon)).trim();
|
|
578
|
-
index = semicolon;
|
|
579
|
-
}
|
|
580
|
-
if (!parameters.has(key)) {
|
|
581
|
-
parameters.set(key, value);
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
return parameters;
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
class TmpFile extends File {
|
|
588
|
-
constructor(blob, path2, name, options) {
|
|
589
|
-
super([blob], name, options);
|
|
590
|
-
this.path = path2;
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
class TmpFileUploadHandlerPlugin {
|
|
594
|
-
name = "~tmp-file-upload";
|
|
595
|
-
/**
|
|
596
|
-
* Should parse the original request body instead of batched sub-requests.
|
|
597
|
-
*/
|
|
598
|
-
after = ["~batch"];
|
|
599
|
-
/**
|
|
600
|
-
* Should run inside the limit and compression plugins, so spooling receives
|
|
601
|
-
* the size-checked, decompressed bytes.
|
|
602
|
-
*/
|
|
603
|
-
before = ["~request-limit", "~request-compression"];
|
|
604
|
-
tmpDir;
|
|
605
|
-
maxBodySize;
|
|
606
|
-
spoolThreshold;
|
|
607
|
-
constructor(options = {}) {
|
|
608
|
-
this.tmpDir = options.tmpDir ?? tmpdir();
|
|
609
|
-
this.maxBodySize = options.maxBodySize ?? {
|
|
610
|
-
memory: Number.POSITIVE_INFINITY,
|
|
611
|
-
file: Number.POSITIVE_INFINITY,
|
|
612
|
-
stream: Number.POSITIVE_INFINITY
|
|
613
|
-
};
|
|
614
|
-
this.spoolThreshold = options.spoolThreshold ?? 64 * 1024;
|
|
615
|
-
}
|
|
616
|
-
init(options) {
|
|
617
|
-
const routingInterceptor = async ({ next, ...interceptorOptions }) => {
|
|
618
|
-
const tmpFiles = new RequestTmpFiles(this.tmpDir);
|
|
619
|
-
let cleanupDeferred = false;
|
|
620
|
-
try {
|
|
621
|
-
const result = await next({
|
|
622
|
-
...interceptorOptions,
|
|
623
|
-
request: {
|
|
624
|
-
...interceptorOptions.request,
|
|
625
|
-
resolveBody: (hint) => this.resolveBody(interceptorOptions, hint, tmpFiles)
|
|
626
|
-
}
|
|
627
|
-
});
|
|
628
|
-
if (result.matched && tmpFiles.inUse) {
|
|
629
|
-
const body = result.response.body;
|
|
630
|
-
if (isAsyncIteratorObject(body)) {
|
|
631
|
-
cleanupDeferred = true;
|
|
632
|
-
return {
|
|
633
|
-
matched: true,
|
|
634
|
-
response: {
|
|
635
|
-
...result.response,
|
|
636
|
-
/**
|
|
637
|
-
* @warning
|
|
638
|
-
* Remember use `override` for AsyncIteratorObject to remain other special properties
|
|
639
|
-
*/
|
|
640
|
-
body: override(body, wrapAsyncIterator(body, { onFinish: () => tmpFiles.cleanup() }))
|
|
641
|
-
}
|
|
642
|
-
};
|
|
643
|
-
}
|
|
644
|
-
if (body instanceof ReadableStream) {
|
|
645
|
-
cleanupDeferred = true;
|
|
646
|
-
return {
|
|
647
|
-
matched: true,
|
|
648
|
-
response: {
|
|
649
|
-
...result.response,
|
|
650
|
-
/**
|
|
651
|
-
* @warning
|
|
652
|
-
* Remember use `override` for ReadableStream to remain other special properties
|
|
653
|
-
*/
|
|
654
|
-
body: override(body, wrapReadableStream(body, { onFinish: () => tmpFiles.cleanup() }))
|
|
655
|
-
}
|
|
656
|
-
};
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
return result;
|
|
660
|
-
} finally {
|
|
661
|
-
if (!cleanupDeferred) {
|
|
662
|
-
await tmpFiles.cleanup();
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
};
|
|
666
|
-
return {
|
|
667
|
-
...options,
|
|
668
|
-
routingInterceptors: [routingInterceptor, ...toArray(options.routingInterceptors)]
|
|
669
|
-
};
|
|
670
|
-
}
|
|
671
|
-
async resolveBody(interceptorOptions, hint, tmpFiles) {
|
|
672
|
-
const { request } = interceptorOptions;
|
|
673
|
-
const resolvedHint = hint ?? resolveStandardBodyHint(request.headers);
|
|
674
|
-
if (resolvedHint === "none") {
|
|
675
|
-
return request.resolveBody(hint);
|
|
676
|
-
}
|
|
677
|
-
const maxBodySize = await value(this.maxBodySize, interceptorOptions);
|
|
678
|
-
if (resolvedHint === "form-data") {
|
|
679
|
-
return this.parseMultipartBody(request, tmpFiles, maxBodySize);
|
|
680
|
-
}
|
|
681
|
-
if (resolvedHint === "file") {
|
|
682
|
-
return this.parseFileBody(request, tmpFiles, maxBodySize);
|
|
683
|
-
}
|
|
684
|
-
if (resolvedHint === "json" || resolvedHint === "url-search-params") {
|
|
685
|
-
return this.parseLimitedBody(request, hint, resolvedHint, maxBodySize.memory);
|
|
686
|
-
}
|
|
687
|
-
const eventLimit = resolvedHint === "event-stream" ? maxBodySize.memory : Number.POSITIVE_INFINITY;
|
|
688
|
-
return this.parseLimitedBody(request, hint, resolvedHint, maxBodySize.stream, eventLimit);
|
|
689
|
-
}
|
|
690
|
-
/**
|
|
691
|
-
* Enforces size limits on a body the standard parser handles, counting the
|
|
692
|
-
* raw bytes before handing them back for regular parsing.
|
|
693
|
-
*/
|
|
694
|
-
async parseLimitedBody(request, hint, resolvedHint, limit, eventLimit = Number.POSITIVE_INFINITY) {
|
|
695
|
-
if (limit === Number.POSITIVE_INFINITY && eventLimit === Number.POSITIVE_INFINITY) {
|
|
696
|
-
return request.resolveBody(hint);
|
|
697
|
-
}
|
|
698
|
-
assertContentLengthWithin(request.headers, limit);
|
|
699
|
-
const stream = await request.resolveBody("octet-stream");
|
|
700
|
-
if (!(stream instanceof ReadableStream)) {
|
|
701
|
-
return stream;
|
|
702
|
-
}
|
|
703
|
-
const fits = eventLimit < limit ? createEventSizeCheck(eventLimit) : void 0;
|
|
704
|
-
const response = new Response(limitStream(stream, limit, fits), {
|
|
705
|
-
headers: toFetchHeaders(request.headers)
|
|
706
|
-
});
|
|
707
|
-
return toStandardBody(response, { hint: resolvedHint });
|
|
708
|
-
}
|
|
709
|
-
async parseFileBody(request, tmpFiles, maxBodySize) {
|
|
710
|
-
assertContentLengthWithin(request.headers, maxBodySize.file);
|
|
711
|
-
const stream = await request.resolveBody("octet-stream");
|
|
712
|
-
if (!(stream instanceof ReadableStream)) {
|
|
713
|
-
return stream;
|
|
714
|
-
}
|
|
715
|
-
const contentDisposition = flattenStandardHeader(request.headers["content-disposition"]);
|
|
716
|
-
const fileName = contentDisposition !== void 0 ? getFilenameFromContentDisposition(contentDisposition) : void 0;
|
|
717
|
-
const contentType = flattenStandardHeader(request.headers["content-type"]);
|
|
718
|
-
const upload = new UploadWriter(tmpFiles, new Budget(maxBodySize.memory), new Budget(maxBodySize.file), this.spoolThreshold);
|
|
719
|
-
for await (const chunk of stream) {
|
|
720
|
-
await upload.write(chunk);
|
|
721
|
-
}
|
|
722
|
-
return upload.end(fileName ?? "blob", contentType ?? "");
|
|
723
|
-
}
|
|
724
|
-
async parseMultipartBody(request, tmpFiles, maxBodySize) {
|
|
725
|
-
const contentType = flattenStandardHeader(request.headers["content-type"]);
|
|
726
|
-
const boundary = contentType === void 0 ? void 0 : parseHeaderParameters(contentType).get("boundary");
|
|
727
|
-
if (boundary === void 0 || boundary === "") {
|
|
728
|
-
throw new TypeError("Invalid multipart body: content-type header is missing the boundary parameter");
|
|
729
|
-
}
|
|
730
|
-
const totalLimit = maxBodySize.memory + maxBodySize.file;
|
|
731
|
-
assertContentLengthWithin(request.headers, totalLimit);
|
|
732
|
-
const stream = await request.resolveBody("octet-stream");
|
|
733
|
-
if (!(stream instanceof ReadableStream)) {
|
|
734
|
-
return stream;
|
|
735
|
-
}
|
|
736
|
-
const limited = totalLimit === Number.POSITIVE_INFINITY ? stream : limitStream(stream, totalLimit);
|
|
737
|
-
const form = new FormData();
|
|
738
|
-
const memory = new Budget(maxBodySize.memory);
|
|
739
|
-
const file = new Budget(maxBodySize.file);
|
|
740
|
-
await parseMultipart(limited, boundary, (part) => {
|
|
741
|
-
const name = part.name;
|
|
742
|
-
memory.charge(part.headerSize);
|
|
743
|
-
if (part.filename === void 0) {
|
|
744
|
-
const chunks = [];
|
|
745
|
-
return {
|
|
746
|
-
write: (chunk) => {
|
|
747
|
-
memory.charge(chunk.length);
|
|
748
|
-
chunks.push(Buffer.from(chunk));
|
|
749
|
-
},
|
|
750
|
-
end: () => {
|
|
751
|
-
form.append(name, Buffer.concat(chunks).toString());
|
|
752
|
-
}
|
|
753
|
-
};
|
|
754
|
-
}
|
|
755
|
-
const filename = part.filename;
|
|
756
|
-
const type = part.type ?? "text/plain";
|
|
757
|
-
const upload = new UploadWriter(tmpFiles, memory, file, this.spoolThreshold);
|
|
758
|
-
return {
|
|
759
|
-
write: (chunk) => upload.write(chunk),
|
|
760
|
-
end: async () => {
|
|
761
|
-
form.append(name, await upload.end(filename, type));
|
|
762
|
-
}
|
|
763
|
-
};
|
|
764
|
-
});
|
|
765
|
-
return form;
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
function assertContentLengthWithin(headers, limit) {
|
|
769
|
-
const contentLength = Number(flattenStandardHeader(headers["content-length"]));
|
|
770
|
-
if (Number.isFinite(contentLength) && contentLength > limit) {
|
|
771
|
-
throw new ORPCError("PAYLOAD_TOO_LARGE");
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
function limitStream(stream, limit, fits = () => true) {
|
|
775
|
-
let total = 0;
|
|
776
|
-
return stream.pipeThrough(new TransformStream({
|
|
777
|
-
transform(chunk, controller) {
|
|
778
|
-
total += chunk.byteLength;
|
|
779
|
-
if (total > limit || !fits(chunk)) {
|
|
780
|
-
controller.error(new ORPCError("PAYLOAD_TOO_LARGE"));
|
|
781
|
-
return;
|
|
782
|
-
}
|
|
783
|
-
controller.enqueue(chunk);
|
|
784
|
-
}
|
|
785
|
-
}));
|
|
786
|
-
}
|
|
787
|
-
const CR = 13;
|
|
788
|
-
const LF = 10;
|
|
789
|
-
function createEventSizeCheck(eventLimit) {
|
|
790
|
-
let eventSize = 0;
|
|
791
|
-
let trailing = "none";
|
|
792
|
-
return (chunk) => {
|
|
793
|
-
const bytes = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
794
|
-
let nextCR = indexOrEnd(bytes, CR, 0);
|
|
795
|
-
let nextLF = indexOrEnd(bytes, LF, 0);
|
|
796
|
-
let offset = 0;
|
|
797
|
-
while (true) {
|
|
798
|
-
const lineEnding = Math.min(nextCR, nextLF);
|
|
799
|
-
if (lineEnding > offset) {
|
|
800
|
-
eventSize += lineEnding - offset;
|
|
801
|
-
trailing = "none";
|
|
802
|
-
}
|
|
803
|
-
if (lineEnding === bytes.length) {
|
|
804
|
-
return eventSize <= eventLimit;
|
|
805
|
-
}
|
|
806
|
-
const byte = bytes[lineEnding];
|
|
807
|
-
offset = lineEnding + 1;
|
|
808
|
-
if (byte === CR) {
|
|
809
|
-
nextCR = indexOrEnd(bytes, CR, offset);
|
|
810
|
-
} else {
|
|
811
|
-
nextLF = indexOrEnd(bytes, LF, offset);
|
|
812
|
-
}
|
|
813
|
-
if (eventSize === 0) {
|
|
814
|
-
continue;
|
|
815
|
-
}
|
|
816
|
-
if (++eventSize > eventLimit) {
|
|
817
|
-
return false;
|
|
818
|
-
}
|
|
819
|
-
if (trailing === "line" || trailing === "cr" && byte === CR) {
|
|
820
|
-
eventSize = 0;
|
|
821
|
-
trailing = "none";
|
|
822
|
-
} else {
|
|
823
|
-
trailing = byte === CR ? "cr" : "line";
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
};
|
|
827
|
-
}
|
|
828
|
-
function indexOrEnd(bytes, byte, from) {
|
|
829
|
-
const index = bytes.indexOf(byte, from);
|
|
830
|
-
return index === -1 ? bytes.length : index;
|
|
831
|
-
}
|
|
832
|
-
class Budget {
|
|
833
|
-
constructor(limit) {
|
|
834
|
-
this.limit = limit;
|
|
835
|
-
}
|
|
836
|
-
used = 0;
|
|
837
|
-
charge(size) {
|
|
838
|
-
if (!this.tryCharge(size)) {
|
|
839
|
-
throw new ORPCError("PAYLOAD_TOO_LARGE");
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
tryCharge(size) {
|
|
843
|
-
if (this.used + size > this.limit) {
|
|
844
|
-
return false;
|
|
845
|
-
}
|
|
846
|
-
this.used += size;
|
|
847
|
-
return true;
|
|
848
|
-
}
|
|
849
|
-
refund(size) {
|
|
850
|
-
this.used -= size;
|
|
851
|
-
}
|
|
852
|
-
}
|
|
853
|
-
class UploadWriter {
|
|
854
|
-
constructor(tmpFiles, memory, file, spoolThreshold) {
|
|
855
|
-
this.tmpFiles = tmpFiles;
|
|
856
|
-
this.memory = memory;
|
|
857
|
-
this.file = file;
|
|
858
|
-
this.spoolThreshold = spoolThreshold;
|
|
859
|
-
}
|
|
860
|
-
held = [];
|
|
861
|
-
heldSize = 0;
|
|
862
|
-
tmpPath;
|
|
863
|
-
async write(chunk) {
|
|
864
|
-
this.file.charge(chunk.length);
|
|
865
|
-
if (this.tmpPath !== void 0) {
|
|
866
|
-
return this.tmpFiles.append(this.tmpPath, chunk);
|
|
867
|
-
}
|
|
868
|
-
if (this.heldSize + chunk.length <= this.spoolThreshold && this.memory.tryCharge(chunk.length)) {
|
|
869
|
-
this.held.push(Buffer.from(chunk));
|
|
870
|
-
this.heldSize += chunk.length;
|
|
871
|
-
return;
|
|
872
|
-
}
|
|
873
|
-
this.tmpPath = await this.tmpFiles.create(Buffer.concat([...this.held, chunk]));
|
|
874
|
-
this.memory.refund(this.heldSize);
|
|
875
|
-
this.held = [];
|
|
876
|
-
}
|
|
877
|
-
async end(name, type) {
|
|
878
|
-
if (this.tmpPath !== void 0) {
|
|
879
|
-
return this.tmpFiles.seal(this.tmpPath, name, type);
|
|
880
|
-
}
|
|
881
|
-
return new File([Buffer.concat(this.held, this.heldSize)], name, { type });
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
class RequestTmpFiles {
|
|
885
|
-
constructor(tmpDir) {
|
|
886
|
-
this.tmpDir = tmpDir;
|
|
887
|
-
}
|
|
888
|
-
dir;
|
|
889
|
-
count = 0;
|
|
890
|
-
get inUse() {
|
|
891
|
-
return this.dir !== void 0;
|
|
892
|
-
}
|
|
893
|
-
async create(content) {
|
|
894
|
-
try {
|
|
895
|
-
this.dir ??= mkdtemp(path.join(this.tmpDir, "orpc-upload-"));
|
|
896
|
-
const tmpPath = path.join(await this.dir, String(this.count++));
|
|
897
|
-
await appendFile(tmpPath, content);
|
|
898
|
-
return tmpPath;
|
|
899
|
-
} catch (cause) {
|
|
900
|
-
throw new ORPCError("INTERNAL_SERVER_ERROR", { cause });
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
async append(tmpPath, chunk) {
|
|
904
|
-
try {
|
|
905
|
-
await appendFile(tmpPath, chunk);
|
|
906
|
-
} catch (cause) {
|
|
907
|
-
throw new ORPCError("INTERNAL_SERVER_ERROR", { cause });
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
async seal(tmpPath, name, type) {
|
|
911
|
-
try {
|
|
912
|
-
return new TmpFile(await openAsBlob(tmpPath), tmpPath, name, { type });
|
|
913
|
-
} catch (cause) {
|
|
914
|
-
throw new ORPCError("INTERNAL_SERVER_ERROR", { cause });
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
async cleanup() {
|
|
918
|
-
if (this.dir !== void 0) {
|
|
919
|
-
try {
|
|
920
|
-
await rm(await this.dir, { recursive: true, force: true });
|
|
921
|
-
} catch {
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
}
|
|
926
|
-
|
|
927
|
-
export { BatchResponseCompressionHandlerPlugin, StaticFileHandlerPlugin, TmpFile, TmpFileUploadHandlerPlugin };
|
|
1
|
+
export * from "./batch-response-compression-handler-plugin.mjs";
|
|
2
|
+
export * from "./static-file-handler-plugin.mjs";
|
|
3
|
+
export * from "./tmp-file-upload-handler-plugin.mjs";
|