blob: df5450c7354c6107fb866fa05c8cf75e8c729c9b [file] [log] [blame]
Takuto Ikuta2e08a7d2022-01-27 02:01:231var __create = Object.create;
2var __defProp = Object.defineProperty;
3var __defProps = Object.defineProperties;
4var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6var __getOwnPropNames = Object.getOwnPropertyNames;
7var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8var __getProtoOf = Object.getPrototypeOf;
9var __hasOwnProp = Object.prototype.hasOwnProperty;
10var __propIsEnum = Object.prototype.propertyIsEnumerable;
11var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12var __spreadValues = (a, b) => {
13 for (var prop in b || (b = {}))
14 if (__hasOwnProp.call(b, prop))
15 __defNormalProp(a, prop, b[prop]);
16 if (__getOwnPropSymbols)
17 for (var prop of __getOwnPropSymbols(b)) {
18 if (__propIsEnum.call(b, prop))
19 __defNormalProp(a, prop, b[prop]);
20 }
21 return a;
22};
23var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
25var __reExport = (target, module2, copyDefault, desc) => {
26 if (module2 && typeof module2 === "object" || typeof module2 === "function") {
27 for (let key of __getOwnPropNames(module2))
28 if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
29 __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
30 }
31 return target;
32};
33var __toESM = (module2, isNodeMode) => {
34 return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", !isNodeMode && module2 && module2.__esModule ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
35};
36
37// lib/npm/node-platform.ts
38var fs = require("fs");
39var os = require("os");
40var path = require("path");
41var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
42var knownWindowsPackages = {
43 "win32 arm64 LE": "esbuild-windows-arm64",
44 "win32 ia32 LE": "esbuild-windows-32",
45 "win32 x64 LE": "esbuild-windows-64"
46};
47var knownUnixlikePackages = {
48 "android arm64 LE": "esbuild-android-arm64",
49 "darwin arm64 LE": "esbuild-darwin-arm64",
50 "darwin x64 LE": "esbuild-darwin-64",
51 "freebsd arm64 LE": "esbuild-freebsd-arm64",
52 "freebsd x64 LE": "esbuild-freebsd-64",
53 "linux arm LE": "esbuild-linux-arm",
54 "linux arm64 LE": "esbuild-linux-arm64",
55 "linux ia32 LE": "esbuild-linux-32",
56 "linux mips64el LE": "esbuild-linux-mips64le",
57 "linux ppc64 LE": "esbuild-linux-ppc64le",
58 "linux s390x BE": "esbuild-linux-s390x",
59 "linux x64 LE": "esbuild-linux-64",
60 "netbsd x64 LE": "esbuild-netbsd-64",
61 "openbsd x64 LE": "esbuild-openbsd-64",
62 "sunos x64 LE": "esbuild-sunos-64"
63};
64function pkgAndSubpathForCurrentPlatform() {
65 let pkg;
66 let subpath;
67 let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
68 if (platformKey in knownWindowsPackages) {
69 pkg = knownWindowsPackages[platformKey];
70 subpath = "esbuild.exe";
71 } else if (platformKey in knownUnixlikePackages) {
72 pkg = knownUnixlikePackages[platformKey];
73 subpath = "bin/esbuild";
74 } else {
75 throw new Error(`Unsupported platform: ${platformKey}`);
76 }
77 return { pkg, subpath };
78}
79function downloadedBinPath(pkg, subpath) {
80 const esbuildLibDir = path.dirname(require.resolve("esbuild"));
81 return path.join(esbuildLibDir, `downloaded-${pkg}-${path.basename(subpath)}`);
82}
83
84// lib/npm/node-install.ts
85var fs2 = require("fs");
86var os2 = require("os");
87var path2 = require("path");
88var zlib = require("zlib");
89var https = require("https");
90var child_process = require("child_process");
91var toPath = path2.join(__dirname, "bin", "esbuild");
92var isToPathJS = true;
93function validateBinaryVersion(...command) {
94 command.push("--version");
95 const stdout = child_process.execFileSync(command.shift(), command).toString().trim();
96 if (stdout !== "0.14.13") {
97 throw new Error(`Expected ${JSON.stringify("0.14.13")} but got ${JSON.stringify(stdout)}`);
98 }
99}
100function isYarn() {
101 const { npm_config_user_agent } = process.env;
102 if (npm_config_user_agent) {
103 return /\byarn\//.test(npm_config_user_agent);
104 }
105 return false;
106}
107function fetch(url) {
108 return new Promise((resolve, reject) => {
109 https.get(url, (res) => {
110 if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)
111 return fetch(res.headers.location).then(resolve, reject);
112 if (res.statusCode !== 200)
113 return reject(new Error(`Server responded with ${res.statusCode}`));
114 let chunks = [];
115 res.on("data", (chunk) => chunks.push(chunk));
116 res.on("end", () => resolve(Buffer.concat(chunks)));
117 }).on("error", reject);
118 });
119}
120function extractFileFromTarGzip(buffer, subpath) {
121 try {
122 buffer = zlib.unzipSync(buffer);
123 } catch (err) {
124 throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);
125 }
126 let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");
127 let offset = 0;
128 subpath = `package/${subpath}`;
129 while (offset < buffer.length) {
130 let name = str(offset, 100);
131 let size = parseInt(str(offset + 124, 12), 8);
132 offset += 512;
133 if (!isNaN(size)) {
134 if (name === subpath)
135 return buffer.subarray(offset, offset + size);
136 offset += size + 511 & ~511;
137 }
138 }
139 throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);
140}
141function installUsingNPM(pkg, subpath, binPath) {
142 const env = __spreadProps(__spreadValues({}, process.env), { npm_config_global: void 0 });
143 const esbuildLibDir = path2.dirname(require.resolve("esbuild"));
144 const installDir = path2.join(esbuildLibDir, "npm-install");
145 fs2.mkdirSync(installDir);
146 try {
147 fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");
148 child_process.execSync(`npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${"0.14.13"}`, { cwd: installDir, stdio: "pipe", env });
149 const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);
150 fs2.renameSync(installedBinPath, binPath);
151 } finally {
152 try {
153 removeRecursive(installDir);
154 } catch {
155 }
156 }
157}
158function removeRecursive(dir) {
159 for (const entry of fs2.readdirSync(dir)) {
160 const entryPath = path2.join(dir, entry);
161 let stats;
162 try {
163 stats = fs2.lstatSync(entryPath);
164 } catch {
165 continue;
166 }
167 if (stats.isDirectory())
168 removeRecursive(entryPath);
169 else
170 fs2.unlinkSync(entryPath);
171 }
172 fs2.rmdirSync(dir);
173}
174function applyManualBinaryPathOverride(overridePath) {
175 const pathString = JSON.stringify(overridePath);
176 fs2.writeFileSync(toPath, `#!/usr/bin/env node
177require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });
178`);
179 const libMain = path2.join(__dirname, "lib", "main.js");
180 const code = fs2.readFileSync(libMain, "utf8");
181 fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};
182${code}`);
183}
184function maybeOptimizePackage(binPath) {
185 if (os2.platform() !== "win32" && !isYarn()) {
186 const tempPath = path2.join(__dirname, "bin-esbuild");
187 try {
188 fs2.linkSync(binPath, tempPath);
189 fs2.renameSync(tempPath, toPath);
190 isToPathJS = false;
191 fs2.unlinkSync(tempPath);
192 } catch {
193 }
194 }
195}
196async function downloadDirectlyFromNPM(pkg, subpath, binPath) {
197 const url = `https://registry.npmjs.org/${pkg}/-/${pkg}-${"0.14.13"}.tgz`;
198 console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);
199 try {
200 fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));
201 fs2.chmodSync(binPath, 493);
202 } catch (e) {
203 console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);
204 throw e;
205 }
206}
207async function checkAndPreparePackage() {
208 if (ESBUILD_BINARY_PATH) {
209 applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);
210 return;
211 }
212 const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
213 let binPath;
214 try {
215 binPath = require.resolve(`${pkg}/${subpath}`);
216 } catch (e) {
217 console.error(`[esbuild] Failed to find package "${pkg}" on the file system
218
219This can happen if you use the "--no-optional" flag. The "optionalDependencies"
220package.json feature is used by esbuild to install the correct binary executable
221for your current platform. This install script will now attempt to work around
222this. If that fails, you need to remove the "--no-optional" flag to use esbuild.
223`);
224 binPath = downloadedBinPath(pkg, subpath);
225 try {
226 console.error(`[esbuild] Trying to install package "${pkg}" using npm`);
227 installUsingNPM(pkg, subpath, binPath);
228 } catch (e2) {
229 console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);
230 try {
231 await downloadDirectlyFromNPM(pkg, subpath, binPath);
232 } catch (e3) {
233 throw new Error(`Failed to install package "${pkg}"`);
234 }
235 }
236 }
237 maybeOptimizePackage(binPath);
238}
239checkAndPreparePackage().then(() => {
240 if (isToPathJS) {
241 validateBinaryVersion("node", toPath);
242 } else {
243 validateBinaryVersion(toPath);
244 }
245});