Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the native DecompressionStream API to gunzip the .tgz archive #4024

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions lib/deno/mod.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type * as types from "../shared/types"
import * as common from "../shared/common"
import * as ourselves from "./mod"
import * as denoflate from "https://deno.land/x/[email protected]/mod.ts"

declare const ESBUILD_VERSION: string

Expand Down Expand Up @@ -70,7 +69,7 @@ async function installFromNPM(name: string, subpath: string): Promise<string> {
const npmRegistry = Deno.env.get("NPM_CONFIG_REGISTRY") || "https://registry.npmjs.org"
const url = `${npmRegistry}/${name}/-/${name.replace("@esbuild/", "")}-${version}.tgz`
const buffer = await fetch(url).then(r => r.arrayBuffer())
const executable = extractFileFromTarGzip(new Uint8Array(buffer), subpath)
const executable = await extractFileFromTarGzip(new Uint8Array(buffer), subpath)

await Deno.mkdir(finalDir, {
recursive: true,
Expand Down Expand Up @@ -117,9 +116,29 @@ function getCachePath(name: string): { finalPath: string, finalDir: string } {
return { finalPath, finalDir }
}

function extractFileFromTarGzip(buffer: Uint8Array, file: string): Uint8Array {
async function gunzip(data: Uint8Array): Promise<Uint8Array> {
const stream = new DecompressionStream('gzip');
const writer = stream.writable.getWriter();
const reader = stream.readable.getReader();
writer.write(data);
writer.close();
const chunks: Uint8Array[] = [];
while (true) {
const { value, done } = await reader.read();
if (done) break;
chunks.push(value);
}
const result = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
for (let i = 0, offset = 0; i < chunks.length; i++) {
result.set(chunks[i], offset);
offset += chunks[i].length;
}
return result;
}

async function extractFileFromTarGzip(buffer: Uint8Array, file: string): Promise<Uint8Array> {
try {
buffer = denoflate.gunzip(buffer)
buffer = await gunzip(buffer)
} catch (err: any) {
throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`)
}
Expand Down