CoolFace
Apppublic

sourav-das/stem-separator

sourceHugging Facemitupdated 6mo agoView on Hugging Face
3likes
install.js290 linesDownload Raw Back to esbuild
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 ESM18  // file that has been converted to a CommonJS file using a Babel-19  // compatible transform (i.e. "__esModule" has not been set), then set20  // "default" to the CommonJS "module.exports" for node compatibility.21  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,22  mod23));24 25// lib/npm/node-platform.ts26var 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  "openharmony arm64 LE": "@esbuild/openharmony-arm64"62};63function pkgAndSubpathForCurrentPlatform() {64  let pkg;65  let subpath;66  let isWASM = false;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 if (platformKey in knownWebAssemblyFallbackPackages) {75    pkg = knownWebAssemblyFallbackPackages[platformKey];76    subpath = "bin/esbuild";77    isWASM = true;78  } else {79    throw new Error(`Unsupported platform: ${platformKey}`);80  }81  return { pkg, subpath, isWASM };82}83function downloadedBinPath(pkg, subpath) {84  const esbuildLibDir = path.dirname(require.resolve("esbuild"));85  return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);86}87 88// lib/npm/node-install.ts89var fs2 = require("fs");90var os2 = require("os");91var path2 = require("path");92var zlib = require("zlib");93var https = require("https");94var child_process = require("child_process");95var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version;96var toPath = path2.join(__dirname, "bin", "esbuild");97var isToPathJS = true;98function validateBinaryVersion(...command) {99  command.push("--version");100  let stdout;101  try {102    stdout = child_process.execFileSync(command.shift(), command, {103      // Without this, this install script strangely crashes with the error104      // "EACCES: permission denied, write" but only on Ubuntu Linux when node is105      // installed from the Snap Store. This is not a problem when you download106      // the official version of node. The problem appears to be that stderr107      // (i.e. file descriptor 2) isn't writable?108      //109      // More info:110      // - https://snapcraft.io/ (what the Snap Store is)111      // - https://nodejs.org/dist/ (download the official version of node)112      // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035113      //114      stdio: "pipe"115    }).toString().trim();116  } catch (err) {117    if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) {118      let os3 = "this version of macOS";119      try {120        os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim();121      } catch {122      }123      throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated.124 125The Go compiler (which esbuild relies on) no longer supports ${os3},126which means the "esbuild" binary executable can't be run. You can either:127 128  * Update your version of macOS to one that the Go compiler supports129  * Use the "esbuild-wasm" package instead of the "esbuild" package130  * Build esbuild yourself using an older version of the Go compiler131`);132    }133    throw err;134  }135  if (stdout !== versionFromPackageJSON) {136    throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`);137  }138}139function isYarn() {140  const { npm_config_user_agent } = process.env;141  if (npm_config_user_agent) {142    return /\byarn\//.test(npm_config_user_agent);143  }144  return false;145}146function fetch(url) {147  return new Promise((resolve, reject) => {148    https.get(url, (res) => {149      if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)150        return fetch(res.headers.location).then(resolve, reject);151      if (res.statusCode !== 200)152        return reject(new Error(`Server responded with ${res.statusCode}`));153      let chunks = [];154      res.on("data", (chunk) => chunks.push(chunk));155      res.on("end", () => resolve(Buffer.concat(chunks)));156    }).on("error", reject);157  });158}159function extractFileFromTarGzip(buffer, subpath) {160  try {161    buffer = zlib.unzipSync(buffer);162  } catch (err) {163    throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);164  }165  let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");166  let offset = 0;167  subpath = `package/${subpath}`;168  while (offset < buffer.length) {169    let name = str(offset, 100);170    let size = parseInt(str(offset + 124, 12), 8);171    offset += 512;172    if (!isNaN(size)) {173      if (name === subpath) return buffer.subarray(offset, offset + size);174      offset += size + 511 & ~511;175    }176  }177  throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);178}179function installUsingNPM(pkg, subpath, binPath) {180  const env = { ...process.env, npm_config_global: void 0 };181  const esbuildLibDir = path2.dirname(require.resolve("esbuild"));182  const installDir = path2.join(esbuildLibDir, "npm-install");183  fs2.mkdirSync(installDir);184  try {185    fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");186    child_process.execSync(187      `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`,188      { cwd: installDir, stdio: "pipe", env }189    );190    const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);191    fs2.renameSync(installedBinPath, binPath);192  } finally {193    try {194      removeRecursive(installDir);195    } catch {196    }197  }198}199function removeRecursive(dir) {200  for (const entry of fs2.readdirSync(dir)) {201    const entryPath = path2.join(dir, entry);202    let stats;203    try {204      stats = fs2.lstatSync(entryPath);205    } catch {206      continue;207    }208    if (stats.isDirectory()) removeRecursive(entryPath);209    else fs2.unlinkSync(entryPath);210  }211  fs2.rmdirSync(dir);212}213function applyManualBinaryPathOverride(overridePath) {214  const pathString = JSON.stringify(overridePath);215  fs2.writeFileSync(toPath, `#!/usr/bin/env node216require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });217`);218  const libMain = path2.join(__dirname, "lib", "main.js");219  const code = fs2.readFileSync(libMain, "utf8");220  fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};221${code}`);222}223function maybeOptimizePackage(binPath) {224  const { isWASM } = pkgAndSubpathForCurrentPlatform();225  if (os2.platform() !== "win32" && !isYarn() && !isWASM) {226    const tempPath = path2.join(__dirname, "bin-esbuild");227    try {228      fs2.linkSync(binPath, tempPath);229      fs2.renameSync(tempPath, toPath);230      isToPathJS = false;231      fs2.unlinkSync(tempPath);232    } catch {233    }234  }235}236async function downloadDirectlyFromNPM(pkg, subpath, binPath) {237  const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`;238  console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);239  try {240    fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));241    fs2.chmodSync(binPath, 493);242  } catch (e) {243    console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);244    throw e;245  }246}247async function checkAndPreparePackage() {248  if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {249    if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {250      console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);251    } else {252      applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);253      return;254    }255  }256  const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();257  let binPath;258  try {259    binPath = require.resolve(`${pkg}/${subpath}`);260  } catch (e) {261    console.error(`[esbuild] Failed to find package "${pkg}" on the file system262 263This can happen if you use the "--no-optional" flag. The "optionalDependencies"264package.json feature is used by esbuild to install the correct binary executable265for your current platform. This install script will now attempt to work around266this. If that fails, you need to remove the "--no-optional" flag to use esbuild.267`);268    binPath = downloadedBinPath(pkg, subpath);269    try {270      console.error(`[esbuild] Trying to install package "${pkg}" using npm`);271      installUsingNPM(pkg, subpath, binPath);272    } catch (e2) {273      console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);274      try {275        await downloadDirectlyFromNPM(pkg, subpath, binPath);276      } catch (e3) {277        throw new Error(`Failed to install package "${pkg}"`);278      }279    }280  }281  maybeOptimizePackage(binPath);282}283checkAndPreparePackage().then(() => {284  if (isToPathJS) {285    validateBinaryVersion(process.execPath, toPath);286  } else {287    validateBinaryVersion(toPath);288  }289});290