blob: 86b6c4364c2474be84de426c265abfa747980596 [file] [log] [blame]
Simon Zünd67f366b2024-10-24 05:25:241"use strict";
Takuto Ikuta2e08a7d2022-01-27 02:01:232var __create = Object.create;
3var __defProp = Object.defineProperty;
Takuto Ikuta2e08a7d2022-01-27 02:01:234var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
Takuto Ikuta2e08a7d2022-01-27 02:01:235var __getOwnPropNames = Object.getOwnPropertyNames;
Takuto Ikuta2e08a7d2022-01-27 02:01:236var __getProtoOf = Object.getPrototypeOf;
7var __hasOwnProp = Object.prototype.hasOwnProperty;
Simon Zünd67f366b2024-10-24 05:25:248var __copyProps = (to, from, except, desc) => {
9 if (from && typeof from === "object" || typeof from === "function") {
10 for (let key of __getOwnPropNames(from))
11 if (!__hasOwnProp.call(to, key) && key !== except)
12 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
Simon Zündd5b287e2024-10-23 10:55:3013 }
Simon Zünd67f366b2024-10-24 05:25:2414 return to;
Simon Zündd5b287e2024-10-23 10:55:3015};
Simon Zünd67f366b2024-10-24 05:25:2416var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17 // If the importer is in node compatibility mode or this is not an ESM
18 // file that has been converted to a CommonJS file using a Babel-
19 // compatible transform (i.e. "__esModule" has not been set), then set
20 // "default" to the CommonJS "module.exports" for node compatibility.
21 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22 mod
23));
Takuto Ikuta2e08a7d2022-01-27 02:01:2324
25// lib/npm/node-platform.ts
26var fs = require("fs");
27var os = require("os");
28var path = require("path");
29var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
Simon Zünd67f366b2024-10-24 05:25:2430var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
Takuto Ikuta2e08a7d2022-01-27 02:01:2331var knownWindowsPackages = {
Simon Zünd67f366b2024-10-24 05:25:2432 "win32 arm64 LE": "@esbuild/win32-arm64",
33 "win32 ia32 LE": "@esbuild/win32-ia32",
34 "win32 x64 LE": "@esbuild/win32-x64"
Takuto Ikuta2e08a7d2022-01-27 02:01:2335};
36var knownUnixlikePackages = {
Simon Zünd67f366b2024-10-24 05:25:2437 "aix ppc64 BE": "@esbuild/aix-ppc64",
38 "android arm64 LE": "@esbuild/android-arm64",
39 "darwin arm64 LE": "@esbuild/darwin-arm64",
40 "darwin x64 LE": "@esbuild/darwin-x64",
41 "freebsd arm64 LE": "@esbuild/freebsd-arm64",
42 "freebsd x64 LE": "@esbuild/freebsd-x64",
43 "linux arm LE": "@esbuild/linux-arm",
44 "linux arm64 LE": "@esbuild/linux-arm64",
45 "linux ia32 LE": "@esbuild/linux-ia32",
46 "linux mips64el LE": "@esbuild/linux-mips64el",
47 "linux ppc64 LE": "@esbuild/linux-ppc64",
48 "linux riscv64 LE": "@esbuild/linux-riscv64",
49 "linux s390x BE": "@esbuild/linux-s390x",
50 "linux x64 LE": "@esbuild/linux-x64",
51 "linux loong64 LE": "@esbuild/linux-loong64",
52 "netbsd x64 LE": "@esbuild/netbsd-x64",
53 "openbsd arm64 LE": "@esbuild/openbsd-arm64",
54 "openbsd x64 LE": "@esbuild/openbsd-x64",
55 "sunos x64 LE": "@esbuild/sunos-x64"
56};
57var knownWebAssemblyFallbackPackages = {
58 "android arm LE": "@esbuild/android-arm",
59 "android x64 LE": "@esbuild/android-x64"
Takuto Ikuta2e08a7d2022-01-27 02:01:2360};
61function pkgAndSubpathForCurrentPlatform() {
62 let pkg;
63 let subpath;
Simon Zünd67f366b2024-10-24 05:25:2464 let isWASM = false;
Takuto Ikuta2e08a7d2022-01-27 02:01:2365 let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
66 if (platformKey in knownWindowsPackages) {
67 pkg = knownWindowsPackages[platformKey];
68 subpath = "esbuild.exe";
69 } else if (platformKey in knownUnixlikePackages) {
70 pkg = knownUnixlikePackages[platformKey];
71 subpath = "bin/esbuild";
Simon Zünd67f366b2024-10-24 05:25:2472 } else if (platformKey in knownWebAssemblyFallbackPackages) {
73 pkg = knownWebAssemblyFallbackPackages[platformKey];
74 subpath = "bin/esbuild";
75 isWASM = true;
Takuto Ikuta2e08a7d2022-01-27 02:01:2376 } else {
77 throw new Error(`Unsupported platform: ${platformKey}`);
78 }
Simon Zünd67f366b2024-10-24 05:25:2479 return { pkg, subpath, isWASM };
Takuto Ikuta2e08a7d2022-01-27 02:01:2380}
81function downloadedBinPath(pkg, subpath) {
82 const esbuildLibDir = path.dirname(require.resolve("esbuild"));
Simon Zünd67f366b2024-10-24 05:25:2483 return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
Takuto Ikuta2e08a7d2022-01-27 02:01:2384}
85
86// lib/npm/node-install.ts
87var fs2 = require("fs");
88var os2 = require("os");
89var path2 = require("path");
90var zlib = require("zlib");
91var https = require("https");
92var child_process = require("child_process");
Simon Zünd67f366b2024-10-24 05:25:2493var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version;
Takuto Ikuta2e08a7d2022-01-27 02:01:2394var toPath = path2.join(__dirname, "bin", "esbuild");
95var isToPathJS = true;
96function validateBinaryVersion(...command) {
97 command.push("--version");
Simon Zünd67f366b2024-10-24 05:25:2498 let stdout;
99 try {
100 stdout = child_process.execFileSync(command.shift(), command, {
101 // Without this, this install script strangely crashes with the error
102 // "EACCES: permission denied, write" but only on Ubuntu Linux when node is
103 // installed from the Snap Store. This is not a problem when you download
104 // the official version of node. The problem appears to be that stderr
105 // (i.e. file descriptor 2) isn't writable?
106 //
107 // More info:
108 // - https://snapcraft.io/ (what the Snap Store is)
109 // - https://nodejs.org/dist/ (download the official version of node)
110 // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035
111 //
112 stdio: "pipe"
113 }).toString().trim();
114 } catch (err) {
115 if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) {
116 let os3 = "this version of macOS";
117 try {
118 os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim();
119 } catch {
120 }
121 throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated.
122
123The Go compiler (which esbuild relies on) no longer supports ${os3},
124which means the "esbuild" binary executable can't be run. You can either:
125
126 * Update your version of macOS to one that the Go compiler supports
127 * Use the "esbuild-wasm" package instead of the "esbuild" package
128 * Build esbuild yourself using an older version of the Go compiler
129`);
130 }
131 throw err;
132 }
133 if (stdout !== versionFromPackageJSON) {
134 throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`);
Takuto Ikuta2e08a7d2022-01-27 02:01:23135 }
136}
137function isYarn() {
138 const { npm_config_user_agent } = process.env;
139 if (npm_config_user_agent) {
140 return /\byarn\//.test(npm_config_user_agent);
141 }
142 return false;
143}
144function fetch(url) {
145 return new Promise((resolve, reject) => {
146 https.get(url, (res) => {
147 if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)
148 return fetch(res.headers.location).then(resolve, reject);
149 if (res.statusCode !== 200)
150 return reject(new Error(`Server responded with ${res.statusCode}`));
151 let chunks = [];
152 res.on("data", (chunk) => chunks.push(chunk));
153 res.on("end", () => resolve(Buffer.concat(chunks)));
154 }).on("error", reject);
155 });
156}
157function extractFileFromTarGzip(buffer, subpath) {
158 try {
159 buffer = zlib.unzipSync(buffer);
160 } catch (err) {
161 throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);
162 }
163 let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");
164 let offset = 0;
165 subpath = `package/${subpath}`;
166 while (offset < buffer.length) {
167 let name = str(offset, 100);
168 let size = parseInt(str(offset + 124, 12), 8);
169 offset += 512;
170 if (!isNaN(size)) {
Simon Zünd67f366b2024-10-24 05:25:24171 if (name === subpath) return buffer.subarray(offset, offset + size);
Takuto Ikuta2e08a7d2022-01-27 02:01:23172 offset += size + 511 & ~511;
173 }
174 }
175 throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);
176}
177function installUsingNPM(pkg, subpath, binPath) {
Simon Zünd67f366b2024-10-24 05:25:24178 const env = { ...process.env, npm_config_global: void 0 };
Takuto Ikuta2e08a7d2022-01-27 02:01:23179 const esbuildLibDir = path2.dirname(require.resolve("esbuild"));
180 const installDir = path2.join(esbuildLibDir, "npm-install");
181 fs2.mkdirSync(installDir);
182 try {
183 fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");
Simon Zünd67f366b2024-10-24 05:25:24184 child_process.execSync(
185 `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`,
186 { cwd: installDir, stdio: "pipe", env }
187 );
Takuto Ikuta2e08a7d2022-01-27 02:01:23188 const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);
189 fs2.renameSync(installedBinPath, binPath);
190 } finally {
191 try {
192 removeRecursive(installDir);
193 } catch {
194 }
195 }
196}
197function removeRecursive(dir) {
198 for (const entry of fs2.readdirSync(dir)) {
199 const entryPath = path2.join(dir, entry);
200 let stats;
201 try {
202 stats = fs2.lstatSync(entryPath);
203 } catch {
204 continue;
205 }
Simon Zünd67f366b2024-10-24 05:25:24206 if (stats.isDirectory()) removeRecursive(entryPath);
207 else fs2.unlinkSync(entryPath);
Takuto Ikuta2e08a7d2022-01-27 02:01:23208 }
209 fs2.rmdirSync(dir);
210}
211function applyManualBinaryPathOverride(overridePath) {
212 const pathString = JSON.stringify(overridePath);
213 fs2.writeFileSync(toPath, `#!/usr/bin/env node
214require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });
215`);
216 const libMain = path2.join(__dirname, "lib", "main.js");
217 const code = fs2.readFileSync(libMain, "utf8");
218 fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};
219${code}`);
220}
221function maybeOptimizePackage(binPath) {
222 if (os2.platform() !== "win32" && !isYarn()) {
223 const tempPath = path2.join(__dirname, "bin-esbuild");
224 try {
225 fs2.linkSync(binPath, tempPath);
226 fs2.renameSync(tempPath, toPath);
227 isToPathJS = false;
228 fs2.unlinkSync(tempPath);
229 } catch {
230 }
231 }
232}
233async function downloadDirectlyFromNPM(pkg, subpath, binPath) {
Simon Zünd67f366b2024-10-24 05:25:24234 const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`;
Takuto Ikuta2e08a7d2022-01-27 02:01:23235 console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);
236 try {
237 fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));
238 fs2.chmodSync(binPath, 493);
239 } catch (e) {
240 console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);
241 throw e;
242 }
243}
244async function checkAndPreparePackage() {
Simon Zünd67f366b2024-10-24 05:25:24245 if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
246 if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {
247 console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
248 } else {
249 applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);
250 return;
251 }
Takuto Ikuta2e08a7d2022-01-27 02:01:23252 }
253 const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
254 let binPath;
255 try {
256 binPath = require.resolve(`${pkg}/${subpath}`);
257 } catch (e) {
258 console.error(`[esbuild] Failed to find package "${pkg}" on the file system
259
260This can happen if you use the "--no-optional" flag. The "optionalDependencies"
261package.json feature is used by esbuild to install the correct binary executable
262for your current platform. This install script will now attempt to work around
263this. If that fails, you need to remove the "--no-optional" flag to use esbuild.
264`);
265 binPath = downloadedBinPath(pkg, subpath);
266 try {
267 console.error(`[esbuild] Trying to install package "${pkg}" using npm`);
268 installUsingNPM(pkg, subpath, binPath);
269 } catch (e2) {
270 console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);
271 try {
272 await downloadDirectlyFromNPM(pkg, subpath, binPath);
273 } catch (e3) {
274 throw new Error(`Failed to install package "${pkg}"`);
275 }
276 }
277 }
278 maybeOptimizePackage(binPath);
279}
280checkAndPreparePackage().then(() => {
281 if (isToPathJS) {
Simon Zünd67f366b2024-10-24 05:25:24282 validateBinaryVersion(process.execPath, toPath);
Takuto Ikuta2e08a7d2022-01-27 02:01:23283 } else {
284 validateBinaryVersion(toPath);
285 }
286});