( url: string, target: string, progressCb?: (progress: number) => void, )
| 57 | } |
| 58 | |
| 59 | export async function downloadZip( |
| 60 | url: string, |
| 61 | target: string, |
| 62 | progressCb?: (progress: number) => void, |
| 63 | ): Promise<DownloadResult> { |
| 64 | const tmpDir = tempy.directory() |
| 65 | const partial = path.join(tmpDir, 'partial') |
| 66 | |
| 67 | // We try 3 times, |
| 68 | // Once + 2 retries |
| 69 | const RETRIES_COUNT = 2 |
| 70 | |
| 71 | const [zippedSha256, sha256] = await retry( |
| 72 | async () => { |
| 73 | return await Promise.all([fetchChecksum(url), fetchChecksum(url.slice(0, url.length - 3))]) |
| 74 | }, |
| 75 | { |
| 76 | retries: RETRIES_COUNT, |
| 77 | onFailedAttempt: (err) => debug('An error occurred while downloading the checksums files', err), |
| 78 | }, |
| 79 | ) |
| 80 | |
| 81 | const result = await retry( |
| 82 | async () => { |
| 83 | const response = await fetch(url, { |
| 84 | compress: false, |
| 85 | agent: getProxyAgent(url), |
| 86 | }) |
| 87 | if (!response.ok) { |
| 88 | throw new Error(`Failed to fetch the engine file at ${url} - ${response.status} ${response.statusText}`) |
| 89 | } |
| 90 | |
| 91 | const lastModified = response.headers.get('last-modified')! |
| 92 | const size = parseFloat(response.headers.get('content-length') as string) |
| 93 | const ws = fs.createWriteStream(partial) |
| 94 | |
| 95 | // eslint-disable-next-line no-async-promise-executor |
| 96 | return await new Promise(async (resolve, reject) => { |
| 97 | let bytesRead = 0 |
| 98 | |
| 99 | if (response.body === null) { |
| 100 | return reject(new Error(`Failed to fetch the engine file at ${url} - response.body is null`)) |
| 101 | } |
| 102 | |
| 103 | response.body.once('error', reject).on('data', (chunk) => { |
| 104 | bytesRead += chunk.length |
| 105 | |
| 106 | if (size && progressCb) { |
| 107 | progressCb(bytesRead / size) |
| 108 | } |
| 109 | }) |
| 110 | |
| 111 | const gunzip = zlib.createGunzip() |
| 112 | gunzip.on('error', reject) |
| 113 | |
| 114 | const zipStream = response.body.pipe(gunzip) |
| 115 | const zippedHashPromise = hasha.fromStream(response.body, { |
| 116 | algorithm: 'sha256', |
no test coverage detected