Skip to content

Commit 2ad7381

Browse files
committed
Add Node compatibility to gz.js.
Node has a built-in zlib library we can just use. This also changes the webpack config to tell it that it we don't need this library when building for the browser. Without this change, the build fails because Webpack wants to know explicitly what, if anything, it should shim the library with.
1 parent dad84a4 commit 2ad7381

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/utils/gz.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,20 @@ export async function compress(
3131
data: string | Uint8Array,
3232
compressionLevel?: number
3333
): Promise<Uint8Array<ArrayBuffer>> {
34+
if (!(typeof window === 'object' && 'Worker' in window)) {
35+
// Try to fall back to Node's zlib library.
36+
const zlib = await import('zlib');
37+
return new Promise((resolve, reject) => {
38+
zlib.gzip(data, (errorOrNull, result) => {
39+
if (errorOrNull) {
40+
reject(errorOrNull);
41+
} else {
42+
resolve(new Uint8Array(result.buffer as ArrayBuffer));
43+
}
44+
});
45+
});
46+
}
47+
3448
const zeeWorker = new Worker(zeeWorkerPath);
3549
workerOnMessage(zeeWorker);
3650

@@ -55,6 +69,24 @@ export async function compress(
5569

5670
// Neuters data's buffer, if data is a typed array.
5771
export async function decompress(data: Uint8Array): Promise<Uint8Array> {
72+
if (!(typeof window === 'object' && 'Worker' in window)) {
73+
// Handle the case where we're not running in the browser, e.g. when
74+
// this code is used as part of a library in a Node project.
75+
// We don't get here when running Firefox profiler tests, because our
76+
// tests create a mock window with a mock Worker class.
77+
// Try to fall back to Node's zlib library.
78+
const zlib = await import('zlib');
79+
return new Promise((resolve, reject) => {
80+
zlib.gunzip(data, (errorOrNull, result) => {
81+
if (errorOrNull) {
82+
reject(errorOrNull);
83+
} else {
84+
resolve(new Uint8Array(result.buffer as ArrayBuffer));
85+
}
86+
});
87+
});
88+
}
89+
5890
const zeeWorker = new Worker(zeeWorkerPath);
5991
return new Promise(function (resolve, reject) {
6092
workerOnMessage(zeeWorker);

webpack.config.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const config = {
3232
// that Jest can profit from it too.
3333
'firefox-profiler-res': path.resolve(__dirname, 'res'),
3434
},
35+
fallback: { zlib: false },
3536
},
3637
devtool: 'source-map',
3738
module: {

0 commit comments

Comments
 (0)