|
2 | 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
3 | 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
4 | 4 |
|
5 | | -import gzWorkerPath from 'firefox-profiler-res/gz-worker.js'; |
| 5 | +import gzWorkerPath from './gz.worker.js'; |
6 | 6 |
|
7 | 7 | function runGzWorker( |
8 | 8 | kind: 'compress' | 'decompress', |
@@ -34,12 +34,45 @@ export async function compress( |
34 | 34 | // Encode the data if it's a string |
35 | 35 | const arrayData = |
36 | 36 | typeof data === 'string' ? new TextEncoder().encode(data) : data; |
| 37 | + |
| 38 | + if (!(typeof window === 'object' && 'Worker' in window)) { |
| 39 | + // Try to fall back to Node's zlib library. |
| 40 | + const zlib = await import('zlib'); |
| 41 | + return new Promise((resolve, reject) => { |
| 42 | + zlib.gzip(data, (errorOrNull, result) => { |
| 43 | + if (errorOrNull) { |
| 44 | + reject(errorOrNull); |
| 45 | + } else { |
| 46 | + resolve(new Uint8Array(result.buffer as ArrayBuffer)); |
| 47 | + } |
| 48 | + }); |
| 49 | + }); |
| 50 | + } |
| 51 | + |
37 | 52 | return runGzWorker('compress', arrayData); |
38 | 53 | } |
39 | 54 |
|
40 | 55 | export async function decompress( |
41 | 56 | data: Uint8Array<ArrayBuffer> |
42 | 57 | ): Promise<Uint8Array<ArrayBuffer>> { |
| 58 | + if (!(typeof window === 'object' && 'Worker' in window)) { |
| 59 | + // Handle the case where we're not running in the browser, e.g. when |
| 60 | + // this code is used as part of a library in a Node project. |
| 61 | + // We don't get here when running Firefox profiler tests, because our |
| 62 | + // tests create a mock window with a mock Worker class. |
| 63 | + // Try to fall back to Node's zlib library. |
| 64 | + const zlib = await import('zlib'); |
| 65 | + return new Promise((resolve, reject) => { |
| 66 | + zlib.gunzip(data, (errorOrNull, result) => { |
| 67 | + if (errorOrNull) { |
| 68 | + reject(errorOrNull); |
| 69 | + } else { |
| 70 | + resolve(new Uint8Array(result.buffer as ArrayBuffer)); |
| 71 | + } |
| 72 | + }); |
| 73 | + }); |
| 74 | + } |
| 75 | + |
43 | 76 | return runGzWorker('decompress', data); |
44 | 77 | } |
45 | 78 |
|
|
0 commit comments