diff --git a/js/node_modules/.bin/esbuild b/js/node_modules/.bin/esbuild deleted file mode 120000 index c83ac07..0000000 --- a/js/node_modules/.bin/esbuild +++ /dev/null @@ -1 +0,0 @@ -../esbuild/bin/esbuild \ No newline at end of file diff --git a/js/node_modules/.yarn-integrity b/js/node_modules/.yarn-integrity deleted file mode 100644 index 372c2c3..0000000 --- a/js/node_modules/.yarn-integrity +++ /dev/null @@ -1,54 +0,0 @@ -{ - "systemParams": "darwin-x64-115", - "modulesFolders": [ - "node_modules" - ], - "flags": [], - "linkedModules": [ - "@nostr-dev-kit/ndk", - "@nostrwatch/nocap", - "@nostrwatch/nocap-websocket-adapter-default", - "@nostrwatch/nostrawl", - "@notemine/wrapper", - "@sandwichfarm/torfetch", - "dexie-queue", - "nostr-geotags", - "nostrawl", - "nostrwatch-js", - "notemine", - "transferwise", - "ws-tor" - ], - "topLevelPatterns": [ - "esbuild@0.24.0" - ], - "lockfileEntries": { - "@esbuild/aix-ppc64@0.24.0": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.0.tgz#b57697945b50e99007b4c2521507dc613d4a648c", - "@esbuild/android-arm64@0.24.0": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.0.tgz#1add7e0af67acefd556e407f8497e81fddad79c0", - "@esbuild/android-arm@0.24.0": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.0.tgz#ab7263045fa8e090833a8e3c393b60d59a789810", - "@esbuild/android-x64@0.24.0": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.0.tgz#e8f8b196cfdfdd5aeaebbdb0110983460440e705", - "@esbuild/darwin-arm64@0.24.0": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.0.tgz#2d0d9414f2acbffd2d86e98253914fca603a53dd", - "@esbuild/darwin-x64@0.24.0": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.0.tgz#33087aab31a1eb64c89daf3d2cf8ce1775656107", - "@esbuild/freebsd-arm64@0.24.0": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.0.tgz#bb76e5ea9e97fa3c753472f19421075d3a33e8a7", - "@esbuild/freebsd-x64@0.24.0": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.0.tgz#e0e2ce9249fdf6ee29e5dc3d420c7007fa579b93", - "@esbuild/linux-arm64@0.24.0": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.0.tgz#d1b2aa58085f73ecf45533c07c82d81235388e75", - "@esbuild/linux-arm@0.24.0": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.0.tgz#8e4915df8ea3e12b690a057e77a47b1d5935ef6d", - "@esbuild/linux-ia32@0.24.0": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.0.tgz#8200b1110666c39ab316572324b7af63d82013fb", - "@esbuild/linux-loong64@0.24.0": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.0.tgz#6ff0c99cf647504df321d0640f0d32e557da745c", - "@esbuild/linux-mips64el@0.24.0": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.0.tgz#3f720ccd4d59bfeb4c2ce276a46b77ad380fa1f3", - "@esbuild/linux-ppc64@0.24.0": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.0.tgz#9d6b188b15c25afd2e213474bf5f31e42e3aa09e", - "@esbuild/linux-riscv64@0.24.0": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.0.tgz#f989fdc9752dfda286c9cd87c46248e4dfecbc25", - "@esbuild/linux-s390x@0.24.0": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.0.tgz#29ebf87e4132ea659c1489fce63cd8509d1c7319", - "@esbuild/linux-x64@0.24.0": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.0.tgz#4af48c5c0479569b1f359ffbce22d15f261c0cef", - "@esbuild/netbsd-x64@0.24.0": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.0.tgz#1ae73d23cc044a0ebd4f198334416fb26c31366c", - "@esbuild/openbsd-arm64@0.24.0": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.0.tgz#5d904a4f5158c89859fd902c427f96d6a9e632e2", - "@esbuild/openbsd-x64@0.24.0": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.0.tgz#4c8aa88c49187c601bae2971e71c6dc5e0ad1cdf", - "@esbuild/sunos-x64@0.24.0": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.0.tgz#8ddc35a0ea38575fa44eda30a5ee01ae2fa54dd4", - "@esbuild/win32-arm64@0.24.0": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.0.tgz#6e79c8543f282c4539db684a207ae0e174a9007b", - "@esbuild/win32-ia32@0.24.0": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.0.tgz#057af345da256b7192d18b676a02e95d0fa39103", - "@esbuild/win32-x64@0.24.0": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.0.tgz#168ab1c7e1c318b922637fad8f339d48b01e1244", - "esbuild@0.24.0": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.0.tgz#f2d470596885fcb2e91c21eb3da3b3c89c0b55e7" - }, - "files": [], - "artifacts": {} -} \ No newline at end of file diff --git a/js/node_modules/@esbuild/darwin-x64/README.md b/js/node_modules/@esbuild/darwin-x64/README.md deleted file mode 100644 index a2fd0cb..0000000 --- a/js/node_modules/@esbuild/darwin-x64/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# esbuild - -This is the macOS 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/js/node_modules/@esbuild/darwin-x64/bin/esbuild b/js/node_modules/@esbuild/darwin-x64/bin/esbuild deleted file mode 100755 index 0dfde3f..0000000 Binary files a/js/node_modules/@esbuild/darwin-x64/bin/esbuild and /dev/null differ diff --git a/js/node_modules/@esbuild/darwin-x64/package.json b/js/node_modules/@esbuild/darwin-x64/package.json deleted file mode 100644 index bb46c3f..0000000 --- a/js/node_modules/@esbuild/darwin-x64/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "@esbuild/darwin-x64", - "version": "0.24.0", - "description": "The macOS 64-bit binary for esbuild, a JavaScript bundler.", - "repository": { - "type": "git", - "url": "git+https://github.com/evanw/esbuild.git" - }, - "license": "MIT", - "preferUnplugged": true, - "engines": { - "node": ">=18" - }, - "os": [ - "darwin" - ], - "cpu": [ - "x64" - ] -} diff --git a/js/node_modules/esbuild/LICENSE.md b/js/node_modules/esbuild/LICENSE.md deleted file mode 100644 index 2027e8d..0000000 --- a/js/node_modules/esbuild/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Evan Wallace - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/js/node_modules/esbuild/README.md b/js/node_modules/esbuild/README.md deleted file mode 100644 index 93863d1..0000000 --- a/js/node_modules/esbuild/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# esbuild - -This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details. diff --git a/js/node_modules/esbuild/bin/esbuild b/js/node_modules/esbuild/bin/esbuild deleted file mode 100755 index 06f4563..0000000 --- a/js/node_modules/esbuild/bin/esbuild +++ /dev/null @@ -1,221 +0,0 @@ -#!/usr/bin/env node -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// lib/npm/node-platform.ts -var fs = require("fs"); -var os = require("os"); -var path = require("path"); -var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; -var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; -var packageDarwin_arm64 = "@esbuild/darwin-arm64"; -var packageDarwin_x64 = "@esbuild/darwin-x64"; -var knownWindowsPackages = { - "win32 arm64 LE": "@esbuild/win32-arm64", - "win32 ia32 LE": "@esbuild/win32-ia32", - "win32 x64 LE": "@esbuild/win32-x64" -}; -var knownUnixlikePackages = { - "aix ppc64 BE": "@esbuild/aix-ppc64", - "android arm64 LE": "@esbuild/android-arm64", - "darwin arm64 LE": "@esbuild/darwin-arm64", - "darwin x64 LE": "@esbuild/darwin-x64", - "freebsd arm64 LE": "@esbuild/freebsd-arm64", - "freebsd x64 LE": "@esbuild/freebsd-x64", - "linux arm LE": "@esbuild/linux-arm", - "linux arm64 LE": "@esbuild/linux-arm64", - "linux ia32 LE": "@esbuild/linux-ia32", - "linux mips64el LE": "@esbuild/linux-mips64el", - "linux ppc64 LE": "@esbuild/linux-ppc64", - "linux riscv64 LE": "@esbuild/linux-riscv64", - "linux s390x BE": "@esbuild/linux-s390x", - "linux x64 LE": "@esbuild/linux-x64", - "linux loong64 LE": "@esbuild/linux-loong64", - "netbsd x64 LE": "@esbuild/netbsd-x64", - "openbsd arm64 LE": "@esbuild/openbsd-arm64", - "openbsd x64 LE": "@esbuild/openbsd-x64", - "sunos x64 LE": "@esbuild/sunos-x64" -}; -var knownWebAssemblyFallbackPackages = { - "android arm LE": "@esbuild/android-arm", - "android x64 LE": "@esbuild/android-x64" -}; -function pkgAndSubpathForCurrentPlatform() { - let pkg; - let subpath; - let isWASM2 = false; - let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; - if (platformKey in knownWindowsPackages) { - pkg = knownWindowsPackages[platformKey]; - subpath = "esbuild.exe"; - } else if (platformKey in knownUnixlikePackages) { - pkg = knownUnixlikePackages[platformKey]; - subpath = "bin/esbuild"; - } else if (platformKey in knownWebAssemblyFallbackPackages) { - pkg = knownWebAssemblyFallbackPackages[platformKey]; - subpath = "bin/esbuild"; - isWASM2 = true; - } else { - throw new Error(`Unsupported platform: ${platformKey}`); - } - return { pkg, subpath, isWASM: isWASM2 }; -} -function pkgForSomeOtherPlatform() { - const libMainJS = require.resolve("esbuild"); - const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); - if (path.basename(nodeModulesDirectory) === "node_modules") { - for (const unixKey in knownUnixlikePackages) { - try { - const pkg = knownUnixlikePackages[unixKey]; - if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; - } catch { - } - } - for (const windowsKey in knownWindowsPackages) { - try { - const pkg = knownWindowsPackages[windowsKey]; - if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; - } catch { - } - } - } - return null; -} -function downloadedBinPath(pkg, subpath) { - const esbuildLibDir = path.dirname(require.resolve("esbuild")); - return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); -} -function generateBinPath() { - if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { - if (!fs.existsSync(ESBUILD_BINARY_PATH)) { - console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); - } else { - return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; - } - } - const { pkg, subpath, isWASM: isWASM2 } = pkgAndSubpathForCurrentPlatform(); - let binPath2; - try { - binPath2 = require.resolve(`${pkg}/${subpath}`); - } catch (e) { - binPath2 = downloadedBinPath(pkg, subpath); - if (!fs.existsSync(binPath2)) { - try { - require.resolve(pkg); - } catch { - const otherPkg = pkgForSomeOtherPlatform(); - if (otherPkg) { - let suggestions = ` -Specifically the "${otherPkg}" package is present but this platform -needs the "${pkg}" package instead. People often get into this -situation by installing esbuild on Windows or macOS and copying "node_modules" -into a Docker image that runs Linux, or by copying "node_modules" between -Windows and WSL environments. - -If you are installing with npm, you can try not copying the "node_modules" -directory when you copy the files over, and running "npm ci" or "npm install" -on the destination platform after the copy. Or you could consider using yarn -instead of npm which has built-in support for installing a package on multiple -platforms simultaneously. - -If you are installing with yarn, you can try listing both this platform and the -other platform in your ".yarnrc.yml" file using the "supportedArchitectures" -feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures -Keep in mind that this means multiple copies of esbuild will be present. -`; - if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { - suggestions = ` -Specifically the "${otherPkg}" package is present but this platform -needs the "${pkg}" package instead. People often get into this -situation by installing esbuild with npm running inside of Rosetta 2 and then -trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta -2 is Apple's on-the-fly x86_64-to-arm64 translation service). - -If you are installing with npm, you can try ensuring that both npm and node are -not running under Rosetta 2 and then reinstalling esbuild. This likely involves -changing how you installed npm and/or node. For example, installing node with -the universal installer here should work: https://nodejs.org/en/download/. Or -you could consider using yarn instead of npm which has built-in support for -installing a package on multiple platforms simultaneously. - -If you are installing with yarn, you can try listing both "arm64" and "x64" -in your ".yarnrc.yml" file using the "supportedArchitectures" feature: -https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures -Keep in mind that this means multiple copies of esbuild will be present. -`; - } - throw new Error(` -You installed esbuild for another platform than the one you're currently using. -This won't work because esbuild is written with native code and needs to -install a platform-specific binary executable. -${suggestions} -Another alternative is to use the "esbuild-wasm" package instead, which works -the same way on all platforms. But it comes with a heavy performance cost and -can sometimes be 10x slower than the "esbuild" package, so you may also not -want to do that. -`); - } - throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. - -If you are installing esbuild with npm, make sure that you don't specify the -"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature -of "package.json" is used by esbuild to install the correct binary executable -for your current platform.`); - } - throw e; - } - } - if (/\.zip\//.test(binPath2)) { - let pnpapi; - try { - pnpapi = require("pnpapi"); - } catch (e) { - } - if (pnpapi) { - const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; - const binTargetPath = path.join( - root, - "node_modules", - ".cache", - "esbuild", - `pnpapi-${pkg.replace("/", "-")}-${"0.24.0"}-${path.basename(subpath)}` - ); - if (!fs.existsSync(binTargetPath)) { - fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); - fs.copyFileSync(binPath2, binTargetPath); - fs.chmodSync(binTargetPath, 493); - } - return { binPath: binTargetPath, isWASM: isWASM2 }; - } - } - return { binPath: binPath2, isWASM: isWASM2 }; -} - -// lib/npm/node-shim.ts -var { binPath, isWASM } = generateBinPath(); -if (isWASM) { - require("child_process").execFileSync("node", [binPath].concat(process.argv.slice(2)), { stdio: "inherit" }); -} else { - require("child_process").execFileSync(binPath, process.argv.slice(2), { stdio: "inherit" }); -} diff --git a/js/node_modules/esbuild/install.js b/js/node_modules/esbuild/install.js deleted file mode 100644 index 86b6c43..0000000 --- a/js/node_modules/esbuild/install.js +++ /dev/null @@ -1,286 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// lib/npm/node-platform.ts -var fs = require("fs"); -var os = require("os"); -var path = require("path"); -var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; -var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; -var knownWindowsPackages = { - "win32 arm64 LE": "@esbuild/win32-arm64", - "win32 ia32 LE": "@esbuild/win32-ia32", - "win32 x64 LE": "@esbuild/win32-x64" -}; -var knownUnixlikePackages = { - "aix ppc64 BE": "@esbuild/aix-ppc64", - "android arm64 LE": "@esbuild/android-arm64", - "darwin arm64 LE": "@esbuild/darwin-arm64", - "darwin x64 LE": "@esbuild/darwin-x64", - "freebsd arm64 LE": "@esbuild/freebsd-arm64", - "freebsd x64 LE": "@esbuild/freebsd-x64", - "linux arm LE": "@esbuild/linux-arm", - "linux arm64 LE": "@esbuild/linux-arm64", - "linux ia32 LE": "@esbuild/linux-ia32", - "linux mips64el LE": "@esbuild/linux-mips64el", - "linux ppc64 LE": "@esbuild/linux-ppc64", - "linux riscv64 LE": "@esbuild/linux-riscv64", - "linux s390x BE": "@esbuild/linux-s390x", - "linux x64 LE": "@esbuild/linux-x64", - "linux loong64 LE": "@esbuild/linux-loong64", - "netbsd x64 LE": "@esbuild/netbsd-x64", - "openbsd arm64 LE": "@esbuild/openbsd-arm64", - "openbsd x64 LE": "@esbuild/openbsd-x64", - "sunos x64 LE": "@esbuild/sunos-x64" -}; -var knownWebAssemblyFallbackPackages = { - "android arm LE": "@esbuild/android-arm", - "android x64 LE": "@esbuild/android-x64" -}; -function pkgAndSubpathForCurrentPlatform() { - let pkg; - let subpath; - let isWASM = false; - let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; - if (platformKey in knownWindowsPackages) { - pkg = knownWindowsPackages[platformKey]; - subpath = "esbuild.exe"; - } else if (platformKey in knownUnixlikePackages) { - pkg = knownUnixlikePackages[platformKey]; - subpath = "bin/esbuild"; - } else if (platformKey in knownWebAssemblyFallbackPackages) { - pkg = knownWebAssemblyFallbackPackages[platformKey]; - subpath = "bin/esbuild"; - isWASM = true; - } else { - throw new Error(`Unsupported platform: ${platformKey}`); - } - return { pkg, subpath, isWASM }; -} -function downloadedBinPath(pkg, subpath) { - const esbuildLibDir = path.dirname(require.resolve("esbuild")); - return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); -} - -// lib/npm/node-install.ts -var fs2 = require("fs"); -var os2 = require("os"); -var path2 = require("path"); -var zlib = require("zlib"); -var https = require("https"); -var child_process = require("child_process"); -var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version; -var toPath = path2.join(__dirname, "bin", "esbuild"); -var isToPathJS = true; -function validateBinaryVersion(...command) { - command.push("--version"); - let stdout; - try { - stdout = child_process.execFileSync(command.shift(), command, { - // Without this, this install script strangely crashes with the error - // "EACCES: permission denied, write" but only on Ubuntu Linux when node is - // installed from the Snap Store. This is not a problem when you download - // the official version of node. The problem appears to be that stderr - // (i.e. file descriptor 2) isn't writable? - // - // More info: - // - https://snapcraft.io/ (what the Snap Store is) - // - https://nodejs.org/dist/ (download the official version of node) - // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035 - // - stdio: "pipe" - }).toString().trim(); - } catch (err) { - if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) { - let os3 = "this version of macOS"; - try { - os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim(); - } catch { - } - throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated. - -The Go compiler (which esbuild relies on) no longer supports ${os3}, -which means the "esbuild" binary executable can't be run. You can either: - - * Update your version of macOS to one that the Go compiler supports - * Use the "esbuild-wasm" package instead of the "esbuild" package - * Build esbuild yourself using an older version of the Go compiler -`); - } - throw err; - } - if (stdout !== versionFromPackageJSON) { - throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`); - } -} -function isYarn() { - const { npm_config_user_agent } = process.env; - if (npm_config_user_agent) { - return /\byarn\//.test(npm_config_user_agent); - } - return false; -} -function fetch(url) { - return new Promise((resolve, reject) => { - https.get(url, (res) => { - if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location) - return fetch(res.headers.location).then(resolve, reject); - if (res.statusCode !== 200) - return reject(new Error(`Server responded with ${res.statusCode}`)); - let chunks = []; - res.on("data", (chunk) => chunks.push(chunk)); - res.on("end", () => resolve(Buffer.concat(chunks))); - }).on("error", reject); - }); -} -function extractFileFromTarGzip(buffer, subpath) { - try { - buffer = zlib.unzipSync(buffer); - } catch (err) { - throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`); - } - let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, ""); - let offset = 0; - subpath = `package/${subpath}`; - while (offset < buffer.length) { - let name = str(offset, 100); - let size = parseInt(str(offset + 124, 12), 8); - offset += 512; - if (!isNaN(size)) { - if (name === subpath) return buffer.subarray(offset, offset + size); - offset += size + 511 & ~511; - } - } - throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`); -} -function installUsingNPM(pkg, subpath, binPath) { - const env = { ...process.env, npm_config_global: void 0 }; - const esbuildLibDir = path2.dirname(require.resolve("esbuild")); - const installDir = path2.join(esbuildLibDir, "npm-install"); - fs2.mkdirSync(installDir); - try { - fs2.writeFileSync(path2.join(installDir, "package.json"), "{}"); - child_process.execSync( - `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`, - { cwd: installDir, stdio: "pipe", env } - ); - const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath); - fs2.renameSync(installedBinPath, binPath); - } finally { - try { - removeRecursive(installDir); - } catch { - } - } -} -function removeRecursive(dir) { - for (const entry of fs2.readdirSync(dir)) { - const entryPath = path2.join(dir, entry); - let stats; - try { - stats = fs2.lstatSync(entryPath); - } catch { - continue; - } - if (stats.isDirectory()) removeRecursive(entryPath); - else fs2.unlinkSync(entryPath); - } - fs2.rmdirSync(dir); -} -function applyManualBinaryPathOverride(overridePath) { - const pathString = JSON.stringify(overridePath); - fs2.writeFileSync(toPath, `#!/usr/bin/env node -require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' }); -`); - const libMain = path2.join(__dirname, "lib", "main.js"); - const code = fs2.readFileSync(libMain, "utf8"); - fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString}; -${code}`); -} -function maybeOptimizePackage(binPath) { - if (os2.platform() !== "win32" && !isYarn()) { - const tempPath = path2.join(__dirname, "bin-esbuild"); - try { - fs2.linkSync(binPath, tempPath); - fs2.renameSync(tempPath, toPath); - isToPathJS = false; - fs2.unlinkSync(tempPath); - } catch { - } - } -} -async function downloadDirectlyFromNPM(pkg, subpath, binPath) { - const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`; - console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`); - try { - fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath)); - fs2.chmodSync(binPath, 493); - } catch (e) { - console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`); - throw e; - } -} -async function checkAndPreparePackage() { - if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { - if (!fs2.existsSync(ESBUILD_BINARY_PATH)) { - console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); - } else { - applyManualBinaryPathOverride(ESBUILD_BINARY_PATH); - return; - } - } - const { pkg, subpath } = pkgAndSubpathForCurrentPlatform(); - let binPath; - try { - binPath = require.resolve(`${pkg}/${subpath}`); - } catch (e) { - console.error(`[esbuild] Failed to find package "${pkg}" on the file system - -This can happen if you use the "--no-optional" flag. The "optionalDependencies" -package.json feature is used by esbuild to install the correct binary executable -for your current platform. This install script will now attempt to work around -this. If that fails, you need to remove the "--no-optional" flag to use esbuild. -`); - binPath = downloadedBinPath(pkg, subpath); - try { - console.error(`[esbuild] Trying to install package "${pkg}" using npm`); - installUsingNPM(pkg, subpath, binPath); - } catch (e2) { - console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`); - try { - await downloadDirectlyFromNPM(pkg, subpath, binPath); - } catch (e3) { - throw new Error(`Failed to install package "${pkg}"`); - } - } - } - maybeOptimizePackage(binPath); -} -checkAndPreparePackage().then(() => { - if (isToPathJS) { - validateBinaryVersion(process.execPath, toPath); - } else { - validateBinaryVersion(toPath); - } -}); diff --git a/js/node_modules/esbuild/lib/main.d.ts b/js/node_modules/esbuild/lib/main.d.ts deleted file mode 100644 index c705307..0000000 --- a/js/node_modules/esbuild/lib/main.d.ts +++ /dev/null @@ -1,705 +0,0 @@ -export type Platform = 'browser' | 'node' | 'neutral' -export type Format = 'iife' | 'cjs' | 'esm' -export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx' -export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent' -export type Charset = 'ascii' | 'utf8' -export type Drop = 'console' | 'debugger' - -interface CommonOptions { - /** Documentation: https://esbuild.github.io/api/#sourcemap */ - sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both' - /** Documentation: https://esbuild.github.io/api/#legal-comments */ - legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external' - /** Documentation: https://esbuild.github.io/api/#source-root */ - sourceRoot?: string - /** Documentation: https://esbuild.github.io/api/#sources-content */ - sourcesContent?: boolean - - /** Documentation: https://esbuild.github.io/api/#format */ - format?: Format - /** Documentation: https://esbuild.github.io/api/#global-name */ - globalName?: string - /** Documentation: https://esbuild.github.io/api/#target */ - target?: string | string[] - /** Documentation: https://esbuild.github.io/api/#supported */ - supported?: Record - /** Documentation: https://esbuild.github.io/api/#platform */ - platform?: Platform - - /** Documentation: https://esbuild.github.io/api/#mangle-props */ - mangleProps?: RegExp - /** Documentation: https://esbuild.github.io/api/#mangle-props */ - reserveProps?: RegExp - /** Documentation: https://esbuild.github.io/api/#mangle-props */ - mangleQuoted?: boolean - /** Documentation: https://esbuild.github.io/api/#mangle-props */ - mangleCache?: Record - /** Documentation: https://esbuild.github.io/api/#drop */ - drop?: Drop[] - /** Documentation: https://esbuild.github.io/api/#drop-labels */ - dropLabels?: string[] - /** Documentation: https://esbuild.github.io/api/#minify */ - minify?: boolean - /** Documentation: https://esbuild.github.io/api/#minify */ - minifyWhitespace?: boolean - /** Documentation: https://esbuild.github.io/api/#minify */ - minifyIdentifiers?: boolean - /** Documentation: https://esbuild.github.io/api/#minify */ - minifySyntax?: boolean - /** Documentation: https://esbuild.github.io/api/#line-limit */ - lineLimit?: number - /** Documentation: https://esbuild.github.io/api/#charset */ - charset?: Charset - /** Documentation: https://esbuild.github.io/api/#tree-shaking */ - treeShaking?: boolean - /** Documentation: https://esbuild.github.io/api/#ignore-annotations */ - ignoreAnnotations?: boolean - - /** Documentation: https://esbuild.github.io/api/#jsx */ - jsx?: 'transform' | 'preserve' | 'automatic' - /** Documentation: https://esbuild.github.io/api/#jsx-factory */ - jsxFactory?: string - /** Documentation: https://esbuild.github.io/api/#jsx-fragment */ - jsxFragment?: string - /** Documentation: https://esbuild.github.io/api/#jsx-import-source */ - jsxImportSource?: string - /** Documentation: https://esbuild.github.io/api/#jsx-development */ - jsxDev?: boolean - /** Documentation: https://esbuild.github.io/api/#jsx-side-effects */ - jsxSideEffects?: boolean - - /** Documentation: https://esbuild.github.io/api/#define */ - define?: { [key: string]: string } - /** Documentation: https://esbuild.github.io/api/#pure */ - pure?: string[] - /** Documentation: https://esbuild.github.io/api/#keep-names */ - keepNames?: boolean - - /** Documentation: https://esbuild.github.io/api/#color */ - color?: boolean - /** Documentation: https://esbuild.github.io/api/#log-level */ - logLevel?: LogLevel - /** Documentation: https://esbuild.github.io/api/#log-limit */ - logLimit?: number - /** Documentation: https://esbuild.github.io/api/#log-override */ - logOverride?: Record - - /** Documentation: https://esbuild.github.io/api/#tsconfig-raw */ - tsconfigRaw?: string | TsconfigRaw -} - -export interface TsconfigRaw { - compilerOptions?: { - alwaysStrict?: boolean - baseUrl?: string - experimentalDecorators?: boolean - importsNotUsedAsValues?: 'remove' | 'preserve' | 'error' - jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev' - jsxFactory?: string - jsxFragmentFactory?: string - jsxImportSource?: string - paths?: Record - preserveValueImports?: boolean - strict?: boolean - target?: string - useDefineForClassFields?: boolean - verbatimModuleSyntax?: boolean - } -} - -export interface BuildOptions extends CommonOptions { - /** Documentation: https://esbuild.github.io/api/#bundle */ - bundle?: boolean - /** Documentation: https://esbuild.github.io/api/#splitting */ - splitting?: boolean - /** Documentation: https://esbuild.github.io/api/#preserve-symlinks */ - preserveSymlinks?: boolean - /** Documentation: https://esbuild.github.io/api/#outfile */ - outfile?: string - /** Documentation: https://esbuild.github.io/api/#metafile */ - metafile?: boolean - /** Documentation: https://esbuild.github.io/api/#outdir */ - outdir?: string - /** Documentation: https://esbuild.github.io/api/#outbase */ - outbase?: string - /** Documentation: https://esbuild.github.io/api/#external */ - external?: string[] - /** Documentation: https://esbuild.github.io/api/#packages */ - packages?: 'bundle' | 'external' - /** Documentation: https://esbuild.github.io/api/#alias */ - alias?: Record - /** Documentation: https://esbuild.github.io/api/#loader */ - loader?: { [ext: string]: Loader } - /** Documentation: https://esbuild.github.io/api/#resolve-extensions */ - resolveExtensions?: string[] - /** Documentation: https://esbuild.github.io/api/#main-fields */ - mainFields?: string[] - /** Documentation: https://esbuild.github.io/api/#conditions */ - conditions?: string[] - /** Documentation: https://esbuild.github.io/api/#write */ - write?: boolean - /** Documentation: https://esbuild.github.io/api/#allow-overwrite */ - allowOverwrite?: boolean - /** Documentation: https://esbuild.github.io/api/#tsconfig */ - tsconfig?: string - /** Documentation: https://esbuild.github.io/api/#out-extension */ - outExtension?: { [ext: string]: string } - /** Documentation: https://esbuild.github.io/api/#public-path */ - publicPath?: string - /** Documentation: https://esbuild.github.io/api/#entry-names */ - entryNames?: string - /** Documentation: https://esbuild.github.io/api/#chunk-names */ - chunkNames?: string - /** Documentation: https://esbuild.github.io/api/#asset-names */ - assetNames?: string - /** Documentation: https://esbuild.github.io/api/#inject */ - inject?: string[] - /** Documentation: https://esbuild.github.io/api/#banner */ - banner?: { [type: string]: string } - /** Documentation: https://esbuild.github.io/api/#footer */ - footer?: { [type: string]: string } - /** Documentation: https://esbuild.github.io/api/#entry-points */ - entryPoints?: string[] | Record | { in: string, out: string }[] - /** Documentation: https://esbuild.github.io/api/#stdin */ - stdin?: StdinOptions - /** Documentation: https://esbuild.github.io/plugins/ */ - plugins?: Plugin[] - /** Documentation: https://esbuild.github.io/api/#working-directory */ - absWorkingDir?: string - /** Documentation: https://esbuild.github.io/api/#node-paths */ - nodePaths?: string[]; // The "NODE_PATH" variable from Node.js -} - -export interface StdinOptions { - contents: string | Uint8Array - resolveDir?: string - sourcefile?: string - loader?: Loader -} - -export interface Message { - id: string - pluginName: string - text: string - location: Location | null - notes: Note[] - - /** - * Optional user-specified data that is passed through unmodified. You can - * use this to stash the original error, for example. - */ - detail: any -} - -export interface Note { - text: string - location: Location | null -} - -export interface Location { - file: string - namespace: string - /** 1-based */ - line: number - /** 0-based, in bytes */ - column: number - /** in bytes */ - length: number - lineText: string - suggestion: string -} - -export interface OutputFile { - path: string - contents: Uint8Array - hash: string - /** "contents" as text (changes automatically with "contents") */ - readonly text: string -} - -export interface BuildResult { - errors: Message[] - warnings: Message[] - /** Only when "write: false" */ - outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined) - /** Only when "metafile: true" */ - metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined) - /** Only when "mangleCache" is present */ - mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) -} - -export interface BuildFailure extends Error { - errors: Message[] - warnings: Message[] -} - -/** Documentation: https://esbuild.github.io/api/#serve-arguments */ -export interface ServeOptions { - port?: number - host?: string - servedir?: string - keyfile?: string - certfile?: string - fallback?: string - onRequest?: (args: ServeOnRequestArgs) => void -} - -export interface ServeOnRequestArgs { - remoteAddress: string - method: string - path: string - status: number - /** The time to generate the response, not to send it */ - timeInMS: number -} - -/** Documentation: https://esbuild.github.io/api/#serve-return-values */ -export interface ServeResult { - port: number - host: string -} - -export interface TransformOptions extends CommonOptions { - /** Documentation: https://esbuild.github.io/api/#sourcefile */ - sourcefile?: string - /** Documentation: https://esbuild.github.io/api/#loader */ - loader?: Loader - /** Documentation: https://esbuild.github.io/api/#banner */ - banner?: string - /** Documentation: https://esbuild.github.io/api/#footer */ - footer?: string -} - -export interface TransformResult { - code: string - map: string - warnings: Message[] - /** Only when "mangleCache" is present */ - mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) - /** Only when "legalComments" is "external" */ - legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined) -} - -export interface TransformFailure extends Error { - errors: Message[] - warnings: Message[] -} - -export interface Plugin { - name: string - setup: (build: PluginBuild) => (void | Promise) -} - -export interface PluginBuild { - /** Documentation: https://esbuild.github.io/plugins/#build-options */ - initialOptions: BuildOptions - - /** Documentation: https://esbuild.github.io/plugins/#resolve */ - resolve(path: string, options?: ResolveOptions): Promise - - /** Documentation: https://esbuild.github.io/plugins/#on-start */ - onStart(callback: () => - (OnStartResult | null | void | Promise)): void - - /** Documentation: https://esbuild.github.io/plugins/#on-end */ - onEnd(callback: (result: BuildResult) => - (OnEndResult | null | void | Promise)): void - - /** Documentation: https://esbuild.github.io/plugins/#on-resolve */ - onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) => - (OnResolveResult | null | undefined | Promise)): void - - /** Documentation: https://esbuild.github.io/plugins/#on-load */ - onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) => - (OnLoadResult | null | undefined | Promise)): void - - /** Documentation: https://esbuild.github.io/plugins/#on-dispose */ - onDispose(callback: () => void): void - - // This is a full copy of the esbuild library in case you need it - esbuild: { - context: typeof context, - build: typeof build, - buildSync: typeof buildSync, - transform: typeof transform, - transformSync: typeof transformSync, - formatMessages: typeof formatMessages, - formatMessagesSync: typeof formatMessagesSync, - analyzeMetafile: typeof analyzeMetafile, - analyzeMetafileSync: typeof analyzeMetafileSync, - initialize: typeof initialize, - version: typeof version, - } -} - -/** Documentation: https://esbuild.github.io/plugins/#resolve-options */ -export interface ResolveOptions { - pluginName?: string - importer?: string - namespace?: string - resolveDir?: string - kind?: ImportKind - pluginData?: any - with?: Record -} - -/** Documentation: https://esbuild.github.io/plugins/#resolve-results */ -export interface ResolveResult { - errors: Message[] - warnings: Message[] - - path: string - external: boolean - sideEffects: boolean - namespace: string - suffix: string - pluginData: any -} - -export interface OnStartResult { - errors?: PartialMessage[] - warnings?: PartialMessage[] -} - -export interface OnEndResult { - errors?: PartialMessage[] - warnings?: PartialMessage[] -} - -/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */ -export interface OnResolveOptions { - filter: RegExp - namespace?: string -} - -/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */ -export interface OnResolveArgs { - path: string - importer: string - namespace: string - resolveDir: string - kind: ImportKind - pluginData: any - with: Record -} - -export type ImportKind = - | 'entry-point' - - // JS - | 'import-statement' - | 'require-call' - | 'dynamic-import' - | 'require-resolve' - - // CSS - | 'import-rule' - | 'composes-from' - | 'url-token' - -/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */ -export interface OnResolveResult { - pluginName?: string - - errors?: PartialMessage[] - warnings?: PartialMessage[] - - path?: string - external?: boolean - sideEffects?: boolean - namespace?: string - suffix?: string - pluginData?: any - - watchFiles?: string[] - watchDirs?: string[] -} - -/** Documentation: https://esbuild.github.io/plugins/#on-load-options */ -export interface OnLoadOptions { - filter: RegExp - namespace?: string -} - -/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */ -export interface OnLoadArgs { - path: string - namespace: string - suffix: string - pluginData: any - with: Record -} - -/** Documentation: https://esbuild.github.io/plugins/#on-load-results */ -export interface OnLoadResult { - pluginName?: string - - errors?: PartialMessage[] - warnings?: PartialMessage[] - - contents?: string | Uint8Array - resolveDir?: string - loader?: Loader - pluginData?: any - - watchFiles?: string[] - watchDirs?: string[] -} - -export interface PartialMessage { - id?: string - pluginName?: string - text?: string - location?: Partial | null - notes?: PartialNote[] - detail?: any -} - -export interface PartialNote { - text?: string - location?: Partial | null -} - -/** Documentation: https://esbuild.github.io/api/#metafile */ -export interface Metafile { - inputs: { - [path: string]: { - bytes: number - imports: { - path: string - kind: ImportKind - external?: boolean - original?: string - with?: Record - }[] - format?: 'cjs' | 'esm' - with?: Record - } - } - outputs: { - [path: string]: { - bytes: number - inputs: { - [path: string]: { - bytesInOutput: number - } - } - imports: { - path: string - kind: ImportKind | 'file-loader' - external?: boolean - }[] - exports: string[] - entryPoint?: string - cssBundle?: string - } - } -} - -export interface FormatMessagesOptions { - kind: 'error' | 'warning' - color?: boolean - terminalWidth?: number -} - -export interface AnalyzeMetafileOptions { - color?: boolean - verbose?: boolean -} - -export interface WatchOptions { -} - -export interface BuildContext { - /** Documentation: https://esbuild.github.io/api/#rebuild */ - rebuild(): Promise> - - /** Documentation: https://esbuild.github.io/api/#watch */ - watch(options?: WatchOptions): Promise - - /** Documentation: https://esbuild.github.io/api/#serve */ - serve(options?: ServeOptions): Promise - - cancel(): Promise - dispose(): Promise -} - -// This is a TypeScript type-level function which replaces any keys in "In" -// that aren't in "Out" with "never". We use this to reject properties with -// typos in object literals. See: https://stackoverflow.com/questions/49580725 -type SameShape = In & { [Key in Exclude]: never } - -/** - * This function invokes the "esbuild" command-line tool for you. It returns a - * promise that either resolves with a "BuildResult" object or rejects with a - * "BuildFailure" object. - * - * - Works in node: yes - * - Works in browser: yes - * - * Documentation: https://esbuild.github.io/api/#build - */ -export declare function build(options: SameShape): Promise> - -/** - * This is the advanced long-running form of "build" that supports additional - * features such as watch mode and a local development server. - * - * - Works in node: yes - * - Works in browser: no - * - * Documentation: https://esbuild.github.io/api/#build - */ -export declare function context(options: SameShape): Promise> - -/** - * This function transforms a single JavaScript file. It can be used to minify - * JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript - * to older JavaScript. It returns a promise that is either resolved with a - * "TransformResult" object or rejected with a "TransformFailure" object. - * - * - Works in node: yes - * - Works in browser: yes - * - * Documentation: https://esbuild.github.io/api/#transform - */ -export declare function transform(input: string | Uint8Array, options?: SameShape): Promise> - -/** - * Converts log messages to formatted message strings suitable for printing in - * the terminal. This allows you to reuse the built-in behavior of esbuild's - * log message formatter. This is a batch-oriented API for efficiency. - * - * - Works in node: yes - * - Works in browser: yes - */ -export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise - -/** - * Pretty-prints an analysis of the metafile JSON to a string. This is just for - * convenience to be able to match esbuild's pretty-printing exactly. If you want - * to customize it, you can just inspect the data in the metafile yourself. - * - * - Works in node: yes - * - Works in browser: yes - * - * Documentation: https://esbuild.github.io/api/#analyze - */ -export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise - -/** - * A synchronous version of "build". - * - * - Works in node: yes - * - Works in browser: no - * - * Documentation: https://esbuild.github.io/api/#build - */ -export declare function buildSync(options: SameShape): BuildResult - -/** - * A synchronous version of "transform". - * - * - Works in node: yes - * - Works in browser: no - * - * Documentation: https://esbuild.github.io/api/#transform - */ -export declare function transformSync(input: string | Uint8Array, options?: SameShape): TransformResult - -/** - * A synchronous version of "formatMessages". - * - * - Works in node: yes - * - Works in browser: no - */ -export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[] - -/** - * A synchronous version of "analyzeMetafile". - * - * - Works in node: yes - * - Works in browser: no - * - * Documentation: https://esbuild.github.io/api/#analyze - */ -export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string - -/** - * This configures the browser-based version of esbuild. It is necessary to - * call this first and wait for the returned promise to be resolved before - * making other API calls when using esbuild in the browser. - * - * - Works in node: yes - * - Works in browser: yes ("options" is required) - * - * Documentation: https://esbuild.github.io/api/#browser - */ -export declare function initialize(options: InitializeOptions): Promise - -export interface InitializeOptions { - /** - * The URL of the "esbuild.wasm" file. This must be provided when running - * esbuild in the browser. - */ - wasmURL?: string | URL - - /** - * The result of calling "new WebAssembly.Module(buffer)" where "buffer" - * is a typed array or ArrayBuffer containing the binary code of the - * "esbuild.wasm" file. - * - * You can use this as an alternative to "wasmURL" for environments where it's - * not possible to download the WebAssembly module. - */ - wasmModule?: WebAssembly.Module - - /** - * By default esbuild runs the WebAssembly-based browser API in a web worker - * to avoid blocking the UI thread. This can be disabled by setting "worker" - * to false. - */ - worker?: boolean -} - -export let version: string - -// Call this function to terminate esbuild's child process. The child process -// is not terminated and re-created after each API call because it's more -// efficient to keep it around when there are multiple API calls. -// -// In node this happens automatically before the parent node process exits. So -// you only need to call this if you know you will not make any more esbuild -// API calls and you want to clean up resources. -// -// Unlike node, Deno lacks the necessary APIs to clean up child processes -// automatically. You must manually call stop() in Deno when you're done -// using esbuild or Deno will continue running forever. -// -// Another reason you might want to call this is if you are using esbuild from -// within a Deno test. Deno fails tests that create a child process without -// killing it before the test ends, so you have to call this function (and -// await the returned promise) in every Deno test that uses esbuild. -export declare function stop(): Promise - -// Note: These declarations exist to avoid type errors when you omit "dom" from -// "lib" in your "tsconfig.json" file. TypeScript confusingly declares the -// global "WebAssembly" type in "lib.dom.d.ts" even though it has nothing to do -// with the browser DOM and is present in many non-browser JavaScript runtimes -// (e.g. node and deno). Declaring it here allows esbuild's API to be used in -// these scenarios. -// -// There's an open issue about getting this problem corrected (although these -// declarations will need to remain even if this is fixed for backward -// compatibility with older TypeScript versions): -// -// https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/826 -// -declare global { - namespace WebAssembly { - interface Module { - } - } - interface URL { - } -} diff --git a/js/node_modules/esbuild/lib/main.js b/js/node_modules/esbuild/lib/main.js deleted file mode 100644 index a2a6591..0000000 --- a/js/node_modules/esbuild/lib/main.js +++ /dev/null @@ -1,2244 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// lib/npm/node.ts -var node_exports = {}; -__export(node_exports, { - analyzeMetafile: () => analyzeMetafile, - analyzeMetafileSync: () => analyzeMetafileSync, - build: () => build, - buildSync: () => buildSync, - context: () => context, - default: () => node_default, - formatMessages: () => formatMessages, - formatMessagesSync: () => formatMessagesSync, - initialize: () => initialize, - stop: () => stop, - transform: () => transform, - transformSync: () => transformSync, - version: () => version -}); -module.exports = __toCommonJS(node_exports); - -// lib/shared/stdio_protocol.ts -function encodePacket(packet) { - let visit = (value) => { - if (value === null) { - bb.write8(0); - } else if (typeof value === "boolean") { - bb.write8(1); - bb.write8(+value); - } else if (typeof value === "number") { - bb.write8(2); - bb.write32(value | 0); - } else if (typeof value === "string") { - bb.write8(3); - bb.write(encodeUTF8(value)); - } else if (value instanceof Uint8Array) { - bb.write8(4); - bb.write(value); - } else if (value instanceof Array) { - bb.write8(5); - bb.write32(value.length); - for (let item of value) { - visit(item); - } - } else { - let keys = Object.keys(value); - bb.write8(6); - bb.write32(keys.length); - for (let key of keys) { - bb.write(encodeUTF8(key)); - visit(value[key]); - } - } - }; - let bb = new ByteBuffer(); - bb.write32(0); - bb.write32(packet.id << 1 | +!packet.isRequest); - visit(packet.value); - writeUInt32LE(bb.buf, bb.len - 4, 0); - return bb.buf.subarray(0, bb.len); -} -function decodePacket(bytes) { - let visit = () => { - switch (bb.read8()) { - case 0: - return null; - case 1: - return !!bb.read8(); - case 2: - return bb.read32(); - case 3: - return decodeUTF8(bb.read()); - case 4: - return bb.read(); - case 5: { - let count = bb.read32(); - let value2 = []; - for (let i = 0; i < count; i++) { - value2.push(visit()); - } - return value2; - } - case 6: { - let count = bb.read32(); - let value2 = {}; - for (let i = 0; i < count; i++) { - value2[decodeUTF8(bb.read())] = visit(); - } - return value2; - } - default: - throw new Error("Invalid packet"); - } - }; - let bb = new ByteBuffer(bytes); - let id = bb.read32(); - let isRequest = (id & 1) === 0; - id >>>= 1; - let value = visit(); - if (bb.ptr !== bytes.length) { - throw new Error("Invalid packet"); - } - return { id, isRequest, value }; -} -var ByteBuffer = class { - constructor(buf = new Uint8Array(1024)) { - this.buf = buf; - this.len = 0; - this.ptr = 0; - } - _write(delta) { - if (this.len + delta > this.buf.length) { - let clone = new Uint8Array((this.len + delta) * 2); - clone.set(this.buf); - this.buf = clone; - } - this.len += delta; - return this.len - delta; - } - write8(value) { - let offset = this._write(1); - this.buf[offset] = value; - } - write32(value) { - let offset = this._write(4); - writeUInt32LE(this.buf, value, offset); - } - write(bytes) { - let offset = this._write(4 + bytes.length); - writeUInt32LE(this.buf, bytes.length, offset); - this.buf.set(bytes, offset + 4); - } - _read(delta) { - if (this.ptr + delta > this.buf.length) { - throw new Error("Invalid packet"); - } - this.ptr += delta; - return this.ptr - delta; - } - read8() { - return this.buf[this._read(1)]; - } - read32() { - return readUInt32LE(this.buf, this._read(4)); - } - read() { - let length = this.read32(); - let bytes = new Uint8Array(length); - let ptr = this._read(bytes.length); - bytes.set(this.buf.subarray(ptr, ptr + length)); - return bytes; - } -}; -var encodeUTF8; -var decodeUTF8; -var encodeInvariant; -if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") { - let encoder = new TextEncoder(); - let decoder = new TextDecoder(); - encodeUTF8 = (text) => encoder.encode(text); - decodeUTF8 = (bytes) => decoder.decode(bytes); - encodeInvariant = 'new TextEncoder().encode("")'; -} else if (typeof Buffer !== "undefined") { - encodeUTF8 = (text) => Buffer.from(text); - decodeUTF8 = (bytes) => { - let { buffer, byteOffset, byteLength } = bytes; - return Buffer.from(buffer, byteOffset, byteLength).toString(); - }; - encodeInvariant = 'Buffer.from("")'; -} else { - throw new Error("No UTF-8 codec found"); -} -if (!(encodeUTF8("") instanceof Uint8Array)) - throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false - -This indicates that your JavaScript environment is broken. You cannot use -esbuild in this environment because esbuild relies on this invariant. This -is not a problem with esbuild. You need to fix your environment instead. -`); -function readUInt32LE(buffer, offset) { - return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24; -} -function writeUInt32LE(buffer, value, offset) { - buffer[offset++] = value; - buffer[offset++] = value >> 8; - buffer[offset++] = value >> 16; - buffer[offset++] = value >> 24; -} - -// lib/shared/common.ts -var quote = JSON.stringify; -var buildLogLevelDefault = "warning"; -var transformLogLevelDefault = "silent"; -function validateTarget(target) { - validateStringValue(target, "target"); - if (target.indexOf(",") >= 0) throw new Error(`Invalid target: ${target}`); - return target; -} -var canBeAnything = () => null; -var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean"; -var mustBeString = (value) => typeof value === "string" ? null : "a string"; -var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object"; -var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer"; -var mustBeFunction = (value) => typeof value === "function" ? null : "a function"; -var mustBeArray = (value) => Array.isArray(value) ? null : "an array"; -var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object"; -var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object"; -var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module"; -var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null"; -var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean"; -var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object"; -var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array"; -var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array"; -var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL"; -function getFlag(object, keys, key, mustBeFn) { - let value = object[key]; - keys[key + ""] = true; - if (value === void 0) return void 0; - let mustBe = mustBeFn(value); - if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`); - return value; -} -function checkForInvalidFlags(object, keys, where) { - for (let key in object) { - if (!(key in keys)) { - throw new Error(`Invalid option ${where}: ${quote(key)}`); - } - } -} -function validateInitializeOptions(options) { - let keys = /* @__PURE__ */ Object.create(null); - let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL); - let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule); - let worker = getFlag(options, keys, "worker", mustBeBoolean); - checkForInvalidFlags(options, keys, "in initialize() call"); - return { - wasmURL, - wasmModule, - worker - }; -} -function validateMangleCache(mangleCache) { - let validated; - if (mangleCache !== void 0) { - validated = /* @__PURE__ */ Object.create(null); - for (let key in mangleCache) { - let value = mangleCache[key]; - if (typeof value === "string" || value === false) { - validated[key] = value; - } else { - throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`); - } - } - } - return validated; -} -function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) { - let color = getFlag(options, keys, "color", mustBeBoolean); - let logLevel = getFlag(options, keys, "logLevel", mustBeString); - let logLimit = getFlag(options, keys, "logLimit", mustBeInteger); - if (color !== void 0) flags.push(`--color=${color}`); - else if (isTTY2) flags.push(`--color=true`); - flags.push(`--log-level=${logLevel || logLevelDefault}`); - flags.push(`--log-limit=${logLimit || 0}`); -} -function validateStringValue(value, what, key) { - if (typeof value !== "string") { - throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`); - } - return value; -} -function pushCommonFlags(flags, options, keys) { - let legalComments = getFlag(options, keys, "legalComments", mustBeString); - let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString); - let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean); - let target = getFlag(options, keys, "target", mustBeStringOrArray); - let format = getFlag(options, keys, "format", mustBeString); - let globalName = getFlag(options, keys, "globalName", mustBeString); - let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp); - let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp); - let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean); - let minify = getFlag(options, keys, "minify", mustBeBoolean); - let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean); - let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean); - let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean); - let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger); - let drop = getFlag(options, keys, "drop", mustBeArray); - let dropLabels = getFlag(options, keys, "dropLabels", mustBeArray); - let charset = getFlag(options, keys, "charset", mustBeString); - let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean); - let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean); - let jsx = getFlag(options, keys, "jsx", mustBeString); - let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString); - let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString); - let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString); - let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean); - let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean); - let define = getFlag(options, keys, "define", mustBeObject); - let logOverride = getFlag(options, keys, "logOverride", mustBeObject); - let supported = getFlag(options, keys, "supported", mustBeObject); - let pure = getFlag(options, keys, "pure", mustBeArray); - let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean); - let platform = getFlag(options, keys, "platform", mustBeString); - let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject); - if (legalComments) flags.push(`--legal-comments=${legalComments}`); - if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`); - if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`); - if (target) { - if (Array.isArray(target)) flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`); - else flags.push(`--target=${validateTarget(target)}`); - } - if (format) flags.push(`--format=${format}`); - if (globalName) flags.push(`--global-name=${globalName}`); - if (platform) flags.push(`--platform=${platform}`); - if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`); - if (minify) flags.push("--minify"); - if (minifySyntax) flags.push("--minify-syntax"); - if (minifyWhitespace) flags.push("--minify-whitespace"); - if (minifyIdentifiers) flags.push("--minify-identifiers"); - if (lineLimit) flags.push(`--line-limit=${lineLimit}`); - if (charset) flags.push(`--charset=${charset}`); - if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`); - if (ignoreAnnotations) flags.push(`--ignore-annotations`); - if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`); - if (dropLabels) flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`); - if (mangleProps) flags.push(`--mangle-props=${mangleProps.source}`); - if (reserveProps) flags.push(`--reserve-props=${reserveProps.source}`); - if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`); - if (jsx) flags.push(`--jsx=${jsx}`); - if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`); - if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`); - if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`); - if (jsxDev) flags.push(`--jsx-dev`); - if (jsxSideEffects) flags.push(`--jsx-side-effects`); - if (define) { - for (let key in define) { - if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`); - flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`); - } - } - if (logOverride) { - for (let key in logOverride) { - if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`); - flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`); - } - } - if (supported) { - for (let key in supported) { - if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`); - const value = supported[key]; - if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`); - flags.push(`--supported:${key}=${value}`); - } - } - if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`); - if (keepNames) flags.push(`--keep-names`); -} -function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) { - var _a2; - let flags = []; - let entries = []; - let keys = /* @__PURE__ */ Object.create(null); - let stdinContents = null; - let stdinResolveDir = null; - pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); - pushCommonFlags(flags, options, keys); - let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); - let bundle = getFlag(options, keys, "bundle", mustBeBoolean); - let splitting = getFlag(options, keys, "splitting", mustBeBoolean); - let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean); - let metafile = getFlag(options, keys, "metafile", mustBeBoolean); - let outfile = getFlag(options, keys, "outfile", mustBeString); - let outdir = getFlag(options, keys, "outdir", mustBeString); - let outbase = getFlag(options, keys, "outbase", mustBeString); - let tsconfig = getFlag(options, keys, "tsconfig", mustBeString); - let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray); - let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray); - let mainFields = getFlag(options, keys, "mainFields", mustBeArray); - let conditions = getFlag(options, keys, "conditions", mustBeArray); - let external = getFlag(options, keys, "external", mustBeArray); - let packages = getFlag(options, keys, "packages", mustBeString); - let alias = getFlag(options, keys, "alias", mustBeObject); - let loader = getFlag(options, keys, "loader", mustBeObject); - let outExtension = getFlag(options, keys, "outExtension", mustBeObject); - let publicPath = getFlag(options, keys, "publicPath", mustBeString); - let entryNames = getFlag(options, keys, "entryNames", mustBeString); - let chunkNames = getFlag(options, keys, "chunkNames", mustBeString); - let assetNames = getFlag(options, keys, "assetNames", mustBeString); - let inject = getFlag(options, keys, "inject", mustBeArray); - let banner = getFlag(options, keys, "banner", mustBeObject); - let footer = getFlag(options, keys, "footer", mustBeObject); - let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints); - let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString); - let stdin = getFlag(options, keys, "stdin", mustBeObject); - let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault; - let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean); - let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); - keys.plugins = true; - checkForInvalidFlags(options, keys, `in ${callName}() call`); - if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`); - if (bundle) flags.push("--bundle"); - if (allowOverwrite) flags.push("--allow-overwrite"); - if (splitting) flags.push("--splitting"); - if (preserveSymlinks) flags.push("--preserve-symlinks"); - if (metafile) flags.push(`--metafile`); - if (outfile) flags.push(`--outfile=${outfile}`); - if (outdir) flags.push(`--outdir=${outdir}`); - if (outbase) flags.push(`--outbase=${outbase}`); - if (tsconfig) flags.push(`--tsconfig=${tsconfig}`); - if (packages) flags.push(`--packages=${packages}`); - if (resolveExtensions) { - let values = []; - for (let value of resolveExtensions) { - validateStringValue(value, "resolve extension"); - if (value.indexOf(",") >= 0) throw new Error(`Invalid resolve extension: ${value}`); - values.push(value); - } - flags.push(`--resolve-extensions=${values.join(",")}`); - } - if (publicPath) flags.push(`--public-path=${publicPath}`); - if (entryNames) flags.push(`--entry-names=${entryNames}`); - if (chunkNames) flags.push(`--chunk-names=${chunkNames}`); - if (assetNames) flags.push(`--asset-names=${assetNames}`); - if (mainFields) { - let values = []; - for (let value of mainFields) { - validateStringValue(value, "main field"); - if (value.indexOf(",") >= 0) throw new Error(`Invalid main field: ${value}`); - values.push(value); - } - flags.push(`--main-fields=${values.join(",")}`); - } - if (conditions) { - let values = []; - for (let value of conditions) { - validateStringValue(value, "condition"); - if (value.indexOf(",") >= 0) throw new Error(`Invalid condition: ${value}`); - values.push(value); - } - flags.push(`--conditions=${values.join(",")}`); - } - if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`); - if (alias) { - for (let old in alias) { - if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`); - flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`); - } - } - if (banner) { - for (let type in banner) { - if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`); - flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`); - } - } - if (footer) { - for (let type in footer) { - if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`); - flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`); - } - } - if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`); - if (loader) { - for (let ext in loader) { - if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`); - flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`); - } - } - if (outExtension) { - for (let ext in outExtension) { - if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`); - flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`); - } - } - if (entryPoints) { - if (Array.isArray(entryPoints)) { - for (let i = 0, n = entryPoints.length; i < n; i++) { - let entryPoint = entryPoints[i]; - if (typeof entryPoint === "object" && entryPoint !== null) { - let entryPointKeys = /* @__PURE__ */ Object.create(null); - let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString); - let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString); - checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i); - if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i); - if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i); - entries.push([output, input]); - } else { - entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]); - } - } - } else { - for (let key in entryPoints) { - entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]); - } - } - } - if (stdin) { - let stdinKeys = /* @__PURE__ */ Object.create(null); - let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array); - let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString); - let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString); - let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString); - checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object'); - if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); - if (loader2) flags.push(`--loader=${loader2}`); - if (resolveDir) stdinResolveDir = resolveDir; - if (typeof contents === "string") stdinContents = encodeUTF8(contents); - else if (contents instanceof Uint8Array) stdinContents = contents; - } - let nodePaths = []; - if (nodePathsInput) { - for (let value of nodePathsInput) { - value += ""; - nodePaths.push(value); - } - } - return { - entries, - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir, - nodePaths, - mangleCache: validateMangleCache(mangleCache) - }; -} -function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) { - let flags = []; - let keys = /* @__PURE__ */ Object.create(null); - pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); - pushCommonFlags(flags, options, keys); - let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); - let sourcefile = getFlag(options, keys, "sourcefile", mustBeString); - let loader = getFlag(options, keys, "loader", mustBeString); - let banner = getFlag(options, keys, "banner", mustBeString); - let footer = getFlag(options, keys, "footer", mustBeString); - let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); - checkForInvalidFlags(options, keys, `in ${callName}() call`); - if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`); - if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); - if (loader) flags.push(`--loader=${loader}`); - if (banner) flags.push(`--banner=${banner}`); - if (footer) flags.push(`--footer=${footer}`); - return { - flags, - mangleCache: validateMangleCache(mangleCache) - }; -} -function createChannel(streamIn) { - const requestCallbacksByKey = {}; - const closeData = { didClose: false, reason: "" }; - let responseCallbacks = {}; - let nextRequestID = 0; - let nextBuildKey = 0; - let stdout = new Uint8Array(16 * 1024); - let stdoutUsed = 0; - let readFromStdout = (chunk) => { - let limit = stdoutUsed + chunk.length; - if (limit > stdout.length) { - let swap = new Uint8Array(limit * 2); - swap.set(stdout); - stdout = swap; - } - stdout.set(chunk, stdoutUsed); - stdoutUsed += chunk.length; - let offset = 0; - while (offset + 4 <= stdoutUsed) { - let length = readUInt32LE(stdout, offset); - if (offset + 4 + length > stdoutUsed) { - break; - } - offset += 4; - handleIncomingPacket(stdout.subarray(offset, offset + length)); - offset += length; - } - if (offset > 0) { - stdout.copyWithin(0, offset, stdoutUsed); - stdoutUsed -= offset; - } - }; - let afterClose = (error) => { - closeData.didClose = true; - if (error) closeData.reason = ": " + (error.message || error); - const text = "The service was stopped" + closeData.reason; - for (let id in responseCallbacks) { - responseCallbacks[id](text, null); - } - responseCallbacks = {}; - }; - let sendRequest = (refs, value, callback) => { - if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null); - let id = nextRequestID++; - responseCallbacks[id] = (error, response) => { - try { - callback(error, response); - } finally { - if (refs) refs.unref(); - } - }; - if (refs) refs.ref(); - streamIn.writeToStdin(encodePacket({ id, isRequest: true, value })); - }; - let sendResponse = (id, value) => { - if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason); - streamIn.writeToStdin(encodePacket({ id, isRequest: false, value })); - }; - let handleRequest = async (id, request) => { - try { - if (request.command === "ping") { - sendResponse(id, {}); - return; - } - if (typeof request.key === "number") { - const requestCallbacks = requestCallbacksByKey[request.key]; - if (!requestCallbacks) { - return; - } - const callback = requestCallbacks[request.command]; - if (callback) { - await callback(id, request); - return; - } - } - throw new Error(`Invalid command: ` + request.command); - } catch (e) { - const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")]; - try { - sendResponse(id, { errors }); - } catch { - } - } - }; - let isFirstPacket = true; - let handleIncomingPacket = (bytes) => { - if (isFirstPacket) { - isFirstPacket = false; - let binaryVersion = String.fromCharCode(...bytes); - if (binaryVersion !== "0.24.0") { - throw new Error(`Cannot start service: Host version "${"0.24.0"}" does not match binary version ${quote(binaryVersion)}`); - } - return; - } - let packet = decodePacket(bytes); - if (packet.isRequest) { - handleRequest(packet.id, packet.value); - } else { - let callback = responseCallbacks[packet.id]; - delete responseCallbacks[packet.id]; - if (packet.value.error) callback(packet.value.error, {}); - else callback(null, packet.value); - } - }; - let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => { - let refCount = 0; - const buildKey = nextBuildKey++; - const requestCallbacks = {}; - const buildRefs = { - ref() { - if (++refCount === 1) { - if (refs) refs.ref(); - } - }, - unref() { - if (--refCount === 0) { - delete requestCallbacksByKey[buildKey]; - if (refs) refs.unref(); - } - } - }; - requestCallbacksByKey[buildKey] = requestCallbacks; - buildRefs.ref(); - buildOrContextImpl( - callName, - buildKey, - sendRequest, - sendResponse, - buildRefs, - streamIn, - requestCallbacks, - options, - isTTY2, - defaultWD2, - (err, res) => { - try { - callback(err, res); - } finally { - buildRefs.unref(); - } - } - ); - }; - let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => { - const details = createObjectStash(); - let start = (inputPath) => { - try { - if (typeof input !== "string" && !(input instanceof Uint8Array)) - throw new Error('The input to "transform" must be a string or a Uint8Array'); - let { - flags, - mangleCache - } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault); - let request = { - command: "transform", - flags, - inputFS: inputPath !== null, - input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input - }; - if (mangleCache) request.mangleCache = mangleCache; - sendRequest(refs, request, (error, response) => { - if (error) return callback(new Error(error), null); - let errors = replaceDetailsInMessages(response.errors, details); - let warnings = replaceDetailsInMessages(response.warnings, details); - let outstanding = 1; - let next = () => { - if (--outstanding === 0) { - let result = { - warnings, - code: response.code, - map: response.map, - mangleCache: void 0, - legalComments: void 0 - }; - if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments; - if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache; - callback(null, result); - } - }; - if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null); - if (response.codeFS) { - outstanding++; - fs3.readFile(response.code, (err, contents) => { - if (err !== null) { - callback(err, null); - } else { - response.code = contents; - next(); - } - }); - } - if (response.mapFS) { - outstanding++; - fs3.readFile(response.map, (err, contents) => { - if (err !== null) { - callback(err, null); - } else { - response.map = contents; - next(); - } - }); - } - next(); - }); - } catch (e) { - let flags = []; - try { - pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault); - } catch { - } - const error = extractErrorMessageV8(e, streamIn, details, void 0, ""); - sendRequest(refs, { command: "error", flags, error }, () => { - error.detail = details.load(error.detail); - callback(failureErrorWithLog("Transform failed", [error], []), null); - }); - } - }; - if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) { - let next = start; - start = () => fs3.writeFile(input, next); - } - start(null); - }; - let formatMessages2 = ({ callName, refs, messages, options, callback }) => { - if (!options) throw new Error(`Missing second argument in ${callName}() call`); - let keys = {}; - let kind = getFlag(options, keys, "kind", mustBeString); - let color = getFlag(options, keys, "color", mustBeBoolean); - let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger); - checkForInvalidFlags(options, keys, `in ${callName}() call`); - if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`); - if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`); - let request = { - command: "format-msgs", - messages: sanitizeMessages(messages, "messages", null, "", terminalWidth), - isWarning: kind === "warning" - }; - if (color !== void 0) request.color = color; - if (terminalWidth !== void 0) request.terminalWidth = terminalWidth; - sendRequest(refs, request, (error, response) => { - if (error) return callback(new Error(error), null); - callback(null, response.messages); - }); - }; - let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => { - if (options === void 0) options = {}; - let keys = {}; - let color = getFlag(options, keys, "color", mustBeBoolean); - let verbose = getFlag(options, keys, "verbose", mustBeBoolean); - checkForInvalidFlags(options, keys, `in ${callName}() call`); - let request = { - command: "analyze-metafile", - metafile - }; - if (color !== void 0) request.color = color; - if (verbose !== void 0) request.verbose = verbose; - sendRequest(refs, request, (error, response) => { - if (error) return callback(new Error(error), null); - callback(null, response.result); - }); - }; - return { - readFromStdout, - afterClose, - service: { - buildOrContext, - transform: transform2, - formatMessages: formatMessages2, - analyzeMetafile: analyzeMetafile2 - } - }; -} -function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) { - const details = createObjectStash(); - const isContext = callName === "context"; - const handleError = (e, pluginName) => { - const flags = []; - try { - pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault); - } catch { - } - const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName); - sendRequest(refs, { command: "error", flags, error: message }, () => { - message.detail = details.load(message.detail); - callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null); - }); - }; - let plugins; - if (typeof options === "object") { - const value = options.plugins; - if (value !== void 0) { - if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), ""); - plugins = value; - } - } - if (plugins && plugins.length > 0) { - if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), ""); - handlePlugins( - buildKey, - sendRequest, - sendResponse, - refs, - streamIn, - requestCallbacks, - options, - plugins, - details - ).then( - (result) => { - if (!result.ok) return handleError(result.error, result.pluginName); - try { - buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks); - } catch (e) { - handleError(e, ""); - } - }, - (e) => handleError(e, "") - ); - return; - } - try { - buildOrContextContinue(null, (result, done) => done([], []), () => { - }); - } catch (e) { - handleError(e, ""); - } - function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) { - const writeDefault = streamIn.hasFS; - const { - entries, - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir, - nodePaths, - mangleCache - } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault); - if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`); - const request = { - command: "build", - key: buildKey, - entries, - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir: absWorkingDir || defaultWD2, - nodePaths, - context: isContext - }; - if (requestPlugins) request.plugins = requestPlugins; - if (mangleCache) request.mangleCache = mangleCache; - const buildResponseToResult = (response, callback2) => { - const result = { - errors: replaceDetailsInMessages(response.errors, details), - warnings: replaceDetailsInMessages(response.warnings, details), - outputFiles: void 0, - metafile: void 0, - mangleCache: void 0 - }; - const originalErrors = result.errors.slice(); - const originalWarnings = result.warnings.slice(); - if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles); - if (response.metafile) result.metafile = JSON.parse(response.metafile); - if (response.mangleCache) result.mangleCache = response.mangleCache; - if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, "")); - runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => { - if (originalErrors.length > 0 || onEndErrors.length > 0) { - const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)); - return callback2(error, null, onEndErrors, onEndWarnings); - } - callback2(null, result, onEndErrors, onEndWarnings); - }); - }; - let latestResultPromise; - let provideLatestResult; - if (isContext) - requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => { - buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => { - const response = { - errors: onEndErrors, - warnings: onEndWarnings - }; - if (provideLatestResult) provideLatestResult(err, result); - latestResultPromise = void 0; - provideLatestResult = void 0; - sendResponse(id, response); - resolve(); - }); - }); - sendRequest(refs, request, (error, response) => { - if (error) return callback(new Error(error), null); - if (!isContext) { - return buildResponseToResult(response, (err, res) => { - scheduleOnDisposeCallbacks(); - return callback(err, res); - }); - } - if (response.errors.length > 0) { - return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null); - } - let didDispose = false; - const result = { - rebuild: () => { - if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => { - let settlePromise; - provideLatestResult = (err, result2) => { - if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2); - }; - const triggerAnotherBuild = () => { - const request2 = { - command: "rebuild", - key: buildKey - }; - sendRequest(refs, request2, (error2, response2) => { - if (error2) { - reject(new Error(error2)); - } else if (settlePromise) { - settlePromise(); - } else { - triggerAnotherBuild(); - } - }); - }; - triggerAnotherBuild(); - }); - return latestResultPromise; - }, - watch: (options2 = {}) => new Promise((resolve, reject) => { - if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`); - const keys = {}; - checkForInvalidFlags(options2, keys, `in watch() call`); - const request2 = { - command: "watch", - key: buildKey - }; - sendRequest(refs, request2, (error2) => { - if (error2) reject(new Error(error2)); - else resolve(void 0); - }); - }), - serve: (options2 = {}) => new Promise((resolve, reject) => { - if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`); - const keys = {}; - const port = getFlag(options2, keys, "port", mustBeInteger); - const host = getFlag(options2, keys, "host", mustBeString); - const servedir = getFlag(options2, keys, "servedir", mustBeString); - const keyfile = getFlag(options2, keys, "keyfile", mustBeString); - const certfile = getFlag(options2, keys, "certfile", mustBeString); - const fallback = getFlag(options2, keys, "fallback", mustBeString); - const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction); - checkForInvalidFlags(options2, keys, `in serve() call`); - const request2 = { - command: "serve", - key: buildKey, - onRequest: !!onRequest - }; - if (port !== void 0) request2.port = port; - if (host !== void 0) request2.host = host; - if (servedir !== void 0) request2.servedir = servedir; - if (keyfile !== void 0) request2.keyfile = keyfile; - if (certfile !== void 0) request2.certfile = certfile; - if (fallback !== void 0) request2.fallback = fallback; - sendRequest(refs, request2, (error2, response2) => { - if (error2) return reject(new Error(error2)); - if (onRequest) { - requestCallbacks["serve-request"] = (id, request3) => { - onRequest(request3.args); - sendResponse(id, {}); - }; - } - resolve(response2); - }); - }), - cancel: () => new Promise((resolve) => { - if (didDispose) return resolve(); - const request2 = { - command: "cancel", - key: buildKey - }; - sendRequest(refs, request2, () => { - resolve(); - }); - }), - dispose: () => new Promise((resolve) => { - if (didDispose) return resolve(); - didDispose = true; - const request2 = { - command: "dispose", - key: buildKey - }; - sendRequest(refs, request2, () => { - resolve(); - scheduleOnDisposeCallbacks(); - refs.unref(); - }); - }) - }; - refs.ref(); - callback(null, result); - }); - } -} -var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => { - let onStartCallbacks = []; - let onEndCallbacks = []; - let onResolveCallbacks = {}; - let onLoadCallbacks = {}; - let onDisposeCallbacks = []; - let nextCallbackID = 0; - let i = 0; - let requestPlugins = []; - let isSetupDone = false; - plugins = [...plugins]; - for (let item of plugins) { - let keys = {}; - if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`); - const name = getFlag(item, keys, "name", mustBeString); - if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`); - try { - let setup = getFlag(item, keys, "setup", mustBeFunction); - if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`); - checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`); - let plugin = { - name, - onStart: false, - onEnd: false, - onResolve: [], - onLoad: [] - }; - i++; - let resolve = (path3, options = {}) => { - if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed'); - if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`); - let keys2 = /* @__PURE__ */ Object.create(null); - let pluginName = getFlag(options, keys2, "pluginName", mustBeString); - let importer = getFlag(options, keys2, "importer", mustBeString); - let namespace = getFlag(options, keys2, "namespace", mustBeString); - let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString); - let kind = getFlag(options, keys2, "kind", mustBeString); - let pluginData = getFlag(options, keys2, "pluginData", canBeAnything); - let importAttributes = getFlag(options, keys2, "with", mustBeObject); - checkForInvalidFlags(options, keys2, "in resolve() call"); - return new Promise((resolve2, reject) => { - const request = { - command: "resolve", - path: path3, - key: buildKey, - pluginName: name - }; - if (pluginName != null) request.pluginName = pluginName; - if (importer != null) request.importer = importer; - if (namespace != null) request.namespace = namespace; - if (resolveDir != null) request.resolveDir = resolveDir; - if (kind != null) request.kind = kind; - else throw new Error(`Must specify "kind" when calling "resolve"`); - if (pluginData != null) request.pluginData = details.store(pluginData); - if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with"); - sendRequest(refs, request, (error, response) => { - if (error !== null) reject(new Error(error)); - else resolve2({ - errors: replaceDetailsInMessages(response.errors, details), - warnings: replaceDetailsInMessages(response.warnings, details), - path: response.path, - external: response.external, - sideEffects: response.sideEffects, - namespace: response.namespace, - suffix: response.suffix, - pluginData: details.load(response.pluginData) - }); - }); - }); - }; - let promise = setup({ - initialOptions, - resolve, - onStart(callback) { - let registeredText = `This error came from the "onStart" callback registered here:`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart"); - onStartCallbacks.push({ name, callback, note: registeredNote }); - plugin.onStart = true; - }, - onEnd(callback) { - let registeredText = `This error came from the "onEnd" callback registered here:`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd"); - onEndCallbacks.push({ name, callback, note: registeredNote }); - plugin.onEnd = true; - }, - onResolve(options, callback) { - let registeredText = `This error came from the "onResolve" callback registered here:`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve"); - let keys2 = {}; - let filter = getFlag(options, keys2, "filter", mustBeRegExp); - let namespace = getFlag(options, keys2, "namespace", mustBeString); - checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`); - if (filter == null) throw new Error(`onResolve() call is missing a filter`); - let id = nextCallbackID++; - onResolveCallbacks[id] = { name, callback, note: registeredNote }; - plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" }); - }, - onLoad(options, callback) { - let registeredText = `This error came from the "onLoad" callback registered here:`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad"); - let keys2 = {}; - let filter = getFlag(options, keys2, "filter", mustBeRegExp); - let namespace = getFlag(options, keys2, "namespace", mustBeString); - checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`); - if (filter == null) throw new Error(`onLoad() call is missing a filter`); - let id = nextCallbackID++; - onLoadCallbacks[id] = { name, callback, note: registeredNote }; - plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" }); - }, - onDispose(callback) { - onDisposeCallbacks.push(callback); - }, - esbuild: streamIn.esbuild - }); - if (promise) await promise; - requestPlugins.push(plugin); - } catch (e) { - return { ok: false, error: e, pluginName: name }; - } - } - requestCallbacks["on-start"] = async (id, request) => { - details.clear(); - let response = { errors: [], warnings: [] }; - await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => { - try { - let result = await callback(); - if (result != null) { - if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`); - let keys = {}; - let errors = getFlag(result, keys, "errors", mustBeArray); - let warnings = getFlag(result, keys, "warnings", mustBeArray); - checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`); - if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0)); - if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0)); - } - } catch (e) { - response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name)); - } - })); - sendResponse(id, response); - }; - requestCallbacks["on-resolve"] = async (id, request) => { - let response = {}, name = "", callback, note; - for (let id2 of request.ids) { - try { - ({ name, callback, note } = onResolveCallbacks[id2]); - let result = await callback({ - path: request.path, - importer: request.importer, - namespace: request.namespace, - resolveDir: request.resolveDir, - kind: request.kind, - pluginData: details.load(request.pluginData), - with: request.with - }); - if (result != null) { - if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`); - let keys = {}; - let pluginName = getFlag(result, keys, "pluginName", mustBeString); - let path3 = getFlag(result, keys, "path", mustBeString); - let namespace = getFlag(result, keys, "namespace", mustBeString); - let suffix = getFlag(result, keys, "suffix", mustBeString); - let external = getFlag(result, keys, "external", mustBeBoolean); - let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean); - let pluginData = getFlag(result, keys, "pluginData", canBeAnything); - let errors = getFlag(result, keys, "errors", mustBeArray); - let warnings = getFlag(result, keys, "warnings", mustBeArray); - let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray); - let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray); - checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`); - response.id = id2; - if (pluginName != null) response.pluginName = pluginName; - if (path3 != null) response.path = path3; - if (namespace != null) response.namespace = namespace; - if (suffix != null) response.suffix = suffix; - if (external != null) response.external = external; - if (sideEffects != null) response.sideEffects = sideEffects; - if (pluginData != null) response.pluginData = details.store(pluginData); - if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0); - if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); - if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); - if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); - break; - } - } catch (e) { - response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; - break; - } - } - sendResponse(id, response); - }; - requestCallbacks["on-load"] = async (id, request) => { - let response = {}, name = "", callback, note; - for (let id2 of request.ids) { - try { - ({ name, callback, note } = onLoadCallbacks[id2]); - let result = await callback({ - path: request.path, - namespace: request.namespace, - suffix: request.suffix, - pluginData: details.load(request.pluginData), - with: request.with - }); - if (result != null) { - if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`); - let keys = {}; - let pluginName = getFlag(result, keys, "pluginName", mustBeString); - let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array); - let resolveDir = getFlag(result, keys, "resolveDir", mustBeString); - let pluginData = getFlag(result, keys, "pluginData", canBeAnything); - let loader = getFlag(result, keys, "loader", mustBeString); - let errors = getFlag(result, keys, "errors", mustBeArray); - let warnings = getFlag(result, keys, "warnings", mustBeArray); - let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray); - let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray); - checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`); - response.id = id2; - if (pluginName != null) response.pluginName = pluginName; - if (contents instanceof Uint8Array) response.contents = contents; - else if (contents != null) response.contents = encodeUTF8(contents); - if (resolveDir != null) response.resolveDir = resolveDir; - if (pluginData != null) response.pluginData = details.store(pluginData); - if (loader != null) response.loader = loader; - if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0); - if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); - if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); - if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); - break; - } - } catch (e) { - response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; - break; - } - } - sendResponse(id, response); - }; - let runOnEndCallbacks = (result, done) => done([], []); - if (onEndCallbacks.length > 0) { - runOnEndCallbacks = (result, done) => { - (async () => { - const onEndErrors = []; - const onEndWarnings = []; - for (const { name, callback, note } of onEndCallbacks) { - let newErrors; - let newWarnings; - try { - const value = await callback(result); - if (value != null) { - if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`); - let keys = {}; - let errors = getFlag(value, keys, "errors", mustBeArray); - let warnings = getFlag(value, keys, "warnings", mustBeArray); - checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`); - if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0); - if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0); - } - } catch (e) { - newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)]; - } - if (newErrors) { - onEndErrors.push(...newErrors); - try { - result.errors.push(...newErrors); - } catch { - } - } - if (newWarnings) { - onEndWarnings.push(...newWarnings); - try { - result.warnings.push(...newWarnings); - } catch { - } - } - } - done(onEndErrors, onEndWarnings); - })(); - }; - } - let scheduleOnDisposeCallbacks = () => { - for (const cb of onDisposeCallbacks) { - setTimeout(() => cb(), 0); - } - }; - isSetupDone = true; - return { - ok: true, - requestPlugins, - runOnEndCallbacks, - scheduleOnDisposeCallbacks - }; -}; -function createObjectStash() { - const map = /* @__PURE__ */ new Map(); - let nextID = 0; - return { - clear() { - map.clear(); - }, - load(id) { - return map.get(id); - }, - store(value) { - if (value === void 0) return -1; - const id = nextID++; - map.set(id, value); - return id; - } - }; -} -function extractCallerV8(e, streamIn, ident) { - let note; - let tried = false; - return () => { - if (tried) return note; - tried = true; - try { - let lines = (e.stack + "").split("\n"); - lines.splice(1, 1); - let location = parseStackLinesV8(streamIn, lines, ident); - if (location) { - note = { text: e.message, location }; - return note; - } - } catch { - } - }; -} -function extractErrorMessageV8(e, streamIn, stash, note, pluginName) { - let text = "Internal error"; - let location = null; - try { - text = (e && e.message || e) + ""; - } catch { - } - try { - location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), ""); - } catch { - } - return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 }; -} -function parseStackLinesV8(streamIn, lines, ident) { - let at = " at "; - if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) { - for (let i = 1; i < lines.length; i++) { - let line = lines[i]; - if (!line.startsWith(at)) continue; - line = line.slice(at.length); - while (true) { - let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line); - if (match) { - line = match[1]; - continue; - } - match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line); - if (match) { - line = match[1]; - continue; - } - match = /^(\S+):(\d+):(\d+)$/.exec(line); - if (match) { - let contents; - try { - contents = streamIn.readFileSync(match[1], "utf8"); - } catch { - break; - } - let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || ""; - let column = +match[3] - 1; - let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0; - return { - file: match[1], - namespace: "file", - line: +match[2], - column: encodeUTF8(lineText.slice(0, column)).length, - length: encodeUTF8(lineText.slice(column, column + length)).length, - lineText: lineText + "\n" + lines.slice(1).join("\n"), - suggestion: "" - }; - } - break; - } - } - } - return null; -} -function failureErrorWithLog(text, errors, warnings) { - let limit = 5; - text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => { - if (i === limit) return "\n..."; - if (!e.location) return ` -error: ${e.text}`; - let { file, line, column } = e.location; - let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : ""; - return ` -${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`; - }).join(""); - let error = new Error(text); - for (const [key, value] of [["errors", errors], ["warnings", warnings]]) { - Object.defineProperty(error, key, { - configurable: true, - enumerable: true, - get: () => value, - set: (value2) => Object.defineProperty(error, key, { - configurable: true, - enumerable: true, - value: value2 - }) - }); - } - return error; -} -function replaceDetailsInMessages(messages, stash) { - for (const message of messages) { - message.detail = stash.load(message.detail); - } - return messages; -} -function sanitizeLocation(location, where, terminalWidth) { - if (location == null) return null; - let keys = {}; - let file = getFlag(location, keys, "file", mustBeString); - let namespace = getFlag(location, keys, "namespace", mustBeString); - let line = getFlag(location, keys, "line", mustBeInteger); - let column = getFlag(location, keys, "column", mustBeInteger); - let length = getFlag(location, keys, "length", mustBeInteger); - let lineText = getFlag(location, keys, "lineText", mustBeString); - let suggestion = getFlag(location, keys, "suggestion", mustBeString); - checkForInvalidFlags(location, keys, where); - if (lineText) { - const relevantASCII = lineText.slice( - 0, - (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80) - ); - if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) { - lineText = relevantASCII; - } - } - return { - file: file || "", - namespace: namespace || "", - line: line || 0, - column: column || 0, - length: length || 0, - lineText: lineText || "", - suggestion: suggestion || "" - }; -} -function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) { - let messagesClone = []; - let index = 0; - for (const message of messages) { - let keys = {}; - let id = getFlag(message, keys, "id", mustBeString); - let pluginName = getFlag(message, keys, "pluginName", mustBeString); - let text = getFlag(message, keys, "text", mustBeString); - let location = getFlag(message, keys, "location", mustBeObjectOrNull); - let notes = getFlag(message, keys, "notes", mustBeArray); - let detail = getFlag(message, keys, "detail", canBeAnything); - let where = `in element ${index} of "${property}"`; - checkForInvalidFlags(message, keys, where); - let notesClone = []; - if (notes) { - for (const note of notes) { - let noteKeys = {}; - let noteText = getFlag(note, noteKeys, "text", mustBeString); - let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull); - checkForInvalidFlags(note, noteKeys, where); - notesClone.push({ - text: noteText || "", - location: sanitizeLocation(noteLocation, where, terminalWidth) - }); - } - } - messagesClone.push({ - id: id || "", - pluginName: pluginName || fallbackPluginName, - text: text || "", - location: sanitizeLocation(location, where, terminalWidth), - notes: notesClone, - detail: stash ? stash.store(detail) : -1 - }); - index++; - } - return messagesClone; -} -function sanitizeStringArray(values, property) { - const result = []; - for (const value of values) { - if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`); - result.push(value); - } - return result; -} -function sanitizeStringMap(map, property) { - const result = /* @__PURE__ */ Object.create(null); - for (const key in map) { - const value = map[key]; - if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`); - result[key] = value; - } - return result; -} -function convertOutputFiles({ path: path3, contents, hash }) { - let text = null; - return { - path: path3, - contents, - hash, - get text() { - const binary = this.contents; - if (text === null || binary !== contents) { - contents = binary; - text = decodeUTF8(binary); - } - return text; - } - }; -} - -// lib/npm/node-platform.ts -var fs = require("fs"); -var os = require("os"); -var path = require("path"); -var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; -var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; -var packageDarwin_arm64 = "@esbuild/darwin-arm64"; -var packageDarwin_x64 = "@esbuild/darwin-x64"; -var knownWindowsPackages = { - "win32 arm64 LE": "@esbuild/win32-arm64", - "win32 ia32 LE": "@esbuild/win32-ia32", - "win32 x64 LE": "@esbuild/win32-x64" -}; -var knownUnixlikePackages = { - "aix ppc64 BE": "@esbuild/aix-ppc64", - "android arm64 LE": "@esbuild/android-arm64", - "darwin arm64 LE": "@esbuild/darwin-arm64", - "darwin x64 LE": "@esbuild/darwin-x64", - "freebsd arm64 LE": "@esbuild/freebsd-arm64", - "freebsd x64 LE": "@esbuild/freebsd-x64", - "linux arm LE": "@esbuild/linux-arm", - "linux arm64 LE": "@esbuild/linux-arm64", - "linux ia32 LE": "@esbuild/linux-ia32", - "linux mips64el LE": "@esbuild/linux-mips64el", - "linux ppc64 LE": "@esbuild/linux-ppc64", - "linux riscv64 LE": "@esbuild/linux-riscv64", - "linux s390x BE": "@esbuild/linux-s390x", - "linux x64 LE": "@esbuild/linux-x64", - "linux loong64 LE": "@esbuild/linux-loong64", - "netbsd x64 LE": "@esbuild/netbsd-x64", - "openbsd arm64 LE": "@esbuild/openbsd-arm64", - "openbsd x64 LE": "@esbuild/openbsd-x64", - "sunos x64 LE": "@esbuild/sunos-x64" -}; -var knownWebAssemblyFallbackPackages = { - "android arm LE": "@esbuild/android-arm", - "android x64 LE": "@esbuild/android-x64" -}; -function pkgAndSubpathForCurrentPlatform() { - let pkg; - let subpath; - let isWASM = false; - let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; - if (platformKey in knownWindowsPackages) { - pkg = knownWindowsPackages[platformKey]; - subpath = "esbuild.exe"; - } else if (platformKey in knownUnixlikePackages) { - pkg = knownUnixlikePackages[platformKey]; - subpath = "bin/esbuild"; - } else if (platformKey in knownWebAssemblyFallbackPackages) { - pkg = knownWebAssemblyFallbackPackages[platformKey]; - subpath = "bin/esbuild"; - isWASM = true; - } else { - throw new Error(`Unsupported platform: ${platformKey}`); - } - return { pkg, subpath, isWASM }; -} -function pkgForSomeOtherPlatform() { - const libMainJS = require.resolve("esbuild"); - const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); - if (path.basename(nodeModulesDirectory) === "node_modules") { - for (const unixKey in knownUnixlikePackages) { - try { - const pkg = knownUnixlikePackages[unixKey]; - if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; - } catch { - } - } - for (const windowsKey in knownWindowsPackages) { - try { - const pkg = knownWindowsPackages[windowsKey]; - if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; - } catch { - } - } - } - return null; -} -function downloadedBinPath(pkg, subpath) { - const esbuildLibDir = path.dirname(require.resolve("esbuild")); - return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); -} -function generateBinPath() { - if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { - if (!fs.existsSync(ESBUILD_BINARY_PATH)) { - console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); - } else { - return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; - } - } - const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform(); - let binPath; - try { - binPath = require.resolve(`${pkg}/${subpath}`); - } catch (e) { - binPath = downloadedBinPath(pkg, subpath); - if (!fs.existsSync(binPath)) { - try { - require.resolve(pkg); - } catch { - const otherPkg = pkgForSomeOtherPlatform(); - if (otherPkg) { - let suggestions = ` -Specifically the "${otherPkg}" package is present but this platform -needs the "${pkg}" package instead. People often get into this -situation by installing esbuild on Windows or macOS and copying "node_modules" -into a Docker image that runs Linux, or by copying "node_modules" between -Windows and WSL environments. - -If you are installing with npm, you can try not copying the "node_modules" -directory when you copy the files over, and running "npm ci" or "npm install" -on the destination platform after the copy. Or you could consider using yarn -instead of npm which has built-in support for installing a package on multiple -platforms simultaneously. - -If you are installing with yarn, you can try listing both this platform and the -other platform in your ".yarnrc.yml" file using the "supportedArchitectures" -feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures -Keep in mind that this means multiple copies of esbuild will be present. -`; - if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { - suggestions = ` -Specifically the "${otherPkg}" package is present but this platform -needs the "${pkg}" package instead. People often get into this -situation by installing esbuild with npm running inside of Rosetta 2 and then -trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta -2 is Apple's on-the-fly x86_64-to-arm64 translation service). - -If you are installing with npm, you can try ensuring that both npm and node are -not running under Rosetta 2 and then reinstalling esbuild. This likely involves -changing how you installed npm and/or node. For example, installing node with -the universal installer here should work: https://nodejs.org/en/download/. Or -you could consider using yarn instead of npm which has built-in support for -installing a package on multiple platforms simultaneously. - -If you are installing with yarn, you can try listing both "arm64" and "x64" -in your ".yarnrc.yml" file using the "supportedArchitectures" feature: -https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures -Keep in mind that this means multiple copies of esbuild will be present. -`; - } - throw new Error(` -You installed esbuild for another platform than the one you're currently using. -This won't work because esbuild is written with native code and needs to -install a platform-specific binary executable. -${suggestions} -Another alternative is to use the "esbuild-wasm" package instead, which works -the same way on all platforms. But it comes with a heavy performance cost and -can sometimes be 10x slower than the "esbuild" package, so you may also not -want to do that. -`); - } - throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. - -If you are installing esbuild with npm, make sure that you don't specify the -"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature -of "package.json" is used by esbuild to install the correct binary executable -for your current platform.`); - } - throw e; - } - } - if (/\.zip\//.test(binPath)) { - let pnpapi; - try { - pnpapi = require("pnpapi"); - } catch (e) { - } - if (pnpapi) { - const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; - const binTargetPath = path.join( - root, - "node_modules", - ".cache", - "esbuild", - `pnpapi-${pkg.replace("/", "-")}-${"0.24.0"}-${path.basename(subpath)}` - ); - if (!fs.existsSync(binTargetPath)) { - fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); - fs.copyFileSync(binPath, binTargetPath); - fs.chmodSync(binTargetPath, 493); - } - return { binPath: binTargetPath, isWASM }; - } - } - return { binPath, isWASM }; -} - -// lib/npm/node.ts -var child_process = require("child_process"); -var crypto = require("crypto"); -var path2 = require("path"); -var fs2 = require("fs"); -var os2 = require("os"); -var tty = require("tty"); -var worker_threads; -if (process.env.ESBUILD_WORKER_THREADS !== "0") { - try { - worker_threads = require("worker_threads"); - } catch { - } - let [major, minor] = process.versions.node.split("."); - if ( - // { - if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) { - throw new Error( - `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle. - -More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.` - ); - } - if (false) { - return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]]; - } else { - const { binPath, isWASM } = generateBinPath(); - if (isWASM) { - return ["node", [binPath]]; - } else { - return [binPath, []]; - } - } -}; -var isTTY = () => tty.isatty(2); -var fsSync = { - readFile(tempFile, callback) { - try { - let contents = fs2.readFileSync(tempFile, "utf8"); - try { - fs2.unlinkSync(tempFile); - } catch { - } - callback(null, contents); - } catch (err) { - callback(err, null); - } - }, - writeFile(contents, callback) { - try { - let tempFile = randomFileName(); - fs2.writeFileSync(tempFile, contents); - callback(tempFile); - } catch { - callback(null); - } - } -}; -var fsAsync = { - readFile(tempFile, callback) { - try { - fs2.readFile(tempFile, "utf8", (err, contents) => { - try { - fs2.unlink(tempFile, () => callback(err, contents)); - } catch { - callback(err, contents); - } - }); - } catch (err) { - callback(err, null); - } - }, - writeFile(contents, callback) { - try { - let tempFile = randomFileName(); - fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile)); - } catch { - callback(null); - } - } -}; -var version = "0.24.0"; -var build = (options) => ensureServiceIsRunning().build(options); -var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions); -var transform = (input, options) => ensureServiceIsRunning().transform(input, options); -var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options); -var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options); -var buildSync = (options) => { - if (worker_threads && !isInternalWorkerThread) { - if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.buildSync(options); - } - let result; - runServiceSync((service) => service.buildOrContext({ - callName: "buildSync", - refs: null, - options, - isTTY: isTTY(), - defaultWD, - callback: (err, res) => { - if (err) throw err; - result = res; - } - })); - return result; -}; -var transformSync = (input, options) => { - if (worker_threads && !isInternalWorkerThread) { - if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.transformSync(input, options); - } - let result; - runServiceSync((service) => service.transform({ - callName: "transformSync", - refs: null, - input, - options: options || {}, - isTTY: isTTY(), - fs: fsSync, - callback: (err, res) => { - if (err) throw err; - result = res; - } - })); - return result; -}; -var formatMessagesSync = (messages, options) => { - if (worker_threads && !isInternalWorkerThread) { - if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.formatMessagesSync(messages, options); - } - let result; - runServiceSync((service) => service.formatMessages({ - callName: "formatMessagesSync", - refs: null, - messages, - options, - callback: (err, res) => { - if (err) throw err; - result = res; - } - })); - return result; -}; -var analyzeMetafileSync = (metafile, options) => { - if (worker_threads && !isInternalWorkerThread) { - if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.analyzeMetafileSync(metafile, options); - } - let result; - runServiceSync((service) => service.analyzeMetafile({ - callName: "analyzeMetafileSync", - refs: null, - metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), - options, - callback: (err, res) => { - if (err) throw err; - result = res; - } - })); - return result; -}; -var stop = () => { - if (stopService) stopService(); - if (workerThreadService) workerThreadService.stop(); - return Promise.resolve(); -}; -var initializeWasCalled = false; -var initialize = (options) => { - options = validateInitializeOptions(options || {}); - if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`); - if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`); - if (options.worker) throw new Error(`The "worker" option only works in the browser`); - if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once'); - ensureServiceIsRunning(); - initializeWasCalled = true; - return Promise.resolve(); -}; -var defaultWD = process.cwd(); -var longLivedService; -var stopService; -var ensureServiceIsRunning = () => { - if (longLivedService) return longLivedService; - let [command, args] = esbuildCommandAndArgs(); - let child = child_process.spawn(command, args.concat(`--service=${"0.24.0"}`, "--ping"), { - windowsHide: true, - stdio: ["pipe", "pipe", "inherit"], - cwd: defaultWD - }); - let { readFromStdout, afterClose, service } = createChannel({ - writeToStdin(bytes) { - child.stdin.write(bytes, (err) => { - if (err) afterClose(err); - }); - }, - readFileSync: fs2.readFileSync, - isSync: false, - hasFS: true, - esbuild: node_exports - }); - child.stdin.on("error", afterClose); - child.on("error", afterClose); - const stdin = child.stdin; - const stdout = child.stdout; - stdout.on("data", readFromStdout); - stdout.on("end", afterClose); - stopService = () => { - stdin.destroy(); - stdout.destroy(); - child.kill(); - initializeWasCalled = false; - longLivedService = void 0; - stopService = void 0; - }; - let refCount = 0; - child.unref(); - if (stdin.unref) { - stdin.unref(); - } - if (stdout.unref) { - stdout.unref(); - } - const refs = { - ref() { - if (++refCount === 1) child.ref(); - }, - unref() { - if (--refCount === 0) child.unref(); - } - }; - longLivedService = { - build: (options) => new Promise((resolve, reject) => { - service.buildOrContext({ - callName: "build", - refs, - options, - isTTY: isTTY(), - defaultWD, - callback: (err, res) => err ? reject(err) : resolve(res) - }); - }), - context: (options) => new Promise((resolve, reject) => service.buildOrContext({ - callName: "context", - refs, - options, - isTTY: isTTY(), - defaultWD, - callback: (err, res) => err ? reject(err) : resolve(res) - })), - transform: (input, options) => new Promise((resolve, reject) => service.transform({ - callName: "transform", - refs, - input, - options: options || {}, - isTTY: isTTY(), - fs: fsAsync, - callback: (err, res) => err ? reject(err) : resolve(res) - })), - formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({ - callName: "formatMessages", - refs, - messages, - options, - callback: (err, res) => err ? reject(err) : resolve(res) - })), - analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({ - callName: "analyzeMetafile", - refs, - metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), - options, - callback: (err, res) => err ? reject(err) : resolve(res) - })) - }; - return longLivedService; -}; -var runServiceSync = (callback) => { - let [command, args] = esbuildCommandAndArgs(); - let stdin = new Uint8Array(); - let { readFromStdout, afterClose, service } = createChannel({ - writeToStdin(bytes) { - if (stdin.length !== 0) throw new Error("Must run at most one command"); - stdin = bytes; - }, - isSync: true, - hasFS: true, - esbuild: node_exports - }); - callback(service); - let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.24.0"}`), { - cwd: defaultWD, - windowsHide: true, - input: stdin, - // We don't know how large the output could be. If it's too large, the - // command will fail with ENOBUFS. Reserve 16mb for now since that feels - // like it should be enough. Also allow overriding this with an environment - // variable. - maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024 - }); - readFromStdout(stdout); - afterClose(null); -}; -var randomFileName = () => { - return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`); -}; -var workerThreadService = null; -var startWorkerThreadService = (worker_threads2) => { - let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel(); - let worker = new worker_threads2.Worker(__filename, { - workerData: { workerPort, defaultWD, esbuildVersion: "0.24.0" }, - transferList: [workerPort], - // From node's documentation: https://nodejs.org/api/worker_threads.html - // - // Take care when launching worker threads from preload scripts (scripts loaded - // and run using the `-r` command line flag). Unless the `execArgv` option is - // explicitly set, new Worker threads automatically inherit the command line flags - // from the running process and will preload the same preload scripts as the main - // thread. If the preload script unconditionally launches a worker thread, every - // thread spawned will spawn another until the application crashes. - // - execArgv: [] - }); - let nextID = 0; - let fakeBuildError = (text) => { - let error = new Error(`Build failed with 1 error: -error: ${text}`); - let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }]; - error.errors = errors; - error.warnings = []; - return error; - }; - let validateBuildSyncOptions = (options) => { - if (!options) return; - let plugins = options.plugins; - if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`); - }; - let applyProperties = (object, properties) => { - for (let key in properties) { - object[key] = properties[key]; - } - }; - let runCallSync = (command, args) => { - let id = nextID++; - let sharedBuffer = new SharedArrayBuffer(8); - let sharedBufferView = new Int32Array(sharedBuffer); - let msg = { sharedBuffer, id, command, args }; - worker.postMessage(msg); - let status = Atomics.wait(sharedBufferView, 0, 0); - if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status); - let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort); - if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`); - if (reject) { - applyProperties(reject, properties); - throw reject; - } - return resolve; - }; - worker.unref(); - return { - buildSync(options) { - validateBuildSyncOptions(options); - return runCallSync("build", [options]); - }, - transformSync(input, options) { - return runCallSync("transform", [input, options]); - }, - formatMessagesSync(messages, options) { - return runCallSync("formatMessages", [messages, options]); - }, - analyzeMetafileSync(metafile, options) { - return runCallSync("analyzeMetafile", [metafile, options]); - }, - stop() { - worker.terminate(); - workerThreadService = null; - } - }; -}; -var startSyncServiceWorker = () => { - let workerPort = worker_threads.workerData.workerPort; - let parentPort = worker_threads.parentPort; - let extractProperties = (object) => { - let properties = {}; - if (object && typeof object === "object") { - for (let key in object) { - properties[key] = object[key]; - } - } - return properties; - }; - try { - let service = ensureServiceIsRunning(); - defaultWD = worker_threads.workerData.defaultWD; - parentPort.on("message", (msg) => { - (async () => { - let { sharedBuffer, id, command, args } = msg; - let sharedBufferView = new Int32Array(sharedBuffer); - try { - switch (command) { - case "build": - workerPort.postMessage({ id, resolve: await service.build(args[0]) }); - break; - case "transform": - workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) }); - break; - case "formatMessages": - workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) }); - break; - case "analyzeMetafile": - workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) }); - break; - default: - throw new Error(`Invalid command: ${command}`); - } - } catch (reject) { - workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); - } - Atomics.add(sharedBufferView, 0, 1); - Atomics.notify(sharedBufferView, 0, Infinity); - })(); - }); - } catch (reject) { - parentPort.on("message", (msg) => { - let { sharedBuffer, id } = msg; - let sharedBufferView = new Int32Array(sharedBuffer); - workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); - Atomics.add(sharedBufferView, 0, 1); - Atomics.notify(sharedBufferView, 0, Infinity); - }); - } -}; -if (isInternalWorkerThread) { - startSyncServiceWorker(); -} -var node_default = node_exports; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - analyzeMetafile, - analyzeMetafileSync, - build, - buildSync, - context, - formatMessages, - formatMessagesSync, - initialize, - stop, - transform, - transformSync, - version -}); diff --git a/js/node_modules/esbuild/package.json b/js/node_modules/esbuild/package.json deleted file mode 100644 index 720860f..0000000 --- a/js/node_modules/esbuild/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "esbuild", - "version": "0.24.0", - "description": "An extremely fast JavaScript and CSS bundler and minifier.", - "repository": { - "type": "git", - "url": "git+https://github.com/evanw/esbuild.git" - }, - "scripts": { - "postinstall": "node install.js" - }, - "main": "lib/main.js", - "types": "lib/main.d.ts", - "engines": { - "node": ">=18" - }, - "bin": { - "esbuild": "bin/esbuild" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.24.0", - "@esbuild/android-arm": "0.24.0", - "@esbuild/android-arm64": "0.24.0", - "@esbuild/android-x64": "0.24.0", - "@esbuild/darwin-arm64": "0.24.0", - "@esbuild/darwin-x64": "0.24.0", - "@esbuild/freebsd-arm64": "0.24.0", - "@esbuild/freebsd-x64": "0.24.0", - "@esbuild/linux-arm": "0.24.0", - "@esbuild/linux-arm64": "0.24.0", - "@esbuild/linux-ia32": "0.24.0", - "@esbuild/linux-loong64": "0.24.0", - "@esbuild/linux-mips64el": "0.24.0", - "@esbuild/linux-ppc64": "0.24.0", - "@esbuild/linux-riscv64": "0.24.0", - "@esbuild/linux-s390x": "0.24.0", - "@esbuild/linux-x64": "0.24.0", - "@esbuild/netbsd-x64": "0.24.0", - "@esbuild/openbsd-arm64": "0.24.0", - "@esbuild/openbsd-x64": "0.24.0", - "@esbuild/sunos-x64": "0.24.0", - "@esbuild/win32-arm64": "0.24.0", - "@esbuild/win32-ia32": "0.24.0", - "@esbuild/win32-x64": "0.24.0" - }, - "license": "MIT" -} diff --git a/js/package.json b/js/package.json deleted file mode 100644 index db8fd16..0000000 --- a/js/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@notemine/wasm-shim", - "version": "0.0.1", - "main": "index.js", - "type": "module", - "license": "MIT", - "scripts": { - "post-build": "node post-build.js" - }, - "dependencies": { - "esbuild": "0.24.0" - }, - "files": [ - "initWasm.bundle.js" - ], - "exports": { - "./initWasm": "./initWasm.bundle.js" - } -} \ No newline at end of file diff --git a/js/post-build.js b/js/post-build.js deleted file mode 100644 index 5cc2143..0000000 --- a/js/post-build.js +++ /dev/null @@ -1,110 +0,0 @@ -import fs from 'fs'; -import path from 'path'; -import esbuild from 'esbuild'; -import { fileURLToPath } from 'url'; - -// Define __dirname in ESM -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -const pkgDir = path.resolve(__dirname, '../pkg'); -const wasmPath = path.join(pkgDir, 'notemine_bg.wasm'); -const wasmBase64Path = path.join(pkgDir, 'wasmBase64.js'); -const initWasmSrcPath = path.join(pkgDir, 'initWasm.js'); -const initWasmBundlePath = path.join(pkgDir, 'initWasm.bundle.js'); -const packageJsonPath = path.join(pkgDir, 'package.json'); - -function encodeWasmToBase64(wasmFilePath) { - const wasmBuffer = fs.readFileSync(wasmFilePath); - return wasmBuffer.toString('base64'); -} - -function generateWasmBase64Module(base64Wasm) { - const wasmModuleContent = `// wasmBase64.js -export const wasmBase64 = "${base64Wasm}"; -`; - fs.writeFileSync(wasmBase64Path, wasmModuleContent, 'utf8'); -} - -function generateInitWasmModule() { - const initWasmContent = `// initWasm.js -import { wasmBase64 } from './wasmBase64.js'; - -export async function initWasm() { - try { - // Decode Base64 to Uint8Array - const wasmBinary = Uint8Array.from(atob(wasmBase64), (c) => c.charCodeAt(0)); - - // Instantiate the WASM module - const result = await WebAssembly.instantiate(wasmBinary.buffer, {}); - - return result.instance; - } catch (error) { - console.error('WASM Instantiation Failed:', error); - throw error; - } -} -`; - fs.writeFileSync(initWasmSrcPath, initWasmContent, 'utf8'); -} - -async function bundleInitWasm() { - await esbuild.build({ - entryPoints: [initWasmSrcPath], - bundle: true, - outfile: initWasmBundlePath, - format: 'esm', - platform: 'browser', - target: ['esnext'], - minify: true, - sourcemap: false, - }); -} - -function updatePackageJson() { - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); - - if (!packageJson.files) { - packageJson.files = []; - } - - if (!packageJson.files.includes('initWasm.bundle.js')) { - packageJson.files.push('initWasm.bundle.js'); - } - - if (!packageJson.exports) { - packageJson.exports = {}; - } - - packageJson.exports['./initWasm'] = './initWasm.bundle.js'; - - - fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8'); -} - -async function main() { - if (!fs.existsSync(wasmPath)) { - console.error(`WASM file not found at ${wasmPath}. Please run wasm-bindgen first.`); - process.exit(1); - } - - const base64Wasm = encodeWasmToBase64(wasmPath); - console.log('WASM file encoded to Base64.'); - - generateWasmBase64Module(base64Wasm); - console.log('wasmBase64.js module generated.'); - - generateInitWasmModule(); - console.log('initWasm.js module generated.'); - - await bundleInitWasm(); - console.log('initWasm.js bundled with esbuild.'); - - updatePackageJson(); - console.log('package.json updated with initWasm export.'); -} - -main().catch((err) => { - console.error(err); - process.exit(1); -}); diff --git a/js/yarn.lock b/js/yarn.lock deleted file mode 100644 index 616955e..0000000 --- a/js/yarn.lock +++ /dev/null @@ -1,153 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@esbuild/aix-ppc64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.0.tgz#b57697945b50e99007b4c2521507dc613d4a648c" - integrity sha512-WtKdFM7ls47zkKHFVzMz8opM7LkcsIp9amDUBIAWirg70RM71WRSjdILPsY5Uv1D42ZpUfaPILDlfactHgsRkw== - -"@esbuild/android-arm64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.0.tgz#1add7e0af67acefd556e407f8497e81fddad79c0" - integrity sha512-Vsm497xFM7tTIPYK9bNTYJyF/lsP590Qc1WxJdlB6ljCbdZKU9SY8i7+Iin4kyhV/KV5J2rOKsBQbB77Ab7L/w== - -"@esbuild/android-arm@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.0.tgz#ab7263045fa8e090833a8e3c393b60d59a789810" - integrity sha512-arAtTPo76fJ/ICkXWetLCc9EwEHKaeya4vMrReVlEIUCAUncH7M4bhMQ+M9Vf+FFOZJdTNMXNBrWwW+OXWpSew== - -"@esbuild/android-x64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.0.tgz#e8f8b196cfdfdd5aeaebbdb0110983460440e705" - integrity sha512-t8GrvnFkiIY7pa7mMgJd7p8p8qqYIz1NYiAoKc75Zyv73L3DZW++oYMSHPRarcotTKuSs6m3hTOa5CKHaS02TQ== - -"@esbuild/darwin-arm64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.0.tgz#2d0d9414f2acbffd2d86e98253914fca603a53dd" - integrity sha512-CKyDpRbK1hXwv79soeTJNHb5EiG6ct3efd/FTPdzOWdbZZfGhpbcqIpiD0+vwmpu0wTIL97ZRPZu8vUt46nBSw== - -"@esbuild/darwin-x64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.0.tgz#33087aab31a1eb64c89daf3d2cf8ce1775656107" - integrity sha512-rgtz6flkVkh58od4PwTRqxbKH9cOjaXCMZgWD905JOzjFKW+7EiUObfd/Kav+A6Gyud6WZk9w+xu6QLytdi2OA== - -"@esbuild/freebsd-arm64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.0.tgz#bb76e5ea9e97fa3c753472f19421075d3a33e8a7" - integrity sha512-6Mtdq5nHggwfDNLAHkPlyLBpE5L6hwsuXZX8XNmHno9JuL2+bg2BX5tRkwjyfn6sKbxZTq68suOjgWqCicvPXA== - -"@esbuild/freebsd-x64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.0.tgz#e0e2ce9249fdf6ee29e5dc3d420c7007fa579b93" - integrity sha512-D3H+xh3/zphoX8ck4S2RxKR6gHlHDXXzOf6f/9dbFt/NRBDIE33+cVa49Kil4WUjxMGW0ZIYBYtaGCa2+OsQwQ== - -"@esbuild/linux-arm64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.0.tgz#d1b2aa58085f73ecf45533c07c82d81235388e75" - integrity sha512-TDijPXTOeE3eaMkRYpcy3LarIg13dS9wWHRdwYRnzlwlA370rNdZqbcp0WTyyV/k2zSxfko52+C7jU5F9Tfj1g== - -"@esbuild/linux-arm@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.0.tgz#8e4915df8ea3e12b690a057e77a47b1d5935ef6d" - integrity sha512-gJKIi2IjRo5G6Glxb8d3DzYXlxdEj2NlkixPsqePSZMhLudqPhtZ4BUrpIuTjJYXxvF9njql+vRjB2oaC9XpBw== - -"@esbuild/linux-ia32@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.0.tgz#8200b1110666c39ab316572324b7af63d82013fb" - integrity sha512-K40ip1LAcA0byL05TbCQ4yJ4swvnbzHscRmUilrmP9Am7//0UjPreh4lpYzvThT2Quw66MhjG//20mrufm40mA== - -"@esbuild/linux-loong64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.0.tgz#6ff0c99cf647504df321d0640f0d32e557da745c" - integrity sha512-0mswrYP/9ai+CU0BzBfPMZ8RVm3RGAN/lmOMgW4aFUSOQBjA31UP8Mr6DDhWSuMwj7jaWOT0p0WoZ6jeHhrD7g== - -"@esbuild/linux-mips64el@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.0.tgz#3f720ccd4d59bfeb4c2ce276a46b77ad380fa1f3" - integrity sha512-hIKvXm0/3w/5+RDtCJeXqMZGkI2s4oMUGj3/jM0QzhgIASWrGO5/RlzAzm5nNh/awHE0A19h/CvHQe6FaBNrRA== - -"@esbuild/linux-ppc64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.0.tgz#9d6b188b15c25afd2e213474bf5f31e42e3aa09e" - integrity sha512-HcZh5BNq0aC52UoocJxaKORfFODWXZxtBaaZNuN3PUX3MoDsChsZqopzi5UupRhPHSEHotoiptqikjN/B77mYQ== - -"@esbuild/linux-riscv64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.0.tgz#f989fdc9752dfda286c9cd87c46248e4dfecbc25" - integrity sha512-bEh7dMn/h3QxeR2KTy1DUszQjUrIHPZKyO6aN1X4BCnhfYhuQqedHaa5MxSQA/06j3GpiIlFGSsy1c7Gf9padw== - -"@esbuild/linux-s390x@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.0.tgz#29ebf87e4132ea659c1489fce63cd8509d1c7319" - integrity sha512-ZcQ6+qRkw1UcZGPyrCiHHkmBaj9SiCD8Oqd556HldP+QlpUIe2Wgn3ehQGVoPOvZvtHm8HPx+bH20c9pvbkX3g== - -"@esbuild/linux-x64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.0.tgz#4af48c5c0479569b1f359ffbce22d15f261c0cef" - integrity sha512-vbutsFqQ+foy3wSSbmjBXXIJ6PL3scghJoM8zCL142cGaZKAdCZHyf+Bpu/MmX9zT9Q0zFBVKb36Ma5Fzfa8xA== - -"@esbuild/netbsd-x64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.0.tgz#1ae73d23cc044a0ebd4f198334416fb26c31366c" - integrity sha512-hjQ0R/ulkO8fCYFsG0FZoH+pWgTTDreqpqY7UnQntnaKv95uP5iW3+dChxnx7C3trQQU40S+OgWhUVwCjVFLvg== - -"@esbuild/openbsd-arm64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.0.tgz#5d904a4f5158c89859fd902c427f96d6a9e632e2" - integrity sha512-MD9uzzkPQbYehwcN583yx3Tu5M8EIoTD+tUgKF982WYL9Pf5rKy9ltgD0eUgs8pvKnmizxjXZyLt0z6DC3rRXg== - -"@esbuild/openbsd-x64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.0.tgz#4c8aa88c49187c601bae2971e71c6dc5e0ad1cdf" - integrity sha512-4ir0aY1NGUhIC1hdoCzr1+5b43mw99uNwVzhIq1OY3QcEwPDO3B7WNXBzaKY5Nsf1+N11i1eOfFcq+D/gOS15Q== - -"@esbuild/sunos-x64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.0.tgz#8ddc35a0ea38575fa44eda30a5ee01ae2fa54dd4" - integrity sha512-jVzdzsbM5xrotH+W5f1s+JtUy1UWgjU0Cf4wMvffTB8m6wP5/kx0KiaLHlbJO+dMgtxKV8RQ/JvtlFcdZ1zCPA== - -"@esbuild/win32-arm64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.0.tgz#6e79c8543f282c4539db684a207ae0e174a9007b" - integrity sha512-iKc8GAslzRpBytO2/aN3d2yb2z8XTVfNV0PjGlCxKo5SgWmNXx82I/Q3aG1tFfS+A2igVCY97TJ8tnYwpUWLCA== - -"@esbuild/win32-ia32@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.0.tgz#057af345da256b7192d18b676a02e95d0fa39103" - integrity sha512-vQW36KZolfIudCcTnaTpmLQ24Ha1RjygBo39/aLkM2kmjkWmZGEJ5Gn9l5/7tzXA42QGIoWbICfg6KLLkIw6yw== - -"@esbuild/win32-x64@0.24.0": - version "0.24.0" - resolved "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.0.tgz#168ab1c7e1c318b922637fad8f339d48b01e1244" - integrity sha512-7IAFPrjSQIJrGsK6flwg7NFmwBoSTyF3rl7If0hNUFQU4ilTsEPL6GuMuU9BfIWVVGuRnuIidkSMC+c0Otu8IA== - -esbuild@0.24.0: - version "0.24.0" - resolved "https://registry.npmjs.org/esbuild/-/esbuild-0.24.0.tgz#f2d470596885fcb2e91c21eb3da3b3c89c0b55e7" - integrity sha512-FuLPevChGDshgSicjisSooU0cemp/sGXR841D5LHMB7mTVOmsEHcAxaH3irL53+8YDIeVNQEySh4DaYU/iuPqQ== - optionalDependencies: - "@esbuild/aix-ppc64" "0.24.0" - "@esbuild/android-arm" "0.24.0" - "@esbuild/android-arm64" "0.24.0" - "@esbuild/android-x64" "0.24.0" - "@esbuild/darwin-arm64" "0.24.0" - "@esbuild/darwin-x64" "0.24.0" - "@esbuild/freebsd-arm64" "0.24.0" - "@esbuild/freebsd-x64" "0.24.0" - "@esbuild/linux-arm" "0.24.0" - "@esbuild/linux-arm64" "0.24.0" - "@esbuild/linux-ia32" "0.24.0" - "@esbuild/linux-loong64" "0.24.0" - "@esbuild/linux-mips64el" "0.24.0" - "@esbuild/linux-ppc64" "0.24.0" - "@esbuild/linux-riscv64" "0.24.0" - "@esbuild/linux-s390x" "0.24.0" - "@esbuild/linux-x64" "0.24.0" - "@esbuild/netbsd-x64" "0.24.0" - "@esbuild/openbsd-arm64" "0.24.0" - "@esbuild/openbsd-x64" "0.24.0" - "@esbuild/sunos-x64" "0.24.0" - "@esbuild/win32-arm64" "0.24.0" - "@esbuild/win32-ia32" "0.24.0" - "@esbuild/win32-x64" "0.24.0" diff --git a/packages/wrapper/src/index.ts b/packages/wrapper/src/index.ts index f3c2fc1..ec4fc53 100644 --- a/packages/wrapper/src/index.ts +++ b/packages/wrapper/src/index.ts @@ -1,51 +1,78 @@ - import { Subject, BehaviorSubject } from 'rxjs'; //@ts-ignore: multi-stage build hack to facilitate inline base64 wasm within an inline web-worker. import MineWorker from '../dist/mine.worker.js'; +/** Options for configuring the miner */ export interface MinerOptions { + /** The content to include in the mined event */ content?: string; + /** Tags associated with the mined event */ tags?: string[][]; + /** Public key used for the event */ pubkey?: string; + /** Difficulty level for mining */ difficulty?: number; + /** Number of workers to use for mining */ numberOfWorkers?: number; } +/** Data structure representing a progress event during mining */ export interface ProgressEvent { + /** ID of the worker making progress */ workerId: number; + /** Current hash rate of the worker (in hashes per second) */ hashRate?: number; + /** Current best proof-of-work data */ bestPowData?: BestPowData; } +/** Data structure for reporting an error event */ export interface ErrorEvent { + /** The error that occurred */ error: any; + /** Optional message with more details about the error */ message?: string; } +/** Data structure for reporting a cancelled mining event */ export interface CancelledEvent { + /** Reason for the cancellation */ reason?: string; } +/** Data structure for reporting a successful mining event */ export interface SuccessEvent { + /** The result of the mining operation */ result: MinedResult | null; } +/** Best proof-of-work data found so far */ export interface BestPowData { + /** Best proof-of-work value */ bestPow: number; + /** Nonce used to achieve the proof-of-work */ nonce: string; + /** Hash that met the proof-of-work requirements */ hash: string; } +/** Proof-of-work data including worker information */ export interface WorkerPow extends BestPowData { + /** ID of the worker who found this proof-of-work */ workerId?: number; } +/** Data structure representing a mined event result */ export interface MinedResult { + /** The mined event data */ event: any; + /** Total time taken to mine (in milliseconds) */ totalTime: number; + /** Hash rate achieved during mining */ hashRate: number; } +/** Class representing a miner for Notemine events */ export class Notemine { private readonly REFRESH_EVERY_MS = 250; @@ -60,11 +87,17 @@ export class Notemine { private _totalHashRate = 0; static _defaultTags: string[][] = [['miner', 'notemine']]; + /** Observable indicating whether mining is currently active */ public mining$ = new BehaviorSubject(false); + /** Observable indicating if mining was cancelled */ public cancelled$ = new BehaviorSubject(false); + /** Observable for the result of the mining operation */ public result$ = new BehaviorSubject(null); + /** Observable for the list of active workers */ public workers$ = new BehaviorSubject([]); + /** Observable tracking the proof-of-work data for each worker */ public workersPow$ = new BehaviorSubject>({}); + /** Observable for the worker that found the best proof-of-work */ public highestPow$ = new BehaviorSubject(null); private progressSubject = new Subject(); @@ -72,11 +105,19 @@ export class Notemine { private cancelledEventSubject = new Subject(); private successSubject = new Subject(); + /** Observable for mining progress updates */ public progress$ = this.progressSubject.asObservable(); + /** Observable for errors encountered during mining */ public error$ = this.errorSubject.asObservable(); + /** Observable for mining cancellations */ public cancelledEvent$ = this.cancelledEventSubject.asObservable(); + /** Observable for successful mining results */ public success$ = this.successSubject.asObservable(); + /** + * Creates a new Notemine miner instance + * @param options - Configuration options for the miner + */ constructor(options?: MinerOptions) { this._content = options?.content || ''; this._tags = [...Notemine._defaultTags, ...(options?.tags || [])]; @@ -85,58 +126,74 @@ export class Notemine { this._numberOfWorkers = options?.numberOfWorkers || navigator.hardwareConcurrency || 4; } + /** Sets the content to be used in the mining event */ set content(content: string) { this._content = content; } + /** Gets the current mining content */ get content(): string { return this._content; } + /** Sets the tags to be used in the mining event */ set tags(tags: string[][]) { this._tags = Array.from(new Set([...this._tags, ...tags])); } + /** Gets the current tags */ get tags(): string[][] { return this._tags; } + /** Sets the public key for the event */ set pubkey(pubkey: string) { this._pubkey = pubkey; } + /** Gets the current public key */ get pubkey(): string { return this._pubkey; } + /** Sets the mining difficulty */ set difficulty(difficulty: number) { this._difficulty = difficulty; } + /** Gets the current mining difficulty */ get difficulty(): number { return this._difficulty; } + /** Sets the number of workers for mining */ set numberOfWorkers(numberOfWorkers: number) { this._numberOfWorkers = numberOfWorkers; } + /** Gets the number of workers currently being used */ get numberOfWorkers(): number { return this._numberOfWorkers; } + /** Sets the last refresh interval */ set lastRefresh(interval: number) { this._lastRefresh = interval; } + /** Gets the last refresh interval */ get lastRefresh(): number { return this._lastRefresh; } + /** Gets the total hash rate achieved */ get totalHashRate(): number { return this._totalHashRate; } + /** + * Starts the mining process. Throws an error if pubkey or content is not set. + */ async mine(): Promise { if (this.mining$.getValue()) return; @@ -160,10 +217,12 @@ export class Notemine { await this.initializeWorkers(); } + /** Stops the mining process */ stop(): void { this.cancel(); } + /** Cancels the mining process */ cancel(): void { if (!this.mining$.getValue()) return; @@ -174,6 +233,9 @@ export class Notemine { this.cancelledEventSubject.next({ reason: 'Mining cancelled by user.' }); } + /** + * Initializes worker threads for mining + */ private async initializeWorkers(): Promise { try { ////console.log('Initializing workers...'); @@ -205,6 +267,10 @@ export class Notemine { } } + /** + * Handles messages received from the mining workers + * @param e - The message event from a worker + */ private handleWorkerMessage(e: MessageEvent): void { const data = e.data; const { type, workerId, hashRate } = data; @@ -253,6 +319,10 @@ export class Notemine { } } + /** + * Handles errors encountered by the mining workers + * @param e - The error event from a worker + */ private handleWorkerError(e: ErrorEvent): void { console.error('Worker encountered an error:', e); const errorDetails = { @@ -262,6 +332,10 @@ export class Notemine { this.errorSubject.next({ error: JSON.stringify(errorDetails) }); } + /** + * Prepares the mining event with necessary data + * @returns A JSON string representing the event + */ private prepareEvent(): string { const event = { pubkey: this.pubkey, @@ -274,6 +348,11 @@ export class Notemine { return JSON.stringify(event); } + /** + * Calculates and tracks the hash rate for a worker + * @param workerId - The ID of the worker + * @param hashRate - The hash rate to track + */ private calculateHashRate(workerId: number, hashRate: number) { if (!hashRate) return; @@ -288,8 +367,13 @@ export class Notemine { this.recordMaxRate(workerId, hashRate); this.refreshHashRate(); -} + } + /** + * Records the maximum hash rate for a worker + * @param workerId - The ID of the worker + * @param hashRate - The hash rate to record + */ private async recordMaxRate(workerId: number, hashRate: number){ //console.log(`Worker ${workerId} hash rate: ${Math.round(hashRate/1000)}`); const maxHashRate = this._workerMaxHashRates.get(workerId); @@ -298,6 +382,11 @@ export class Notemine { } } + /** + * Calculates the average hash rate from an array of hash rates + * @param arr - Array of hash rate values + * @returns The average hash rate + */ private averageHashRate(arr: number[]): number { let sum = 0; for (let i = 0; i < arr.length; i++) { @@ -306,6 +395,9 @@ export class Notemine { return arr.length === 0 ? 0 : sum / arr.length; } + /** + * Refreshes the total hash rate for all workers + */ private refreshHashRate() { if (Date.now() - this.lastRefresh < this.REFRESH_EVERY_MS) { return; @@ -323,5 +415,4 @@ export class Notemine { this._totalHashRate = Math.round(totalRate/1000); this._lastRefresh = Date.now(); } - }