-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathindex.js
More file actions
67 lines (50 loc) · 1.47 KB
/
Copy pathindex.js
File metadata and controls
67 lines (50 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import {Transform as TransformStream, PassThrough as PassThroughStream} from 'node:stream';
import zlib from 'node:zlib';
import mimicResponse from 'mimic-response';
export default function decompressResponse(response) {
const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();
if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {
return response;
}
delete response.headers['content-encoding'];
let isEmpty = true;
function handleContentEncoding(data) {
const decompressStream = contentEncoding === 'br'
? zlib.createBrotliDecompress()
: ((contentEncoding === 'deflate' && data.length > 0 && (data[0] & 0x08) === 0) // eslint-disable-line no-bitwise
? zlib.createInflateRaw()
: zlib.createUnzip());
decompressStream.once('error', error => {
if (isEmpty && !response.readable) {
finalStream.end();
return;
}
finalStream.destroy(error);
});
checker.pipe(decompressStream).pipe(finalStream);
}
const checker = new TransformStream({
transform(data, _encoding, callback) {
if (isEmpty === false) {
callback(null, data);
return;
}
isEmpty = false;
handleContentEncoding(data);
callback(null, data);
},
flush(callback) {
callback();
},
});
const finalStream = new PassThroughStream({
autoDestroy: false,
destroy(error, callback) {
response.destroy();
callback(error);
},
});
mimicResponse(response, finalStream);
response.pipe(checker);
return finalStream;
}