install.js 11 KB

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