source: node_modules/esbuild/install.js@ 3d60932

Last change on this file since 3d60932 was 57e58a3, checked in by ste08 <sjovanoska@…>, 4 months ago

Initial commit

  • Property mode set to 100644
File size: 10.8 KB
Line 
1"use strict";
2var __create = Object.create;
3var __defProp = Object.defineProperty;
4var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5var __getOwnPropNames = Object.getOwnPropertyNames;
6var __getProtoOf = Object.getPrototypeOf;
7var __hasOwnProp = Object.prototype.hasOwnProperty;
8var __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 });
13 }
14 return to;
15};
16var __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));
24
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;
30var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
31var knownWindowsPackages = {
32 "win32 arm64 LE": "@esbuild/win32-arm64",
33 "win32 ia32 LE": "@esbuild/win32-ia32",
34 "win32 x64 LE": "@esbuild/win32-x64"
35};
36var knownUnixlikePackages = {
37 "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 arm64 LE": "@esbuild/netbsd-arm64",
53 "netbsd x64 LE": "@esbuild/netbsd-x64",
54 "openbsd arm64 LE": "@esbuild/openbsd-arm64",
55 "openbsd x64 LE": "@esbuild/openbsd-x64",
56 "sunos x64 LE": "@esbuild/sunos-x64"
57};
58var knownWebAssemblyFallbackPackages = {
59 "android arm LE": "@esbuild/android-arm",
60 "android x64 LE": "@esbuild/android-x64"
61};
62function pkgAndSubpathForCurrentPlatform() {
63 let pkg;
64 let subpath;
65 let isWASM = false;
66 let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
67 if (platformKey in knownWindowsPackages) {
68 pkg = knownWindowsPackages[platformKey];
69 subpath = "esbuild.exe";
70 } else if (platformKey in knownUnixlikePackages) {
71 pkg = knownUnixlikePackages[platformKey];
72 subpath = "bin/esbuild";
73 } else if (platformKey in knownWebAssemblyFallbackPackages) {
74 pkg = knownWebAssemblyFallbackPackages[platformKey];
75 subpath = "bin/esbuild";
76 isWASM = true;
77 } else {
78 throw new Error(`Unsupported platform: ${platformKey}`);
79 }
80 return { pkg, subpath, isWASM };
81}
82function downloadedBinPath(pkg, subpath) {
83 const esbuildLibDir = path.dirname(require.resolve("esbuild"));
84 return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
85}
86
87// lib/npm/node-install.ts
88var fs2 = require("fs");
89var os2 = require("os");
90var path2 = require("path");
91var zlib = require("zlib");
92var https = require("https");
93var child_process = require("child_process");
94var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version;
95var toPath = path2.join(__dirname, "bin", "esbuild");
96var isToPathJS = true;
97function validateBinaryVersion(...command) {
98 command.push("--version");
99 let stdout;
100 try {
101 stdout = child_process.execFileSync(command.shift(), command, {
102 // Without this, this install script strangely crashes with the error
103 // "EACCES: permission denied, write" but only on Ubuntu Linux when node is
104 // installed from the Snap Store. This is not a problem when you download
105 // the official version of node. The problem appears to be that stderr
106 // (i.e. file descriptor 2) isn't writable?
107 //
108 // More info:
109 // - https://snapcraft.io/ (what the Snap Store is)
110 // - https://nodejs.org/dist/ (download the official version of node)
111 // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035
112 //
113 stdio: "pipe"
114 }).toString().trim();
115 } catch (err) {
116 if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) {
117 let os3 = "this version of macOS";
118 try {
119 os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim();
120 } catch {
121 }
122 throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated.
123
124The Go compiler (which esbuild relies on) no longer supports ${os3},
125which means the "esbuild" binary executable can't be run. You can either:
126
127 * Update your version of macOS to one that the Go compiler supports
128 * Use the "esbuild-wasm" package instead of the "esbuild" package
129 * Build esbuild yourself using an older version of the Go compiler
130`);
131 }
132 throw err;
133 }
134 if (stdout !== versionFromPackageJSON) {
135 throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`);
136 }
137}
138function isYarn() {
139 const { npm_config_user_agent } = process.env;
140 if (npm_config_user_agent) {
141 return /\byarn\//.test(npm_config_user_agent);
142 }
143 return false;
144}
145function fetch(url) {
146 return new Promise((resolve, reject) => {
147 https.get(url, (res) => {
148 if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)
149 return fetch(res.headers.location).then(resolve, reject);
150 if (res.statusCode !== 200)
151 return reject(new Error(`Server responded with ${res.statusCode}`));
152 let chunks = [];
153 res.on("data", (chunk) => chunks.push(chunk));
154 res.on("end", () => resolve(Buffer.concat(chunks)));
155 }).on("error", reject);
156 });
157}
158function extractFileFromTarGzip(buffer, subpath) {
159 try {
160 buffer = zlib.unzipSync(buffer);
161 } catch (err) {
162 throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);
163 }
164 let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");
165 let offset = 0;
166 subpath = `package/${subpath}`;
167 while (offset < buffer.length) {
168 let name = str(offset, 100);
169 let size = parseInt(str(offset + 124, 12), 8);
170 offset += 512;
171 if (!isNaN(size)) {
172 if (name === subpath) return buffer.subarray(offset, offset + size);
173 offset += size + 511 & ~511;
174 }
175 }
176 throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);
177}
178function installUsingNPM(pkg, subpath, binPath) {
179 const env = { ...process.env, npm_config_global: void 0 };
180 const esbuildLibDir = path2.dirname(require.resolve("esbuild"));
181 const installDir = path2.join(esbuildLibDir, "npm-install");
182 fs2.mkdirSync(installDir);
183 try {
184 fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");
185 child_process.execSync(
186 `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`,
187 { cwd: installDir, stdio: "pipe", env }
188 );
189 const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);
190 fs2.renameSync(installedBinPath, binPath);
191 } finally {
192 try {
193 removeRecursive(installDir);
194 } catch {
195 }
196 }
197}
198function removeRecursive(dir) {
199 for (const entry of fs2.readdirSync(dir)) {
200 const entryPath = path2.join(dir, entry);
201 let stats;
202 try {
203 stats = fs2.lstatSync(entryPath);
204 } catch {
205 continue;
206 }
207 if (stats.isDirectory()) removeRecursive(entryPath);
208 else fs2.unlinkSync(entryPath);
209 }
210 fs2.rmdirSync(dir);
211}
212function applyManualBinaryPathOverride(overridePath) {
213 const pathString = JSON.stringify(overridePath);
214 fs2.writeFileSync(toPath, `#!/usr/bin/env node
215require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });
216`);
217 const libMain = path2.join(__dirname, "lib", "main.js");
218 const code = fs2.readFileSync(libMain, "utf8");
219 fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};
220${code}`);
221}
222function maybeOptimizePackage(binPath) {
223 if (os2.platform() !== "win32" && !isYarn()) {
224 const tempPath = path2.join(__dirname, "bin-esbuild");
225 try {
226 fs2.linkSync(binPath, tempPath);
227 fs2.renameSync(tempPath, toPath);
228 isToPathJS = false;
229 fs2.unlinkSync(tempPath);
230 } catch {
231 }
232 }
233}
234async function downloadDirectlyFromNPM(pkg, subpath, binPath) {
235 const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`;
236 console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);
237 try {
238 fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));
239 fs2.chmodSync(binPath, 493);
240 } catch (e) {
241 console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);
242 throw e;
243 }
244}
245async function checkAndPreparePackage() {
246 if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
247 if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {
248 console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
249 } else {
250 applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);
251 return;
252 }
253 }
254 const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
255 let binPath;
256 try {
257 binPath = require.resolve(`${pkg}/${subpath}`);
258 } catch (e) {
259 console.error(`[esbuild] Failed to find package "${pkg}" on the file system
260
261This can happen if you use the "--no-optional" flag. The "optionalDependencies"
262package.json feature is used by esbuild to install the correct binary executable
263for your current platform. This install script will now attempt to work around
264this. If that fails, you need to remove the "--no-optional" flag to use esbuild.
265`);
266 binPath = downloadedBinPath(pkg, subpath);
267 try {
268 console.error(`[esbuild] Trying to install package "${pkg}" using npm`);
269 installUsingNPM(pkg, subpath, binPath);
270 } catch (e2) {
271 console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);
272 try {
273 await downloadDirectlyFromNPM(pkg, subpath, binPath);
274 } catch (e3) {
275 throw new Error(`Failed to install package "${pkg}"`);
276 }
277 }
278 }
279 maybeOptimizePackage(binPath);
280}
281checkAndPreparePackage().then(() => {
282 if (isToPathJS) {
283 validateBinaryVersion(process.execPath, toPath);
284 } else {
285 validateBinaryVersion(toPath);
286 }
287});
Note: See TracBrowser for help on using the repository browser.