Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
90 lines (68 loc) · 2.12 KB
/
Copy pathindex.js
File metadata and controls
90 lines (68 loc) · 2.12 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import {Transform as TransformStream, PassThrough as PassThroughStream} from 'node:stream';
import zlib from 'node:zlib';
import mimicResponse from 'mimic-response';
// Detect zstd support (available in Node.js >= 22.15.0)
const supportsZstd = typeof zlib.createZstdDecompress === 'function';
export default function decompressResponse(response) {
const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();
const supportedEncodings = ['gzip', 'deflate', 'br'];
if (supportsZstd) {
supportedEncodings.push('zstd');
}
if (!supportedEncodings.includes(contentEncoding)) {
return response;
}
let isEmpty = true;
// Clone headers to avoid modifying the original response headers
const headers = {...response.headers};
const finalStream = new PassThroughStream({
autoDestroy: false,
});
// Only destroy response on error, not on normal completion
finalStream.once('error', () => {
response.destroy();
});
function handleContentEncoding(data) {
let decompressStream;
if (contentEncoding === 'zstd') {
decompressStream = zlib.createZstdDecompress();
} else if (contentEncoding === 'br') {
decompressStream = zlib.createBrotliDecompress();
} else if (contentEncoding === 'deflate' && data.length > 0 && (data[0] & 0x08) === 0) { // eslint-disable-line no-bitwise
decompressStream = zlib.createInflateRaw();
} else {
decompressStream = 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) {
if (isEmpty) {
finalStream.end();
}
callback();
},
});
delete headers['content-encoding'];
delete headers['content-length'];
finalStream.headers = headers;
mimicResponse(response, finalStream);
response.pipe(checker);
return finalStream;
}