UNPKG

1.99 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = summarizeRequest;
7
8var _utils = require("@parcel/utils");
9
10var _path = _interopRequireDefault(require("path"));
11
12function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
14const NODE_MODULES = `${_path.default.sep}node_modules${_path.default.sep}`;
15const BUFFER_LIMIT = 5000000; // 5mb
16
17async function summarizeRequest(fs, req) {
18 let [{
19 content,
20 hash,
21 size
22 }, isSource] = await Promise.all([summarizeDiskRequest(fs, req), isFilePathSource(fs, req.filePath)]);
23 return {
24 content,
25 hash,
26 size,
27 isSource
28 };
29}
30
31async function isFilePathSource(fs, filePath) {
32 return !filePath.includes(NODE_MODULES) || (await fs.realpath(filePath)) !== filePath;
33}
34
35async function summarizeDiskRequest(fs, req) {
36 let code = req.code;
37 let content;
38 let hash;
39 let size;
40
41 if (code == null) {
42 // As an optimization for the common case of source code, while we read in
43 // data to compute its md5 and size, buffer its contents in memory.
44 // This avoids reading the data now, and then again during transformation.
45 // If it exceeds BUFFER_LIMIT, throw it out and replace it with a stream to
46 // lazily read it at a later point.
47 content = Buffer.from([]);
48 size = 0;
49 hash = await (0, _utils.md5FromReadableStream)(fs.createReadStream(req.filePath).pipe(new _utils.TapStream(buf => {
50 size += buf.length;
51
52 if (content instanceof Buffer) {
53 if (size > BUFFER_LIMIT) {
54 // if buffering this content would put this over BUFFER_LIMIT, replace
55 // it with a stream
56 content = fs.createReadStream(req.filePath);
57 } else {
58 content = Buffer.concat([content, buf]);
59 }
60 }
61 })));
62 } else {
63 content = code;
64 hash = (0, _utils.md5FromString)(code);
65 size = Buffer.from(code).length;
66 }
67
68 return {
69 content,
70 hash,
71 size
72 };
73}
\No newline at end of file